TensorFlow学习(二)
TensorFlow学习(二)
线性回归(例)
利用梯度下降法来进行线性回归拟合
代码
import tensorflow as tf
import numpy as np
x_data = np.random.rand(100) #生成100个随机点
y_data = x_data * 0.1 + 2
b = tf.Variable(0.) #构造优化模型
k = tf.Variable(0.)
y = k * x_data + b
loss = tf.reduce_mean(tf.square(y_data-y)) #reduce_mean求平均值
optimizer = tf.train.GradientDescentOptimizer(0.2) #定义一个梯度下降法来进行训练的优化器
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(2000):
sess.run(train)
print(sess.run([k,b]))
结果为:
[0.10000114, 1.9999993]
非线性回归(例)
利用神将网络来进行非线性回归拟合
代码
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
x_data = np.linspace(-0.5,0.5,200)[:,np.newaxis]
noise = np.random.normal(0,0.02,x_data.shape)
y_data = np.square(x_data) + noise
x = tf.placeholder(tf.float32,[None,1])
y = tf.placeholder(tf.float32,[None,1])
#构建神经网络,输入一层,中间10个神经元,输出一层
#中间层
weight_l1 = tf.Variable(tf.random_normal([1,10]))
biases_l1 = tf.Variable(tf.zeros([1,10]))
wx_plus_b_l1 = tf.matmul(x,weight_l1) + biases_l1
L1 = tf.nn.tanh(wx_plus_b_l1) #双曲正切函数作为激活函数
#输出层
weight_l2 = tf.Variable(tf.random_normal([10,1]))
biases_l2 = tf.Variable(tf.zeros([1,1]))
wx_plus_b_l2 = tf.matmul(L1,weight_l2) + biases_l2
predietion = tf.nn.tanh(wx_plus_b_l2)
#定义代价函数,训练方法
loss = tf.reduce_mean(tf.square(y-predietion))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(2000):
sess.run(train_step,feed_dict={x:x_data,y:y_data})
prediction_v = sess.run(predietion,feed_dict={x:x_data})
plt.figure()
plt.scatter(x_data,y_data)
plt.plot(x_data,prediction_v,'r',lw=5)
plt.show()
结果为:

手写数字识别(例)
MNIST数据集:手写数字的数据集,一共有六万个训练样本,一万个测试样本,样本如下:

-
每一张图片包含2828个像素,我们把一个数组展开成一个向量,长度为2828=784.所以在MNIST训练集数据中是一个形状为[60000,784]的张量。图片中每个像素的强度值介于0-1之间。

-
MNIST数据集的标签为0-9的数字,我们把标签转化为“one-hot vectors”,一个one-hot向量除了某一位数字为1外其他维度都是0.比如标签0表示为[1 0 0 0 0 0 0 0 0 0 0 ],标签3表示为[0 0 0 1 0 0 0 0 0 0]
所以训练集标签是一个形状为[60000,10]的张量 -
softmax函数
softmax模型可以用来给不同对象分配概率:


- 神经网络结构

代码如下(结果为准确率):
- 神经网络结构
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
#每个批次的大小
batch_size = 100
#计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size
#定义两个placeholder
x = tf.placeholder(tf.float32,[None,784])
y = 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))
#交叉熵代价函数
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#初始化变量
init = tf.global_variables_initializer()
#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(init)
for epoch in range(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))
结果为:


被折叠的 条评论
为什么被折叠?



