报错如下
/Users/liushanlin/miniforge3/envs/py3.9/bin/python /Users/liushanlin/PycharmProjects/DLstudy/run/lenet_mnist.py
[INFO] accessing MNIST...
[INFO] compiling model...
Traceback (most recent call last):
File "/Users/liushanlin/PycharmProjects/DLstudy/run/lenet_mnist.py", line 27, in <module>
model = LeNet.build(width=28, height=28, depth=1, classes=10)
File "/Users/liushanlin/PycharmProjects/DLstudy/nn/conv/lenet.py", line 13, in build
model = Sequential()
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/training/tracking/base.py", line 530, in _method_wrapper
result = method(self, *args, **kwargs)
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/keras/engine/sequential.py", line 107, in __init__
super(functional.Functional, self).__init__( # pylint: disable=bad-super-call
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/training/tracking/base.py", line 530, in _method_wrapper
result = method(self, *args, **kwargs)
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/keras/engine/training.py", line 289, in __init__
self._init_batch_counters()
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/training/tracking/base.py", line 530, in _method_wrapper
result = method(self, *args, **kwargs)
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/keras/engine/training.py", line 297, in _init_batch_counters
self._train_counter = tf.Variable(0, dtype='int64', aggregation=agg)
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/ops/variables.py", line 268, in __call__
return cls._variable_v2_call(*args, **kwargs)
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/ops/variables.py", line 250, in _variable_v2_call
return previous_getter(
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/ops/variables.py", line 243, in <lambda>
previous_getter = lambda **kws: default_variable_creator_v2(None, **kws)
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/ops/variable_scope.py", line 2662, in default_variable_creator_v2
return resource_variable_ops.ResourceVariable(
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/ops/variables.py", line 270, in __call__
return super(VariableMetaclass, cls).__call__(*args, **kwargs)
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/ops/resource_variable_ops.py", line 1602, in __init__
self._init_from_args(
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/ops/resource_variable_ops.py", line 1756, in _init_from_args
handle = eager_safe_variable_handle(
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/ops/resource_variable_ops.py", line 238, in eager_safe_variable_handle
return _variable_handle_from_shape_and_dtype(shape, dtype, shared_name, name,
File "/Users/liushanlin/miniforge3/envs/py3.9/lib/python3.9/site-packages/tensorflow/python/ops/resource_variable_ops.py", line 178, in _variable_handle_from_shape_and_dtype
cpp_shape_inference_pb2.CppShapeInferenceResult.HandleShapeAndType(
TypeError: Parameter to MergeFrom() must be instance of same class: expected tensorflow.TensorShapeProto got tensorflow.TensorShapeProto.
代码如下:
from nn.conv.lenet import LeNet
from tensorflow.keras.optimizers import SGD
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn import datasets
from keras import backend as K
import matplotlib.pyplot as plt
import numpy as np
print("[INFO] accessing MNIST...")
dataset = datasets.fetch_openml("mnist_784")
data = dataset.data.values
if K.image_data_format == "channels_first":
data = data.reshape(data.shape[0], 1, 28, 28)
else:
data = data.reshape(data.shape[0], 28, 28, 1)
(trainX, testX, trainY, testY) = train_test_split(data / 255.0, dataset.target.astype(int), test_size=0.25, random_state=42)
le = LabelBinarizer()
trainY = le.fit_transform(trainY)
testY = le.transform(testY)
print("[INFO] compiling model...")
opt = SGD(0.01)
model = LeNet.build(width=28, height=28, depth=1, classes=10)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
print("[INFO] training network...")
H = model.fit(trainX, trainY, validation_data=(testX, testY), batch_size=128, epochs=20, verbose=1)
print("[INFO] evaluating network...")
predictions = model.predict(testX, batch_size=128)
print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), target_names=[str(x) for x in le.classes_]))
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, 20), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, 20), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, 20), H.history["accuracy"], label="acc")
plt.plot(np.arange(0, 20), H.history["val_accuracy"], label="val_acc")
plt.title("Training loss adn Accuracy")
plt.xlabel("Epochs #")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.show()
LeNet.py
from keras.models import Sequential
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.layers.core import Activation
from keras.layers.core import Flatten
from keras.layers.core import Dense
from keras import backend as K
class LeNet:
@staticmethod
def build(width, height, depth, classes):
model = Sequential()
inputShape = (height, width, depth)
if K.image_data_format == "channels_first":
inputShape = (depth, height, width)
model.add(Conv2D(20, (5, 5), padding="same", input_shape=inputShape))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(20, (5, 5), padding="same", input_shape=inputShape))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Flatten())
model.add(Dense(500))
model.add(Activation("relu"))
model.add(Dense(classes))
model.add(Activation("softmax"))
return model
现在通过调试发现问题出在这句:
model = Sequential()
有偿求解答!!!