@hoge_piyo

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

keras: model.predict()の際のエラー解消

解決したいこと

kerasで画像認識モデルを構築していた際、model.predict()でエラーが出てしまったので、これを解消したいです。

発生している問題・エラー

This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: SSE SSE2 SSE3 SSE4.1 SSE4.2 AVX AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
Traceback (most recent call last):
  File "c:\Users\user\Documents\AI\ai_test2.py", line 84, in <module>
    predictions = model.predict(x_test[0], batch_size=None, verbose=3, steps=None)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\user~1\AppData\Local\Temp\__autograph_generated_filegijegug6.py", line 15, in tf__predict_function
    retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
    ^^^^^
ValueError: in user code:

    File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\engine\training.py", line 2416, in predict_function  *
        return step_function(self, iterator)
    File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\engine\training.py", line 2401, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\engine\training.py", line 2389, in run_step  **
        outputs = model.predict_step(data)
    File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\engine\training.py", line 2357, in predict_step
        return self(x, training=False)
    File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\utils\traceback_utils.py", line 70, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\engine\input_spec.py", line 298, in assert_input_compatibility
        raise ValueError(

    ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 28, 28, 3), found shape=(None, 28, 3)

該当するソースコード

import keras
from keras.layers import Conv2D, MaxPooling2D
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, Input
from keras.preprocessing.image import array_to_img, img_to_array, load_img
import os
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import glob
import pickle
from PIL import Image
from keras.src.utils import np_utils

rps = ['rock/', 'paper/', 'scissors/']  #0, 1, 2

TRAIN_BASE_DIR = 'resize_data/train/'
TEST_BASE_DIR = 'resize_data/test/'

x_train = []
y_train = []
x_test, y_test = [], []



for idx, name in enumerate(rps):
    path = TRAIN_BASE_DIR + name + '*.jpg'
    files = glob.glob(path)
    for file in files:
        image = load_img(file)
        image = np.asarray(image)/255.0
        x_train.append(image)
        y_train.append(np.asarray(idx))

x_train, y_train = np.array(x_train), np.array(y_train)



for idx, name in enumerate(rps):
    path = TEST_BASE_DIR + name + '*.jpg'
    files = glob.glob(path)
    for file in files:
        image = load_img(file)
        image = np.asarray(image)/255.0
        x_test.append(image)
        y_test.append(np.asarray(idx))

x_test, y_test = np.array(x_test), np.array(y_test)



model = Sequential([
    Flatten(),
    Input(shape=(28, 28, 3)),
    Dropout(0.2),
    Dense(128, activation='relu'),
    Dense(3, activation='softmax')
])

model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

model.fit(x_train, y_train, epochs=100)
model.save('my_model.h5')

model.summary()

# model = keras.models.load_model('my_model.h5')
model.evaluate(x_test, y_test)

plt.imshow(x_test[0])
plt.show()
predictions = model.predict(x_test[0], batch_size=None, verbose=3, steps=None)
print(predictions)

自分で試したこと

エラー内容を見ると期待されるshapeは
(None, 28, 28, 3)
に対し、実際は
(None, 28, 3)
となっているので、shapeを確認してみましたが、

>>> import glob
>>> import numpy as np
>>> from PIL import Image
>>> img = glob.glob('resize_data/test/*/*.jpg')
>>> img = Image.open(img[0])
>>> img = np.array(img)
>>> print(img.shape)
(28, 28, 3)

となっていました。

質問

期待されるinput_shapeの(None, 28, 28, 3)のNoneとは何でしょうか。
また実際に入力されたデータのshapeが(None, 28, 3)となっているのはなぜでしょうか。

0 likes

1Answer

期待されるinput_shapeの(None, 28, 28, 3)のNoneとは何でしょうか。

batchの次元です.可変であるべきなのでNoneになってます.

また実際に入力されたデータのshapeが(None, 28, 3)となっているのはなぜでしょうか。

元々(28, 28, 3)だったものの最初の次元がbatchの次元と見做され(None, 28, 3)になってます.

今回1つだけデータを与えたいということであれば,

predictions = model.predict(np.array([x_test[0]]), batch_size=None, verbose=3, steps=None)
predictions = model.predict(x_test[:1] batch_size=None, verbose=3, steps=None)

のように書くべきです.いずれもmodel.predict()に渡すことになるshapeは(1, 28, 28, 3)となり,バッチサイズは1として与えることになり整合性が取れます.

0Like

Comments

  1. @hoge_piyo

    Questioner

    回答ありがとうございます。
    predictions = predict(np.array(x_test[0])~)
    predictions = predict(x_test[:1]~)
    というのはどのような処理となるのでしょうか。
    また、出力を3択にしたいのですが、verboseをを変えることで出力を変えられるという認識でよろしいでしょうか。

  2. 解決案として2つの例を示したまでのことです.

    出力はすでに3択になってますよ.出力層がDense(3, activation='softmax')であるので,argmaxをとればどのindexが最大値かわかると思います.

    verboseは学習ログや予測ログの詳細度です.のでモデルの算出する値に直接影響しません.

  3. @hoge_piyo

    Questioner

    解決しました。
    ありがとうございました。

Your answer might help someone💌