Tensor flow 实战Google深度学习框架 笔记Code Part TensorFlow 入门

计算图的使用

import tensorflow as tf
a = tf.constant([1.0,2.0],name="a")
b = tf.constant([2.0,3.0],name="b")
result=a+b
print(a.graph is tf.get_default_graph())
import tensorflow as tf

g1 =tf.Grapf()
with g1.as_default():
    v=tf.get_variable("v",initializer=tf.zeros_initializer(shape=[1]))
g2 =tf.Grapf()
with g2.as_default():
    v=tf.get_variable("v",initializer=tf.ones_initializer(shape=[1]))

with tf.Session(graph=g1) as sess:
    tf.initializer_all_variables().run()
    with tf.variable_scope("",reuse=True):
        print(sess.run(tf.get_variable("v")))

with tf.Session(graph=g2) as sess:
    tf.initializer_all_variables().run()
    with tf.variable_scope("",reuse=True):
        print(sess.run(tf.get_variable("v")))
g=tf.Graph()
with g.device(\'/gpu:0\'):
        result=a+b

张量

import tensorflow as tf
#tf.constant是一个计算 计算的结果是一个张量 保存在变量a中
a = tf.constant([1.0,2.0],name="a")
b = tf.constant([2.0,3.0],name="b")
result = tf.add(a,b,name="add")
print result
import tensotflow as tf 
a = tf.constant([1,2],name="a")
b = tf.constant([2.0,3.0],name="b")
result=a+b
#error:类型不匹配  改正:a = tf.constant([1,2],name="a",dtype=tf.float32)
#使用张量记录中间结果
a = tf.constant([1.0,2.0],name="a")
b = tf.constant([2.0,3.0],name="b")
result =a+b

#直接计算向量的和 可读性差
result = tf.constant([1.0,2.0],name="a")+ tf.constant([2.0,3.0],name="b")

会话

sess = tf.Session()

sess.run(...)

sess.close()
with tf.Session() as sess:
    sess.run(...)
sess = tf.Session()
with sess.as_default():
    print(result.eval())
sess = tf.Session()

print(sess.run(result))
print(result.eval(session=sess))
#使用这个语句生成的会话会自动设置成默认会话
sess = tf.InteractiveSession()
print(result.eval())
sess.close()
#使用下句来配置需要生成的会话
config = tf.ConfigProto(allow_soft_placement=True,log_device_placement=True)
sess1=tf.InteractiveSession(config=config)
sess2=tf.Session(config=config)

实现神经网络

#实现矩阵乘法功能
a=tf.matmul(x,w1)
y=tf.matmul(a,w2)
#随机初始化一个2*3的矩阵变量 标准差为2
weights=tf.Variable(tf.random_normal(2,3),steddev=2)
biases=tf.Variable(tf.zeros([3]))
#通过其他变量的初始值来初始化新的变量
w2=tf.Variable(weights.initialized_value())
w3=tf.Variable(weights.initialized_value()*2.0)
import tensorflow as tf
w1 =tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))
w2 =tf.Variable(tf.random_normal([3,1],stddev=1,seed=1))

x=tf.constant([0.7,0.9])

a=tf.matmul(x,w1)
y=tf.matmul(a,w2)

sess=tf.Session()

sess.run(w1.initializer)
sess.run(w2.initializer)

print(sess.run(y))
sess.close()
#初始化所有变量
init_op=tf.initialize_all_variables()
sess.run(init_op)
#维度和类型是变量最重要的两个属性
w1 =tf.Variable(tf.random_normal([2,3],stddev=1),name="w1")
w2 =tf.Variable(tf.random_normal([3,1],dtype=tf.float64,stddev=1,seed=1),
name="w2")
#程序将报错 类型错误
w1.assign(w2)#tf.assign(A,new_number)赋值

w1 =tf.Variable(tf.random_normal([2,3],stddev=1,seed=1),name="w1")
w2 =tf.Variable(tf.random_normal([2,2],stddev=1,seed=1),name="w2")
#程序将报错 维度不一致
tf.assign(w1,w2)
#通过设置参数validate=False  可以改变维度
tf.assign(w1,w2,validate_shape=False)
import tensorflow as tf
w1 =tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))
w2 =tf.Variable(tf.random_normal([3,1],stddev=1,seed=1))
#定义placeholder作为存放输入数据的地方 这里的维度也不一定要定义
x=tf.placeholder(tf.float32,shape=(1,2),name="input")

a=tf.matmul(x,w1)
y=tf.matmul(a,w2)

sess=tf.Session()
init_op=tf.initialize_all_variables()
sess.run(init_op)
#下面将报错 因为没有输入数据
print(sess.run(y))

print(sess.run(y,feed_dict={x:[[0.7,0.9]]}))
x=tf.placeholder(tf.float32,shape=(3,2),name="input")
print(sess.run(y,feed_dict={x: [[0.7,0.9],[0.1,0.4],[0.5,0.8]]}))

tf.clip_by_value(A, min, max):输入一个张量A,把A中的每一个元素的值都压缩在min和max之间。

小于min的让它等于min,大于max的元素的值等于max。

tf.log 对数计算

求最大值tf.reduce_max(input_tensor, reduction_indices=None, keep_dims=False, name=None)

求平均值tf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None)

参数1--input_tensor:待求值的tensor。

参数2--reduction_indices:在哪一维上求解。

参数(3)(4)可忽略

#定义损失函数来刻画预测值与真实值得差距
cross_entropy=-tf.reduce_mean(
    y_*tf.log(tf.clip_by_value(y,le-10,1.0))

#定义学习率 
learning_rate=0.001

#定义反向传播算法来优化神经网络中的参数
train_step=\tf.train.AamOptimizer(learining_rate).minimize(cross_entropy)

三种常用优化方法

tf.train.Optimizer

tf.train.GradientDescentOptimizer

tf.train.AdadeltaOptimizer

完整神经网络样例程序

在一个模拟数据集上训练一个神经网络剞劂二分类问题

import tensorflow

#NumPy是一个科学计算的工具包 这里通过NumPy工具包生成模拟数据集
from numpy.random import RandomState

#定义训练数据batch的大小
batch_size=8

#定义神经网络参数 
w1 =tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))
w2 =tf.Variable(tf.random_normal([3,1],stddev=1,seed=1))

#在shape的一个维度上使用None 可以方便使用不同的batch的大小 在训练时需要把数据分
#成比较小的batch 但是在测试时 可以一次性使用全部的数据 当数据集比较小时像这样比较
#方便测试,但数据集比较大时,将大量数据放入一个batch可能会导致内存溢出(内存不够)
x=tf.placeholder(tf.float32,shape=(None,2),name=\'x-input\')
y_=tf.placeholder(tf.float32,shape=(None,1),name=\'y-input\')

#定义神经网络前向传播的过程
a=tf.matmul(x,w1)
y=tf.matmul(a,w2)

#定义损失函数和方向传播算法
cross_entropy=-tf.reduce.mean(
    y_*tf.log(tf.clip_by_value(y,le-10,1.0)))
train_step=tf.train.AamOPtimizer(0.001).minimizer(cross_entropy)

#通过随机数生成一个模拟数据集
rdm=RandomState(1)
 dataset_size=128
X=rdm.rand(dataset_size,2)

#定义规则来给出样本的标签。在这里所有x1+x2<1的样例都被认为是正样本(比如零件#合格),而其他则认为i是不合格(比如零件不合格)。在这里用0来表示负样本,1来表示正#样本。大部分解决分类问题的神经网络都会采用0和1的表示方法。
Y=[[int(x1+x2<1)] for (x1,x2) in X]

#创建一个会话来运行TensorFlow程序。
with tf.Session() as sess:
    init_op =tf.initialize_all_variables()
    #初始化变量
    sess.run(init_op)
    print sess.run(w1)
    print sess.run(w2)
#输出初始化的参数(训练之前)

#设定训练轮数
STEPS=5000
for i in range(STEPS):
    #每次选取batch_size个样本进行训练
    start =(i*batch_size)%dataset_size
    end =min (start+batch_size,dataset_size)

    #通过选取的样本训练神经网络并更新参数
    sess.run(train_step,
                 feed_dict={x:X[start:end],y_:Y[start:end]})
     if i%1000=0:
        #每隔一段时间计算在所有数据上的交叉熵并输出。=-=-=-=
        total_cross_entropy=sess.run(
               cross_entropy,feed_dict={x:X,y_:Y})
        print("After %d training step(s) ,cross entropy on all data is %g"
                %(i,total_cross_tntropy))
        #通过这个结果可以发现随着训练的进行 交叉熵是逐渐变小的 交叉熵越小说明预测
        # 结果和真实的结果差距越小

print sess.run(w1)
print sess.run(w2)