关于入门深度学习mnist数据集前向计算的记录

【关于入门深度学习mnist数据集前向计算的记录】import osimport lr as lrimport tensorflow as tffrom pyspark.sql.functions import stddevfrom tensorflow.keras import datasetsos.environ['TF_CPP_MIN_LOG_LEVEL']='2'#只打印error的信息(x,y),_=datasets.mnist.load_data()#x:[60k,28,28]#y:[60k]x=tf.convert_to_tensor(x,dtype=tf.float32)/255#使x的值从0~255降到0~1y=tf.convert_to_tensor(y,dtype=tf.int32)print(x.shape,y.shape,x.dtype,y.dtype)print(tf.reduce_min(x),tf.reduce_max(x))print(tf.reduce_min(y),tf.reduce_max(y))train_db=tf.data.Dataset.from_tensor_slices((x,y)).batch(100)#每次从60k中取100张train_iter=iter(train_db)#迭代器sample=next(train_iter)print('batch:',sample[0].shape,sample[1].shape)#[b,784]=>[b,256]=>[b,128]=>[b,10]#[dim_in,dim_out],[dim_out]w1=tf.Variable(tf.random.truncated_normal([784,256],stddev=0.1))#防止梯度爆炸,需要设定均值和方差的范围,原来是均值为0 , 方差为1,现在设置方差为0.1b1=tf.Variable(tf.zeros([256]))w2=tf.Variable(tf.random.truncated_normal([256,128],stddev=0.1))b2=tf.Variable(tf.zeros([128]))w3=tf.Variable(tf.random.truncated_normal([128,10],stddev=0.1))b3=tf.Variable(tf.zeros([10]))#h1=x@w1+b1x指的是之前的一个batch,100个28*28的图片for epoch in range(10):#对整个数据集进行10次迭代for step,(x,y) in enumerate(train_db):# x:[100,28,28]y:[100]对每个batch进行,整体进度x=tf.reshape(x,[-1,28*28])#[b,28,28]=>[b,28*28]维度变换with tf.GradientTape() as tape:#tf.Variableh1 = x @ w1 + b1# [b,784]@[784,256]+[256]=>[b,256]h1 = tf.nn.relu(h1)# 加入非线性因素h2 = h1 @ w2 + b2# [b,256]@[256,128]+[128]=>[b,128]h2 = tf.nn.relu(h2)out = h2 @ w3 + b3# [b,128]@[128,10]+[10]=>[b,10]前项计算结束# compute loss# out:[b,10]# y:[b]=>[b,10]y_onehot = tf.one_hot(y, depth=10)#将yone_hot编码为长度为10的一维数组 , 好与x*w+b的[b,10]进行相减误差运算# mes=mean(sum(y_onehot-out)^2)loss = tf.square(y_onehot - out)# mean:scalarloss = tf.reduce_mean(loss)#求均值 , 就是计算100张图片的平均误差#compute gradientgrads=tape.gradient(loss,[w1,b1,w2,b2,w3,b3])#loss函数中队w1,b1,w2,b2,w3,b3求导# print(grads)#w1=w1-lr*w1_grad求下一个w1,梯度下降算法# w1 = w1 - lr * grads[0]#tf.Variable相减之后还是tf.tensor,需要原地更新# b1 = b1 - lr * grads[1]# w2 = w2 - lr * grads[2]# b2 = b2 - lr * grads[3]# w3 = w3 - lr * grads[4]# b3 = b3 - lr * grads[5]lr = 1e-3#0.001w1.assign_sub(lr * grads[0])b1.assign_sub(lr * grads[1])w2.assign_sub(lr * grads[2])b2.assign_sub(lr * grads[3])w3.assign_sub(lr * grads[4])b3.assign_sub(lr * grads[5])# print(isinstance(b3, tf.Variable))# print(isinstance(b3, tf.Tensor))if step%100==0:#每进行100个batch输出一次print(epoch,step,loss,float(loss))#本次学习也算是继续理解线性回归模型,mnist图像识别的学习,收获还是很不错的,不过还有一些知识希望在之后的学习中进行计算理解 。还挺开心的学这个东西 , 挺有意思的哈哈 。

    推荐阅读