teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

2018/10/11 11:37

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -1,8 +1,45 @@
1
- 各サンプルから抽出した特徴量を1次元に潰したいのであれば、以下のようにすればよいのでないでしょうか
1
+ 以下のようにしてみてどうでしょうか
2
2
 
3
+ ```python
4
+ import os
5
+ import numpy as np
6
+ from keras.preprocessing.image import ImageDataGenerator
3
7
 
8
+ base_dir = (r'C:\Users\HN4-00012\Documents\kosen fike\bunnkasai\loads15_data_small')
9
+ train_dir = os.path.join(base_dir,'train')
10
+ validation_dir = os.path.join(base_dir,'validation')
11
+ test_dir = os.path.join(base_dir,'test')
12
+
13
+ datagen = ImageDataGenerator(rescale=1./255)
14
+
15
+ def extract_features(dirpath):
16
+ features = []
4
- ```python
17
+ labels = []
18
+ generator = datagen.flow_from_directory(
19
+ dirpath, target_size=(150, 150), batch_size=32, class_mode='categorical')
20
+
21
+ num_steps = len(generator)
22
+ for step, (img_batch, label_batch) in enumerate(generator, 1):
23
+ print('step: {}, img_batch: {}, label_batch: {}'.format(
24
+ step, img_batch.shape, label_batch.shape))
25
+
26
+ feat_batch = conv_base.predict(img_batch)
27
+ features.extend(feat_batch)
28
+ labels.extend(label_batch)
29
+
30
+ if step >= num_steps:
31
+ break
32
+
33
+ features = np.array(features)
34
+ features = features.reshape(len(features), -1)
35
+ labels = np.array(labels).astype(int)
36
+ return features, labels
37
+
5
- train_features = np.reshape(train_features, (2000, -1))
38
+ train_features, train_labels = extract_features(train_dir)
6
- validation_features = np.reshape(validation_features, (1000, -1))
39
+ validation_features, validation_labels = extract_features(validation_dir)
7
- test_features = np.reshape(test_features, (1000, -1))
40
+ test_features, test_labels = extract_features(test_dir)
8
- ```
41
+ ```
42
+
43
+
44
+ * datagen.flow_from_directory() で3クラス以上の場合は class_mode='categorical' を指定します。
45
+ * ステップ数は num_steps = len(generator) で取得できるので、if step >= num_steps で break すればよいです。