模型评估
线性回归的模型评估指标是 MSE(均方误差) 或 R2
逻辑回归的模型评估指标是 预测准确值
1.线性回归
① MSE
② R2
例:
from sklearn import linear_model
# 1.准备测试数据
X_test = [[6],[8],[10],[14],[18]]
y_test = [[7],[9],[13],[17.5],[18]]
# 2.构建模型
model = linear_model.LinearRegression()
# 3.训练模型
model.fit(X_test,y_test)
# 4.模型评估——模型评估有两个指标:MSE 和 R2
y_pred = model.predict(X_test)
# 模型评估指标1:MSE
# ① 使用numpy库
import numpy as np
mse1 = np.mean((y_pred-y_test)**2)
print("mse1:",mse1)
# ② 使用sklearn库中的mean_squared_error
from sklearn.metrics import mean_squared_error
mse2 = mean_squared_error(y_test,y_pred)
print("mse2:",mse2)
# mse1: 1.7495689655172406
# mse2: 1.7495689655172406
# 模型评估指标2:R2
# ① 直接使用model.score(X的原始数据,y的原始数据)
score1 = model.score(X_test,y_test)
print("score1:",score1)
# ② 使用sklearn库中的r2_score
from sklearn.metrics import r2_score
score2 = r2_score(y_test,y_pred)
print("score2:",score2)
# score1: 0.9100015964240102
# score2: 0.9100015964240102
2.逻辑回归
from sklearn import linear_model
# 1.准备训练数据
X_train = [[8,11],[9,8.5],[11,15],[16,18],[12,11],[15,12]]
y_train = [1,0,1,0,1,0]
# 2.构建模型
model = linear_model.LogisticRegression()
# 3.训练模型
model.fit(X_train,y_train)
# 4.评估模型
y_pred = model.predict(X_train)
print(y_pred) # [1 0 1 1 0 0] 与y_train相比,有4个相同
score = model.score(X_train,y_train)
print(score) # 0.6666666666666666
# 另一种模型评估的方法
# accuracy_score 精确度
# from sklearn.metrics import accuracy_score
# score = accuracy_score(y_train,y_pred)
# print(score) # 0.6666666666666666
# 5.模型预测
y_test = [[18,5]]
result = model.predict(y_test)
print("预测的结果为",result)
# 预测的结果为 [0]