当前位置:   article > 正文

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

tensorflow2 mnist

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

使用长截图的方法,目前可行的是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

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

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

  1. import tensorflow as tf
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. %matplotlib inline
  5. print("Tensorflow version:", tf.__version__)
  1. mnist =tf.keras.datasets.mnist
  2. (train_images,train_labels),(test_images,test_labels)= mnist.load_data()

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

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

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

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

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

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

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

对label进行热码处理:

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

build the model :

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

define the loss function:

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

 训练函数:

  1. loss_list_train =[]
  2. loss_list_valid =[]
  3. acc_list_train =[]
  4. acc_list_valid =[]
  5. W_list=[]
  6. B_list=[]
  7. total_step = int (train_num/batch_size)
  8. for epoch in range(training_epochs):
  9. for step in range(total_step):
  10. xs=train_x[step*batch_size:(step+1)*batch_size,:]
  11. ys=train_y[step*batch_size:(step+1)*batch_size]
  12. grads = grad(xs,ys,W,B)
  13. #calculate the stiffness W B
  14. optimizer.apply_gradients(zip(grads,[W,B]))
  15. loss_train =loss(train_x,train_y,W,B).numpy()
  16. loss_valid =loss(valid_x,valid_y,W,B).numpy()
  17. acc_train =accuracy(train_x,train_y,W,B).numpy()
  18. acc_valid =accuracy(valid_x,valid_y,W,B).numpy()
  19. loss_list_train.append(loss_train)
  20. loss_list_valid.append(loss_valid)
  21. acc_list_train.append(acc_train)
  22. acc_list_valid.append(acc_valid)
  23. 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))
  1. # graph
  2. plt.xlabel("Epochs")
  3. plt.ylabel("loss")
  4. plt.plot(loss_list_train,'blue',label="Train_loss")
  5. plt.plot(loss_list_valid,'red',label="Valid_loss")
  6. plt.legend(loc=1)
  1. # graph
  2. plt.xlabel("Epochs")
  3. plt.ylabel("acc")
  4. plt.plot(acc_list_train,'blue',label="Train_acc")
  5. plt.plot(acc_list_valid,'red',label="Valid_acc")
  6. plt.legend(loc=1)

准确率结果:

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

数据的预测:

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

进行数字的可视化:

  1. import matplotlib.pyplot as plt
  2. import numpy as np

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

  1. def plot_images(images, labels, preds, index=0, num=10): # 定义之后一次最多可以显示10张图片
  2. fig = plt.gcf()
  3. fig.set_size_inches(10, 4) # 设置幕布的长和宽
  4. if num > 10:
  5. num = 10
  6. for i in range(0, num):
  7. ax = plt.subplot(2, 5, i + 1) # 起到了规划图形之间的分布 同时也有i的循环来指定输出哪一幅图像
  8. # ax.imshow(np.reshape(images[index], (28, 28)), cmap='binary')
  9. tmp = images[index]
  10. tmp = tmp.reshape(28, 28)
  11. ax.imshow(tmp, cmap='binary')
  12. title = "label=" + str(labels[index])
  13. if len(preds) > 0: # 因为有时只是想输出图像 可能会在没有预测值之前
  14. title += ",predict=" + str(preds[index])
  15. ax.set_title(title, fontsize=10) # fontsize是字体大小
  16. ax.set_xticks([])
  17. ax.set_yticks([])
  18. index += 1
  19. plt.show()

最后显示命令:

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/350227
推荐阅读
相关标签
  

闽ICP备14008679号