Professional Documents
Culture Documents
Python TensorFlow
郭忠義
jykuo@ntut.edu.tw
臺北科技大學資訊工程系
1
Linear Regression
線性迴歸
找到一條直線方程式 H = W*X + b,擬合藍色線,Y = X
訓練資料,X=[1, 2, 3],Y = [1, 2, 3]
用微分法求極值,將上式分別對和做一階偏微分,並令
其等於0:
Linear Regression
此二元一次線性方程組可用克萊姆法則求解,得解
sklearn
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
def linearTest(x, y):
from sklearn.linear_model import LinearRegression
#轉成陣列
x = np.array(x).reshape(len(x),1)
def linearIris():
y = np.array(y).reshape(len(y),1)
hua = load_iris()
clf = LinearRegression()
#獲取花瓣的長和寬
clf.fit(x,y)
x = [n[0] for n in hua.data]
pre = clf.predict(x)
y = [n[1] for n in hua.data]
#畫圖
linearTest(x, y)
plt.scatter(x,y,s=100)
x = [1, 2, 3, 4, 5]
plt.plot(x,pre,"r-",linewidth=4)
y = [1, 5, 9, 12,14]
for idx, m in enumerate(x):
linearTest(x, y)
plt.plot([m,m],[y[idx],pre[idx]], 'g-')
x = np.random.rand(100).astype(np.float32)
plt.show()
y = x * 0.1 + 0.3
print("係數", clf.coef_)
linearTest(x, y)
print("截距", clf.intercept_)
print(np.mean(y-pre)**2)
print(clf.predict([[5.0]]))
TensorFlow
線性迴歸
訓練資料,X= [1, 2, 3],Y = [1, 2, 3],使用佔位函式,
後面再給訓練資料的值。
建構直線方程式 H = W*X + b,隨機值初始化 W、b。
W = tf.Variable(tf.random_normal([1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
X = tf.placeholder(tf.float32, shape=[None])
Y = tf.placeholder(tf.float32, shape=[None])
print(W, b, X, Y)
# Our H (hypothesis) XW+b
H=X*W+b
TensorFlow
線性迴歸
建構損失函式(loss/cost function),使用最小方差。
最佳化器,使用梯度最佳化,學習率 0.001。
# cost/loss function
cost = tf.reduce_mean(tf.square(H - Y))
# Minimize
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)
TensorFlow
線性迴歸
執行計算圖訓練(會話 Session),初始化全部變數。
訓練 2001次,以 feed_dict 輸入佔位變數 X, Y 測試資料。
線性回歸 邏輯回歸
變量服從常態分布 是 否
函數值在[0,1]間
3. TensorFlow
範例–邏輯迴歸
從訓練數據特徵學習出一個 0/1分類模型。預測函數
𝑧 𝜃 𝜃 𝑥 𝜃 𝑥 … 𝜃 𝑥 𝜃 𝑥
1 1
ℎ 𝑧 ,ℎ 𝑥
1 𝑒 1 𝑒
將線性函式映射到sigmoid函式,Sigmoid函式
1
𝑦
1 𝑒
ℎ 𝑥 <0.5,說明目前資料屬於0類
ℎ 𝑥 >0.5,說明目前資料屬於1類
3. TensorFlow
範例–邏輯迴歸
優點:計算代價不高,易於理解和實現;
缺點:容易欠擬合,分類精度不高
觀測值的機率(極大似然機率)
損失代價函數:
3. TensorFlow
範例–邏輯迴歸
3. TensorFlow
範例–Softmax迴歸
3. TensorFlow
範例–Softmax迴歸
執行結果,W趨近 1 、b 趨近 0。
當多分類問題時,logistic推廣為softmax.
假設函數
損失函數
為解決softmax回歸的參數冗余帶來的數值問題,可以加入權
重衰減項