pip3 install tensorflow
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) # 啓動默認圖 # 調用sess的run()方法來執行矩陣乘法的op,傳入值爲product,輸出矩陣的乘法op # 返回值是一個numpy.ndarray對象 with tf.Session() as sess: result = sess.run(product) print(type(result),result)
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)
import tensorflow as tf # 建立變量,初始化爲標量0 state = tf.Variable(0, name='counter') # 建立一個op,使state增長1 one = tf.constant(1) new_value = tf.add(state, one) update = tf.assign(state, new_value) # 初始全部化變量 init_op = tf.global_variables_initializer() # 啓動圖,運行op with tf.Session() as sess: # 運行init sess.run(init_op) print(sess.run(state)) for _ in range(3): sess.run(update) print('new_value:',sess.run(new_value)) print('state:',sess.run(state))
import tensorflow as tf input1 = tf.constant(3.0) input2 = tf.constant(2.0) input3 = tf.constant(5.0) intermed = tf.add(input2, input3) mul = tf.multiply(input1, intermed) with tf.Session() as sess: result = sess.run([mul, intermed]) print(result)
tf.placeholder(dtype, shape=None, name=None):佔位符沒有初始值,但必須指定類型數組
參數:數據結構
dtype:數據類型,tf.int32,float32,string等dom
shape:數據形狀,默認None,shape=1,shape=[2,3],shape=[None,3]fetch
name:名稱spa
返回:Tensor類型code
feed_dict:字典,給出placeholder的值對象
import tensorflow as tf
import numpy as np
# exp-1 x = tf.placeholder(tf.string) with tf.Session() as sess: output = sess.run(x, feed_dict={x: 'Hello World!'}) print(output) # exp-2 x = tf.placeholder(tf.string) y = tf.placeholder(tf.int32) z = tf.placeholder(tf.float32) with tf.Session() as sess: output = sess.run([x,y,z], feed_dict={x: 'Hello World!', y:1, z:0.1}) print(output)
# exp-3 x = tf.placeholder(tf.float32, shape=(None,3)) y = tf.matmul(x, x) with tf.Session() as sess: rand_array = np.random.rand(3,3) print(sess.run(y, feed_dict={x: rand_array}))