AttributeError: module 'keras.api._v2.keras.utils' has no attribute 'Sequential' i have just started Neural network so help would be appriciated

AttributeError: module 'keras.api._v2.keras.utils' has no attribute 'Sequential' i have just started Neural network so help would be appriciated

import cv2
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from keras import Sequential
from tensorflow import keras
import os

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)


model = tf.keras.utils.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

model.compile(optimizer='adam', loss='spare_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3)
model.save('handwritten.model')
Traceback (most recent call last):
  File "C:\Users\DELL\PycharmProjects\NeuralNetworks\main.py", line 15, in <module>
    model = tf.keras.utils.Sequential()
AttributeError: module 'keras.api._v2.keras.utils' has no attribute 'Sequential'
Process finished with exit code 1**

您应该使用 tf.keras.Sequential()tf.keras.models.Sequential()。此外,您需要定义一个有效的损失函数。这是一个工作示例:

import cv2
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from keras import Sequential
from tensorflow import keras
import os

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)


model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3)
model.save('handwritten.model')