現在、Kerasを使ってアップルとオレンジの画像を分類をしようとしています。
環境はGoogle Colaboratoryです。
ネットで見つけたものをそのまま利用しディレクトリ名もそのまま合わせ、学習用画像はそれぞれ20枚ずつ、テスト用画像は5枚ずつ用意しています。
コードは以下のようなものです。
Python3
1from keras.models import Sequential 2from keras.layers import Activation, Dense, Dropout 3from keras.utils.np_utils import to_categorical 4from keras.optimizers import Adagrad 5from keras.optimizers import Adam 6import numpy as np 7from PIL import Image 8import os 9# 学習用のデータを作る. 10image_list = [] 11label_list = [] 12 13# ./data/train 以下のorange,appleディレクトリ以下の画像を読み込む。 14for dir in os.listdir("data/train"): 15 if dir == ".DS_Store": 16 continue 17dir1 = "data/train/" + dir 18 label = 0 19 20 if dir == "apple": # appleはラベル0 21 label = 0 22 elif dir == "orange": # orangeはラベル1 23 label = 1 24 25 for file in os.listdir(dir1): 26 if file != ".DS_Store": 27 # 配列label_listに正解ラベルを追加(りんご:0 オレンジ:1) 28 label_list.append(label) 29 filepath = dir1 + "/" + file 30# 画像を25x25pixelに変換し、1要素が[R,G,B]3要素を含む配列の25x25の2次元配列として読み込む。 31 # [R,G,B]はそれぞれが0-255の配列。 32 image = np.array(Image.open(filepath).resize((25, 25))) 33 print(filepath) 34 # 配列を変換し、[[Redの配列],[Greenの配列],[Blueの配列]] のような形にする。 35 image = image.transpose(2, 0, 1) 36 # さらにフラットな1次元配列に変換。最初の1/3はRed、次がGreenの、最後がBlueの要素がフラットに並ぶ。 37 image = image.reshape(1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0] 38 # 出来上がった配列をimage_listに追加。 39 image_list.append(image / 255.) 40# kerasに渡すためにnumpy配列に変換。 41image_list = np.array(image_list) 42 43# ラベルの配列を1と0からなるラベル配列に変更 44# 0 -> [1,0], 1 -> [0,1] という感じ。 45Y = to_categorical(label_list) 46 47# モデルを生成してニューラルネットを構築 48model = Sequential() 49model.add(Dense(200, input_dim=1875)) 50model.add(Activation("relu")) 51model.add(Dropout(0.2)) 52 53model.add(Dense(200)) 54model.add(Activation("relu")) 55model.add(Dropout(0.2)) 56 57model.add(Dense(2)) 58model.add(Activation("softmax")) 59# オプティマイザにAdamを使用 60opt = Adam(lr=0.001) 61# モデルをコンパイル 62model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) 63# 学習を実行。10%はテストに使用。 64model.fit(image_list, Y, nb_epoch=1500, batch_size=100, validation_split=0.1) 65 66# テスト用ディレクトリ(./data/train/)の画像でチェック。正解率を表示する。 67total = 0. 68ok_count = 0. 69 70for dir in os.listdir("data/train"): 71 if dir == ".DS_Store": 72 continue 73 74 dir1 = "data/test/" + dir 75 label = 0 76 77 if dir == "apple": 78 label = 0 79 elif dir == "orange": 80 label = 1 81 82 for file in os.listdir(dir1): 83 if file != ".DS_Store": 84 label_list.append(label) 85 filepath = dir1 + "/" + file 86 image = np.array(Image.open(filepath).resize((25, 25))) 87 print(filepath) 88 image = image.transpose(2, 0, 1) 89 image = image.reshape(1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0] 90 result = model.predict_classes(np.array([image / 255.])) 91 print("label:", label, "result:", result[0]) 92 93 total += 1. 94 95 if label == result[0]: 96 ok_count += 1. 97 98print("seikai: ", ok_count / total * 100, "%")
上記のようなコードを実行したら、次のようなエラーが出ました。
ValueError Traceback (most recent call last) <ipython-input-5-fb62631d675b> in <module>() 66 model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) 67 # 学習を実行。10%はテストに使用。 ---> 68 model.fit(image_list, Y, nb_epoch=1500, batch_size=100, validation_split=0.1) 69 70 # テスト用ディレクトリ(./data/train/)の画像でチェック。正解率を表示する。 /usr/local/lib/python3.6/dist-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs) 950 sample_weight=sample_weight, 951 class_weight=class_weight, --> 952 batch_size=batch_size) 953 # Prepare validation data. 954 do_validation = False /usr/local/lib/python3.6/dist-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size) 749 feed_input_shapes, 750 check_batch_axis=False, # Don't enforce the batch size. --> 751 exception_prefix='input') 752 753 if y is not None: /usr/local/lib/python3.6/dist-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix) 136 ': expected ' + names[i] + ' to have shape ' + 137 str(shape) + ' but got array with shape ' + --> 138 str(data_shape)) 139 return data 140 ValueError: Error when checking input: expected dense_1_input to have shape (1875,) but got array with shape (1,)
隠れそうに問題があるのかな?と思ったのですが、初学者なのであまりよくわかりませんでした。
どなたか回答よろしくお願いします!!めちゃくちゃ困っています!!
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/04/26 02:27
2019/04/26 02:33