TensorFlow 入门笔记 (1)(个人学习使用)
环境配置
Ubuntu16.04(VMware Workstation Pro 14)
Python2.7
TensorFlow1.3.0
TensorFlow基本概念
张量(tensor): 多维数组,Python中用列表表示
计算图:搭建神经网络的过程,只搭建不优化
会话:执行计算图中的节点运算
基于TensorFlow的NN:用张量表示数据,用计算图搭建神经网络,用会话执行计算图,优化参数、权重,得到模型
神经网络实现过程
1.准备数据集,提取特征,作为输入喂给神经网络
2.搭建神经网络,从输入到输出(先搭建计算图,然后用会话执行)
备注:NN前向传播----->计算输出
3.大量特征数据喂给NN,迭代优化NN参数
备注:NN反向传播 ------> 优化参数训练模型
4.使用训练好的模型进行预测和分类
前向传播:搭建网络,实现推理
反向传播:训练模型参数,在所有参数上使用梯度下降,使定义的损失函数最小
神经网络模型
- 神经元模型
- 激活函数
- 神经网络
Tensor Flow代码实战
#! /usr/bin/env python
#coding:utf-8
#两层简单神经网络(全连接)
import tensorflow as tf
import numpy as np
BATCH_SIZE = 8
seed = 23345
#基于seed产生随机数
rng = np.random.RandomState(seed)
#随机数返回32行2列的矩阵,表示32组体积和重量,作为输入数据集
X = rng.rand(32,2)
#数据标签
Y = [[int(x0+x1 < 1)] for (x0,x1) in X]
print "X:\n",X
print "Y:\n",Y
#1定义神经网络的输入、参数和输出,定义前向传播过程
x=tf.placeholder(tf.float32,shape=(None,2))
y_=tf.placeholder(tf.float32,shape=(None,1))
w1=tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))
w2=tf.Variable(tf.random_normal([3,1],stddev=1,seed=1))
a=tf.matmul(x,w1)
y=tf.matmul(a,w2)
#2定义损失函数和反向传播方法
loss = tf.reduce_mean(tf.square(y-y_))
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss)
#3生成会话,训练STEPS轮
with tf.Session() as sess:
init_op=tf.global_variables_initializer()
sess.run(init_op)
print "w1:\n",sess.run(w1)
print "w2:\n",sess.run(w2)
print "\n"
#训练模型
STEPS = 3000
for i in range(STEPS):
start = (i*BATCH_SIZE) % 32
end = start + BATCH_SIZE
sess.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]})
if i % 500 == 0:
total_loss = sess.run(loss,feed_dict={x:X,y_:Y})
print("After training %d steps,loss on all the data is %g:\n",(i,total_loss))
#训练输出后的参数取值
print "w1:\n",sess.run(w1)
print "w2:\n",sess.run(w2)
print "\n"