如何正确设置Conv2D参数?
How to set Conv2D parameters correctly?
我正在尝试在 MNIST 数据集上构建 CNN 模型,但出现错误,我无法解决。
这是我的代码
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D
from numpy import expand_dims
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = expand_dims(x_train, 3)
x_test = expand_dims(x_test, 3)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
model = Sequential()
model.add(Conv2D(64, kernel_size=3, activation="relu", input_shape=(28, 28, 1)))
model.add(Conv2D(64, kernel_size=3, activation="relu"))
model.add(Flatten())
model.add(Dense(10, activation="softmax"))
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=3)
model.save("model")
new_model = tf.keras.models.load_model("model")
predictions = new_model.predict([x_test])
print(predictions[10])
我遇到了这个错误
TypeError: Value passed to parameter 'input' has DataType uint8 not in list of allowed values: float16, bfloat16, float32, float64
有什么帮助吗?
您收到此错误是因为您的输入是 uint8 类型,而您的网络具有浮点值。您只需将输入转换为浮点数据类型。
在这里,将您的数据部分更改为:
import numpy as np
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = expand_dims(x_train, -1)
x_test = expand_dims(x_test, -1)
x_train = x_train.astype(np.float32)
x_test = x_test.astype(np.float32)
奇怪的是,我没有遇到你遇到的错误,但我应该遇到,这就是解决方案。
我正在尝试在 MNIST 数据集上构建 CNN 模型,但出现错误,我无法解决。 这是我的代码
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D
from numpy import expand_dims
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = expand_dims(x_train, 3)
x_test = expand_dims(x_test, 3)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
model = Sequential()
model.add(Conv2D(64, kernel_size=3, activation="relu", input_shape=(28, 28, 1)))
model.add(Conv2D(64, kernel_size=3, activation="relu"))
model.add(Flatten())
model.add(Dense(10, activation="softmax"))
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=3)
model.save("model")
new_model = tf.keras.models.load_model("model")
predictions = new_model.predict([x_test])
print(predictions[10])
我遇到了这个错误
TypeError: Value passed to parameter 'input' has DataType uint8 not in list of allowed values: float16, bfloat16, float32, float64
有什么帮助吗?
您收到此错误是因为您的输入是 uint8 类型,而您的网络具有浮点值。您只需将输入转换为浮点数据类型。 在这里,将您的数据部分更改为:
import numpy as np
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = expand_dims(x_train, -1)
x_test = expand_dims(x_test, -1)
x_train = x_train.astype(np.float32)
x_test = x_test.astype(np.float32)
奇怪的是,我没有遇到你遇到的错误,但我应该遇到,这就是解决方案。