# Tensorflow入门-实现神经网络

## 实现无隐含层的神经网络

### 读入数据

``````import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(‘MNIST_data/‘,one_hot=True)``````

``````print mnist.train.images.shape
print mnist.train.labels.shape
print mnist.test.images.shape
print mnist.test.labels.shape
print mnist.validation.images.shape
print mnist.validation.labels.shape
######################
##这里有55000*784,784为每一个图片的维度,被拉成一个长的向量
(55000, 784)
(55000, 10)
(10000, 784)
(10000, 10)
(5000, 784)
(5000, 10)``````

`x = tf.placeholder(tf.float32,[None,784])`其表示,在进行run的时候才读入数据.

`y = tf.nn.softmax(tf.matmul(x,W)+b)` softmax为转出每个标签的概率,表示预测的结果.其公式为:

softmaxi=exp(xi)∑jexp(xj)

H=?∑y?log(y′)

#### 注意reduce_sum的使用:

`reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))`

`tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)`

``````sess = tf.InteractiveSession()
#real data
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]))
#predict
y = tf.nn.softmax(tf.matmul(x,W)+b)
#loss
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))
#train ways
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)``````

### 进行训练

``````##重点,全局参数初始化
tf.global_variables_initializer().run()
##迭代1000次,每次取出100个样本进行训练SGD
for i in range(1000):
batch_x,batch_y = mnist.train.next_batch(100)
train_step.run({x:batch_x,y_:batch_y})``````

`train_step.run({x:batch_x,y_:batch_y})`这种方式为在运行的时候,feed_dict给x,y_的值,其中x为训练样本,y_为对应的真值.

### 评估

``````#test
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))       #高维度的
acuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))    #要用reduce_mean
print acuracy.eval({x:mnist.test.images,y_:mnist.test.labels})``````

## 实现多层神经网络

``````import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
sess = tf.InteractiveSession()

#定义添加隐含层的函数
def add_layer(inputs, in_size, out_size,keep_prob=1.0,activation_function=None):
Weights = tf.Variable(tf.truncated_normal([in_size,out_size],stddev=0.1))
biases = tf.Variable(tf.zeros([out_size]))
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
outputs = tf.nn.dropout(outputs,keep_prob)  #随机失活
return outputs

# holder变量
x = tf.placeholder(tf.float32,[None,784])
y_ = tf.placeholder(tf.float32,[None,10])
keep_prob = tf.placeholder(tf.float32)     # 概率

h1 = add_layer(x,784,300,keep_prob,tf.nn.relu)
##输出层
w = tf.Variable(tf.zeros([300,10]))     #300*10
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(h1,w)+b)

#定义loss,optimizer
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))
train_step  =tf.train.AdagradOptimizer(0.35).minimize(cross_entropy)

correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))       #高维度的
acuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))    #要用reduce_mean

tf.global_variables_initializer().run()
for i in range(3000):
batch_x,batch_y  = mnist.train.next_batch(100)
train_step.run({x:batch_x,y_:batch_y,keep_prob:0.75})
if i%1000==0:
train_accuracy = acuracy.eval({x:batch_x,y_:batch_y,keep_prob:1.0})
print("step %d,train_accuracy %g"%(i,train_accuracy))

###########test

print acuracy.eval({x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0})``````

``````h1 = add_layer(x,784,300,keep_prob,tf.nn.relu)
h2 = add_layer(h1,300,400,keep_prob,tf.nn.relu)
##输出层
w = tf.Variable(tf.zeros([400,10]))     #300*10
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(h2,w)+b)``````

1. https://github.com/tensorflow/tensorflow
2. tensorflow实战

## tensorflow入门教程

1. LSTM 大学之道,在明明德的博客: (译)理解 LSTM 网络 (Understanding LSTM Networks by colah) TensorFlow入门(五)多层 LSTM 通俗易懂版 TensorFlow入门(三)多层 CNNs 实现 mnist分类 另一个博客,写的代码很好: TensorFlow 实现多层 LSTM 的 MNIST 分类 + 可视化 博客:写的很好 用tensorflow搭建RNN(LSTM)进行MNIST 手写数字辨识 博客: Tensorflow

## TensorFlow 入门之手写识别(MNIST) softmax算法

TensorFlow 入门之手写识别(MNIST) softmax算法 MNIST 卢富毓 softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算法 我们知道MNIST的每一张图片都表示一个数字,从0到9.我们希望得到给定图片代表每个数字的概率.比如说,我们的模型可能推测一张包含9的图片代表数字9的概率是80%但是判断它是8的概率是5%(因为8和9都有上半部分的小圆),然后给予它代表其他数字的概率更小的值. 这是一个使用softmax回归(sof

## 转：TensorFlow入门（六） 双端 LSTM 实现序列标注（分词）

http://blog.csdn.net/Jerr__y/article/details/70471066 欢迎转载,但请务必注明原文出处及作者信息. @author: huangyongye @creat_date: 2017-04-19 前言 本例子主要介绍如何使用 TensorFlow 来一步一步构建双端 LSTM 网络(听名字就感觉好腻害的样子),并完成序列标注的问题.先声明一下,本文中采用的方法主要参考了[中文分词系列] 4. 基于双向LSTM的seq2seq字标注这篇文章.该文章用