mnist数据集,keras实现简单密集链接(全连接)

本文介绍了使用TensorFlow 2.3中的Keras库进行MNIST数据集手写数字识别的全过程,包括数据预处理、模型构建、训练及评估。通过实例展示了如何创建一个简单的神经网络并实现图像分类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我用到的是tensorflow2.3里的keras,cuda:10.1
代码:
#%%

import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt



#%%

mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()


#%%

class_names = []
for i in range(0, 10):
    class_names.append('%d' % i)


#%%

# class_names

#%%

# train_images.shape

#%%

# len(train_labels)

#%%

# train_labels

#%%

# test_images.shape

#%%

# len(test_labels)

#%%

plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()


#%%

train_images = train_images / 255
test_images = test_images / 255

#%%

plt.figure(figsize=(5, 5))
for i in range(25):
    plt.subplot(5, 5, i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
plt.show()


#%%

model = keras.Sequential([keras.layers.Flatten(input_shape=(train_images.shape[1:])),
                          keras.layers.Dense(128, activation='relu'),
                          keras.layers.Dense(10)])
"""
该网络的第一层 tf.keras.layers.Flatten 将图像格式从二维数组(28 x 28 像素)转换成一维数组(28 x 28 = 784 像素)。将该层视为图像中未堆叠
的像素行并将其排列起来。该层没有要学习的参数,它只会重新格式化数据。

展平像素后,网络会包括两个 tf.keras.layers.Dense 层的序列。它们是密集连接或全连接神经层。第一个 Dense 层有 128 个节点(或神经元)。第二个
(也是最后一个)层会返回一个长度为 10 的 logits 数组。每个节点都包含一个得分,用来表示当前图像属于 10 个类中的哪一类。
"""

#%%

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])


#%%

model.fit(train_images, train_labels, epochs=20)


#%%

test_loss, test_accuracy = model.evaluate(test_images, test_labels, verbose=2)

print('\nTest accuracy:', test_accuracy)

#%%

probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])

#%%

# 在新数据集上预测
predictions = probability_model.predict(test_images)

#%%
# 输出第一个数字的结果
p = np.array(predictions[0], np.uint8)

#%%

print(np.argmax(predictions[0]))

#%%

plt.figure()
plt.imshow(test_images[0])
plt.colorbar()
plt.grid(False)
plt.show()


#%%

# 使用训练好的Model对单个图像进行预测
img = test_images[1]
print(img.shape)

#%%

img = (np.expand_dims(img, 0))
print(img.shape)

#%%

predictions_single = probability_model.predict(img)
print(predictions_single)

#%%

np.argmax(predictions_single[0])

#%%

plt.figure()
plt.imshow(test_images[1])
plt.colorbar()
plt.grid(False)
plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值