【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特徴量を削除したり工夫する必要がある.

【pandas】 DataFrameの操作について

Irisで試す

# データCSVの読み込み
iris = pd.read_csv("input.csv")

f:id:umashika5555:20171113212446p:plain

# データのある特徴列を削除する
iris.drop("Id", axis=1, inplace=True)

f:id:umashika5555:20171113212515p:plain

# 同データのカウント
# ”Species”という特徴列の名義特徴量の種類をそれぞれカウント
iris["Species"].value_counts()

f:id:umashika5555:20171113212537p:plain

# 各特徴列の値の個数をカウント
# null値があるかもチェック
# memoryなども表示してくれる
iris.info()

f:id:umashika5555:20171113212608p:plain

# count, mean, std, min, 25, 50, 75, maxを算出
iris.describe()

f:id:umashika5555:20171113212623p:plain

特徴量の削除

violinplotによって特徴量の分布が同じようなときjointplotによって, それらの特徴量の相関関係を調べる.
実際に相関係数の絶対値が1に近づいたらどちらかの特徴量を学習から削除することができるそう.
f:id:umashika5555:20171113035634p:plain
上図で2つの特徴量の分布が同じようなのでjointplotを利用し, 相関計数を調べる.
相関係数は0.86とかなり高い値なのでどちらかの特徴量列を外す場合があるらしい.
f:id:umashika5555:20171113035600p:plain

【seaborn】 plotについて

seabornライブラリでデータを可視化したい場合, BoxplotとViolinplotなどがある.
ラベルAとラベルBの正規化, 標準化済の特徴量3つをとってきて比較することに用いられる.
Boxplotでは下図のような図をプロットでき, 中央値などがわかりやすい.
f:id:umashika5555:20171113033851p:plain
(図引用: https://qiita.com/TomHortons/items/5b585a6860ff5ccd5ba5)

Violinplotでは下図のように分布の形や, 多峰性を確認しやすい.
f:id:umashika5555:20171113034241p:plain

【参考】
https://qiita.com/TomHortons/items/5b585a6860ff5ccd5ba5

【pandas】 DataFrameに辞書形式で格納する

>>> pd.DataFrame({"feature1":[1,2,3],"feature2":[0.1,0.2,0.3]})
feature1	feature2
0	1	0.1
1	2	0.2
2	3	0.3


【参考】
【pandas】 CSVの読み込み - メモ的な何か
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html

【pandas】 DataFrame.describe()について

DataFrame.describe()はDataFrameに格納されているそれぞれの特徴量(横軸)に対して
数値データならcount, mean, std, min, 25%, 50%, 75%, maxを計算,
カテゴリデータならcount, unique(カテゴリの種類), top(先頭), freq(最頻値)を計算してくれる便利な機能

【参考】
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html