前提
学習用データとテスト用データに分けたい
(例)
Python(Google Colab )でCNNを用いた三つの画像分類を行うシステムを作っています。
分類器の作成中に以下のエラーメッセージが発生しました。
実現したいこと
ここに実現したいことを箇条書きで書いてください。
- 分類器の機能を動作するようにする
- オリジナルの画像データを用いて画像分類を行いたい(三分類)
発生している問題・エラーメッセージ
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/ Requirement already satisfied: Pillow==7.0.0 in /usr/local/lib/python3.7/dist-packages (7.0.0) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-4-f0fc28ec8cdd> in <module> 267 268 if __name__ == '__main__': --> 269 main() 2 frames /usr/local/lib/python3.7/dist-packages/sklearn/model_selection/_split.py in _validate_shuffle_split(n_samples, test_size, train_size, default_test_size) 2099 "With n_samples={}, test_size={} and train_size={}, the " 2100 "resulting train set will be empty. Adjust any of the " -> 2101 "aforementioned parameters.".format(n_samples, test_size, train_size) 2102 ) 2103 ValueError: With n_samples=0, test_size=0.2 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters.
該当のソースコード(一番下のソースコードでエラーです。それ以外に問題がある場合の為、仮定を乗せています。長くてすみません(´;ω;`))
Python
1# -*- coding: utf-8 -*- 2import numpy as np 3from tensorflow.keras.models import Sequential, model_from_json 4from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D 5from tensorflow.keras.optimizers import RMSprop 6from tensorflow.keras.datasets import cifar10 7from tensorflow.keras.preprocessing.image import array_to_img, img_to_array, load_img 8from tensorflow.keras.utils import to_categorical 9from sklearn.model_selection import train_test_split 10import matplotlib.pyplot as plt 11import re 12import os 13import pickle 14!pip install Pillow==7.0.0 15 16def list_imgs(directory, ext='jpg|jpeg|bmp|png|ppm'): 17 return [os.path.join(root, f) for root, _, files in os.walk(directory) for f in files if re.match(r'([\w]+\.(?:' + ext + '))', f.lower())] 18 19def plot_history(history, 20 save_graph_img_path, 21 fig_size_width, 22 fig_size_height, 23 lim_font_size): 24 25 acc = history.history['accuracy'] 26 val_acc = history.history['val_accuracy'] 27 loss = history.history['loss'] 28 val_loss = history.history['val_loss'] 29 30 epochs = range(len(acc)) 31 32 # グラフ表示 33 plt.figure(figsize=(fig_size_width, fig_size_height)) 34 plt.rcParams['font.family'] = 'Times New Roman' 35 plt.rcParams['font.size'] = lim_font_size # 全体のフォント 36 #plt.subplot(121) 37 38 # plot accuracy values 39 plt.plot(epochs, acc, color = "blue", linestyle = "solid", label = 'train acc') 40 plt.plot(epochs, val_acc, color = "green", linestyle = "solid", label= 'valid acc') 41 #plt.title('Training and Validation acc') 42 #plt.grid() 43 #plt.legend() 44 45 # plot loss values 46 #plt.subplot(122) 47 plt.plot(epochs, loss, color = "red", linestyle = "solid" ,label = 'train loss') 48 plt.plot(epochs, val_loss, color = "orange", linestyle = "solid" , label= 'valid loss') 49 #plt.title('Training and Validation loss') 50 plt.legend() 51 plt.grid() 52 53 plt.savefig(save_graph_img_path) 54 plt.close() # バッファ解放 55 56def main(): 57 # ハイパーパラメータ 58 batch_size = 5 # バッチサイズ 59 num_classes = 3 # 分類クラス数(今回は3種類) 60 epochs = 200 # エポック数(学習の繰り返し回数) 61 dropout_rate = 0.2 # 過学習防止用:入力の20%を0にする(破棄) 62 63 # 入力画像のパラメータ 64 img_width = 32 # 入力画像の幅 65 img_height = 32 # 入力画像の高さ 66 img_ch = 3 # 3ch画像(RGB)で学習 67 68 # データの保存先(自分の環境に応じて適宜変更) 69 SAVE_DATA_DIR_PATH = "C:/github/sample/python/keras/04_img/ex1_data/" 70 71 # ディレクトリがなければ作成 72 os.makedirs(SAVE_DATA_DIR_PATH, exist_ok=True) 73 74 # グラフ画像のサイズ 75 FIG_SIZE_WIDTH = 12 76 FIG_SIZE_HEIGHT = 10 77 FIG_FONT_SIZE = 25 78 79 data_x = [] 80 data_y = [] 81 num_classes = 3 82 83 # クラス0の画像データ群をロード 84 for filepath in list_imgs(SAVE_DATA_DIR_PATH + "img0"): 85 img = img_to_array(load_img(filepath, target_size=(img_width,img_height, img_ch))) 86 data_x.append(img) 87 data_y.append(0) # 教師データ(正解) 88 89 90 # クラス1の画像データ群をロード 91 for filepath in list_imgs(SAVE_DATA_DIR_PATH + "img1"): 92 img = img_to_array(load_img(filepath, target_size=(img_width,img_height, img_ch))) 93 data_x.append(img) 94 data_y.append(1) # 教師データ(正解) 95 96 # クラス2の画像データ群をロード 97 for filepath in list_imgs(SAVE_DATA_DIR_PATH + "img2"): 98 img = img_to_array(load_img(filepath, target_size=(img_width,img_height, img_ch))) 99 data_x.append(img) 100 data_y.append(2) # 教師データ(正解) 101 102 103 # NumPy配列に変換 104 data_x = np.asarray(data_x) 105 106 # 学習データはNumPy配列に変換し 107 data_y = np.asarray(data_y) 108 109 # 学習用データとテストデータに分割 110 x_train, x_test, y_train, y_test = train_test_split(data_x, data_y, test_size=0.2)
試したこと
解説動画ではpillowのダウンロードが必要とのことですので、それをダウンロードしたのみです。(14行目)それもあってるかわからない…
補足情報
参考文献↓
https://algorithm.joho.info/machine-learning/python-keras-convolutional-neural-network/
CNNで画像分類を行ってみたく、画像ファイル(独自)のみ書き換えて実装してみたいです。
Pythonは基礎知識しかありません。