數(shù)據(jù)集來源UCI Machine Learning Repository: Abalone Data Set
目錄
一、數(shù)據(jù)集探索性分析
二、鮑魚數(shù)據(jù)預(yù)處理
1.對sex特征進(jìn)行OneHot編碼,便于后續(xù)模型納入啞變量
2.添加取值為1的特征
3.?計算鮑魚的真實(shí)年齡
4.篩選特征
5.?將鮑魚數(shù)據(jù)集劃分為訓(xùn)練集和測試集
三、實(shí)現(xiàn)線性回歸和嶺回歸
1.?使用Numpy使用線性回歸
2.使用Sklearn實(shí)現(xiàn)線性回歸
3.使用numpy實(shí)現(xiàn)嶺回歸
4.?利用sklearn實(shí)現(xiàn)嶺回歸
四、?使用LASSO構(gòu)建鮑魚年齡預(yù)測模型
五、?鮑魚年齡預(yù)測模型效果評估
1.計算MAE、MSE及R2系數(shù)
2.殘差圖
一、數(shù)據(jù)集探索性分析
import pandas as pd import numpy as np import seaborn as sns data = pd.read_csv("abalone_dataset.csv") data.head()
#查看數(shù)據(jù)集中樣本數(shù)量和特征數(shù)量 data.shape #查看數(shù)據(jù)信息,檢查是否有缺失值 data.info()
?
data.describe()
?
數(shù)據(jù)集一共有4177個樣本,每個樣本有9個特征。其中rings為鮑魚環(huán)數(shù),加上1.5等于鮑魚年齡,是預(yù)測變量。除了sex為離散特征,其余都為連續(xù)變量。
#觀察sex列的取值分布情況 import numpy as np import matplotlib.pyplot as plt %matplotlib inline sns.countplot(x='sex',data=data) data['sex'].value_counts()
對于連續(xù)特征,可以使用seaborn的distplot函數(shù)繪制直方圖觀察特征取值情況。我們將8個連續(xù)特征的直方圖繪制在一個4行2列的子圖布局中。
i=1 plt.figure(figsize=(16,8)) for col in data.columns[1:]: plt.subplot(4,2,i) i=i+1 sns.distplot(data[col]) plt.tight_layout()
?
sns.pairplot()官網(wǎng)?seaborn.pairplot — seaborn 0.12.2 documentation
默認(rèn)情況下,此函數(shù)將創(chuàng)建一個軸網(wǎng)格,這樣數(shù)據(jù)中的每個數(shù)字變量將在單行的y軸和單列的x軸上共享。對角圖的處理方式不同:繪制單變量分布圖以顯示每列數(shù)據(jù)的邊際分布。也可以顯示變量的子集或在行和列上繪制不同的變量。
#連續(xù)特征之間的散點(diǎn)圖 sns.pairplot(data,hue='sex')
* 1.第一行觀察得出:length和diameter、height存在明顯的線性關(guān)系
* 2.最后一行觀察得出:rings與各個特征均存在正相關(guān)性,其中與height的線性關(guān)系最為直觀
* 3.對角線觀察得出:sex“I”在各個特征取值明顯小于成年鮑魚
#計算特征之間的相關(guān)系數(shù)矩陣 corr_df = data.corr() corr_df
fig,ax =plt.subplots(figsize=(12,12)) #繪制熱力圖 ax = sns.heatmap(corr_df,linewidths=5, cmap='Greens', annot=True, xticklabels=corr_df.columns, yticklabels=corr_df.index) ax.xaxis.set_label_position('top') ax.xaxis.tick_top()
二、鮑魚數(shù)據(jù)預(yù)處理
1.對sex特征進(jìn)行OneHot編碼,便于后續(xù)模型納入啞變量
#類別變量--無先后之分,使用OneHot編碼 #使用Pandas的get_dummies函數(shù)對sex特征做OneHot編碼處理 sex_onehot =pd.get_dummies(data['sex'],prefix='sex') #prefix--前綴 data[sex_onehot.columns] = sex_onehot #將set_onehot加入data中 data.head()
2.添加取值為1的特征
#截距項(xiàng) data['ones']=1 data.head()
3.?計算鮑魚的真實(shí)年齡
data["age"] =data['rings']+1.5 data.head()
4.篩選特征
多重共線性
*最小二乘的參數(shù)估計為如果變量之間存在較強(qiáng)的共線性,則$X^TX$近似奇異,對參數(shù)的估計變得不準(zhǔn)確,造成過度擬合現(xiàn)象。
*解決辦法:正則化、主成分回歸、偏最小二乘回歸所以sex_onehot的三列,線性相關(guān),三列取兩列選入x中
y=data['rings'] #不使用sklearn(包含ones) features_with_ones=['length', 'diameter', 'height', 'whole weight', 'shucked weight', 'viscera weight', 'shell weight', 'sex_F', 'sex_I','ones' ] #使用sklearn(不包含ones) features_without_ones=['length', 'diameter', 'height', 'whole weight', 'shucked weight', 'viscera weight', 'shell weight', 'sex_F', 'sex_I'] X=data[features_with_ones]
5.?將鮑魚數(shù)據(jù)集劃分為訓(xùn)練集和測試集
#80%為訓(xùn)練集,20%為測試集 from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=111)
三、實(shí)現(xiàn)線性回歸和嶺回歸
1.?使用Numpy使用線性回歸
#判斷xTx是否可逆,并計算得出w #解析解求線性回歸系數(shù) def linear_regression(X,y): w = np.zeros_like(X.shape[1]) if np.linalg.det(X.T.dot(X))!=0: w = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y) return w
#使用上述實(shí)現(xiàn)的線性回歸模型在鮑魚訓(xùn)練集上訓(xùn)練模型 w1=linear_regression(X_train,y_train)
w1 = pd.DataFrame(data=w1,index=X.columns,columns=['numpy_w']) w1.round(decimals=2)
所以,?求得的模型為
y=-1.12 * length + 10 * diameter + 20.74 * height + 9.61 * whole_weight - 20.05 * shucked_weight - 12.07 * viscera - weight + 6.55 * shell_weight + 0.01 * sex_F - 0.37 * sex_I + 3.70
2.使用Sklearn實(shí)現(xiàn)線性回歸
from sklearn.linear_model import LinearRegression lr = LinearRegression() lr.fit(x_train[features_without_ones],y_train) print(lr.coef_)
w_lr = [] w_lr.extend(lr.coef_) w_lr.append(lr.intercept_) w1['lr_sklearn_w']=w_lr w1.round(decimals=2)
3.使用numpy實(shí)現(xiàn)嶺回歸
def ridge_regression(X,y,ridge_lambda): penalty_matrix = np.eye(X.shape[1]) penalty_matrix[X.shape[1] - 1][X.shape[1] - 1] = 0 w=np.linalg.inv(X.T.dot(X) + ridge_lambda*penalty_matrix).dot(X.T).dot(y) return w
#正則化系數(shù)設(shè)置為1 w2 = ridge_regression(X_train,y_train,1.0) print(w2)
w1['numpy_ridge_w']=w2 w1.round(decimals=2)
?
4.?利用sklearn實(shí)現(xiàn)嶺回歸
from sklearn.linear_model import Ridge ridge = Ridge(alpha=1.0) ridge.fit(X_train[features_without_ones],y_train) w_ridge = [] w_ridge.extend(ridge.coef_) w_ridge.append(ridge.intercept_) w1["ridge_sklearn_w"] = w_ridge w1.round(decimals=2)
?嶺跡分析
alphas = np.logspace(-10,10,20) coef = pd.DataFrame() for alpha in alphas: ridge_clf = Ridge(alpha=alpha) ridge_clf.fit(X_train[features_without_ones],y_train) df = pd.DataFrame([ridge_clf.coef_],columns=X_train[features_without_ones].columns) df['alpha']=alpha coef = coef.append(df,ignore_index=True) coef.round(decimals=2)
import matplotlib.pyplot as plt %matplotlib inline #繪圖 #顯示中文和正負(fù)號 plt.rcParams['font.sans-serif']=['SimHei','Times New Roman'] plt.rcParams['axes.unicode_minus']=False plt.rcParams['figure.dpi']=300#分辨率 plt.figure(figsize=(9,6)) coef['alpha']=coef['alpha'] for feature in X_train.columns[:-1]: plt.plot('alpha',feature,data=coef) ax=plt.gca() ax.set_xscale('log') plt.legend(loc='upper right') plt.xlabel(r'$\alpha$',fontsize=15) plt.ylabel('系數(shù)',fontsize=15)
四、?使用LASSO構(gòu)建鮑魚年齡預(yù)測模型
LASSO的目標(biāo)函數(shù)
隨著??增大,LASSO的特征系數(shù)逐個減小為0,可以做特征選擇;而嶺回歸變量系數(shù)幾乎趨近與0
from sklearn.linear_model import Lasso lasso=Lasso(alpha=0.01) lasso.fit(X_train[features_without_ones],y_train) print(lasso.coef_) print(lasso.intercept_)
#LASSO的正則化渠道 coef1 = pd.DataFrame() for alpha in np.linspace(0.0001,0.2,20): lasso_clf = Lasso(alpha=alpha) lasso_clf.fit(X_train[features_without_ones],y_train) df = pd.DataFrame([lasso_clf.coef_],columns=X_train[features_without_ones].columns) df['alpha']=alpha coef1 = coef1.append(df,ignore_index=True) coef1.head() plt.figure(figsize=(9,6),dpi=600) for feature in X_train.columns[:-1]: plt.plot('alpha',feature,data=coef1) plt.legend(loc='upper right') plt.xlabel(r'$\alpha$',fontsize=15) plt.ylabel('系數(shù)',fontsize=15) plt.show()
?
coef1
?
五、?鮑魚年齡預(yù)測模型效果評估
1.計算MAE、MSE及R2系數(shù)
from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error from sklearn.metrics import r2_score #MAE y_test_pred_lr=lr.predict(X_test.iloc[:,:-1]) print(round(mean_absolute_error(y_test,y_test_pred_lr),4)) y_test_pred_ridge=ridge.predict(X_test[features_without_ones]) print(round(mean_absolute_error(y_test,y_test_pred_ridge),4)) y_test_pred_lasso=lasso.predict(X_test[features_without_ones]) print(round(mean_absolute_error(y_test,y_test_pred_lasso),4)) #MSE y_test_pred_lr=lr.predict(X_test.iloc[:,:-1]) print(round(mean_absolute_error(y_test,y_test_pred_lr),4)) y_test_pred_ridge=ridge.predict(X_test[features_without_ones]) print(round(mean_absolute_error(y_test,y_test_pred_ridge),4)) y_test_pred_lasso=lasso.predict(X_test[features_without_ones]) print(round(mean_absolute_error(y_test,y_test_pred_lasso),4))
#R2系數(shù) print(round(r2_score(y_test,y_test_pred_lr),4)) print(round(r2_score(y_test,y_test_pred_ridge),4)) print(round(r2_score(y_test,y_test_pred_lasso),4))
2.殘差圖
plt.figure(figsize=(9,6),dpi=600) y_train_pred_ridge=ridge.predict(X_train[features_without_ones]) plt.scatter(y_train_pred_ridge,y_train_pred_ridge - y_train,c='g',alpha=0.6) plt.scatter(y_test_pred_ridge,y_test_pred_ridge - y_test,c='r',alpha=0.6) plt.hlines(y=0,xmin=0,xmax=30,color='b',alpha=0.6) plt.ylabel('Residuals') plt.xlabel('Predict')
文章來源:http://www.zghlxwxcb.cn/news/detail-472871.html
觀察殘差圖,可以發(fā)現(xiàn)測試集的點(diǎn)(紅色)與訓(xùn)練集的點(diǎn)(綠點(diǎn))基本吻合。模型訓(xùn)練效果不錯。文章來源地址http://www.zghlxwxcb.cn/news/detail-472871.html
到了這里,關(guān)于鮑魚數(shù)據(jù)集案例分析-預(yù)測鮑魚年齡(線性回歸/梯度下降法實(shí)操)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!