吳恩達機器學習作業1- 線性回歸作業(python實現)


機器學習練習1 python復現- 線性回歸

單變量線性回歸

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'])
data.head()

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是所有行,最后一列

觀察下 X (訓練集) and y (目標變量)是否正確.

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

y.head()

代價函數是應該是numpy矩陣,所以我們需要轉換X和Y,然后才能使用它們。 我們還需要初始化theta。

#使得numpy得到的數組矩陣化
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))

theta 是一個(1,2)矩陣

theta
matrix([[0, 0]])

看下維度

X.shape, theta.shape, y.shape
((97, 2), (1, 2), (97, 1))

計算代價函數 (theta初始值為0).

computeCost(X, y, theta)
32.072733877455676

batch gradient decent(批量梯度下降)

def gradientDescent(X, y, theta, alpha, iters):
    temp = np.matrix(np.zeros(theta.shape))
    #ravel使多維矩陣降為一維,獲取得到相應矩陣元素的個數
    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)
g
matrix([[-3.24140214,  1.1272942 ]])

最后,我們可以使用我們擬合的參數計算訓練模型的代價函數(誤差)。

computeCost(X, y, g)
4.5159555030789118

現在我們來繪制線性模型以及數據,直觀地看出它的擬合。

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()


多變量線性回歸

練習1還包括一個房屋價格數據集,其中有2個變量(房子的大小,卧室的數量)和目標(房子的價格)。 我們使用我們已經應用的技術來分析數據集。

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

對於此任務,我們添加了另一個預處理步驟 - 特征歸一化。 這個對於pandas來說很簡單

data2 = (data2 - data2.mean()) / data2.std()
data2.head()

現在我們重復第1部分的預處理步驟,並對新數據集運行線性回歸程序。

# add ones column
data2.insert(0, 'Ones', 1)

# set X (training data) and y (target variable)
cols = data2.shape[1]
X2 = data2.iloc[:,0:cols-1]
y2 = data2.iloc[:,cols-1:cols]

# convert to matrices and initialize theta
X2 = np.matrix(X2.values)
y2 = np.matrix(y2.values)
theta2 = np.matrix(np.array([0,0,0]))

# perform linear regression on the data set
g2, cost2 = gradientDescent(X2, y2, theta2, alpha, iters)

# get the cost (error) of the model
computeCost(X2, y2, g2)
0.13070336960771892

我們也可以快速查看這一個的訓練進程。

fig, ax = plt.subplots(figsize=(12,8))
ax.plot(np.arange(iters), cost2, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title('Error vs. Training Epoch')
plt.show()


我們也可以使用scikit-learn的線性回歸函數,而不是從頭開始實現這些算法。 我們將scikit-learn的線性回歸算法應用於第1部分的數據,並看看它的表現。

from sklearn import linear_model
model = linear_model.LinearRegression()
model.fit(X, y)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

scikit-learn model的預測表現

x = np.array(X[:, 1].A1)
f = model.predict(X).flatten()

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()


4. normal equation(正規方程)

# 正規方程
def normalEqn(X,y):
    #linalg.inv表示求逆
    theta = np.linalg.inv(X.T.dot(X)).dot(X.T.dot(y))
    return theta
final_theta2=normalEqn(X, y)#感覺和批量梯度下降的theta的值有點差距
final_theta2
matrix([[-3.89578088],
        [ 1.19303364]])

梯度下降得到的結果是matrix([[-3.24140214, 1.1272942 ]])


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM