跑了一个小程序报这个错误TypeError: The added layer must be an instance of class Layer.

这是程序

import numpy as np
from tensorflow import keras
from tensorflow._api.v1.keras import layers

# Model / data parameters
num_classes = 10
input_shape = (28, 28, 1)

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

# Scale images to the [0, 1] range
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
# Make sure images have shape (28, 28, 1)
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
print("x_train shape:", x_train.shape)
print(x_train.shape[0], "train samples")
print(x_test.shape[0], "test samples")


# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = keras.Sequential(
    [
        keras.Input(shape=input_shape),
        layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
        layers.MaxPooling2D(pool_size=(2, 2)),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.MaxPooling2D(pool_size=(2, 2)),
        layers.Flatten(),
        layers.Dropout(0.5),
        layers.Dense(num_classes, activation="softmax"),
    ]
)

model.summary()

batch_size = 128
epochs = 15

model.compile(loss="categorical_crosstown", optimizer="adam", metrics=["accuracy"])

model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)

score = model.evaluate(x_test, y_test, verbose=0)
print("Test loss:", score[0])
print("Test accuracy:", score[1])

这是报错

x_train shape: (60000, 28, 28, 1)
60000 train samples
10000 test samples
Traceback (most recent call last):
  File "E:/homework1/main.py", line 36, in <module>
    layers.Dense(num_classes, activation="softmax"),
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\checkpointable\base.py", line 474, in _method_wrapper
    method(self, *args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 108, in __init__
    self.add(layer)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\checkpointable\base.py", line 474, in _method_wrapper
    method(self, *args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 140, in add
    'Found: ' + str(layer))
TypeError: The added layer must be an instance of class Layer. Found: Tensor("input_1:0", shape=(?, 28, 28, 1), dtype=float32)


把from tensorflow._api.v1.keras import layers改成
from tensorflow.keras.layers import Conv2D, Flatten, MaxPooling2D, Dropout
试试

可以参考下这篇文章,希望对你有帮助:


import numpy as np
from tensorflow import keras
from tensorflow.keras.layers import Conv2D, Flatten, MaxPooling2D, Dropout,Dense
 
# Model / data parameters
num_classes = 10
input_shape = (28, 28, 1)
 
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
 
# Scale images to the [0, 1] range
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
# Make sure images have shape (28, 28, 1)
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
print("x_train shape:", x_train.shape)
print(x_train.shape[0], "train samples")
print(x_test.shape[0], "test samples")
 
 
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
 
model = keras.Sequential(
    [
        keras.Input(shape=input_shape),
        Conv2D(32, kernel_size=(3, 3), activation="relu"),
        MaxPooling2D(pool_size=(2, 2)),
        Conv2D(64, kernel_size=(3, 3), activation="relu"),
        MaxPooling2D(pool_size=(2, 2)),
        Flatten(),
        Dropout(0.5),
        Dense(num_classes, activation="softmax"),
    ]
)
 
model.summary()
 
batch_size = 128
epochs = 15
 
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
 
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)
 
score = model.evaluate(x_test, y_test, verbose=0)
print("Test loss:", score[0])
print("Test accuracy:", score[1])