import tensorflow as tf
计算模式–计算图
a = tf.constant([1.0, 2.0], name='a')
b = tf.constant([1.0, 2.0], name='b')
result = a + b
print(result)
# 如果没有特殊声明,a.graph返回其所属的计算图,即默认的计算图
print(a.graph == tf.get_default_graph())
print(a.graph)
数据模式–张量
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)
# 获取结果的维度
print(a)
print(tf.Session().run(result))
运行模式–会话
# 1、Session
# 创建一个会话
sess = tf.Session()
print(sess.run(result))
# 关闭会话
sess.close()
# 通过Python的上下文管理器来管理会话
with tf.Session() as sess:
print(sess.run(result))
# 通过Python的上下文管理器来管理会话
sess = tf.Session()
with sess.as_default():
print(result.eval())
sess = tf.Session()
print(sess.run(result))
print(result.eval(session=sess))
# tf.InteractiveSession
sess = tf.InteractiveSession()
print(result.eval())
#sess.close()
# 2、Placeholder
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b # + provides a shortcut for tf.add(a, b)
print(sess.run(adder_node, {a: 3, b:4.5}))
print(sess.run(adder_node, {a: [1,3], b: [2, 4]}))
add_and_triple = adder_node * 3.
print(sess.run(add_and_triple, {a: 3, b:4.5}))
# 3、Variable
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W * x + b
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(linear_model, {x:[1,2,3,4]}))
y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)
print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))
fixW = tf.assign(W, [-1])
fixb = tf.assign(b, [1])
sess.run([fixW, fixb])
print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))
# 4、tf.train
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
sess.run(init) # 重新设置初始化参数
for i in range(1000):
sess.run(train, {x:[1,2,3,4], y:[0,-1,-2,-3]})
print(sess.run([W, b]))
TensorFlow实现线性回归
import numpy as np
import tensorflow as tf
# 模型参数
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# 模型的输入和输出
x = tf.placeholder(tf.float32)
linear_model = W * x + b
y = tf.placeholder(tf.float32)
# 定义损失函数
loss = tf.reduce_sum(tf.square(linear_model - y)) # 均方误差
# 优化算法
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# 训练数据
x_train = [1,2,3,4]
y_train = [0,-1,-2,-3]
# 训练过程
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for i in range(100):
sess.run(train, {x:x_train, y:y_train})
# 训练误差
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x:x_train, y:y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))