Tensorflow2的MNIST数字识别实例及代码(jupyter长截图)

 首先是个关于这个的长截图,包括结果以及代码:

使用长截图的方法,目前可行的是Chrome里F12,其他参照后面链接,edge的浏览器目前不可以

(1条消息) 新版Edge如何长截图_今天怎么又下雨的博客-CSDN博客_edge长截图https://blog.csdn.net/weixin_44122062/article/details/105855048另外可以使用QQ进行长截屏:

用电脑如何截长图,我懂你要的 - 知乎 (zhihu.com)https://zhuanlan.zhihu.com/p/358417947

 下面长截图为相应的代码及结论:

 需要代码及实际的步骤的可以参考下文:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline 

print("Tensorflow version:", tf.__version__)
mnist =tf.keras.datasets.mnist
(train_images,train_labels),(test_images,test_labels)= mnist.load_data()

print("Train image shape:",train_images.shape,"Train label shape:",train_labels.shape)
print("Test image shape:",test_images.shape,"Test label shape:",test_labels.shape)
print("image data:",train_images[1])
print("train labels:",train_labels[1])
def plot_image(image):
    plt.imshow(image.reshape(28,28),cmap='binary')
    plt.show()
plot_image(train_images[1])
total_num =len(train_images)
print(total_num)
valid_split =0.2
train_num=int(total_num*(1-valid_split))
train_x =train_images[:train_num]
train_y =train_labels[:train_num]
valid_x=train_images[train_num:]
valid_y=train_labels[train_num:]
test_x = test_images
test_y =test_labels
valid_x.shape

进行数据的转换,转换为行向量:

train_x =train_x.reshape(-1,784)
valid_x =valid_x.reshape(-1,784)
test_x= test_x.reshape(-1,784)

进行归一化处理,因为像素是255,但对于实际自己数据需要使用:

train_x=tf.cast(train_x/255.0,tf.float32)
valid_x=tf.cast(valid_x/255.0,tf.float32)
test_x =tf.cast(test_x/255.0,tf.float32)

对于12列数据的一般数据归一化:

# 归一化处理
for i in range(12):
    x_data[:,i]=(x_data[:,i]-x_data[:,i].min())/(x_data[:,i].max()-x_data[:,i].min())

对label进行热码处理:

#对标签数据进行独热编码
train_y= tf.one_hot(train_y,depth=10)
valid_y= tf.one_hot(valid_y,depth=10)
test_y= tf.one_hot(test_y,depth=10)

build the model :

# build the model
def model(x,w,b):
    pred = tf.matmul(x,w)+b
    return tf.nn.softmax(pred)
#准备变量
W = tf.Variable(tf.random.normal([784,10],mean=0.0, stddev=1.0, dtype=tf.float32))
# don;t forget the random
B = tf.Variable(tf.zeros(10),dtype = tf.float32)
print(W)
print(B)

define the loss function:

def loss(x,y,w,b):
    pred =model(x,w,b)
    #loss_=tf.keras.losses.categorical_crossentroy(y_true=y,y_pred=pred)
    loss_= tf.keras.losses.categorical_crossentropy(y_true=y,y_pred=pred)
    return tf.reduce_mean(loss_)
#设置超参数
training_epochs =20
learning_rate =0.001
batch_size = 50  #批量训练一次的样本
def grad(x,y,w,b):
    with tf.GradientTape() as tape:
        loss_ =loss(x,y,w,b)
        return tape.gradient(loss_,[w,b])
  #返回梯度向量损失函数的,注意编程时的结构顺序
#选择优化器
optimizer = tf.keras.optimizers.Adam(learning_rate)
# help apply_gradients
def accuracy(x,y,w,b):
    pred =model(x,w,b)
    correct_prediction =tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
    return tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

 训练函数:

loss_list_train =[]
loss_list_valid =[]
acc_list_train =[]
acc_list_valid =[]
W_list=[]
B_list=[]
total_step = int (train_num/batch_size)
for epoch in range(training_epochs):
    for step in range(total_step):
        xs=train_x[step*batch_size:(step+1)*batch_size,:]
        ys=train_y[step*batch_size:(step+1)*batch_size]
        
        grads = grad(xs,ys,W,B) 
        #calculate the stiffness W B
        optimizer.apply_gradients(zip(grads,[W,B]))
    loss_train =loss(train_x,train_y,W,B).numpy()
    loss_valid =loss(valid_x,valid_y,W,B).numpy()
    acc_train =accuracy(train_x,train_y,W,B).numpy()
    acc_valid =accuracy(valid_x,valid_y,W,B).numpy()
    loss_list_train.append(loss_train)
    loss_list_valid.append(loss_valid)
    acc_list_train.append(acc_train)
    acc_list_valid.append(acc_valid)
    
    print("epoch={:3d},train_loss={:.4f},valid_loss={:.4f},train_acc={:.4f},valid_acc={:.4f}".format(epoch+1,loss_train,loss_valid,acc_train,acc_valid))
# graph
plt.xlabel("Epochs")
plt.ylabel("loss")
plt.plot(loss_list_train,'blue',label="Train_loss")
plt.plot(loss_list_valid,'red',label="Valid_loss")
plt.legend(loc=1)
# graph
plt.xlabel("Epochs")
plt.ylabel("acc")
plt.plot(acc_list_train,'blue',label="Train_acc")
plt.plot(acc_list_valid,'red',label="Valid_acc")
plt.legend(loc=1)

准确率结果:

acc_test = accuracy(test_x,test_y,W,B).numpy
print("Test accuracy:",acc_test)

数据的预测:

def predict(x, w, b):
    pred = model(x, w, b)
    result = tf.argmax(pred, 1).numpy()
    return result
pred_test=predict(test_x,W,B)
print(pred_test)

进行数字的可视化:

import matplotlib.pyplot as plt
import numpy as np

主要可视化代码,注意相应结构顺序:

def plot_images(images, labels, preds, index=0, num=10):  # 定义之后一次最多可以显示10张图片
    fig = plt.gcf()
    fig.set_size_inches(10, 4)  # 设置幕布的长和宽
    if num > 10:
        num = 10

    for i in range(0, num):
        ax = plt.subplot(2, 5, i + 1)  # 起到了规划图形之间的分布 同时也有i的循环来指定输出哪一幅图像
        # ax.imshow(np.reshape(images[index], (28, 28)), cmap='binary')
        tmp = images[index]
        tmp = tmp.reshape(28, 28)
        ax.imshow(tmp, cmap='binary')
        title = "label=" + str(labels[index])
        if len(preds) > 0:  # 因为有时只是想输出图像 可能会在没有预测值之前
            title += ",predict=" + str(preds[index])

        ax.set_title(title, fontsize=10)  # fontsize是字体大小
        ax.set_xticks([])
        ax.set_yticks([])
        index += 1
    plt.show()

最后显示命令:

plot_images(test_images,test_labels,pred_test,10,10)

总结:以上为完整的MNIST的TensorFlow2实现过程,相应的文件会单独上传

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 基于TensorFlowMNIST手写数字识别是一种机器学习技术,它可以通过训练模型来识别手写数字MNIST是一个常用的数据集,包含了大量的手写数字图像和对应的标签。TensorFlow是一个流行的深度学习框架,可以用来构建和训练神经网络模型。通过使用TensorFlow,我们可以构建一个卷积神经网络模型,对MNIST数据集进行训练和测试,从而实现手写数字识别的功能。 ### 回答2: 随着机器学习技术的不断发展,MNIST手写数字识别已成为一个基础、常见的图像分类问题。TensorFlow是目前最流行的深度学习框架之一,广泛应用于图像处理、自然语言处理等领域,所以在TensorFlow上实现MNIST手写数字识别任务是非常具有代表性的。 MNIST手写数字识别是指从给定的手写数字图像中识别数字的任务。MNIST数据集是一个由数万张手写数字图片和相应标签组成的数据集,图片都是28*28像素的灰度图像。每一张图片对应着一个标签,表示图片中所代表的数字。通过对已经标记好的图片和标签进行训练,我们将构建一个模型来预测测试集中未知图片的标签。 在TensorFlow中实现MNIST手写数字识别任务,可以通过以下步骤完成: 1. 导入MNIST数据集:TensorFlow中的tf.keras.datasets模块内置了MNIST数据集,可以通过如下代码导入:(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() 2. 数据预处理:对数据进行标准化处理,即将灰度值范围从[0,255]缩放到[0,1]之间。同时将标签值进行独热编码,将每个数字的标签由一个整数转换为一个稀疏向量。采用以下代码完成数据预处理:train_images = train_images / 255.0 test_images = test_images / 255.0 train_labels = tf.keras.utils.to_categorical(train_labels, 10) test_labels = tf.keras.utils.to_categorical(test_labels, 10) 3. 构建模型:采用卷积神经网络(CNN)进行建模,包括卷积层、池化层、Dropout层和全连接层。建议采用可重复使用的模型方法tf.keras.Sequential()。具体代码实现为:model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3,3), activation='relu',input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D((2,2)), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.5)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) 4. 编译模型:指定优化器、损失函数和评估指标。可采用Adam优化器,交叉熵损失函数和准确率评估指标。具体实现代码如下:model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) 5. 训练模型:采用train()函数进行模型训练,完成代码如下:model.fit(train_images, train_labels, epochs=5, validation_data=(test_images, test_labels)) 6. 评估模型:计算测试准确率,完成代码如下:test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test accuracy:', test_acc) 以上就是基于TensorFlowMNIST手写数字识别的简要实现过程。其实实现过程还可以更加复杂,比如调节神经元数量,添加卷积层数量等。总之采用TensorFlow框架实现MNIST手写数字识别是一个可行的任务,未来机器学习发展趋势将越来越向深度学习方向前进。 ### 回答3: MNIST手写数字识别是计算机视觉领域中最基础的问题,使用TensorFlow实现这一问题可以帮助深入理解神经网络的原理和实现,并为其他计算机视觉任务打下基础。 首先,MNIST手写数字数据集由28x28像素的灰度图像组成,包含了数字0到9共10个类别。通过导入TensorFlow及相关库,我们可以很容易地加载MNIST数据集并可视化: ``` import tensorflow as tf import matplotlib.pyplot as plt (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() print("Training images:", train_images.shape) print("Training labels:", train_labels.shape) print("Test images:", test_images.shape) print("Test labels:", test_labels.shape) plt.imshow(train_images[0]) plt.show() ``` 在实现MNIST手写数字识别的神经网络模型中,最常用的是卷积神经网络(Convolutional Neural Networks,CNN),主要由卷积层、激活层、池化层和全连接层等组成。卷积层主要用于提取局部特征,激活层用于引入非线性性质,池化层则用于加速处理并减少过拟合,全连接层则进行最终的分类。 以下为使用TensorFlow搭建CNN实现MNIST手写数字识别代码: ``` model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, kernel_size=(3,3), activation='relu', input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D(pool_size=(2,2)), tf.keras.layers.Conv2D(64, kernel_size=(3,3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2,2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(10, activation='softmax') ]) model.summary() model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) train_images = train_images.reshape((60000, 28, 28, 1)) train_images = train_images / 255.0 test_images = test_images.reshape((10000, 28, 28, 1)) test_images = test_images / 255.0 model.fit(train_images, train_labels, epochs=5, batch_size=64) test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print("Test accuracy:", test_acc) ``` 这段代码中使用了两个卷积层分别提取32和64个特征,池化层进行特征加速和降维,全连接层作为最终分类器输出预测结果。在模型训练时,使用Adam优化器和交叉熵损失函数进行训练,经过5个epoch后可以得到约99%的测试准确率。 总之,通过使用TensorFlow实现MNIST手写数字识别的经历,可以深切认识到深度学习在计算机视觉领域中的应用,以及如何通过搭建和训练神经网络模型来解决实际问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值