Tensorflow的应用(二)

来源:互联网 发布:淘宝 无忧退货退钱吗? 编辑:程序博客网 时间:2024/05/29 12:42

1、简单神经网络实现线性回归

import numpy as npimport tensorflow as tfimport matplotlib.pyplot as pltx_data=np.linspace(-0.5,0.5,200)[:,np.newaxis]#numpy生成200个在-0.5和0.5之间的随机数noise=np.random.normal(0,0.02,x_data.shape)y_data=np.square(x_data)+noise#定义两个placeholderx=tf.placeholder(tf.float32,[None,1])y=tf.placeholder(tf.float32,[None,1])#定义神经网络的中间层weights_L1=tf.Variable(tf.random_normal([1,10]))#输入为一个神经元,隐藏层10个神经元,所以初始定义权重的形状为1行10列biases_L1=tf.Variable(tf.zeros([1,10]))Wx_plus_b_L1=tf.matmul(x,weights_L1)+biases_L1L1=tf.nn.tanh(Wx_plus_b_L1)#激活函数为双曲正切函数#定义神经网络的输出层weights_L2=tf.Variable(tf.random_normal([10,1]))#输入为一个神经元,隐藏层10个神经元,所以初始定义权重的形状为1行10列biases_L2=tf.Variable(tf.zeros([1,1]))Wx_plus_b_L2=tf.matmul(L1,weights_L2)+biases_L2prediction=tf.nn.tanh(Wx_plus_b_L2)#激活函数为双曲正切函数#定义代价函数loss=tf.reduce_mean(tf.square(y-prediction))#定义梯度下降法train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss)with tf.Session() as sess:    #变量初始化    sess.run(tf.global_variables_initializer())    for _ in range(2000):        sess.run(train_step,feed_dict={x:x_data,y:y_data})    #获取预测值    prediction_value=sess.run(prediction,feed_dict={x:x_data})    #画图    plt.figure()    plt.scatter(x_data,y_data)    plt.plot(x_data,prediction_value,'r-',lw=5)    plt.show()
2、手写数字识别

        训练集是60000*784的数据集,每一个样本表示一个数字,测试集是10000×784的数据集,标签是训练集和测试集每个样本对应的实际数字,标签所表示的数字用one-hot向量表示,向量长度为10,训练集的标签大小为60000*10,测试集的标签大小为10000*10.

import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data#载入数据集mnist = input_data.read_data_sets("MNIST_data",one_hot=True)#设置批次大小batch_size=10#计算一共有多少个批次n_batch =mnist.train.num_examples // batch_size#定义两个placeholderx = tf.placeholder(tf.float32,[None,784])#None表示可以是任意数,跟批次大小有关,批次是100,None就是100y = tf.placeholder(tf.float32,[None,10])#创建一个简单的神经网络w=tf.Variable(tf.zeros([784,10]))b=tf.Variable(tf.zeros([10]))prediction=tf.nn.softmax(tf.matmul(x,w)+b)#定义二次代价函数loss=tf.reduce_mean(tf.square(y-prediction))#使用梯度下降法train_step=tf.train.GradientDescentOptimizer(0.3).minimize(loss)#初始化变量init = tf.global_variables_initializer()#结果存放在一个布尔型列表中correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#tf.argmax返回sofmax结果的10个类别的概率中,概率最大的那个类别所在的位置#求准确率accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#cast是将布尔类型的correct_prediction转换为1.0\0.0这样就容易计算准确率with tf.Session() as sess:    sess.run(init)    for epoch in range(50):#迭代21个周期,把所有图片训练21次        for batch in range(n_batch):            batch_xs,batch_ys =  mnist.train.next_batch(batch_size)            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})                acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})        print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))


原创粉丝点击