質問編集履歴

2

実行できているソースなどをすべて記載。

2020/01/04 17:47

投稿

退会済みユーザー
test CHANGED
File without changes
test CHANGED
@@ -28,6 +28,314 @@
28
28
 
29
29
  ```python
30
30
 
31
+ #ラベリングによる学習/検証データの準備
32
+
33
+
34
+
35
+ #import os
36
+
37
+ #os.environ['KERAS_BACKEND']='tensorflow'
38
+
39
+ #
40
+
41
+
42
+
43
+ from PIL import Image
44
+
45
+ import os, glob
46
+
47
+ import numpy as np
48
+
49
+ import random, math
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+ #画像が保存されているルートディレクトリのパス
58
+
59
+ root_dir = "C:/animal_pic"
60
+
61
+ # 商品名
62
+
63
+ categories = ["pos",
64
+
65
+ "neg"]
66
+
67
+
68
+
69
+ # 画像データ用配列
70
+
71
+ X = []
72
+
73
+ # ラベルデータ用配列
74
+
75
+ Y = []
76
+
77
+
78
+
79
+ #画像データごとにadd_sample()を呼び出し、X,Yの配列を返す関数
80
+
81
+ def make_sample(files):
82
+
83
+ global X, Y
84
+
85
+ X = []
86
+
87
+ Y = []
88
+
89
+ for cat, fname in files:
90
+
91
+ add_sample(cat, fname)
92
+
93
+ return np.array(X), np.array(Y)
94
+
95
+
96
+
97
+ #渡された画像データを読み込んでXに格納し、また、
98
+
99
+ #画像データに対応するcategoriesのidxをY格納する関数
100
+
101
+ def add_sample(cat, fname):
102
+
103
+ img = Image.open(fname)
104
+
105
+ img = img.convert("RGB")
106
+
107
+ #img = img.resize((150, 150))
108
+
109
+ data = np.asarray(img)
110
+
111
+ X.append(data)
112
+
113
+ Y.append(cat)
114
+
115
+
116
+
117
+ #全データ格納用配列
118
+
119
+ allfiles = []
120
+
121
+
122
+
123
+ #カテゴリ配列の各値と、それに対応するidxを認識し、全データをallfilesにまとめる
124
+
125
+ for idx, cat in enumerate(categories):
126
+
127
+ image_dir = root_dir + "/" + cat
128
+
129
+ files = glob.glob(image_dir + "/*.tif")
130
+
131
+ for f in files:
132
+
133
+ allfiles.append((idx, f))
134
+
135
+
136
+
137
+ #シャッフル後、学習データと検証データに分ける
138
+
139
+ random.shuffle(allfiles)
140
+
141
+ th = math.floor(len(allfiles) * 0.8)
142
+
143
+ train = allfiles[0:th]
144
+
145
+ test = allfiles[th:]
146
+
147
+ X_train, y_train = make_sample(train)
148
+
149
+ X_test, y_test = make_sample(test)
150
+
151
+ xy = (X_train, X_test, y_train, y_test)
152
+
153
+ #データを保存する
154
+
155
+ np.save("animal_data.npy", xy)
156
+
157
+ ```
158
+
159
+ ###実行結果
160
+
161
+ 表示なし
162
+
163
+ ###
164
+
165
+
166
+
167
+ ```python
168
+
169
+ #モデルの構築
170
+
171
+
172
+
173
+ from keras import layers, models
174
+
175
+
176
+
177
+ model = models.Sequential()
178
+
179
+ model.add(layers.Conv2D(32,(3,3),activation="relu",input_shape=(150,150,3)))
180
+
181
+ model.add(layers.MaxPooling2D((2,2)))
182
+
183
+ model.add(layers.Conv2D(64,(3,3),activation="relu"))
184
+
185
+ model.add(layers.MaxPooling2D((2,2)))
186
+
187
+ model.add(layers.Conv2D(128,(3,3),activation="relu"))
188
+
189
+ model.add(layers.MaxPooling2D((2,2)))
190
+
191
+ model.add(layers.Conv2D(128,(3,3),activation="relu"))
192
+
193
+ model.add(layers.MaxPooling2D((2,2)))
194
+
195
+ model.add(layers.Flatten())
196
+
197
+ model.add(layers.Dense(512,activation="relu"))
198
+
199
+ model.add(layers.Dense(2,activation="sigmoid")) #分類先の種類分設定
200
+
201
+
202
+
203
+ #モデル構成の確認
204
+
205
+ model.summary()
206
+
207
+ ```
208
+
209
+ ### 実行結果
210
+
211
+ _________________________________________________________________
212
+
213
+ Layer (type) Output Shape Param #
214
+
215
+ =================================================================
216
+
217
+ conv2d_5 (Conv2D) (None, 148, 148, 32) 896
218
+
219
+ _________________________________________________________________
220
+
221
+ max_pooling2d_5 (MaxPooling2 (None, 74, 74, 32) 0
222
+
223
+ _________________________________________________________________
224
+
225
+ conv2d_6 (Conv2D) (None, 72, 72, 64) 18496
226
+
227
+ _________________________________________________________________
228
+
229
+ max_pooling2d_6 (MaxPooling2 (None, 36, 36, 64) 0
230
+
231
+ _________________________________________________________________
232
+
233
+ conv2d_7 (Conv2D) (None, 34, 34, 128) 73856
234
+
235
+ _________________________________________________________________
236
+
237
+ max_pooling2d_7 (MaxPooling2 (None, 17, 17, 128) 0
238
+
239
+ _________________________________________________________________
240
+
241
+ conv2d_8 (Conv2D) (None, 15, 15, 128) 147584
242
+
243
+ _________________________________________________________________
244
+
245
+ max_pooling2d_8 (MaxPooling2 (None, 7, 7, 128) 0
246
+
247
+ _________________________________________________________________
248
+
249
+ flatten_2 (Flatten) (None, 6272) 0
250
+
251
+ _________________________________________________________________
252
+
253
+ dense_3 (Dense) (None, 512) 3211776
254
+
255
+ _________________________________________________________________
256
+
257
+ dense_4 (Dense) (None, 2) 1026
258
+
259
+ =================================================================
260
+
261
+ Total params: 3,453,634
262
+
263
+ Trainable params: 3,453,634
264
+
265
+ Non-trainable params: 0
266
+
267
+ ###
268
+
269
+
270
+
271
+ ```python
272
+
273
+ #モデルのコンパイル
274
+
275
+
276
+
277
+ from keras import optimizers
278
+
279
+
280
+
281
+ model.compile(loss="binary_crossentropy",
282
+
283
+ optimizer=optimizers.RMSprop(lr=1e-4),
284
+
285
+ metrics=["acc"])
286
+
287
+ ```
288
+
289
+ ###実行結果
290
+
291
+ 表示なし
292
+
293
+ ###
294
+
295
+ ```python
296
+
297
+ #データの準備
298
+
299
+ from keras.utils import np_utils
300
+
301
+ import numpy as np
302
+
303
+
304
+
305
+ categories = ["pos","neg"]
306
+
307
+ nb_classes = len(categories)
308
+
309
+
310
+
311
+ X_train, X_test, y_train, y_test = np.load("/animal_data.npy")
312
+
313
+
314
+
315
+ #データの正規化
316
+
317
+ X_train = X_train.astype("float") / 255
318
+
319
+ X_test = X_test.astype("float") / 255
320
+
321
+
322
+
323
+ #kerasで扱えるようにcategoriesをベクトルに変換
324
+
325
+ y_train = np_utils.to_categorical(y_train, nb_classes)
326
+
327
+ y_test = np_utils.to_categorical(y_test, nb_classes)
328
+
329
+ ```
330
+
331
+ ###実行結果
332
+
333
+ 表示なし
334
+
335
+ ###
336
+
337
+ ```python
338
+
31
339
  #モデルの学習
32
340
 
33
341
 
@@ -44,6 +352,68 @@
44
352
 
45
353
  ```
46
354
 
355
+ 実行結果 ここでエラーがでてます。
356
+
357
+ ---------------------------------------------------------------------------
358
+
359
+ ValueError Traceback (most recent call last)
360
+
361
+ <ipython-input-5-a383b561d91a> in <module>
362
+
363
+ 4 epochs=10,
364
+
365
+ 5 batch_size=6,
366
+
367
+ ----> 6 validation_data=(X_test,y_test))
368
+
369
+
370
+
371
+ C:\ProgramData\Anaconda3\envs\PythonAI\lib\site-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)
372
+
373
+ 950 sample_weight=sample_weight,
374
+
375
+ 951 class_weight=class_weight,
376
+
377
+ --> 952 batch_size=batch_size)
378
+
379
+ 953 # Prepare validation data.
380
+
381
+ 954 do_validation = False
382
+
383
+
384
+
385
+ C:\ProgramData\Anaconda3\envs\PythonAI\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
386
+
387
+ 749 feed_input_shapes,
388
+
389
+ 750 check_batch_axis=False, # Don't enforce the batch size.
390
+
391
+ --> 751 exception_prefix='input')
392
+
393
+ 752
394
+
395
+ 753 if y is not None:
396
+
397
+
398
+
399
+ C:\ProgramData\Anaconda3\envs\PythonAI\lib\site-packages\keras\engine\training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
400
+
401
+ 126 ': expected ' + names[i] + ' to have ' +
402
+
403
+ 127 str(len(shape)) + ' dimensions, but got array '
404
+
405
+ --> 128 'with shape ' + str(data_shape))
406
+
407
+ 129 if not check_batch_axis:
408
+
409
+ 130 data_shape = data_shape[1:]
410
+
411
+
412
+
413
+ ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (0, 1)
414
+
415
+
416
+
47
417
 
48
418
 
49
419
  ### 試したこと
@@ -71,3 +441,7 @@
71
441
  まだこれらの分野を勉強し始めたばかりで原因も対処法もよくわからないことだらけなので、回答をいただけたらすぐに試したいと思います。
72
442
 
73
443
  よろしくお願いします。
444
+
445
+
446
+
447
+ 実行できているソースなどをすべて記載しました。

1

タグの追加

2020/01/04 17:47

投稿

退会済みユーザー
test CHANGED
File without changes
test CHANGED
File without changes