convert コマンド よく使う操作

画像のリサイズ

a.pngを指定した高さ/幅に同一比のまま縮尺拡大したb.pngを出力する.

# 幅に合わせる
convert -resize 640x a.png b.png
# 高さに合わせる
convert -resize x640 a.png b.png

a.pngという画像を640px * 640pxのb.pngに変換する.

convert -resize 640x640! a.png b.png

ディレクトリ内にある全ての画像に適応するならば

for filename in *.JPG; do convert -resize 640x640! ${filename} ${filename%.JPG}_640x640.jpg; done;

# ファイル名を変えずに実行したい場合
mogrify -resize 640x640! *.png;

ディレクトリresize_dirに変換後の画像を格納する場合

mkdir resize_dir
for filename in *.JPG; do convert -resize 640x640 $filename reseize_dir/${filename%.JPG}_640x640.JPG; done;

画像の形式変換

ディレクトリ内のJPGファイルをPNGファイルに一括変換する.

# ディレクトリ内のJPGファイルを探す
find ./ -name "*.jpg"
# ディレクトリ内のJPGファイルの個数を数える
find ./ -name "*.jpg" | wc -l
# JPGファイルをPNGに変換する
for filename in *.jpg;do convert "$filename" "${filename%.jpg}.png";done

【環境設定】ubuntu 18.04 LTSにslackを入れる

slackのデスクトップアプリケーションを, dpkgでインストールする方法
単純にslackのwebサイトからダウンロードして

$ sudo dpkg -i xxx.deb

とやったらlibappindicator1が無いみたいなエラーがなされたので,

$ sudo apt --fix-broken install
$ sudo apt install libindicator1
$ sudo dpkg -i xxx.deb

と行う.

【環境設定】ubuntu18.04のproxy関連設定

aptの設定

自宅でインストールしたubuntuをプロキシ環境下にあるネットワーク環境に持っていったとき, システム全体のプロキシ設定でブラウジングなどできたので, apt installなどできると思っていたが別に設定しないといけないらしい.
参考にしたのはこれ
usado.jp

$ sudo emacs /etc/environment

http_proxy="http://proxy-server:port/"
https_proxy="http://proxy-server:port/"

gitの設定

qiita.com
qiita.com

$git config --global http.proxy http://proxy.example.com:8080
$git config --global https.proxy http://proxy.example.com:8080

設定場所は.gitconfig

BitBucketの設定

22ポートが閉じられているので443ポートで通信を行う.

$ touch ~/.ssh/config
$ emacs ~/.ssh/config
Host bitbucket.org
    User git
    IdentityFile ~/.ssh/id_rsa
    HostName altssh.bitbucket.org
    Port 443
    ProxyCommand connect.exe -H hoge.proxy.jp:1080 %h %p

qiita.com
qiita.com
qiita.com
re-dzine.net

【環境設定】Ubuntu 18.04LTSでCtrl + Spaceで変換する

mozcを起動してデフォルトでHankaku/Zenkakuの項目をメモして
f:id:umashika5555:20180917024215p:plain
全く同じものをCtrl+Spaceに置き換えてエントリーを追加すればよい.
f:id:umashika5555:20180917024220p:plain
f:id:umashika5555:20180917024217p:plain
mozcを閉じるときに「設定は新しいアプリケーションから適応されます」的なことを言われたので, 新しいアプリを起動して試してみたができなかった.
しかし, 再起動したらできた.

【環境設定】ubuntuにGPUドライバを入れる

自分のノートPCにubuntu 18.04 LTSを入れて, GPUドライバがデフォルトでIntelの内蔵のグラフィックドライバになっていたため, NVIDIAのに変えた.
ここを参考にしたらスンナリできた.
taktak.jp

$ ubuntu-drivers devices
$ sudo ubuntu-drivers autoinstall
$ sudo reboot
$ nvidia-smi

【urllib】プロキシ設定

proxyの使い方メモ
keras.datasets.mnist.load_data()とかしたいときに, プロキシを通す方法

import urllib
proxy_support = urllib.request.ProxyHandler({'https': 'http://proxy.hogehoge.ac.jp:80'})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)

【Python】matplotlibで最低限のグラフをかけるようにする

TeXで表示させるため, グラフが必要な時期になってきた.
Pythonで最低限のグラフを描画する方法をメモ.
sigmoid関数のプロット

import numpy as np
import matplotlib.pyplot as plt

# 関数定義
x = np.linspace(-8, 8, 100)
y = 1/ (1+np.exp(-x))

# 垂直線
plt.vlines(0.0, -0.1, 1.1, colors="r", linestyle="dotted", label="")
# 水平線
plt.hlines(0.0, -8.0, 8.0, colors="k", linestyle="dotted", label="")
plt.hlines(0.5, -8.0, 8.0, colors="k", linestyle="dotted", label="")
plt.hlines(1.0, -8.0, 8.0, colors="k", linestyle="dotted", label="")

# sigmoid 関数
plt.plot(x, y, label="sigmoid function")

# y軸の設定
yticks = [0,0.5,1.0]
plt.yticks(yticks)

# 軸の名称
plt.xlabel(r"z")
plt.ylabel(r"$\phi(z)$")

# 凡例
plt.legend(loc="upper left")

# 図の保存
plt.savefig("./sigmoid.png")
plt.show()

f:id:umashika5555:20180122130503j:plain
TeXファイルに貼り付ける場合は, .epsにしておく必要がある場合がある.
convert コマンドでファイルの種類を変更する.

$ convert sigmoid.png sigmoid.eps

【Python】 pythonからshellの実行

Pythonからshellコマンドを実行する際に以下のようなやり方がある.
今回は次のshellコマンドをpythonで実行するやり方を比較する.

$sha256sum hoge.zip
#返り値:  xxxxxxxxxxx hoge.zip

os.system()を使う方法

import os
file_name = "hoge.zip"
os.system('sha256sum "{}"'.format(file_name))
# 成功
# xxxxxxxxxxx hoge.zip
# 0
# 失敗
# sha256sum: hoge.zip : No such file or directory
# 256

成功したか失敗したかのみしかわからない.
コマンドの出力が受け取れないし, 推奨されていないやり方らしい.

subprocess.check_output()を使う方法

import subprocess
file_name = "hoge.zip"
args = ["sha256sum", file_name]
subprocess.check_output(args)
# 成功
# b'16e3a87f14dce201f90dc0f7dd2a6318e7b9e5aef095e5815123c3a44e92ac97  GA_result.txt\n'
# 失敗
# sha256sum: hoge.zip : No such file or directory
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#  File ".pyenv/versions/3.5.4/lib/python3.5/subprocess.py", line 316, in check_output  **kwargs).stdout
#  File ".pyenv/versions/3.5.4/lib/python3.5/subprocess.py", line 398, in run output=stdout, stderr=stderr)
# subprocess.CalledProcessError: Command '['sha256sum', 'GA_result1.txt']' returned non-zero exit status 1

成功した場合, 返り値はbyte型なのでstr型にdecodeし, pythonコード内でshellの出力結果を得ることができる.

res = subprocess.check_output(args)
hash_value = res.decode("utf-8").split(" ")[0]

ただし, windowsの場合はうまく行かない可能性がある. 原因はまだ良く見てない.

commands.getstatusoutput()を使う方法

昔よく使っていたが, Python3 で廃止されたらしい.
これの代用がsubprocessモジュールになったらしい.

【TeX】 ページを跨いで表を表示する

longtable.styを使う

\newcolumntype{A}{>{\raggedright}p{0.3cm}}
\newcolumntype{N}{>{\raggedright}p{3.6cm}}
\newcolumntype{D}{>{\raggedright}p{10.0cm}}
{\footnotesize
\begin{longtable}[c]{|A|N|D|}
\hline
No & permission-name & Description \tabularnewline \hline
\endfirsthead
0  & \verb|ACCESS_CHECKIN_PROPERTIES| & Allows read/write access to the "properties" table in the checkin database, to change values that get uploaded.\tabularnewline \hline
1  & \verb|ACCESS_COARSE_LOCATION| & Allows an app to access approximate location. \tabularnewline \hline
2  & \verb|ACCESS_FINE_LOCATION| & Allows an app to access precise location.\tabularnewline \hline
3  & \verb|ACCESS_LOCATION_|\\ \verb|EXTRA_COMMANDS| & Allows an application to access extra location provider commands. \tabularnewline \hline
\end{longtable}
}

f:id:umashika5555:20180118020916p:plain

【参考】
http://www.biwako.shiga-u.ac.jp/sensei/kumazawa/tex/longtable.html
https://ctan.org/pkg/longtable

【Python】 再帰的にファイルを取得する

import os
def find_all_files(directory):
    for root, dirs, files in os.walk(directory):
        #yield root # ここをアンコメントするとディレクトリも得られる
        for file in files:
            yield os.path.join(root, file)
        
if __name__ == "__main__":
    path_directory = "SAMPLE"
    for file in find_all_files(path_directory):
        print(file)

treeコマンドのようにファイルを取得できる.
os.walk()とos.path.join()は始めて知った.
os.path.join(path_directory, name_file)でpath_directory + "/" + name_fileとしてくれるようだ.
普段

path ="aaaa"
for file in os.listdir(path):
    path_file = path + "/" + file

とファイルのpathを取得していたためこれは少し感動.
さらにwindowslinuxの"\\"と"/"の違いも一々気にする必要なさそうで便利!

参考
https://qiita.com/suin/items/cdef17e447ceeff6e79d

【Cygwin】 ホームディレクトリを変更する

Cygwinのterminal上ではなく, ホストOSであるWindows環境変数を設定する必要があるそう.
デスクトップ上にCygwinのホームディレクトリを置きたい場合
環境変数名: HOME
パス: /cygdrive/c/Users/username/Desktop
のようにWindows環境変数を設定する.

【Python】 confusion_matrtixの作り方

seabornのheatmapによって表現できる.

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# scikit-learnのconfusion_matrixクラスで
b = np.array([[251,  22,   1,   3,   0,   1,   3,  16,  24],
               [  8, 459,   0,   2,   0,   1,   0,   4,  23],
               [  0,   1, 557,   0,   0,   0,   0,   1,   0],
               [  0,   3,   0,  90,   0,   0,   0,   0,   0],
               [  0,   0,   0,   1,   1,   0,   0,   4,   0],
               [ 35,  20,   1,   8,   0,  50,   0,   7,  31],
               [  0,   3,   0,   5,   0,   0,  78,   0,   0],
               [ 11,   1,   4,   9,   0,   1,   0, 228,   1],
               [ 34,  39,   0,   0,   0,   2,   0,  11, 119]])
labels = ["a","b","c","d","e","f","g","h","i"]
#pandas.dataframeに格納
b = pd.DataFrame(b,index=labels,columns=index)
sns.heatmap(b,annot=True,cmap="Reds")
plt.show()

【データ分析】 特徴量の相関関係の図の見方

f:id:umashika5555:20171113213635p:plain
図[2][4]は正の相関関係があるとわかる.
図[1][1]は緑と赤の分布がほぼ同じであり, 分離が厳しいことがわかる. 図[0][1]でも混じっている.
これを処理するためには, SepalWidthCm特徴量を削除したり工夫する必要がある.