机器学习第四篇:回归模型评估指标

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data=pd.read_csv('F:\\机器学习100天\\007-010 线性回归\\010 多项式回归-实战\\code\\Data.csv')  #路径需要\\
X=data.iloc[: ,:-1].values   # 没有加values会出现InvalidIndexError: (slice(None, None, None), 0)
y=data.iloc[: ,1].values     #如果直接获取列的话,会出现reshape(-1,1)

#拆分数据集
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=0)

#构建二次多项式特征(1,x,x^2 )
from sklearn.preprocessing import PolynomialFeatures
poly_reg=PolynomialFeatures(degree=3)  #degree的个数代表多项式的特征的个数

#特征处理
X_train_poly=poly_reg.fit_transform(X_train)
X_test_poly=poly_reg.fit_transform(X_test)

#简单的线性回归
from sklearn.linear_model import LinearRegression
lr=LinearRegression().fit(X_train_poly,y_train)

#对模型的评分
print('训练集:',lr.score(X_train_poly,y_train))
print('测试集:',lr.score(X_test_poly,y_test))

#预测
y_pred=lr.predict(X_test_poly)
print('预测值:',y_pred)

#计算参数b与w
b=lr.intercept_
w1=lr.coef_[1]
w2=lr.coef_[2]
w3=lr.coef_[3]
print('截距:',b)
print('w1',w1)
print('w2',w2)
print('w3',w3)
#可视化训练集拟合结果

sorted_indices=np.argsort(X_train[:,0])  #将a中的元素从小到大排列,提取其在排列前对应的index(索引)输出。
sorted_X_train=X_train[sorted_indices]
sorted_X_train_poly=poly_reg.fit_transform(sorted_X_train)
plt.figure(1)
plt.scatter(X_train, y_train, color = 'red')
plt.plot(sorted_X_train, lr.predict(sorted_X_train_poly), "bs:")
plt.title('population VS median_house_value (training set)')
plt.xlabel('population')
plt.ylabel('median_house_value')

#可视化测试集拟合结果
sorted_indices=np.argsort(X_test[:,0])  #X_test[:,0] 这样才是列表
sorted_X_test=X_test[sorted_indices]
sorted_X_test_poly=poly_reg.fit_transform(sort_X_test)
plt.figure(2)
plt.scatter(X_test, y_test, color = 'red')
plt.plot(sorted_X_test, lr.predict(sorted_X_test_poly), "bs:")
plt.title('population VS median_house_value (test set)')
plt.xlabel('population')
plt.ylabel('median_house_value')

#模型的评估指标:MSE、RMSE、MAE、R2
print('模型的评估指标:MSE、RMSE、MAE、R2')
# MSE均方误差
from sklearn.metrics import mean_squared_error
MSE=mean_squared_error(y_test,y_pred)
print('MES =',MSE)

#RMSE 均方根误差
RMSE=np.sqrt(MSE)
print('RMES =',RMSE)

#MAE 平均绝对值误差
from sklearn.metrics import mean_absolute_error
MAE = mean_absolute_error(y_test,y_pred)
print('MAE =',MAE)

# R-Squared 拟合度,越接近1越好
from sklearn.metrics import r2_score
R2=r2_score(y_test,y_pred)
print('R2 =',R2)

你可能感兴趣的:(机器学习,数据可视化,python,回归,python)