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")

运行结果

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

相关推荐
wb0430720112 小时前
性能优化实战:基于方法执行监控与AI调用链分析
java·人工智能·spring boot·语言模型·性能优化
AAA小肥杨12 小时前
基于k8s的Python的分布式深度学习训练平台搭建简单实践
人工智能·分布式·python·ai·kubernetes·gpu
lichong95114 小时前
Git 检出到HEAD 再修改提交commit 会消失解决方案
java·前端·git·python·github·大前端·大前端++
Tiny番茄14 小时前
31.下一个排列
数据结构·python·算法·leetcode
mit6.82414 小时前
[Agent可视化] 配置系统 | 实现AI模型切换 | 热重载机制 | fsnotify库(go)
开发语言·人工智能·golang
Percent_bigdata15 小时前
百分点科技发布中国首个AI原生GEO产品Generforce,助力品牌决胜AI搜索新时代
人工智能·科技·ai-native
Gloria_niki15 小时前
YOLOv4 学习总结
人工智能·计算机视觉·目标跟踪
小白学大数据15 小时前
实战:Python爬虫如何模拟登录与维持会话状态
开发语言·爬虫·python
FriendshipT15 小时前
目标检测:使用自己的数据集微调DEIMv2进行物体检测
人工智能·pytorch·python·目标检测·计算机视觉
海森大数据15 小时前
三步破局:一致性轨迹强化学习开启扩散语言模型“又快又好”推理新时代
人工智能·语言模型·自然语言处理