Tensorflow基礎語法
阿新 • • 發佈:2018-12-12
import tensorflow as tf; import numpy as np; state = tf.Variable(0,name='counter') #引數值為0,name為counter # print(state.name) one = tf.constant(1) new_value = tf.add(state,one) update = tf.assign(state,new_value) #assgin英文是:賦值,分配,所以在這裡就是一個賦值過程 init = tf.initialize_all_variables() #如果定義變數一定需要 with tf.Session() as sess: sess.run(init) for _ in range(3): sess.run(update) print(sess.run(state))
import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt #create data 程式碼預測引數。就是為了預測weight接近0.1,biaes接近0.3 x_data = np.random.rand(100).astype(np.float32) y_data = x_data*0.1+0.3 # creat tensorflow structure start # Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0)) #生成一個隨機數列,是一維的,範圍是-1-1 biases = tf.Variable(tf.zeros([1])) #第一次賦值是0 y = Weights*x_data+biases loss = tf.reduce_mean(tf.square(y-y_data))#真實值和預測值的一個差 optimizer = tf.train.GradientDescentOptimizer(0.5)#優化器,optimizer可以有很多種選擇,先選擇GradientDescentOptimizer;0.5是一個學習效率,一般是小於一的數 train = optimizer.minimize(loss)#用優化器減少誤差 init = tf.initialize_all_variables()#都是需要初始化的,就是模型建立好了,需要初始化讓這個模型“活”起來 # creat tensorflow structure end # sess = tf.Session() sess.run(init) #結構啟用!!!sess就像一個指標指像init,並激活! for step in range(200): sess.run(train) if step % 20 == 0: print(step,sess.run(Weights),sess.run(biases))
import tensorflow as tf; import numpy as np; matrix1 = tf.constant([[3,3]]) #constnt恆量 matrix2 = tf.constant([[2],[2]]) product = tf.matmul(matrix1,matrix2) #matmul: matrix muliply 用np.dot(m1,m2)也是對兩個矩陣進行乘法運算 #method 1 # sess = tf.Session() # result = sess.run(product) #sess.run()返回值給result # print(result) #sess.close() #mesthod 2 with tf.Session() as sess: #用sess開啟tf.Session() print(sess.run(product)) #自動close
#placeholder是傳入值 import tensorflow as tf input1 = tf.placeholder(tf.float32) input2 = tf.placeholder(tf.float32) output = tf.multiply (input1,input2) with tf.Session() as sess: print(sess.run(output,feed_dict={input1:[7.],input2:[2.]})) #placeholder傳入的值是和先開始定義的資料是繫結的,在輸出的時候一定需要feed_dict