8.sklearn-模型保存

文章目录

环境配置(必看)

Anaconda-创建虚拟环境的手把手教程相关环境配置看此篇文章,本专栏深度学习相关的版本和配置,均按照此篇文章进行安装。

头文件引用

python 复制代码
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
import joblib

1.保存模型

代码工程

python 复制代码
将模型信息保存到my_ridge.pkl文件中
python 复制代码
def linear3():
    """
    岭回归对波士顿房价进行预测
    :return:
    """
    # 1.获取数据集
    boston = load_boston()
    print(f"特征数量: {boston.data.shape}")
    # 2.划分数据集
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=22)
    # 3.标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)
    # 4.预估器     alpha:正则化力度  max_iter:迭代次数
    estimator = Ridge(alpha=0.5, max_iter=10000)
    estimator.fit(x_train, y_train)

    # 保存模型
    joblib.dump(estimator, "my_ridge.pkl")

    # 5.得出模型
    print(f"岭回归权重系数为: {estimator.coef_}")
    print(f"岭回归权重为: {estimator.intercept_}")
    # 6.模型评估
    y_predict = estimator.predict(x_test)
    # print(f"预测房价: {y_predict}")
    error = mean_squared_error(y_test, y_predict)
    print(f"岭回归-均方误差: {error} \n")

运行结果

生成文件

python 复制代码
此文件中保存的是模型的信息

2.加载模型

代码工程

python 复制代码
def read_model():
    """
    加载本地模型信息
    :return:
    """
    # 1.获取数据集
    boston = load_boston()
    print(f"特征数量: {boston.data.shape}")
    # 2.划分数据集
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=22)
    # 3.标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)
    # 加载模型
    estimator = joblib.load("my_ridge.pkl")
    # 得出模型
    print(f"岭回归权重系数为: {estimator.coef_}")
    print(f"岭回归权重为: {estimator.intercept_}")
    # 模型评估
    y_predict = estimator.predict(x_test)
    # print(f"预测房价: {y_predict}")
    error = mean_squared_error(y_test, y_predict)
    print(f"岭回归-均方误差: {error} \n")

运行结果

可以和上边保存模型的运行结果做对比,对比的结果是一样的,说明保存模型参数成功

相关推荐
老云讲算力市场4 分钟前
深圳奇点点信息科技有限公司连续中标多项AI算力项目
人工智能·科技
程序员天天困6 分钟前
GPT-5.6 来了!三款模型、Ultra 模式、编程能力全面解析
人工智能·chatgpt
AIGS0017 分钟前
向量空间JBoltAI:本体语义如何跨越企业AI的语义鸿沟
java·大数据·人工智能·人工智能ai大模型应用
Lucky_luckyZzz22 分钟前
明略科技·灵听工牌深度测评:四位一体闭环如何落地门店销售管理?
人工智能
xiaotie100523 分钟前
DeerFlow 2.0 Windows LocalSandbox Shell 执行 Bug 完整排查修复报告
人工智能
神奇小汤圆25 分钟前
Loop Engineering 半年实战拆解 :自进化的开发系统已开源
人工智能
熊猫钓鱼>_>33 分钟前
Electron:当 Web 技术统治桌面
大数据·前端·javascript·人工智能·架构·electron·agent
城事漫游Molly43 分钟前
用AI提炼研究问题与假设的完整提示词——从模糊想法到精准RQ/Hypothesis,AI辅助精化全流程
人工智能·机器学习·prompt·ai for science·博士生必读·应用语言学·研究问题
AI刀刀43 分钟前
豆包智能体对话导出后,如何构建长期归档与高效检索体系?
android·人工智能·word·excel·ai导出鸭
workflower44 分钟前
室内外配送机器人-应用路径
人工智能·机器学习·设计模式·矩阵·自动化