#非线性回归
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#使用numpy生成200个随机点
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
#定义两个placeholder
x = tf.placeholder(tf.float32,[None,1])
y = tf.placeholder(tf.float32,[None,1])
#定义神经网络中间层
Weights_L1 = tf.Variable(tf.random_normal([1,10]))
biases_L1 = tf.Variable(tf.zeros([1,10]))
Wx_plus_b_L1 = tf.matmul(x,Weights_L1) + biases_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)
#定义神经网络输出层
Weights_L2 = tf.Variable(tf.random_normal([10,1]))
biases_L2 = tf.Variable(tf.zeros([1,1]))
Wx_plus_b_L2 = tf.matmul(L1,Weights_L2) + biases_L2
prediction = 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()
执行得到:
#手写数据识别
1、MNIST数据集
- 官网:http://yann.lecun.com/exdb/mnist/
- 下载下来的数据集被分成两部分:60,000行训练数据集和10,000行的测试数据集
- 每一张图片包含28*28个像素,把这一个数组展开成一个向量,长度为28*28=784。因此在MNIST训练数据集中mnist.train.images是一个形状为[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]),标签3表示为([0,0,0,1,0,0,0,0,0,0,0])
- 因此,mnist.train.labels是一个[60000,10]的数字矩阵:
2、构建一个神经网络
3、Softmax函数
- softmax经常被放在分类的最后一层,用来给不同的对象分配概率:
- MNIST的结果是0-9,我们的模型可能推测出一张图片是数字9的概率是80%,是数字8的概率是10%,然后其他数字的概率更小,总体概率加起来等于1,这是一个使用softmax回归模型的经典案例。
#MNIST数据集分类简单版本:
import tensorflow as tf
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))
#使用梯度下降法
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))
执行得到:
#作业:
优化程序,把识别准确率提升到95%以上,要求不能使用LSTM网络和卷积神经网络。
Tip:
1、批次大小可以修改;
2、可以增加隐藏层;
3、权值和偏置值可以尝试使用其他初始化方式;
4、代价函数如果使用交叉商效果如何;
5、梯度下降法可以改变学习率,或者使用其他优化方式;
6、训练次数的改变。
#操作
1、关于批次
batch_size = 50:
batch_size = 10:
*批次越小,精确率越高,耗时越多。
*以下维持batch_size = 50:
2、关于学习率
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss):
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss):
*学习率越大,精确率越大。
*以下保持学习率为0.5:
3、关于训练次数
for epoch in range(10):
for epoch in range(25):
*训练次数越多,精确率越高。
PS.此为学习《深度学习框架Tensorflow学习与应用》课程的笔记。【http://www.bilibili.com/video/av20542427/?share_source=copy_link&p=4&ts=1551709559&share_medium=iphone&bbid=7db773463cc4248e755f030556bc67d1】