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

回答編集履歴

2

d

2018/12/21 09:32

投稿

tiitoi
tiitoi

スコア21962

answer CHANGED
@@ -32,4 +32,29 @@
32
32
  result = decode_predictions(preds, top=3)[0]
33
33
  for _, name, score in result:
34
34
  print('{}: {:.2%}'.format(name, score))
35
+ ```
36
+
37
+ ## 追記
38
+
39
+ ```python
40
+ import keras.preprocessing.image as Image
41
+ import numpy as np
42
+ from keras.models import model_from_json
43
+
44
+ model = model_from_json(open('model.json').read())
45
+ model.load_weights('weights.h5')
46
+
47
+ img_path = 'unExample/a6.jpg'
48
+ img = Image.load_img(img_path, target_size=(50, 50))
49
+ x = Image.img_to_array(img)
50
+ x = np.expand_dims(x, axis=0)
51
+
52
+ # 一番スコアが高いクラスだけほしい場合
53
+ pred = model.predict_classes(x)[0]
54
+ print(pred) # 予測したクラス
55
+
56
+ # 各スコアを表示したい場合
57
+ pred = model.predict(x)[0]
58
+ for class_id, socre in enumerate(pred):
59
+ print('class: {}, score: {:.2%}'.format(class_id, socre))
35
60
  ```

1

d

2018/12/21 09:32

投稿

tiitoi
tiitoi

スコア21962

answer CHANGED
@@ -1,5 +1,35 @@
1
+ [ImageNet の学習済みモデルを利用して画像分類を行う。](http://pynote.hatenablog.com/entry/keras-vgg16-mode) 通りで動きました。
1
- こうすると直らなですか?
2
+ 画像を用意して試してみてくださ
2
3
 
3
4
  ```
5
+ import numpy as np
6
+ from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions
7
+ from keras.preprocessing import image
8
+
9
+ # VGG16 を構築する。
10
+ model = VGG16()
11
+
12
+ # 画像を読み込み、モデルの入力サイズでリサイズする。
13
+ img_path = 'sample.jpg'
4
- Image.load_img(img_path, target_size=(50, 50))
14
+ img = image.load_img(img_path, target_size=model.input_shape[1:3])
15
+
16
+ # PIL.Image オブジェクトを np.float32 型の numpy 配列に変換する。
17
+ x = image.img_to_array(img)
18
+ print('x.shape: {}, x.dtype: {}'.format(x.shape, x.dtype))
19
+ # x.shape: (224, 224, 3), x.dtype: float32
20
+
21
+ # 配列の形状を (Height, Width, Channels) から (1, Height, Width, Channels) に変更する。
22
+ x = np.expand_dims(x, axis=0)
23
+ print('x.shape: {}'.format(x.shape)) # x.shape: (1, 224, 224, 3)
24
+
25
+ # VGG16 用の前処理を行う。
26
+ x = preprocess_input(x)
27
+
28
+ # 推論する。
29
+ preds = model.predict(x)
30
+
31
+ # 推論結果をデコードする。
32
+ result = decode_predictions(preds, top=3)[0]
33
+ for _, name, score in result:
34
+ print('{}: {:.2%}'.format(name, score))
5
35
  ```