tensorflow笔记1--基本用法

tensorflow笔记1–基本用法


1. tensorflow编程的基本框架

  • 导入所需要的包
  • 准备数据
  • 构建模型/构建图
    • 定义变量、计算op
    • 定义优化目标及方法op
    • 定义初始化op
  • 启动/运行图
    • 运行初始化op
    • 运行优化目标及方法op
#导入包
import tensorflow as tf
import numpy as np

# 准备数据。使用numpy生成假2行100列的数据即100个二维点。
# .randn()表示标准正态分布;.rand()表示[0,1)均匀分布。括号内为数据的shape。 
x_data = np.float32(np.random.rand(2, 100))    
y_data = np.dot([0.100, 0.200], x_data) + 0.300

# 构建模型/构建图
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
# 定义目标及方法
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
# 初始化变量,旧版本为tf.initialize_all_variables()
init = tf.global_variables_initializer() 

# 启动/运行图
sess = tf.Session()
sess.run(init)
# 拟合平面,不断运行train来更新参数。
for step in range(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]

2. 构建图

  • 创建placeholder,常量,变量的op
  • 创建计算的op
  • 创建优化目标及方法的op
  • 创建初始化op
#placeholder。None表示任意数
x = tf.placeholder(tf.float32,[None, 2],name="x_input")

with tf.Session() as sess:
    input=sess.run(x, feed_dict={x:[7.3.]})

#常量op。例:1x2常量矩阵。
tf.constant([[0., 0.]])
tf.constant(0., shape=[1,2])
tf.constant(tf.zero([1,2]))

#变量op。例:1x2变量矩阵。
tf.Variable(tf.zeros([12]))
tf.Variable([[0., 0.]])
tf.Variable(tf.random_randn([1, 2])
tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))

#计算op。例:矩阵相乘
tf.constant([[3., 3.]])

#目标及方法的op
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

#初始化op
init = tf.global_variables_initializer() 

3. 运行图

法一:

# 启动默认图.
sess = tf.Session()

#运行op
los=sess.run(loss)
sess.run(train)

# 任务完成, 关闭会话.
sess.close()

#为了便于使用诸如 IPython 之类的 Python 交互环境, 可以使用InteractiveSession 代替 Session 类。
#使用 Tensor.eval() 和 Operation.run() 方法代替 Session.run()。这样可以避免使用一个变量来持有会话.
sess = tf.InteractiveSession()
x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

# 使用初始化器 initializer op 的 run() 方法初始化 'x' 
x.initializer.run()

# 增加一个减法op。使用eval方法。 
sub = tf.sub(x, a)
print (sub.eval())

法二:

#自动关闭会话
with tf.Session() as sess:
    los=sess.run(loss)
    sess.run(train)

#指定CPU或GPU
with tf.Session() as sess:
    with tf.device("/gpu:1"):
        matrix1 = tf.constant([[3., 3.]])
        matrix2 = tf.constant([[2.],[2.]])
        product = tf.matmul(matrix1, matrix2)

猜你喜欢

转载自blog.csdn.net/wang_jiankun/article/details/80668302