数值计算表示为计算图,
TensorFlow的程序主干是一个图,
图节点是操作(代码中操作),有多个输入和一个输出
节点间的边表示之间流动的张量(tensors),比如n维数组
使用图,允许小而简单的操作建立复杂模型,会使梯度计算变简单---->自动求导
h=ReLU(Wx+b)
Variables:W,b
Placeholders(占位符):执行时间才会接受的点, x 即input。仅分配一个数据类型,一种大小的张量
Mathematical operations:数学操作节点 矩阵乘法、假发、激活函数等
import tensorflow as tf import numpy as np ################################ 建立图 ################################### b = tf.Variable(tf.zeros((100,))) W = tf.Variable(tf.random_uniform((784,100),-1,1)) x = tf.placeholder(tf.float32,(100,784)) h = tf.nn.relu(tf.matmul(x,W)+b) ################################# 将图部署到会话上 ############################### # 建立会话对象,调用参数Fetches,Feeds # Fetches:list of graph nodes which return the output of the nodes # Feeds:dictionary mapping from graph nodes to actual values,占位符 # 建立会话对象,采取默认环境,CPU,可以添加设备参数. 会话将图部署到硬件上? sess = tf.Session() sess.run(tf.initialize_all_variables()) sess.run(h, {x:np.random.random(100,784)}) ################################ 训练模型 ###################################### prediction = tf.nn.softmax()#输出的预测值 label = tf.placeholder(tf.float32,[100,10]) cross_entropy = -tf.reduce_sum(label * tf.log(prediction),axis=1) # 创建梯度下降的优化器,学习率设置0.5,最小化交叉熵cross_entropy train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess = tf.Session() sess.run(tf.initialize_all_variables()) for i in range(100): batch_x,batch_label = data.next_batch() sess.run(train_step,feed_dict={x: batch_x,label: batch_label}) with tf.variable_scope("foo"): v=tf.get_variable("v",shape=[1])