質問編集履歴
2
コードが抜けていたので修正
title
CHANGED
File without changes
|
body
CHANGED
@@ -9,7 +9,7 @@
|
|
9
9
|
jupyternotebook 1.0.0
|
10
10
|
|
11
11
|
# わからないこと
|
12
|
-
jupyter notebook上でkerasで配布されているサンプルコード[mnist_cnn.py](https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py)を実行し
|
12
|
+
Qiitaの[記事](https://qiita.com/nagayosi/items/0034e5e82813b05e41df)を読みつつ、jupyter notebook上でkerasで配布されているサンプルコードを[mnist_cnn.py](https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py)を実行してみました。サンプルコード自体はうまく作成できましたが```model.predict```でエラーが出て進みません。
|
13
13
|
|
14
14
|
# やったこと
|
15
15
|
- mnist_cnn.pyの実行
|
@@ -99,9 +99,145 @@
|
|
99
99
|
```
|
100
100
|
|
101
101
|
- モデルをロードして、用意した画像の分析結果を得る
|
102
|
-
画像はkaggleのDatasetより拝借。[https://www.kaggle.com/scolianni/mnistasjpg](https://www.kaggle.com/scolianni/mnistasjpg)のtestSample.zipからimg_1.jpgを
|
102
|
+
画像はkaggleのDatasetより拝借。[https://www.kaggle.com/scolianni/mnistasjpg](https://www.kaggle.com/scolianni/mnistasjpg)のtestSample.zipからimg_1.jpgを利用して、predictを実行してみましたが、エラーが発生
|
103
103
|
|
104
|
+
```
|
105
|
+
import keras
|
106
|
+
from keras.datasets import mnist
|
107
|
+
from keras.models import model_from_json
|
108
|
+
from keras.utils import np_utils
|
109
|
+
from keras.preprocessing import image
|
110
|
+
from PIL import Image
|
111
|
+
import matplotlib.pyplot as plt
|
112
|
+
import numpy
|
104
113
|
|
114
|
+
# modelのload
|
115
|
+
model = model_from_json(open('tutorial_mnist.json').read())
|
116
|
+
model.load_weights('tutorial_mnist.h5')
|
117
|
+
model.compile(loss=keras.losses.categorical_crossentropy,
|
118
|
+
optimizer=keras.optimizers.Adadelta(),
|
119
|
+
metrics=['accuracy'])
|
105
120
|
|
121
|
+
# predict
|
122
|
+
filepath = "/Users/atg/work/python/tensorflow/jupyter/mnist_test_data/img_1.jpg"
|
123
|
+
img = Image.open(filepath).convert('RGB') ## Gray->L, RGB->RGB
|
124
|
+
img = img.resize((28, 28))
|
125
|
+
x = numpy.array(img, dtype=numpy.float32)
|
126
|
+
x = x / 255.
|
127
|
+
x = x[None, ...]
|
106
128
|
|
129
|
+
pred = model.predict(x, batch_size=1, verbose=0)
|
130
|
+
score = numpy.max(pred)
|
131
|
+
pred_label = np.argmax(pred)
|
132
|
+
print("pred", pred)
|
133
|
+
print("score", score)
|
134
|
+
print("pred_label", pred_label)
|
135
|
+
```
|
136
|
+
|
137
|
+
* 発生したエラー
|
138
|
+
```
|
139
|
+
---------------------------------------------------------------------------
|
140
|
+
ValueError Traceback (most recent call last)
|
141
|
+
<ipython-input-24-b0c45db13636> in <module>()
|
142
|
+
23 x = x[None, ...]
|
143
|
+
24
|
144
|
+
---> 25 pred = model.predict(x, batch_size=1, verbose=0)
|
145
|
+
26 score = numpy.max(pred)
|
146
|
+
27 pred_label = np.argmax(pred)
|
147
|
+
|
148
|
+
~/work/python/tensorflow/lib/python3.6/site-packages/keras/engine/training.py in predict(self, x, batch_size, verbose, steps)
|
149
|
+
1150 'argument.')
|
150
|
+
1151 # Validate user data.
|
151
|
+
-> 1152 x, _, _ = self._standardize_user_data(x)
|
152
|
+
1153 if self.stateful:
|
153
|
+
1154 if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
|
154
|
+
|
155
|
+
~/work/python/tensorflow/lib/python3.6/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
|
156
|
+
752 feed_input_shapes,
|
157
|
+
753 check_batch_axis=False, # Don't enforce the batch size.
|
158
|
+
--> 754 exception_prefix='input')
|
159
|
+
755
|
160
|
+
756 if y is not None:
|
161
|
+
|
162
|
+
~/work/python/tensorflow/lib/python3.6/site-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
|
163
|
+
134 ': expected ' + names[i] + ' to have shape ' +
|
164
|
+
135 str(shape) + ' but got array with shape ' +
|
165
|
+
--> 136 str(data_shape))
|
166
|
+
137 return data
|
167
|
+
138
|
168
|
+
|
169
|
+
ValueError: Error when checking input: expected conv2d_1_input to have shape (28, 28, 1) but got array with shape (28, 28, 3)
|
170
|
+
```
|
171
|
+
|
172
|
+
期待している次元が違うというエラーということで、reshapeで次元数を変更してみました。
|
173
|
+
|
174
|
+
|
175
|
+
- 変更したコード
|
176
|
+
```
|
177
|
+
import keras
|
178
|
+
from keras.datasets import mnist
|
179
|
+
from keras.models import model_from_json
|
180
|
+
from keras.utils import np_utils
|
181
|
+
from keras.preprocessing import image
|
182
|
+
from PIL import Image
|
183
|
+
import matplotlib.pyplot as plt
|
184
|
+
import numpy
|
185
|
+
|
186
|
+
# modelのload
|
187
|
+
model = model_from_json(open('tutorial_mnist.json').read())
|
188
|
+
model.load_weights('tutorial_mnist.h5')
|
189
|
+
model.compile(loss=keras.losses.categorical_crossentropy,
|
190
|
+
optimizer=keras.optimizers.Adadelta(),
|
191
|
+
metrics=['accuracy'])
|
192
|
+
|
193
|
+
# predict
|
194
|
+
filepath = "/Users/atg/work/python/tensorflow/jupyter/mnist_test_data/img_1.jpg"
|
195
|
+
img = Image.open(filepath).convert('RGB') ## Gray->L, RGB->RGB
|
196
|
+
img = img.resize((28, 28))
|
197
|
+
x = numpy.array(img, dtype=numpy.float32)
|
198
|
+
x = x / 255.
|
199
|
+
x = x[None, ...]
|
200
|
+
x = numpy.reshape(x, [28,28,1])
|
201
|
+
|
202
|
+
pred = model.predict(x, batch_size=1, verbose=0)
|
203
|
+
score = numpy.max(pred)
|
204
|
+
pred_label = np.argmax(pred)
|
205
|
+
print("pred", pred)
|
206
|
+
print("score", score)
|
207
|
+
print("pred_label", pred_label)
|
208
|
+
```
|
209
|
+
|
210
|
+
- エラー
|
211
|
+
|
212
|
+
```
|
213
|
+
---------------------------------------------------------------------------
|
214
|
+
ValueError Traceback (most recent call last)
|
215
|
+
<ipython-input-29-200996341dd9> in <module>()
|
216
|
+
22 x = x / 255.
|
217
|
+
23 x = x[None, ...]
|
218
|
+
---> 24 x = numpy.reshape(x, [28,28,1])
|
219
|
+
25
|
220
|
+
26 pred = model.predict(x, batch_size=1, verbose=0)
|
221
|
+
|
222
|
+
~/work/python/tensorflow/lib/python3.6/site-packages/numpy/core/fromnumeric.py in reshape(a, newshape, order)
|
223
|
+
255 [5, 6]])
|
224
|
+
256 """
|
225
|
+
--> 257 return _wrapfunc(a, 'reshape', newshape, order=order)
|
226
|
+
258
|
227
|
+
259
|
228
|
+
|
229
|
+
~/work/python/tensorflow/lib/python3.6/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
|
230
|
+
50 def _wrapfunc(obj, method, *args, **kwds):
|
231
|
+
51 try:
|
232
|
+
---> 52 return getattr(obj, method)(*args, **kwds)
|
233
|
+
53
|
234
|
+
54 # An AttributeError occurs if the object does not have
|
235
|
+
|
236
|
+
ValueError: cannot reshape array of size 2352 into shape (28,28,1)
|
237
|
+
|
238
|
+
```
|
239
|
+
|
240
|
+
今度はサイズでエラーが発生しましたが、そもそもpredictを行う前の画像の読み込みからモデルに適した形に変換する処理の考え方が間違っているのではと思い、teratailに質問を記載しました。
|
241
|
+
|
107
|
-
モデル作成まではQiitaや海外のフォーラムでも見かけるのですが、実際に作成したモデルで予測させる際は見るサイトで方法が変わり、かつサンプルコードを写経してもうまくいかず、だんだん何が正しい方法
|
242
|
+
モデル作成まではQiitaや海外のフォーラムでも見かけるのですが、実際に作成したモデルで予測させる際は見るサイトで方法が変わり、かつサンプルコードを写経してもうまくいかず、だんだん何が正しい方法なのかがわからなくなってきました。
|
243
|
+
参考になるサイトや方法がありましたら、ご教授頂きたいです。
|
1
日本語がおかしいところを修正
title
CHANGED
File without changes
|
body
CHANGED
@@ -9,7 +9,7 @@
|
|
9
9
|
jupyternotebook 1.0.0
|
10
10
|
|
11
11
|
# わからないこと
|
12
|
-
jupyter notebook上でkerasで配布されているサンプルコード
|
12
|
+
jupyter notebook上でkerasで配布されているサンプルコード[mnist_cnn.py](https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py)を実行し、作成したモデルを使って```model.predict```をしてみたところエラーが出てうまく進みませんでした。
|
13
13
|
|
14
14
|
# やったこと
|
15
15
|
- mnist_cnn.pyの実行
|