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

运行结果

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

相关推荐
知秋一叶1233 小时前
Miloco 深度打通 Home Assistant,实现设备级精准控制
人工智能·智能家居
superman超哥3 小时前
仓颉语言中基本数据类型的深度剖析与工程实践
c语言·开发语言·python·算法·仓颉
春日见3 小时前
在虚拟机上面无法正启动机械臂的控制launch文件
linux·运维·服务器·人工智能·驱动开发·ubuntu
Learner__Q4 小时前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
————A4 小时前
强化学习----->轨迹、回报、折扣因子和回合
人工智能·python
CareyWYR4 小时前
每周AI论文速递(251215-251219)
人工智能
徐先生 @_@|||4 小时前
(Wheel 格式) Python 的标准分发格式的生成规则规范
开发语言·python
weixin_409383124 小时前
在kaggle训练Qwen/Qwen2.5-1.5B-Instruct 通过中二时期qq空间记录作为训练数据 训练出中二的模型为目标 第一次训练 好像太二了
人工智能·深度学习·机器学习·qwen
JoannaJuanCV4 小时前
自动驾驶—CARLA仿真(22)manual_control_steeringwheel demo
人工智能·自动驾驶·pygame·carla
Mqh1807624 小时前
day45 简单CNN
python