本节主要详述tensorflow的基本用法,以下代码在python3.5,tensorflow1.5.0,numpy1.13.3下测试通过,想学习的小伙伴可以直接拷贝运行,一块学习提高呀。
1.平面拟合
代码:
import tensorflow as tf
import numpy as np
# 1.准备数据:使用 NumPy 生成假数据(phony data), 总共 100 个点.
x_data = np.float32(np.random.rand(2, 100)) # 随机输入
y_data = np.dot([0.100, 0.200], x_data) + 0.300
# 2.构造一个线性模型
b = tf.Variable(tf.zeros([1]))
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
y = tf.matmul(W, x_data) + b
# 3.求解模型
# 设置损失函数:误差的均方差
loss = tf.reduce_mean(tf.square(y - y_data))
# 选择梯度下降的方法
optimizer = tf.train.GradientDescentOptimizer(0.5)
# 迭代的目标:最小化损失函数
train = optimizer.minimize(loss)
############################################################
# 以下是用 tf 来解决上面的任务
# 1.初始化变量:tf 的必备步骤,主要声明了变量,就必须初始化才能用
init = tf.global_variables_initializer()
# 设置tensorflow对GPU的使用按需分配
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
# 2.启动图 (graph)
sess = tf.Session(config=config)
sess.run(init)
# 3.迭代,反复执行上面的最小化损失函数这一操作(train op),拟合平面
for step in xrange(0, 201):
sess.run(train)
if step % 20 == 0:
print step, sess.run(W), sess.run(b)
# 得到最佳拟合结果 W: [[0.100 0.200]], b: [0.300]
运行结果:
0 [[ 0.27467242 0.81889796]] [-0.13746099]
20 [[ 0.1619305 0.39317462]] [ 0.18206716]
40 [[ 0.11901411 0.25831661]] [ 0.2642329]
60 [[ 0.10580806 0.21761954]] [ 0.28916073]
80 [[ 0.10176832 0.20532639]] [ 0.29671678]
100 [[ 0.10053726 0.20161074]] [ 0.29900584]
120 [[ 0.100163 0.20048723]] [ 0.29969904]
140 [[ 0.10004941 0.20014738]] [ 0.29990891]
160 [[ 0.10001497 0.20004457]] [ 0.29997244]
180 [[ 0.10000452 0.20001349]] [ 0.29999167]
200 [[ 0.10000138 0.2000041 ]] [ 0.29999748]
2.两个数求和
代码:
input1 = tf.constant(2.0)
input2 = tf.constant(3.0)
input3 = tf.constant(5.0)
intermd = tf.add(input1, input2)
mul = tf.multiply(input2, input3)
with tf.Session() as sess:
result = sess.run([mul, intermd]) # 一次执行多个op
print result
print type(result)
print type(result[0])
运行结果:
[15.0, 5.0]
<type 'list'>
<type 'numpy.float32'>
如果代码有看不懂的小伙伴,可以留言或者私信博主(* ̄︶ ̄)。