tensorflow basic usage of personal notes

Overview

  TensorFlow program is divided into the build phase and the implementation phase. By constructing a graph, the result obtained by the implementation of the FIG.

Construction diagram

  Create source op, op source does not need any input, e.g. constant constantoutput, the source is transmitted to the other op op op do.

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)

In a session start FIG.

  After constructing the map, we need to create Sessionobjects to start drawing.

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

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

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

  Use "with" block of code to automatically shut down the operation.

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

  Usually Tensorflow GPU to perform the operations automatically detected, and defaults to the first GPU, so in some cases may need to manually specify 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

Interactive use

# 进入一个交互式 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 (tensor)

  TensorFlow program uses tensor data structure to represent all data.

variable

# 创建一个变量, 初始化为标量 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)]

Reference website: TensorFlow Chinese community

Guess you like

Origin www.cnblogs.com/Kingham/p/12046549.html