有一個(gè)開源的、商業(yè)上可用的機(jī)器學(xué)習(xí)工具包,叫做scikit-learn。這個(gè)工具包包含了你將在本課程中使用的許多算法的實(shí)現(xiàn)。
實(shí)驗(yàn)一
目標(biāo)
在本實(shí)驗(yàn)中,你將:利用scikit-learn實(shí)現(xiàn)使用梯度下降的線性回歸
工具
您將使用scikit-learn中的函數(shù)以及matplotlib和NumPy。
import numpy as np
np.set_printoptions(precision=2)
from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.preprocessing import StandardScaler
from lab_utils_multi import load_house_data
import matplotlib.pyplot as plt
dlblue = '#0096ff'; dlorange = '#FF9300'; dldarkred='#C00000'; dlmagenta='#FF40FF'; dlpurple='#7030A0';
plt.style.use('./deeplearning.mplstyle')
np.set_printoptions(precision=2) 的作用是告訴 NumPy 在打印數(shù)組時(shí)只保留浮點(diǎn)數(shù)的兩位小數(shù)。
梯度下降
Scikit-learn有一個(gè)梯度下降回歸模型sklearn.linear_model.SGDRegressor。與之前的梯度下降實(shí)現(xiàn)一樣,該模型在規(guī)范化輸入時(shí)表現(xiàn)最好。sklearn預(yù)處理。StandardScaler將執(zhí)行z-score歸一化在以前的實(shí)驗(yàn)室。這里它被稱為“標(biāo)準(zhǔn)分?jǐn)?shù)”。
加載數(shù)據(jù)集
X_train, y_train = load_house_data()
X_features = ['size(sqft)','bedrooms','floors','age']
縮放/規(guī)范化訓(xùn)練數(shù)據(jù)
scaler = StandardScaler()
X_norm = scaler.fit_transform(X_train)
print(f"Peak to Peak range by column in Raw X:{np.ptp(X_train,axis=0)}")
print(f"Peak to Peak range by column in Normalized X:{np.ptp(X_norm,axis=0)}")
創(chuàng)建并擬合回歸模型
sgdr = SGDRegressor(max_iter=1000)
sgdr.fit(X_norm, y_train)
print(sgdr)
print(f"number of iterations completed: {sgdr.n_iter_}, number of weight updates: {sgdr.t_}")
這段代碼使用了 SGDRegressor 類來進(jìn)行線性回歸模型的訓(xùn)練和預(yù)測(cè)。
首先,通過SGDRegressor(max_iter=1000)
創(chuàng)建了一個(gè)隨機(jī)梯度下降(SGD)回歸器對(duì)象sgdr
,并設(shè)置最大迭代次數(shù)為 1000。
然后,使用sgdr.fit(X_norm, y_train)
對(duì)模型進(jìn)行擬合,其中X_norm
是經(jīng)過標(biāo)準(zhǔn)化處理后的特征數(shù)據(jù),y_train
是對(duì)應(yīng)的目標(biāo)變量。
接著,通過print(sgdr)
打印出sgdr
對(duì)象的相關(guān)信息,包括模型參數(shù)和超參數(shù)等。
最后,使用 f-string 格式化字符串,打印出訓(xùn)練完成的迭代次數(shù)sgdr.n_iter_
和權(quán)重更新次數(shù)sgdr.t_
。
查看參數(shù)
注意,參數(shù)與規(guī)范化的輸入數(shù)據(jù)相關(guān)聯(lián)。擬合參數(shù)與之前使用該數(shù)據(jù)的實(shí)驗(yàn)室中發(fā)現(xiàn)的非常接近。
b_norm = sgdr.intercept_
w_norm = sgdr.coef_
print(f"model parameters: w: {w_norm}, b:{b_norm}")
print(f"model parameters from previous lab: w: [110.56 -21.27 -32.71 -37.97], b: 363.16")
作出預(yù)測(cè)
預(yù)測(cè)訓(xùn)練數(shù)據(jù)的目標(biāo)。同時(shí)使用預(yù)測(cè)例程并使用w和b進(jìn)行計(jì)算。
# make a prediction using sgdr.predict()
y_pred_sgd = sgdr.predict(X_norm)
# make a prediction using w,b.
y_pred = np.dot(X_norm, w_norm) + b_norm
print(f"prediction using np.dot() and sgdr.predict match: {(y_pred == y_pred_sgd).all()}")
print(f"Prediction on training set:\n{y_pred[:4]}" )
print(f"Target values \n{y_train[:4]}")
繪制結(jié)果
讓我們繪制預(yù)測(cè)值與目標(biāo)值的對(duì)比圖。
# plot predictions and targets vs original features
fig,ax=plt.subplots(1,4,figsize=(12,3),sharey=True)
for i in range(len(ax)):
ax[i].scatter(X_train[:,i],y_train, label = 'target')
ax[i].set_xlabel(X_features[i])
ax[i].scatter(X_train[:,i],y_pred,color=dlorange, label = 'predict')
ax[0].set_ylabel("Price"); ax[0].legend();
fig.suptitle("target versus prediction using z-score normalized model")
plt.show()
恭喜
在這個(gè)實(shí)驗(yàn)中,你:利用開源機(jī)器學(xué)習(xí)工具包scikit-learn使用該工具包中的梯度下降和特征歸一化實(shí)現(xiàn)線性回歸
實(shí)驗(yàn)二
目標(biāo)
在本實(shí)驗(yàn)中,你將:利用scikit-learn實(shí)現(xiàn)基于正態(tài)方程的近似解線性回歸
工具
您將使用scikit-learn中的函數(shù)以及matplotlib和NumPy
import numpy as np
np.set_printoptions(precision=2)
from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.preprocessing import StandardScaler
from lab_utils_multi import load_house_data
import matplotlib.pyplot as plt
dlblue = '#0096ff'; dlorange = '#FF9300'; dldarkred='#C00000'; dlmagenta='#FF40FF'; dlpurple='#7030A0';
plt.style.use('./deeplearning.mplstyle')
線性回歸,閉式解
Scikit-learn具有線性回歸模型,實(shí)現(xiàn)了封閉形式的線性回歸。讓我們使用早期實(shí)驗(yàn)室的數(shù)據(jù)——一個(gè)1000平方英尺的房子賣了30萬美元,一個(gè)2000平方英尺的房子賣了50萬美元。
加載數(shù)據(jù)集
X_train = np.array([1.0, 2.0]) #features
y_train = np.array([300, 500]) #target value
創(chuàng)建并擬合模型
下面的代碼使用scikit-learn執(zhí)行回歸。第一步創(chuàng)建一個(gè)回歸對(duì)象。第二步使用與對(duì)象相關(guān)的方法之一fit。這將執(zhí)行回歸,將參數(shù)擬合到輸入數(shù)據(jù)。該工具包需要一個(gè)二維X矩陣。
linear_model = LinearRegression()
#X must be a 2-D Matrix
linear_model.fit(X_train.reshape(-1, 1), y_train)
查看參數(shù)
在scikit-learn中,w和b參數(shù)被稱為“系數(shù)”和“截距”
b = linear_model.intercept_
w = linear_model.coef_
print(f"w = {w:}, b = {b:0.2f}")
print(f"'manual' prediction: f_wb = wx+b : {1200*w + b}")
作出預(yù)測(cè)
調(diào)用predict函數(shù)生成預(yù)測(cè)。
y_pred = linear_model.predict(X_train.reshape(-1, 1))
print("Prediction on training set:", y_pred)
X_test = np.array([[1200]])
print(f"Prediction for 1200 sqft house: ${linear_model.predict(X_test)[0]:0.2f}")
第二個(gè)例子
第二個(gè)例子來自早期的一個(gè)具有多個(gè)特征的實(shí)驗(yàn)。最終的參數(shù)值和預(yù)測(cè)非常接近該實(shí)驗(yàn)室非標(biāo)準(zhǔn)化“長期”的結(jié)果。這種不正常的運(yùn)行需要幾個(gè)小時(shí)才能產(chǎn)生結(jié)果,而這幾乎是瞬間的。封閉形式的解決方案在諸如此類的較小數(shù)據(jù)集上工作得很好,但在較大的數(shù)據(jù)集上可能需要計(jì)算。
封閉形式的解不需要規(guī)范化
# load the dataset
X_train, y_train = load_house_data()
X_features = ['size(sqft)','bedrooms','floors','age']
linear_model = LinearRegression()
linear_model.fit(X_train, y_train)
b = linear_model.intercept_
w = linear_model.coef_
print(f"w = {w:}, b = {b:0.2f}")
這里的權(quán)重1和權(quán)重4,相對(duì)于權(quán)重2和權(quán)重3太小,不知道為什么這里不舍去
print(f"Prediction on training set:\n {linear_model.predict(X_train)[:4]}" )
print(f"prediction using w,b:\n {(X_train @ w + b)[:4]}")
print(f"Target values \n {y_train[:4]}")
x_house = np.array([1200, 3,1, 40]).reshape(-1,4)
x_house_predict = linear_model.predict(x_house)[0]
print(f" predicted price of a house with 1200 sqft, 3 bedrooms, 1 floor, 40 years old = ${x_house_predict*1000:0.2f}")
文章來源:http://www.zghlxwxcb.cn/news/detail-839797.html
恭喜
在這個(gè)實(shí)驗(yàn)中,你:利用開源機(jī)器學(xué)習(xí)工具包scikit-learn使用該工具包中的接近形式的解決方案實(shí)現(xiàn)線性回歸文章來源地址http://www.zghlxwxcb.cn/news/detail-839797.html
到了這里,關(guān)于吳恩達(dá)機(jī)器學(xué)習(xí)-可選實(shí)驗(yàn):使用ScikitLearn進(jìn)行線性回歸(Linear Regression using Scikit-Learn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!