使用预测方法时,KERAS CNN模型类型误差

发布于 2025-01-23 07:42:42 字数 2713 浏览 0 评论 0原文

我有一个keras模型,应该采用(150、150、1)灰度图像,因为它的输入并输出一个长度为8。

这是我的模型代码:

from tensorflow.python import keras
model = keras.Sequential([
    keras.layers.Conv2D(filters=32, kernel_size=(3,3), activation="relu", padding='same', input_shape=(150,150,1)),
    keras.layers.MaxPool2D(pool_size=(2,2), padding='same', data_format='channels_last'),
    keras.layers.Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'),
    keras.layers.MaxPool2D(pool_size=(2,2), padding='same', data_format='channels_last'),
    keras.layers.Flatten(),
    keras.layers.Dense(8, activation="softmax")
])

当我尝试使用时.predict()方法,我得到此错误:

Traceback (most recent call last):
  File "KerasCNN.py", line 152, in <module>
    ga.run()
  File "/home/User/Documents/Projects/2022/Keras_CNN/Trial1/env/lib/python3.6/site-packages/pygad/pygad.py", line 1192, in run
    self.last_generation_fitness = self.cal_pop_fitness()
  File "/home/User/Documents/Projects/2022/Keras_CNN/Trial1/env/lib/python3.6/site-packages/pygad/pygad.py", line 1159, in cal_pop_fitness
    fitness = self.fitness_func(sol, sol_idx)
  File "KerasCNN.py", line 112, in fitness
    prediction = model.predict(g_img)
  File "/home/User/Documents/Projects/2022/Keras_CNN/Trial1/env/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/models.py", line 966, in predict
    return self.model.predict(x, batch_size=batch_size, verbose=verbose)
  File "/home/User/Documents/Projects/2022/Keras_CNN/Trial1/env/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/engine/training.py", line 1813, in predict
    f, ins, batch_size=batch_size, verbose=verbose, steps=steps)
  File "/home/User/Documents/Projects/2022/Keras_CNN/Trial1/env/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/engine/training.py", line 1300, in _predict_loop
    index_array = np.arange(num_samples)
TypeError: unsupported operand type(s) for /: 'Dimension' and 'int'

我有一个较早运行的ANN(non-CNN)模型,该模型正常。当我进行一些研究时,我也可以找到有关此错误的任何信息。

这是我用来做出预测的代码:

img = get_image() # (150, 150, 3)
g_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # (150, 150, 1)
g_img = tf.expand_dim(g_img, axis=0)
g_img = tf.expand_dim(g_img, axis=-1) # (1, 150, 150, 1)
prediction = model.predict(g_img)

以下是我的版本号:

tensorflow:1.5.0

python:3.69

numpy:1.19.5

ubuntu:18.04

让我知道我是否可以提供任何其他信息!谢谢!

回答

tf.expand_dim()np.expand_dim()修复了它!

I am have a keras model that is supposed to take a (150, 150, 1) grayscale image as it's input and output an array of length 8.

Here is my model code:

from tensorflow.python import keras
model = keras.Sequential([
    keras.layers.Conv2D(filters=32, kernel_size=(3,3), activation="relu", padding='same', input_shape=(150,150,1)),
    keras.layers.MaxPool2D(pool_size=(2,2), padding='same', data_format='channels_last'),
    keras.layers.Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'),
    keras.layers.MaxPool2D(pool_size=(2,2), padding='same', data_format='channels_last'),
    keras.layers.Flatten(),
    keras.layers.Dense(8, activation="softmax")
])

When I try to use the .predict() method, I get this error:

Traceback (most recent call last):
  File "KerasCNN.py", line 152, in <module>
    ga.run()
  File "/home/User/Documents/Projects/2022/Keras_CNN/Trial1/env/lib/python3.6/site-packages/pygad/pygad.py", line 1192, in run
    self.last_generation_fitness = self.cal_pop_fitness()
  File "/home/User/Documents/Projects/2022/Keras_CNN/Trial1/env/lib/python3.6/site-packages/pygad/pygad.py", line 1159, in cal_pop_fitness
    fitness = self.fitness_func(sol, sol_idx)
  File "KerasCNN.py", line 112, in fitness
    prediction = model.predict(g_img)
  File "/home/User/Documents/Projects/2022/Keras_CNN/Trial1/env/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/models.py", line 966, in predict
    return self.model.predict(x, batch_size=batch_size, verbose=verbose)
  File "/home/User/Documents/Projects/2022/Keras_CNN/Trial1/env/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/engine/training.py", line 1813, in predict
    f, ins, batch_size=batch_size, verbose=verbose, steps=steps)
  File "/home/User/Documents/Projects/2022/Keras_CNN/Trial1/env/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/engine/training.py", line 1300, in _predict_loop
    index_array = np.arange(num_samples)
TypeError: unsupported operand type(s) for /: 'Dimension' and 'int'

I had an ANN (non-CNN) model running earlier that was working fine. When I did some research I could find anything about this error either.

Here is the code I am using to make the prediction:

img = get_image() # (150, 150, 3)
g_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # (150, 150, 1)
g_img = tf.expand_dim(g_img, axis=0)
g_img = tf.expand_dim(g_img, axis=-1) # (1, 150, 150, 1)
prediction = model.predict(g_img)

Here are my version numbers:

tensorflow: 1.5.0

python: 3.69

numpy: 1.19.5

Ubuntu: 18.04

Let me know if theres any other info I can provide! Thanks!

Answer

Replacing tf.expand_dim() with np.expand_dim() fixed it!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千笙结 2025-01-30 07:42:42

这似乎在TF 1.15上很好地运行:

import cv2
import numpy as np
import tensorflow as tf
from tensorflow.python import keras
print(tf.__version__)
model = keras.Sequential([
    keras.layers.Conv2D(filters=32, kernel_size=(3,3), activation="relu", padding='same', input_shape=(150,150,1)),
    keras.layers.MaxPool2D(pool_size=(2,2), padding='same', data_format='channels_last'),
    keras.layers.Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'),
    keras.layers.MaxPool2D(pool_size=(2,2), padding='same', data_format='channels_last'),
    keras.layers.Flatten(),
    keras.layers.Dense(8, activation="softmax")
])
# Create random image
img = np.zeros([150,150,3], dtype=np.uint8)
img[:,:,0] = np.ones([150,150])*64
img[:,:,1] = np.ones([150,150])*128
img[:,:,2] = np.ones([150,150])*192

g_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
g_img = np.expand_dims(g_img, axis=0)
g_img = np.expand_dims(g_img, axis=-1) # (1, 150, 150, 1)
prediction = model.predict(g_img)
print(prediction.shape)
1.15.2
(1, 8)

This seems to run perfectly fine on TF 1.15:

import cv2
import numpy as np
import tensorflow as tf
from tensorflow.python import keras
print(tf.__version__)
model = keras.Sequential([
    keras.layers.Conv2D(filters=32, kernel_size=(3,3), activation="relu", padding='same', input_shape=(150,150,1)),
    keras.layers.MaxPool2D(pool_size=(2,2), padding='same', data_format='channels_last'),
    keras.layers.Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'),
    keras.layers.MaxPool2D(pool_size=(2,2), padding='same', data_format='channels_last'),
    keras.layers.Flatten(),
    keras.layers.Dense(8, activation="softmax")
])
# Create random image
img = np.zeros([150,150,3], dtype=np.uint8)
img[:,:,0] = np.ones([150,150])*64
img[:,:,1] = np.ones([150,150])*128
img[:,:,2] = np.ones([150,150])*192

g_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
g_img = np.expand_dims(g_img, axis=0)
g_img = np.expand_dims(g_img, axis=-1) # (1, 150, 150, 1)
prediction = model.predict(g_img)
print(prediction.shape)
1.15.2
(1, 8)
枯叶蝶 2025-01-30 07:42:42

在您写的代码中,输入形状为(224,256,1),因此将其更改为(150,150,1)
尝试以下操作:

from tensorflow.python import keras
model = keras.Sequential([
    keras.layers.Conv2D(filters=32, kernel_size=(3,3), activation="relu", padding='same', input_shape=(150,150,1)),
    keras.layers.MaxPool2D(pool_size=(2,2), padding='same', data_format='channels_last'),

进行数学以获取所需的输出。

in code you wrote, the input shape is (224,256,1) so change it to (150,150,1)
try this:

from tensorflow.python import keras
model = keras.Sequential([
    keras.layers.Conv2D(filters=32, kernel_size=(3,3), activation="relu", padding='same', input_shape=(150,150,1)),
    keras.layers.MaxPool2D(pool_size=(2,2), padding='same', data_format='channels_last'),

do the math to get the desired output.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文