回答編集履歴
1
あ
test
CHANGED
@@ -1,15 +1,89 @@
|
|
1
|
+
以下のようにしてみてはどうでしょうか。
|
2
|
+
|
3
|
+
|
4
|
+
|
5
|
+
```python
|
6
|
+
|
7
|
+
import os
|
8
|
+
|
9
|
+
import numpy as np
|
10
|
+
|
11
|
+
from keras.preprocessing.image import ImageDataGenerator
|
12
|
+
|
13
|
+
|
14
|
+
|
15
|
+
base_dir = (r'C:\Users\HN4-00012\Documents\kosen fike\bunnkasai\loads15_data_small')
|
16
|
+
|
1
|
-
|
17
|
+
train_dir = os.path.join(base_dir,'train')
|
18
|
+
|
19
|
+
validation_dir = os.path.join(base_dir,'validation')
|
20
|
+
|
21
|
+
test_dir = os.path.join(base_dir,'test')
|
22
|
+
|
23
|
+
|
24
|
+
|
25
|
+
datagen = ImageDataGenerator(rescale=1./255)
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
def extract_features(dirpath):
|
30
|
+
|
31
|
+
features = []
|
32
|
+
|
33
|
+
labels = []
|
34
|
+
|
35
|
+
generator = datagen.flow_from_directory(
|
36
|
+
|
37
|
+
dirpath, target_size=(150, 150), batch_size=32, class_mode='categorical')
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
num_steps = len(generator)
|
42
|
+
|
43
|
+
for step, (img_batch, label_batch) in enumerate(generator, 1):
|
44
|
+
|
45
|
+
print('step: {}, img_batch: {}, label_batch: {}'.format(
|
46
|
+
|
47
|
+
step, img_batch.shape, label_batch.shape))
|
48
|
+
|
49
|
+
|
50
|
+
|
51
|
+
feat_batch = conv_base.predict(img_batch)
|
52
|
+
|
53
|
+
features.extend(feat_batch)
|
54
|
+
|
55
|
+
labels.extend(label_batch)
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
if step >= num_steps:
|
60
|
+
|
61
|
+
break
|
62
|
+
|
63
|
+
|
64
|
+
|
65
|
+
features = np.array(features)
|
66
|
+
|
67
|
+
features = features.reshape(len(features), -1)
|
68
|
+
|
69
|
+
labels = np.array(labels).astype(int)
|
70
|
+
|
71
|
+
return features, labels
|
72
|
+
|
73
|
+
|
74
|
+
|
75
|
+
train_features, train_labels = extract_features(train_dir)
|
76
|
+
|
77
|
+
validation_features, validation_labels = extract_features(validation_dir)
|
78
|
+
|
79
|
+
test_features, test_labels = extract_features(test_dir)
|
80
|
+
|
81
|
+
```
|
2
82
|
|
3
83
|
|
4
84
|
|
5
85
|
|
6
86
|
|
7
|
-
|
87
|
+
* datagen.flow_from_directory() で3クラス以上の場合は class_mode='categorical' を指定します。
|
8
88
|
|
9
|
-
train_features = np.reshape(train_features, (2000, -1))
|
10
|
-
|
11
|
-
|
89
|
+
* ステップ数は num_steps = len(generator) で取得できるので、if step >= num_steps で break すればよいです。
|
12
|
-
|
13
|
-
test_features = np.reshape(test_features, (1000, -1))
|
14
|
-
|
15
|
-
```
|