4、TF實作計算功能
TF:Tensorflow定義變量+常量,實作輸出計數功能
輸出結果
代碼設計
#TF:Tensorflow定義變量+常量,實作輸出計數功能
import tensorflow as tf
state = tf.Variable(0, name='Parameter_name_counter')
#print(state.name)
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(8):
sess.run(update)
print(sess.run(state))
5、TF:Tensorflow完成一次線性函數計算
#TF:Tensorflow完成一次線性函數計算
#思路:TF像搭積木一樣将各個不同的計算子產品拼接成流程圖,完成一次線性函數的計算,并在一個隐式會話中執行。
matrix1 = tf.constant([[3., 3.]]) #聲明matrix1為TF的一個1*2的行向量
matrix2 = tf.constant([[2.],[2.]]) #聲明matrix2為TF的一個2*1的列向量
product = tf.matmul(matrix1, matrix2) #兩個算子相乘,作為新算例
linear = tf.add(product, tf.constant(2.0)) #将product與一個标量2求和拼接.作為最終的linear算例
#直接在會話中執行linear算例,相當于将上面所有的單獨算例拼接成流程圖來執行
with tf.Session() as sess:
result = sess.run(linear)
print(result)
Tensorflow的基礎案例
1、TF根據三維資料拟合平面
Python 程式生成了一些三維資料, 然後用一個平面拟合它.
import numpy as np
# 使用 NumPy 生成假資料(phony data), 總共 100 個點.
x_data = np.float32(np.random.rand(2, 100)) # 随機輸入
y_data = np.dot([0.100, 0.200], x_data) + 0.300
# 構造一個線性模型
#
b = tf.Variable(tf.zeros([1]))
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
y = tf.matmul(W, x_data) + b
# 最小化方差
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
# 初始化變量
init = tf.initialize_all_variables()
# 啟動圖 (graph)
sess = tf.Session()
sess.run(init)
# 拟合平面
for step in xrange(0, 201):
sess.run(train)
if step % 20 == 0:
print step, sess.run(W), sess.run(b)
# 得到最佳拟合結果 W: [[0.100 0.200]], b: [0.300]
Tensorflow的經典案例
後期更新……