1、代價函數
代價函數研究的本質: 本人認爲是在監督學習中找到代價最小,也就是說。是拿着知道結果的訓練樣本。先用假定的函數去預測,h(x)得出得值和真實得做比較。
2、線性迴歸模型
h(x)=X0 + aX
就是直線方程。這裏就是假設函數
3、多變量線性迴歸模型
4、特徵縮放
爲了使得梯度下降快一些,需要對特徵進行縮放。其實就是類似歸一化。
特徵縮放:x1=(x1- x平均)/範圍
範圍就是這個特徵的最大值減去最小值。 x平均就是這個特徵的平均值。
5、學習速率
6、線性迴歸習題
1)計算代價函數
adef computeCost(X, y, theta):
# 訓練數據的樣本個數
m = len(y)
# 這裏的X是包含x0=1這個值的,也就是先包裝好x
# 特徵值 h(theta),h(theta)=theta.T與向量X的乘積
# 預測函數
h = X.dot(theta.T)
# 代價函數沒累加的內項
inner = np.power((h - y), 2)
# 代價函數
j = sum(inner) / (2 * m)
return j
注意:這裏的X是標準的。也就是說已經包含了x0=1這一項了
2)點集輸出
def plotData(x, y):
plt.ion()
plt.figure()
plt.plot(x, y, 'x')
plt.axis([4, 24, -5, 25])
plt.xlabel("Population of City in 10,000s") # setting the x label as population
plt.ylabel("Profit in $10,000s") # setting the y label
plt.show()
3)梯度下降算法:
# 單變量的梯度下降算法
# X還是輸入變量的舉證
def gradientDescent(X, y, theta, alpha, num_iters):
# 訓練數據的樣本個數
m = len(y)
# 初始化一個ndarray,包含每次迭代後的cost
cost = np.zeros(num_iters)
for i in range(num_iters):
# 預測函數
h = X.dot(theta.T)
# 這裏又用了一次矩陣乘法。X是n*1的向量。 h是m*n的向量 ,theta是行向量
temp = theta - (alpha / m) * (h - y).T.dot(X) # 得出一個theta行向量
theta = temp
cost[i] = computeCost(X, y, theta)
return theta, cost
4)最終實現:
import matplotlib.pyplot as plt
import numpy as np
def plotData(x, y):
plt.ion()
plt.figure()
plt.plot(x, y, 'x')
plt.axis([4, 24, -5, 25])
plt.xlabel("Population of City in 10,000s") # setting the x label as population
plt.ylabel("Profit in $10,000s") # setting the y label
plt.show()
if __name__ == "__main__":
data = np.loadtxt('ex1data1.txt', delimiter=",")
X = data[:, 0]
y = data[:, 1]
plotData(X, y)