import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
#下载MNIST手写数字集,将手写数字集28*28图像变成1维的784个数据,
mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)
#定义占位符,MNIST手写数字集有60000张手写数字图片作训练样本,有10000张手写数字图片
#作测试样本
#张量x的None表示MNIST手写数字集中的图片编号,784表示降维后图片中每一个像素点
#张量y的None表示MNIST手写数字集中的图片编号,10表示0~9共10个数字概率,y为样本的目
#标结果(也称标签,导入手写数字集已经捆绑了对应的数字)
x = tf.placeholder(tf.float32, [None,784])
y = tf.placeholder(tf.float32, [None,10])
#定义权重张量w1,偏置张量b1,784个输入层神经元连接1024个隐藏层神经元
#定义隐藏层输出张量a,使用tf.nn.relu激活函数,tf.matmul(x,w1)+b1表示神经元的连接
w1 = tf.Variable(tf.truncated_normal([784,1024]), dtype = tf.float32)
b1 = tf.Variable(tf.zeros([1,1024]), dtype = tf.float32)
a = tf.nn.relu(tf.matmul(x,w1) + b1)
#定义权重张量w2,偏置张量b2,1024个隐藏层神经元连接10个输出层神经元
#定义输出层张量y_,使用tf.nn.softmax激活函数,tf.matmul(a,w2)+b2表示神经元的连接
w2 = tf.Variable(tf.ones([1024,10]))
b2 = tf.Variable(tf.zeros([1,10]))
y_= tf.nn.softmax(tf.matmul(a,w2) + b2)
#定义损失函数和梯度下降法
loss = tf.reduce_mean(-tf.reduce_sum(y*tf.log(y_), axis = 1))
train_step = tf.train.AdamOptimizer(0.0001).minimize(loss)
#初始化特殊张量
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
#每训练一个批次样本数据后后获得识别正确率
correct_prediction = tf.equal(tf.argmax(y_, axis = 1),tf.argmax(y, axis = 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#定义好上面所有的运行方式后,使用sess.run启动tensorflow
#在1000轮训练中,mnist.train.next_batch(100)表示每轮训练取出100张样本图片,用feed_dict
#方法把100张样本图片扔进占位符x,y进行训练,train_step参数是上面定义好的网络权重和偏
#置的调整方法
#每训练100轮就检验一次MNIST手写数据集中的10000张测试图片
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict = {x:batch_xs,y:batch_ys})
if i % 100 == 0:
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}))
#打印训练的参数
print(w1)
print(b1)
print(w2)
print(b2)
print(sess.run(w1))
print(sess.run(b1))
print(sess.run(w2))
print(sess.run(b2))
#将参数写入文件
with open('layer1_weight.h', 'w') as f:
img_numpy=w1.eval(session=sess)#将张量转化为数组
print("layer1_weight.h=",type(img_numpy))#打印信息
f.write("layer1_weight[] = "+str(np.transpose(img_numpy).tolist())+";\n")
f.close()
with open('layer1_bias.h', 'w') as f:
img_numpy=w1.eval(session=sess)
print("layer1_bias.h",type(img_numpy))
f.write("layer1_bias[] = "+str(np.transpose(img_numpy).tolist())+";\n")
f.close()
with open('layer2_weight.h', 'w') as f:
img_numpy=w1.eval(session=sess)
print("layer2_weight.h",type(img_numpy))
f.write("layer2_weight[] = "+str(np.transpose(img_numpy).tolist())+";\n")
f.close()
with open('layer2_bias.h', 'w') as f:
img_numpy=w1.eval(session=sess)
print("layer2_bias.h",type(img_numpy))
f.write("layer2_bias[] = "+str(np.transpose(img_numpy).tolist())+";\n")
f.close()
python读取神经网络权重张量的内容到文件
最新推荐文章于 2022-10-11 15:13:50 发布