画像データはグレースケールにして二値化しています.
白丸が横方向に移動して内部の最大応力が発生した箇所を白丸ごとにラベリングしました.
MLPでは経験者なのですが,CNNは初心者なので何がなんだかわかんない状況です.以下のエラーが出ておりどこを修正すればいいのかご教授願います.
ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (4000, 90, 90)
おそらく,
data_format: 文字列で,"channels_last"(デフォルト)"(batch, height, width, channels)"
TensorFlowでは(サンプル数, 画像の行数, 画像の列数, チャネル数)
バックエンドでTFを使っています.
という形なので,ミニバッチを付け足せばいいと思うのですがどうすればよいですか?
python
1 2 3from keras.models import Sequential 4from keras.layers.convolutional import Conv2D 5from keras.layers import Activation, Dense, Dropout, Flatten 6from keras.utils.np_utils import to_categorical 7from keras.optimizers import Adagrad 8from keras.optimizers import Adam 9from keras.models import load_model 10from keras.callbacks import EarlyStopping, ModelCheckpoint, CSVLogger 11import numpy as np 12from PIL import Image 13import os 14import time 15import csv 16 17 18start_time = time.time() 19print("開始時刻: " + str(start_time)) 20 21# 学習用のデータを作る. 22image_list = [] 23label_list = [] 24 25#ハイパーパラメータ 26#画像サイズ 27x = 90 28y = 90 29A = x*y #入力のノード数 30#エポック数 31B = 50 32#バッチサイズ 33BATCH_SIZE = 32 34#学習率 35LR = 0.00001 36#出力ノード数 37output =4 38 39 40# ./data/train 以下のa,b,cのディレクトリ以下の画像を読み込む。 41for dir in os.listdir("data/train"): 42 if dir == ".DS_Store": 43 continue 44 45 dir1 = "data/train/" + dir 46 label = 0 47 48 if dir == "a": # 左下に最大応力:ラベル0 49 label = 0 50 elif dir == "b": # 右下に最大応力:ラベル1 51 label = 1 52 elif dir == "c": # 右下に最大応力:ラベル1 53 label = 2 54 elif dir == "d": # 右下に最大応力:ラベル1 55 label = 3 56 57 58 59 60 for file in os.listdir(dir1): 61 if file != ".DS_Store": 62 label_list.append(label) #わからない 63 filepath = dir1 + "/" + file 64 image = np.array(Image.open(filepath).resize((x, y))) 65 print(image.shape) 66 print(filepath) 67 #image =np.reshape(image, A) 68 print(image.shape) 69 print('\n') 70 image_list.append(image / 255.) 71 72 73# kerasに渡すためにnumpy配列に変換。 74image_list = np.array(image_list) 75 76 77 78 79# ラベルの配列を1と0からなるラベル配列に変更 80# 0 -> [1,0], 1 -> [0,1] という感じ。 81Y = to_categorical(label_list) #わからない 82 83print("入力データの確認") 84print(image_list.shape) 85#np.savetxt("check/input_data_pixel.csv",image_list,delimiter=",") 86print("ラベルデータの確認") 87print(Y.shape) 88#np.savetxt("check/label_data.csv",Y,delimiter=",") 89 90 91# モデルを生成してニューラルネットを構築 92model = Sequential() 93 94model.add(Conv2D(32,3,input_shape=(x,y,1),kernel_initializer='random_uniform',bias_initializer='zeros')) 95model.add(Activation('relu')) 96model.add(Conv2D(32,3,kernel_initializer='random_uniform',bias_initializer='zeros')) 97model.add(Activation('relu')) 98 99model.add(Conv2D(64,3,kernel_initializer='random_uniform',bias_initializer='zeros')) 100model.add(Activation('relu')) 101 102model.add(Flatten()) 103model.add(Dense(810)) 104model.add(Activation('relu')) 105model.add(Dropout(1.0)) 106 107 108model.add(Dense(output)) 109model.add(Activation("softmax")) 110 111# オプティマイザ(最適化)にAdamを使用 112opt = Adam(lr=LR) 113# モデルをコンパイル 114model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) #わからない 115#CSVに各エポックの学習結果の保存 116csv_logger = CSVLogger('result/training.csv') 117# 学習を実行。20%はテストに使用。 118history = model.fit(image_list, Y, nb_epoch=B,verbose=1,callbacks=[csv_logger], batch_size=BATCH_SIZE, validation_split=0.2) 119 120 121 122# テスト用ディレクトリ(./data/train/)の画像でチェック。正解率を表示する。 123total = 0. 124ok_count = 0. 125#最終の学習結果の表示 126loss, accuracy = model.evaluate(image_list, Y) 127print("\nloss:{} accuracy:{}".format(loss, accuracy)) 128#最終の学習結果を書き込む 129fp = open("result/RESULT.txt","w") 130fp.write("\nloss:{} accuracy:{}".format(loss, accuracy)) 131fp.close() 132#正解率の書き込み 133f = open("result/ANSWER.txt","w") 134 135for dir in os.listdir("data/train"): 136 if dir == ".DS_Store": 137 continue 138 139 dir1 = "data/test/" + dir 140 label = 0 141 142 if dir == "a": # 左下に最大応力:ラベル0 143 label = 0 144 elif dir == "b": # 右下に最大応力:ラベル1 145 label = 1 146 elif dir == "c": # 右下に最大応力:ラベル1 147 label = 2 148 elif dir == "d": # 右下に最大応力:ラベル1 149 label = 3 150 151 152 153 for file in os.listdir(dir1): 154 if file != ".DS_Store": 155 label_list.append(label) 156 filepath = dir1 + "/" + file 157 image = np.array(Image.open(filepath).resize((x, y))) 158 print(filepath) 159 image =np.reshape(image, A) 160 result = model.predict_classes(np.array([image / 255.])) 161 print("label:", label, "result:", result[0]) 162 L = label 163 R = result[0] 164 f.write(filepath) 165 f.write("\nlabel:{} result:{}\n".format(L, R) ) 166 total += 1. 167 168 if label == result[0]: 169 ok_count += 1. 170 171 172 173 174print("正答率: ", ok_count / total * 100, "%") 175SEIKAI =ok_count / total * 100 176f.write("\n正答率:{}".format(SEIKAI)) 177 178end_time = time.time() 179print("終了時刻: ",end_time) 180print ("かかった時間: ", (end_time - start_time)) 181 182ttime = end_time - start_time 183fa = open("result/TIME.txt","w") 184fa.write("\nかかった時間:{} ".format(ttime)) 185fa.close() 186
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/15 14:13
2018/11/15 14:30 編集
2018/11/16 03:47
2018/11/16 03:52
2018/11/16 04:00
2018/11/19 03:18
2018/11/20 05:02