1. 程式人生 > >TensorFlow入門筆記(一)基本操作

TensorFlow入門筆記(一)基本操作

result 官方教程 with orf print blog res ont constant

0. 環境配置

安裝Anaconda,python3環境,然後利用conda命令配置的tensorflow環境。

參考極客學院翻譯TensorFlow官方教程:http://wiki.jikexueyuan.com/project/tensorflow-zh/get_started/basic_usage.html

1. 基本操作

1.1 常數聲明

1 import tensorflow as tf
2 matrix1 = tf.constant([[3., 3.]])
3 matrix2 = tf.constant([[2.], [2.]])
4 product = tf.matmul(matrix1, matrix2)
5 print(matrix1) 6 print(matrix2) 7 print(product)

輸出結果:

Tensor("Const:0", shape=(1, 2), dtype=float32)
Tensor("Const_1:0", shape=(2, 1), dtype=float32)
Tensor("MatMul:0", shape=(1, 1), dtype=float32)

  

1.2 session執行operation

1 sess = tf.Session()
2 result = sess.run(product)
3 print(result)
4 result = sess.run(matrix1)
5 print(result)

輸出結果:

[[ 12.]]
[[ 3. 3.]]

1.3 operation操作變量

 1 state = tf.Variable(0, name="counter")
 2 one = tf.constant(1)
 3 new_value = tf.add(state, one)
 4 update = tf.assign(state, new_value)
 5 
 6 init_op = tf.global_variables_initializer()#初始化所有變量
 7 sess.run(init_op)
 8 for _ in range(3):
9   sess.run(update) 10   print(sess.run([state, new_value])) 11 sess.close()

輸出結果:

[1, 2]
[2, 3]
[3, 4]

1.4 placehold預占位

with tf.Session() as ss:
  input1 = tf.placeholder(tf.float32)
  input2 = tf.placeholder(tf.float32)
  output = tf.multiply(input1, input2)
  print(ss.run([output], feed_dict={input1:[7.], input2:[2.]}))

輸出結果:

[array([ 14.], dtype=float32)]

TensorFlow入門筆記(一)基本操作