版权声明:本文为博主原创文章,如未特别声明,均默认使用CC BY-SA 3.0许可。 https://blog.csdn.net/Geek_of_CSDN/article/details/84890425
基本概念
- 图(graph):用来表示计算任务。图中节点称为OP(operation),接受零至多个Tensor,产生零至多个Tensor
- Tensor:相当于矩阵/数组,用来装载数据
- 会话(Session):用来执行图的运算的东西
- 图通过变量(Variable)维护状态
- feed、fetch:赋值/获取数据
创建图、启动图
import tensorflow as tf
# 创建常量
m1 = tf.constant([[3, 3]])
m2 = tf.constant([[2], [3]])
# 创建矩阵乘法op,传入m1、m2
product = tf.matmul(m1, m2)
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
上面这种方法需要手动用sess.close()
来关闭图,很不方便,所以通常用这种方式打开图:
import tensorflow as tf
# 创建常量
m1 = tf.constant([[3, 3]])
m2 = tf.constant([[2], [3]])
# 创建矩阵乘法op,传入m1、m2
product = tf.matmul(m1, m2)
with tf.Session() as sess:
result = sess.run(product)
print(result)
变量
import tensorflow as tf
x = tf.Variable([1, 2])
a = tf.Variable([3, 3])
sub = tf.subtract(x, a)
add = tf.add(x, sub)
# 在跑代码前一定要init所有的变量,不然会报错
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(sub))
print(sess.run(add))
state = tf.Variable(0, name='counter')
# 创建一个op来让state加1
new_value = tf.add(state, 1)
# 赋值op
update = tf.assign(state, new_value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(state))
for _ in range(5):
sess.run(update)
print(sess.run(state))
最后面print(sess.run(state))
中的sess.run
似乎对图中变量不会产生影响,只是输出了结果。
fetch和feed
import tensorflow as tf
# fetch
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
add = tf.add(input2, input3)
mul = tf.multiply(input1, add)
with tf.Session() as sess:
result = sess.run([mul, add])
print(result)
# feed
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)
with tf.Session() as sess:
print(sess.run(output, feed_dict={input1:[8.], input2:[2.]}))
fetch就是直接从别的地方拿数据过来(例如上面就是在add
处fetch了input2
和input3
),feed就是在运行图的时候输入数据(例如上面就是feed入了8.
和2.
)。
简单的拟合实例
import tensorflow as tf
import numpy as np
x_data = np.random.rand(100)
y_data = x_data * 0.1 + 0.2
b = tf.Variable(0.)
k = tf.Variable(0.)
y = k * x_data + b
# 二次代价函数
loss = tf.reduce_mean(tf.square(y_data - y))
# 定义一个梯度下降
optimizer = tf.train.GradientDescentOptimizer(0.2)
# 最小化代价函数
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for step in range(200 + 1):
sess.run(train)
if step%20 == 0:
print(step, sess.run([k, b]))
这里可以试试改 和 的值,可以发现无论初始值是怎么样的,最后都会拟合到 和 。