机器学习入门 - mnist数据集的使用

从TensorFlow中引入mnist数据集

from tensorflow.keras.datasets import mnist
(train_images, train_lable), (test_images, test_labels) = mnist.load_data()

定义神经网络架构

from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Dense(512, activation="relu")
    layers.Dense(10,activation="sigmoid")
])

编译网络模型

model.compile(optimizer="rmsprop",
              loss="sparse_categorical_crossentropy",
              metrics=["accuracy"])

optimizer: 优化器

loss:损失函数

metrics:指标,指标有很多,这里只关心精度(accuracy)。

开始训练模型:

先将之前加载的数据进行处理:

# 将原来的train_images进行预处理,将其形状改为(60000, 28*28)
# 取值改为【0-1】
train_images = train_images.reshape((60000, 28*28))
train_images = train_images.astype("float32") / 255
# test做同样处理
test_images = test_images.reshape((10000, 28*28))
test_images = test_images.astype("float32") / 255

训练

model.fit(train_images, train_lable, epochs = 5, batch_size=128)
'''
Epoch 1/5
469/469 [==============================] - 5s 9ms/step - loss: 0.2627 - accuracy: 0.9242
Epoch 2/5
469/469 [==============================] - 4s 9ms/step - loss: 0.1068 - accuracy: 0.9683
Epoch 3/5
469/469 [==============================] - 4s 9ms/step - loss: 0.0700 - accuracy: 0.9790
Epoch 4/5
469/469 [==============================] - 4s 9ms/step - loss: 0.0510 - accuracy: 0.9845
Epoch 5/5
469/469 [==============================] - 4s 9ms/step - loss: 0.0379 - accuracy: 0.9886

'''

训练集准确率0.9886

进行测试:

test_digits = test_images[0:10]
predictions = model.predict(test_digits)

predictions[0]
'''
array([1.0754002e-07, 2.0291100e-08, 4.3565451e-06, 1.7092835e-04,
       2.0635899e-11, 1.3739555e-07, 5.0437900e-12, 9.9982047e-01,
       5.4211657e-08, 4.0733948e-06], dtype=float32)
'''

predictions[0].argmax()
# 7

predictions[0][7]
# 0.9998205

test_labels[0]
# 7

test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f"test_acc: {test_acc}")
# 313/313 [==============================] - 1s 4ms/step - loss: 0.0612 - accuracy: 0.9809
# test_acc: 0.98089998960495

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值