更新时间:2025-07-23 GMT+08:00
开发深度学习模型
创建和训练模型
使用如下命令创建并训练模型:
1 2 3 4 5 6 7 8 9 10 11 |
# create model model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10) ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) # training model.fit(train_images, train_labels, epochs=10) |
使用模型
用训练好的模型预测测试集中的某个图片属于什么类别,先显示这个图片,命令如下。
1 2 3 |
# display a test image plt.figure() plt.imshow(test_images[9]) |
图1 显示用以测试的图片

查看结果
查看预测结果,命令如下。
1 2 3 4 5 6 7 8 9 |
# Grab an image from the test dataset. img = test_images[9] # Add the image to a batch where it's the only member. img = (np.expand_dims(img,0)) # make prediction probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()]) predictions_single = probability_model.predict(img) class_names[np.argmax(predictions_single[0])] |
图2 查看预测结果
