1、一元線性回歸
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
a = 2 # 權重
b = 1.5 # 偏置
# 設定隨機種子
np.random.seed(5)
# 生成100個點,區間為-1到1
x_data = np.linspace(-1, 1, 100)
# y = x_data * a + b + 雜訊
y_data = a * x_data + b + np.random.randn(*x_data.shape) * 0.2
# 畫出散點圖
plt.scatter(x_data, y_data)
# 想要學習到的線性函式 y = x_data * a + b
# plt.plot(x_data, x_data * a + b,color='red', linewidth=3)
plt.show()
# 定義訓練資料的佔位符 x為特徵 y為標籤
x = tf.placeholder('float', name='x')
y = tf.placeholder('float', name='y')
# 定義模型函式
def model(x, w, b):
return tf.multiply(x, w) + b
# 構建線性函式的斜率w
w = tf.variable(0.5, name='w')
b = tf.variable(0.0, name='b')
# 前向計算 y = w * x + b
pred = model(x, w, b)
# 使用均方差損失函式
loss_function = tf.reduce_mean(tf.square(y - pred))
# 使用梯度下降優化器
optimizer = tf.train.gradientdescentoptimizer(0.05).minimize(loss_function)
with tf.session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op) # 初始化所有變數
for step in range(5):
for xs, ys in zip(x_data, y_data):
# 執行計算圖
_, loss = sess.run([optimizer, loss_function], \
feed_dict=)
print('w:', sess.run(w), ' b:', sess.run(b))
plt.scatter(x_data, y_data)
plt.plot(x_data, x_data * sess.run(w) + sess.run(b), \
color='red', linewidth=3)
plt.show()
x_test = 5
y = x_test * 2 + 1.5
y_out = x_test * sess.run(w) + sess.run(b)
print('真實結果:', y)
print('**結果', y_out)
Tensorflow卷積神經網路
卷積神經網路 convolutional neural network,cnn 是一種前饋神經網路,在計算機視覺等領域被廣泛應用.本文將簡單介紹其原理並分析tensorflow官方提供的示例.關於神經網路與誤差反向傳播的原理可以參考作者的另一篇博文bp神經網路與python實現.卷積是影象處理中一種...
Tensorflow 深層神經網路
維基百科對深度學習的定義 一類通過多層非線性變換對高複雜性資料建模演算法的合集.tensorflow提供了7種不同的非線性啟用函式,常見的有tf.nn.relu,tf.sigmoid,tf.tanh.使用者也可以自己定義啟用函式.3.1.1 交叉熵 用途 刻畫兩個概率分布之間的距離,交叉熵h越小,兩...
Tensorflow(三) 神經網路
1 前饋傳播 y x w1 b1 w2 b2 import tensorflow as tf x tf.constant 0.9,0.85 shape 1,2 w1 tf.variable tf.random normal 2,3 stddev 1,seed 1 name w1 w2 tf.vari...