Pythonのsklearn(SVM)で画像認識の機械学習をする上で学んだことを備忘録として記録する。
読み込み
ある特定のファイルに存在する画像データを一括で読み込む
→globを使用する
一例:testフォルダにあるJPGファイルを全て読み込む
import glob
file = glob.glob("/Users/Apple/Desktop/test/*JPG")
file
これにより画像ファイル名がリストとして読み込まれる。
画像データとして活用するにはこの後OpenCVでimreadが必要
特徴量変数の作成
複数の画像を一つずつimreadで読み込んでimgに入れたのち、appendで空のリストに追加。それをarrayにする。
file_list= []
for i in file:
img = cv2.imread(i)
file_list.append(img)
file_arr = np.array(file_list)
imreadはndarrayを返すので、この処理でリストの中にarrayが入る形となる。
appendでリストに入れる方法をしないと、繰り返し処理でimgが上書きされてしまう。
*2021.10.14追記
上記コードではfileの中の"ファイル名"を読みに行ってNoneを返すことがある。
正しくは下記がよい。
file_list= []
for i in range(len(file)):
img = cv2.imread(file[i])
file_list.append(img)
file_arr = np.array(file_list)
正解ラベルの作成
特徴量変数の数に応じて、np.zeros, np.onesで作成
機械学習でyとして代入するためには、0と1を結合したものにしなければならない。
→ndarray同士では作れないので、一度リストにして結合したのちにndarrayに戻す。
一例としてラベル0と1をそれぞれ2つずつ作り、一つにまとめたもの
label_0 = np.zeros(2) #ラベル0作成 ndarray
label_1 = np.ones(2) #ラベル1作成 ndarray
label_0_list = label_0.tolist() #リスト化
label_1_list = label_1.tolist() #リスト化
label_list = label_0_list + label_1_list #リスト結合
label = np.array(label_list) #ndarrayに戻す
label #ラベル完成
エラー対応(Found input variables with inconsistent numbers of samples: )
from sklearn.model_selection import train_test_split
from sklearn import svm, metrics
from sklearn.metrics import accuracy_score
x = file_arr
y = label
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2)
clf = svm.LinearSVC()
clf.fit(x_train, y_train)
clf.fit(x_train, y_train)の時に下記エラー発生。
ValueError: Found input variables with inconsistent numbers of samples:
→Numpy配列のshapeでxとyの行数を揃えれば解決。
行数揃え
→行数を合わせるとき、reshape引数に-1を入れると、変換元の要素数に合わせて自動で値が決定するため、簡単に補正できる。