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

一、模型评估

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的具体值
相关推荐
我的xiaodoujiao8 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 20--PO(POM) 设计模式和用例撰写
python·学习·测试工具·设计模式·pytest
子不语18015 分钟前
深度学习(一)——基础知识:Python语言/解释器/环境/编辑器
python·学习
爱学习的爬虫33 分钟前
Python实现Jenkins实现自动化执行Job
python·自动化·jenkins
一晌小贪欢1 小时前
Python爬虫第9课:验证码识别与自动化处理
爬虫·python·自动化·网络爬虫·python爬虫·python3
bin91531 小时前
AI工具赋能Python开发者:项目开发中的创意守护与效率革命
开发语言·人工智能·python·工具·ai工具
被放养的研究生1 小时前
Python常用的一些语句
开发语言·python
Run Freely9371 小时前
Python_封装案例
python
小白狮ww2 小时前
清华联合字节推出 HuMo,实现三模态协同生成人物视频
人工智能·深度学习·机器学习·音视频·视频生成·多模态模型·人物视频
程序员爱钓鱼2 小时前
Python编程实战 · 基础入门篇 | 条件判断 if...else
后端·python
程序员爱钓鱼2 小时前
Python编程实战 · 基础入门篇 | 循环语句 for / while
后端·python