目录node
import tensorflow as tf a = tf.constant([1.0, 2.0], name='a', dtype=tf.float32) # 定义常量向量 b = tf.constant([2.0, 3.0], name='b') result = a + b # 向量相加 print(result) # 先生成一个会话,经过该会话来计算结果 # sess = tf.Session() sess = tf.InteractiveSession() # 自动将生成的会话注册为默认会话 print(sess.run(result)) print(result.eval(session=sess)) sess.close() # 关闭会话,释放资源
g1 = tf.Graph() # 生成新的计算图 with g1.as_default(): # 在计算图g1中定义变量'v',并设置初始值为0 v = tf.get_variable("v", initializer=tf.zeros(shape=[1])) # 在计算图g1中读取变量'v'的值 with tf.Session(graph=g1) as sess: # 经过上下文管理器来使用会话 tf.global_variables_initializer().run() with tf.variable_scope('', reuse=True): print(sess.run(tf.get_variable('v')))
config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=True) sess1 = tf.InteractiveSession(config=config) sess2 = tf.Session(config=config)
神经网络解决分类问题的主要步骤:python
全链接神经网络:相邻两层之间任意两个节点之间都有链接。算法
TensorFlow支持的随机数生成函数:编程
tf.random_normal
:正态分布。tf.truncated_normal
:正态分布,但若随机值偏离平均值超过2个标准差,将被从新随机。tf.random_uniform
:平均分布。tf.random_gamma
:Gamma分布。TensorFlow常数生成函数:数组
tf.zeros([2,3], int32)
:产生全0的数组。tf.ones([2,3], int32)
:产生全1的数组。tf.fill([2,3], 9)
:产生一个所有为给定数字的组合。tf.constant([1,2,3)
:产生一个给定值的常量。# 声明一个2*3的矩阵变量,并赋予均值为0,标准差为2的随机数 weigths = tf.Variable(tf.random_normal([2, 3], mean=0, stddev=2)) biases = tf.Variable(tf.zeros([3]))
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]]) # 1*2的矩阵 a = tf.matmul(x, w1) # 矩阵乘法 y = tf.matmul(a, w2) with tf.Session() as sess: # sess.run(w1.initializer) # 逐个初始化变量 # sess.run(w2.initializer) # 初始化全部变量 init_op = tf.global_variables_initializer() sess.run(init_op) print(sess.run(y)) print(tf.all_variables)
tf.all_variables
:可拿到当前计算图上全部的变量。tf.trainable_variables
:获得全部须要优化的参数。validate_shape=False
。w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) w2 = tf.Variable(tf.random_normal([2, 2], stddev=1, seed=1)) # tf.assign(w1, w2) # wrong tf.assign(w1, w2, validate_shape=False)
# 使用placeholder实现前向传播算法 w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1)) # 输入为n*2矩阵,前向传播结果为n*1的矩阵 # placeholder中数据的维度信息能够根据提供的数据推导得出,全部不必定要给出 x = tf.placeholder(tf.float32, shape=(3, 2), name='input') a = tf.matmul(x, w1) y = tf.matmul(a, w2) sess = tf.Session() init_op = tf.global_variables_initializer() sess.run(init_op) # print(sess.run(y)) # 某个须要的placeholder没有被指定取值,报错 print(sess.run(y, feed_dict={x: [[0.7, 0.9], [0.1, 0.4], [0.5, 0.8]]})) # 指定x的取值
from numpy.random import RandomState 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)) 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, 1e-10, 1.0))) train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy) # 经过随机数生成一个模拟数据集 rdm = RandomState(1) dataset_size = 128 X = rdm.rand(dataset_size, 2) Y = [[int(x1 + x2 < 1)] for (x1, x2) in X] # 建立会话 with tf.Session() as sess: init_op = tf.global_variables_initializer() 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_entropy)) print(sess.run(w1)) print(sess.run(w2))