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)]