第一个TensorFlow程序!
import tensorflow as tf
a=tf.constant([1.0,2.0],name='a')
b=tf.constant([2.0,3.0],name='b')
result=a+b
sess=tf.Session()
#sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
#确定自己的TensorFlow是CPU还是GPU的版本
print(sess.run(result))
TensorFlow中的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])
#[21.0,7.0]
#Feed
#创建占位符
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:7.0,input2:2.0}))
#[14.]
TensorFlow小实例!
import tensorflow as tf
import numpy as np
#使用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))
#定义一个梯度下降法来进行训练的优化器
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(201):
sess.run(train)
if step%20==0:
print(step,sess.run([k,b]))