青縣做網(wǎng)站價格好看的網(wǎng)站ui
前言
有一個開源的、商業(yè)上可用的機器學習工具包,叫做scikit-learn。這個工具包包含了你將在本課程中使用的許多算法的實現(xiàn)。
目標
在本實驗中,你將:
- 利用scikit-learn實現(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')
注意點
可能會出現(xiàn)報錯 No module named ‘sklearn’
這是因為當前環(huán)境下未安裝scikit-learn
【解決辦法】:在cmd中輸入
pip install scikit-learn
梯度下降
Scikit-learn有一個梯度下降回歸模型sklearn.linear_model.SGDRegressor。與之前的梯度下降實現(xiàn)一樣,該模型在規(guī)范化輸入時表現(xiàn)最好。standardscaler將像之前的實驗一樣執(zhí)行z-score歸一化。這里它被稱為“標準分數(shù)”。
加載數(shù)據(jù)集
X_train, y_train = load_house_data()
X_features = ['size(sqft)','bedrooms','floors','age']
縮放/規(guī)范化訓練數(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_}")
視圖參數(shù)
注意,參數(shù)與規(guī)范化的輸入數(shù)據(jù)相關(guān)聯(lián)。擬合參數(shù)與之前使用該數(shù)據(jù)的實驗室中發(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")
做出預測
預測訓練數(shù)據(jù)的目標。使用’ predict '例程并使用 w w w和 b b b進行計算。
# 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é)果
讓我們繪制預測值與目標值的對比圖。
# 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()
祝賀
在這個實驗中,你:
-使用開源機器學習工具包scikit-learn
-實現(xiàn)線性回歸使用梯度下降和特征歸一化的工具包