sumple_cnn_classification.pyとpredict.pyというコードを書き、学習とそれによる二種類の画像の判別を行うプログラム
を作ったのですが、エラーが出てしまってうまく動きません。
sumple_cnn_classification.pyはうまく動いているので、predict.pyのコードが間違っていると思います。predict.pyを制作する際に参考にしたサイトはこちらです。
Kerasによる、ものすごくシンプルな画像分類(りんごとオレンジ)
predict.py
from keras.models import Sequential from keras.layers import Activation, Dense, Dropout from keras.utils.np_utils import to_categorical from keras.optimizers import Adagrad from keras.optimizers import Adam import numpy as np from PIL import Image import os # 学習用のデータを作る. image_list = [] label_list = [] # ./data/train 以下のorange,appleディレクトリ以下の画像を読み込む。 for dir in os.listdir("data/train"): if dir == ".DS_Store": continue dir1 = "data/train/" + dir label = 0 if dir == "次郎": # appleはラベル0 label = 0 elif dir == "次郎ではない": # orangeはラベル1 label = 1 for file in os.listdir(dir1): if file != ".DS_Store": # 配列label_listに正解ラベルを追加(りんご:0 オレンジ:1) label_list.append(label) filepath = dir1 + "/" + file # 画像を25x25pixelに変換し、1要素が[R,G,B]3要素を含む配列の25x25の2次元配列として読み込む。 # [R,G,B]はそれぞれが0-255の配列。 image = np.array(Image.open(filepath).resize((25, 25))) print(filepath) # 配列を変換し、[[Redの配列],[Greenの配列],[Blueの配列]] のような形にする。 image = image.transpose(2, 0, 1) # さらにフラットな1次元配列に変換。最初の1/3はRed、次がGreenの、最後がBlueの要素がフラットに並ぶ。 image = image.reshape( 1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0] # 出来上がった配列をimage_listに追加。 image_list.append(image / 255.) # kerasに渡すためにnumpy配列に変換。 image_list = np.array(image_list) # ラベルの配列を1と0からなるラベル配列に変更 # 0 -> [1,0], 1 -> [0,1] という感じ。 Y = to_categorical(label_list) # モデルを生成してニューラルネットを構築 model = Sequential() model.add(Dense(200, input_dim=1875)) model.add(Activation("relu")) model.add(Dropout(0.2)) model.add(Dense(200)) model.add(Activation("relu")) model.add(Dropout(0.2)) model.add(Dense(2)) model.add(Activation("softmax")) # オプティマイザにAdamを使用 opt = Adam(lr=0.001) # モデルをコンパイル model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) # 学習を実行。10%はテストに使用。 model.fit(image_list, Y, nb_epoch=1500, batch_size=100, validation_split=0.1) # テスト用ディレクトリ(./data/train/)の画像でチェック。正解率を表示する。 total = 0. ok_count = 0. for dir in os.listdir("data/train"): if dir == ".DS_Store": continue dir1 = "data/jirou-test/" + dir label = 0 if dir == "次郎": label = 0 elif dir == "次郎ではない": label = 1 for file in os.listdir(dir1): if file != ".DS_Store": label_list.append(label) filepath = dir1 + "/" + file image = np.array(Image.open(filepath).resize((25, 25))) print(filepath) image = image.transpose(2, 0, 1) image = image.reshape( 1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0] result = model.predict_classes(np.array([image / 255.])) print("label:", label, "result:", result[0]) total += 1. if label == result[0]: ok_count += 1. print("正解率: ", ok_count / total * 100, "%")
エラー文
(base) xxxx@xxxx image-classfication-jiro % /opt/anaconda3/bin/python /Users/xxxx/Downloads/image-classfication-jiro/predict.py Using TensorFlow backend. /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) data/train/not-jiro/images-3.jpeg ・・・・ data/train/jiro/hJLxemaOWndtlpzjbdVroI0DTL91CFuP.jpg data/train/jiro/image.jpg data/train/jiro/XHjnENbJCUCB3Xr7skOdOuq9Aoec7mlt.jpg /Users/xxxx/Downloads/image-classfication-jiro/predict.py:70: UserWarning: The `nb_epoch` argument in `fit` has been renamed `epochs`. model.fit(image_list, Y, nb_epoch=1500, batch_size=100, validation_split=0.1) Traceback (most recent call last): File "/Users/xxxxx/Downloads/image-classfication-jiro/predict.py", line 70, in <module> model.fit(image_list, Y, nb_epoch=1500, batch_size=100, validation_split=0.1) File "/opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py", line 1154, in fit batch_size=batch_size) File "/opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py", line 621, in _standardize_user_data exception_prefix='target') File "/opt/anaconda3/lib/python3.7/site-packages/keras/engine/training_utils.py", line 145, in standardize_input_data str(data_shape)) ValueError: Error when checking target: expected activation_3 to have shape (2,) but got array with shape (1,)