jupyter notebook 识别minst数据集 完整代码
时间: 2023-07-25 21:33:01 浏览: 126
MINST数据集可视化代码
好的,以下是使用Jupyter Notebook识别MNIST数据集的完整Python代码。请确保已经安装了Jupyter Notebook和所需的Python库,例如numpy、matplotlib和tensorflow。
```python
# 导入所需的库
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
# 下载并导入MNIST数据集
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 将图像数据规范化到0到1之间
x_train, x_test = x_train / 255.0, x_test / 255.0
# 构建模型
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10)
])
# 编译模型
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# 训练模型
history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
# 评估模型
model.evaluate(x_test, y_test, verbose=2)
# 可视化训练结果
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
plt.show()
# 使用模型进行预测
probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])
predictions = probability_model.predict(x_test)
# 显示预测结果
for i in range(10):
plt.imshow(x_test[i], cmap=plt.cm.binary)
plt.title("Predicted: " + str(np.argmax(predictions[i])))
plt.show()
```
希望这能够帮助到你!
阅读全文