天天看點

機器學習-線性回歸課後筆記

前言:

 ​

過完理論學習,還是要動手實踐,吳恩達老師的布置的課後作業可在courses上報名就可以看 ​

練習題目:

預測房價,内容參照ex1.pdf

實作代碼+注釋:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 數據特點
path = 'ex1data1.txt'
data = pd.read_csv(path, header=None, names=['Population', 'Profit'])
print(data.head())
print(data.describe())

# 看下資料長什麼樣子
data.plot(kind='scatter', x='Population', y='Profit', figsize=(12,8))
plt.show()

#成本函數:
def computeCost(X, y, theta):
inner = np.power(((X * theta.T) - y), 2)
return np.sum(inner) / (2 * len(X))

data.insert(0, 'Ones', 1)

# set X (training data) and y (target variable)
cols = data.shape[1]
X = data.iloc[:,0:cols-1]#X是所有行,去掉最後一列
y = data.iloc[:,cols-1:cols]#X是所有行,最後一列

print(X.head())#head()是觀察前5行

X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))
print(theta)

#看一下維度
print(X.shape,theta.shape,y.shape)

#計算代價函數 (theta初始值為0).
print(computeCost(X, y, theta))

# batch gradient decent(批量梯度下降)
def gradientDescent(X, y, theta, alpha, iters):
temp = np.matrix(np.zeros(theta.shape))
parameters = int(theta.ravel().shape[1])
cost = np.zeros(iters)

for i in range(iters):
error = (X * theta.T) - y

for j in range(parameters):
term = np.multiply(error, X[:, j])
temp[0, j] = theta[0, j] - ((alpha / len(X)) * np.sum(term))

theta = temp
cost[i] = computeCost(X, y, theta)

return theta, cost
# 初始化一些附加變量 - 學習速率α和要執行的疊代次數。
alpha = 0.01
iters = 1000
# 現在讓我們運作梯度下降算法來将我們的參數θ适合于訓練集。
g, cost = gradientDescent(X, y, theta, alpha, iters)
print(g)

# 最後,我們可以使用我們拟合的參數計算訓練模型的代價函數(誤差)。
print(computeCost(X, y, g))

#現在我們來繪制線性模型以及資料,直覺地看出它的拟合。
x = np.linspace(data.Population.min(), data.Population.max(), 100)
f = g[0, 0] + (g[0, 1] * x)

fig, ax = plt.subplots(figsize=(12,8))
ax.plot(x, f, 'r', label='Prediction')
ax.scatter(data.Population, data.Profit, label='Traning Data')
ax.legend(loc=2)
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('Predicted Profit vs. Population Size')
plt.show()

#由于梯度方程式函數也在每個訓練疊代中輸出一個代價的向量,是以我們也可以繪制。 請注意,代價總是降低 - 這是凸優化問題的一個例子。
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(np.arange(iters), cost, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title('Error vs. Training Epoch')
plt.show()


path =  'ex1data2.txt'
data2 = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
print(data2.head())

# 特征歸一化
data2 = (data2 - data2.mean())/ data2.std()
print(data2.head())

# 現在我們重複第1部分的預處理步驟,并對新資料集運作線性回歸程式。
# 添加ones 一列
data2.insert(0,'Ones',1)

# 設定 X(訓練的資料),y是目标變量
cols = data2.shap[1]
X2 = data2.iloc[:,0:cols-1]
y2 = data2.iloc[:,cols-1:cols]

# 轉換為矩陣并初始化
X2 = np.matrix(X2.values)
y2 = np.matrix(y2.values)
theta = np.matrix(np.array([0,0,0]))

# 對資料集執行線性回歸
g2 , cost2 = gradientDescent(X2,y2,theta,alpha,iters)

#得到模型的成本(誤差)
computeCost(X2)      

結果分析:

機器學習-線性回歸課後筆記

拟合直線

機器學習-線性回歸課後筆記

梯度下降算法的拟合圖示

機器學習-線性回歸課後筆記

正規方程算法的拟合圖示

總的來說,隻要特征變量的數目并不大,正規方程是一個很好的計算參數的替代方法。具體地說,隻要特征變量數量小于1w,通常使用正規方程法,而不是用梯度下降法。

線性回歸方程是非常重要的一個基礎知識,後面需要重點回顧。