回答編集履歴
2
d
test
CHANGED
@@ -67,3 +67,53 @@
|
|
67
67
|
print('{}: {:.2%}'.format(name, score))
|
68
68
|
|
69
69
|
```
|
70
|
+
|
71
|
+
|
72
|
+
|
73
|
+
## 追記
|
74
|
+
|
75
|
+
|
76
|
+
|
77
|
+
```python
|
78
|
+
|
79
|
+
import keras.preprocessing.image as Image
|
80
|
+
|
81
|
+
import numpy as np
|
82
|
+
|
83
|
+
from keras.models import model_from_json
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
model = model_from_json(open('model.json').read())
|
88
|
+
|
89
|
+
model.load_weights('weights.h5')
|
90
|
+
|
91
|
+
|
92
|
+
|
93
|
+
img_path = 'unExample/a6.jpg'
|
94
|
+
|
95
|
+
img = Image.load_img(img_path, target_size=(50, 50))
|
96
|
+
|
97
|
+
x = Image.img_to_array(img)
|
98
|
+
|
99
|
+
x = np.expand_dims(x, axis=0)
|
100
|
+
|
101
|
+
|
102
|
+
|
103
|
+
# 一番スコアが高いクラスだけほしい場合
|
104
|
+
|
105
|
+
pred = model.predict_classes(x)[0]
|
106
|
+
|
107
|
+
print(pred) # 予測したクラス
|
108
|
+
|
109
|
+
|
110
|
+
|
111
|
+
# 各スコアを表示したい場合
|
112
|
+
|
113
|
+
pred = model.predict(x)[0]
|
114
|
+
|
115
|
+
for class_id, socre in enumerate(pred):
|
116
|
+
|
117
|
+
print('class: {}, score: {:.2%}'.format(class_id, socre))
|
118
|
+
|
119
|
+
```
|
1
d
test
CHANGED
@@ -1,9 +1,69 @@
|
|
1
|
+
[ImageNet の学習済みモデルを利用して画像分類を行う。](http://pynote.hatenablog.com/entry/keras-vgg16-mode) 通りで動きました。
|
2
|
+
|
1
|
-
|
3
|
+
画像を用意して試してみてください。
|
2
4
|
|
3
5
|
|
4
6
|
|
5
7
|
```
|
6
8
|
|
9
|
+
import numpy as np
|
10
|
+
|
11
|
+
from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions
|
12
|
+
|
13
|
+
from keras.preprocessing import image
|
14
|
+
|
15
|
+
|
16
|
+
|
17
|
+
# VGG16 を構築する。
|
18
|
+
|
19
|
+
model = VGG16()
|
20
|
+
|
21
|
+
|
22
|
+
|
23
|
+
# 画像を読み込み、モデルの入力サイズでリサイズする。
|
24
|
+
|
25
|
+
img_path = 'sample.jpg'
|
26
|
+
|
7
|
-
|
27
|
+
img = image.load_img(img_path, target_size=model.input_shape[1:3])
|
28
|
+
|
29
|
+
|
30
|
+
|
31
|
+
# PIL.Image オブジェクトを np.float32 型の numpy 配列に変換する。
|
32
|
+
|
33
|
+
x = image.img_to_array(img)
|
34
|
+
|
35
|
+
print('x.shape: {}, x.dtype: {}'.format(x.shape, x.dtype))
|
36
|
+
|
37
|
+
# x.shape: (224, 224, 3), x.dtype: float32
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
# 配列の形状を (Height, Width, Channels) から (1, Height, Width, Channels) に変更する。
|
42
|
+
|
43
|
+
x = np.expand_dims(x, axis=0)
|
44
|
+
|
45
|
+
print('x.shape: {}'.format(x.shape)) # x.shape: (1, 224, 224, 3)
|
46
|
+
|
47
|
+
|
48
|
+
|
49
|
+
# VGG16 用の前処理を行う。
|
50
|
+
|
51
|
+
x = preprocess_input(x)
|
52
|
+
|
53
|
+
|
54
|
+
|
55
|
+
# 推論する。
|
56
|
+
|
57
|
+
preds = model.predict(x)
|
58
|
+
|
59
|
+
|
60
|
+
|
61
|
+
# 推論結果をデコードする。
|
62
|
+
|
63
|
+
result = decode_predictions(preds, top=3)[0]
|
64
|
+
|
65
|
+
for _, name, score in result:
|
66
|
+
|
67
|
+
print('{}: {:.2%}'.format(name, score))
|
8
68
|
|
9
69
|
```
|