机器学习:模型评估和模型保存

一、模型评估

python 复制代码
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

# 使用测试集进行预测
y_pred = model.predict(X_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy*100:.2f}%")

# 打印混淆矩阵
conf_matrix = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(conf_matrix)

# 打印分类报告,包括精确率、召回率和F1分数
class_report = classification_report(y_test, y_pred)
print("Classification Report:")
print(class_report)

二、模型保存

python 复制代码
#使用joblib保存模型
import joblib
joblib.dump(model, "./yorelee_model.pth")
#模型的后缀名是无所谓的

三、后话

模型选择的时候,也可以使用模型融合,即结果由用不同模型的结果按比例得到。

比如pre=(pre_1*a+pre_2*b)/(a+b)。

那么我们在保存模型的时候,这两个模型要一起保存,然后之后训练就导入两个模型,pre这样算出来就行。

python 复制代码
%%time
# 2种模型融合
def model_mix(pred_1, pred_2):
    result = pd.DataFrame(columns=['LinearRegression','XGBRegressor','Combine'])

    for a in range (80):
        for b in range(1,80):
                    y_pred = (a*pred_1 + b*pred_2 ) / (a+b)
                    
                    mse = mean_squared_error(y_test,y_pred)
                    
                    mse = mean_squared_error(y_test,y_pred)
                    new_row = pd.DataFrame([{'LinearRegression':a, 
                                             'XGBRegressor':b, 
                                             'Combine':mse}])
                    result = pd.concat([result, new_row], ignore_index=True)
    return result

linear_predict=model_linear.predict(x_test)
xgb_predict=XGBClassifier.predict(x_test)
model_combine = model_mix(linear_predict,  xgb_predict)

model_combine.sort_values(by='Combine', inplace=True)
model_combine.head()
#各种比例来一份,看看mse最高分,查看 a和b的具体值
相关推荐
xiao5kou4chang6kai42 分钟前
Python-GEE遥感云大数据分析与可视化(如何建立基于云计算的森林监测预警系统)
python·数据分析·云计算·森林监测·森林管理
presenttttt10 分钟前
用Python和OpenCV从零搭建一个完整的双目视觉系统(四)
开发语言·python·opencv·计算机视觉
木头左3 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归
quant_19864 小时前
R语言如何接入实时行情接口
开发语言·经验分享·笔记·python·websocket·金融·r语言
小牛头#4 小时前
clickhouse 各个引擎适用的场景
大数据·clickhouse·机器学习
失败又激情的man9 小时前
python之requests库解析
开发语言·爬虫·python
打酱油的;9 小时前
爬虫-request处理get
爬虫·python·django
kngines9 小时前
【力扣(LeetCode)】数据挖掘面试题0002:当面对实时数据流时您如何设计和实现机器学习模型?
机器学习·数据挖掘·面试题·实时数据
网安INF10 小时前
深度学习中批标准化与神经网络调优
人工智能·深度学习·神经网络·机器学习
用什么都重名11 小时前
MinerU:高效智能PDF文档解析工具完全指南
人工智能·python·pdf·mineru·makedown