案例一:
m1 = tf.constant([[3, 3]]) # 定义一个一行两列的矩阵,op1
m2 = tf.constant([[2], [3]]) # 定义一个两行一列的矩阵,op2
product = tf.matmul(m1, m2) # 创建一个矩阵乘法,把m1和m2传入,op3
# 定义一个会话,启动默认图 # 方法一
sess = tf.Session()
# 调用sess的run方法来执行矩阵乘法op
# run(product)触发了图中3个op
result = sess.run(product)
print(result)
sess.close()
tf.constant函数参考:
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-jabh2d30.html
tf.matmul函数参考:
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-l5x72feg.html
定义三个opration,然后建立一个会话启动默认图,再通过run即可得到计算结果,也可以通过with语句,这样可以省去sess.close()操作。
# 不需要执行关闭的操作 # 方法二
with tf.Session() as sess:
result = sess.run(product)
print(result)
案例二:
x = tf.Variable([1, 2]) # 定义一个变量 op1
a = tf.constant([3, 3]) # 定义一个常数 op2
# 增加一个减去op
sub = tf.subtract(x, a) # 创建一个减法操作 op3
# 增加一个加法op
add = tf.add(x, sub) # 创建一个加法操作 op4
init = tf.global_variables_initializer() # 全局变量初始化 op5
with tf.Session() as sess:
sess.run(init)
print(sess.run(sub))
print(sess.run(add))
tf.Variable参考链接:
https://www.jianshu.com/p/2b9e475391ab
当有定义变量时, 需要使用tf.global_variables_initializer()进行全局变量初始化。在建立的会话中,要先运行init这个操作op5, 然后分别运行op3和op4。
案例三:
# 创建一个变量初始化为0
state = tf.Variable(0, name='counter') #op1
# 创建一个op
new_value = tf.add(state, 1) # op2
# 赋值op
update = tf.assign(state, new_value) # op3
# 初始化变量
init = tf.global_variables_initializer() # op4
with tf.Session() as sess:
sess.run(init)
print(sess.run(state))
for x in range(5):
sess.run(update)
print(sess.run(state))
tf.assign()赋值函数用法参照链接:
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-b4x72chd.html
案例四
# Fetch ##同时运行多个op
input1 = tf.constant(3.0) #op1
input2 = tf.constant(2.0) #op2
input3 = tf.constant(5.0) #op3
add = tf.add(input2, input3) #op4
mul = tf.multiply(input1, add) #op5
with tf.Session() as sess:
result = sess.run([add, mul]) # [add, mul]顺序无所谓
print(result)
sess.run()函数中同时运行多个操作,这里顺序不影响结果。
案例五
# 创建占位符
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)
with tf.Session() as sess:
# feed的数据以字典的形式传入
print(sess.run(output, feed_dict={input1: [8.], input2: [2.]}))
tf.placeholder()函数参照链接:
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-w7yt2fwc.html
案例六
# 用numpy生成100个随机点
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)) # 误差的平方的平均值作为cost function
# 定义一个梯度下降法来进行训练的优化器
opt = tf.train.GradientDescentOptimizer(0.1)
# 定义一个最小化代价函数
train = opt.minimize(loss)
# 初始化变量
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(sess.run([k, b]))
案例七
# 使用numpy生成200个随机点
x_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis] # [:, np.newaxis]生成200行一列的数据
noise = np.random.normal(0, 0.02, x_data.shape)
print(x_data.shape)
y_data = np.square(x_data) + noise # y = x*x+noise
# 先定义两个placeholder
x = tf.placeholder(tf.float32, [None, 1])
y = tf.placeholder(tf.float32, [None, 1])
# 定义两个神经网络中间层
Weights_L1 = tf.Variable(tf.random_normal([1, 10]))
biases_L1 = tf.Variable(tf.zeros([1, 10]))
Wx_plus_b_L1 = tf.matmul(x, Weights_L1) + biases_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)
# 定义神经网络输出层
Weights_L2 = tf.Variable(tf.random_normal([10, 1]))
biases_L2 = tf.Variable(tf.zeros([1, 1]))
Wx_plus_b_L2 = tf.matmul(L1, Weights_L2) + biases_L2
prediction = tf.nn.tanh(Wx_plus_b_L2)
# 二次代价函数
loss = tf.reduce_mean(tf.square(y - prediction))
# 使用梯度下降法训练
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) # 0.1是学习速率
with tf.Session() as sess:
# 变量初始化
sess.run(tf.global_variables_initializer())
for _ in range(2000):
sess.run(train_step, feed_dict={x: x_data, y: y_data})
# 获得预测值
prediction_value = sess.run(prediction, feed_dict={x: x_data})
# 画图
plt.figure()
plt.scatter(x_data, y_data)
plt.plot(x_data, prediction_value, 'r-', lw=5)
plt.show()