tensorflow基本用法个人笔记

综述

  TensorFlow程序分为构建阶段和执行阶段。通过构建一个图、执行这个图来得到结果。

构建图

  创建源op,源op不需要任何输入,例如常量constant,源op的输出被传递给其他op做运算。

import tensorflow as tf

# 创建一个常量 op, 产生一个 1x2 矩阵. 这个 op 被作为一个节点
matrix1 = tf.constant([[3., 3.]])

# 创建另外一个常量 op, 产生一个 2x1 矩阵.
matrix2 = tf.constant([[2.],[2.]])

# 创建一个矩阵乘法 matmul op , 把 'matrix1' 和 'matrix2' 作为输入.
# 返回值 'product' 代表矩阵乘法的结果.
product = tf.matmul(matrix1, matrix2)

在一个会话中启动图

  构造图之后,需要创建Session对象来启动图。

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

#执行刚才的图
result = sess.run(product)
print result
# ==> [[ 12.]]

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

  使用“with”代码块来自动完成关闭动作。

with tf.Session() as sess:
    result = seff.run([product])
    print result

  Tensorflow一般自动检测GPU来执行操作,并默认使用第一个GPU,因此有些情况可能需要手动指定GPU。with...Device

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)
    ...
  • "/cpu:0":机器的CPU
  • "/gpu:0":机器的第一个GPU
  • "/gpu:1":机器的第二个GPU

交互式使用

# 进入一个交互式 TensorFlow 会话.
import tensorflow as tf
sess = tf.InteractiveSession()

x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

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

# 增加一个减法 sub op, 从 'x' 减去 'a'. 运行减法 op, 输出结果 
sub = tf.sub(x, a)
print sub.eval()
# ==> [-2. -1.]

Tensor(张量)

  TensorFlow程序使用tensor数据结构来代表所有数据。

变量

# 创建一个变量, 初始化为标量 0.
state = tf.Variable(0, name="counter")

one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value) #将新值赋给变量state

# 启动图后, 变量必须先经过`初始化` (init) op 初始化,
init_op = tf.initialize_all_variables()

# 启动图, 运行 op
with tf.Session() as sess:
  # 运行 'init' op 来初始化变量
  sess.run(init_op)
  # 打印 'state' 的初始值
  print sess.run(state)
  # 运行 op, 更新 'state', 并打印 'state'
  for _ in range(3):
    sess.run(update)
    print sess.run(state)

# 输出:
# 0
# 1
# 2
# 3

Feed

input1 = tf.placeholder(tf.types.float32)
input2 = tf.placeholder(tf.types.float32)
#placeholder为临时占位符
output = tf.mul(input1, input2)

with tf.Session() as sess:
  print sess.run([output], feed_dict={input1:[7.], input2:[2.]})
  #这里通过feed_dict将数据填入刚才的占位符。
# 输出:
# [array([ 14.], dtype=float32)]

参考网址:TensorFlow中文社区

猜你喜欢

转载自www.cnblogs.com/Kingham/p/12046549.html