首页 技术 正文
技术 2022年11月19日
0 收藏 995 点赞 3,420 浏览 1879 个字

在机器学习中,当确定好一个模型后,我们需要将它保存下来,这样当新数据出现时,我们能够调出这个模型来对新数据进行预测。同时这些新数据将被作为历史数据保存起来,经过一段周期后,使用更新的历史数据再次训练,得到更新的模型。

如果模型的流转都在python内部,那么可以使用内置的pickle库来完成模型的存储和调取。

什么是pickle?pickle是负责将python对象序列化(serialization)和反序列化(de-serialization)的模块。pickle模块可以读入任何python对象,然后将它们转换成字符串,我们再使用dump函数将其储存到文件中,这个过程叫做pickling;反之从文件中提取原始python对象的过程叫做unpickling。

picke.dump() — 将训练好的模型保存在磁盘上

with open(file_name, 'wb') as file:
pickle.dump(model, file)

pickle.load() — 读取保存在磁盘上的模型

with open(file_name, 'rb') as file:
model=pickle.load(file)

以线性回归模型为例:

import numpy as npclass Linear_Regression:
def __init__(self):
self._w = None def fit(self, X, y, lr=0.01, epsilon=0.01, epoch=1000):
#训练数据
#将输入的X,y转换为numpy数组
X, y = np.asarray(X, np.float32), np.asarray(y, np.float32)
#给X增加一列常数项
X=np.hstack((X,np.ones((X.shape[0],1))))
#初始化w
self._w = np.zeros((X.shape[1],1)) for _ in range(epoch):
#随机选择一组样本计算梯度
random_num=np.random.choice(len(X))
x_random=X[random_num].reshape(1,2)
y_random=y[random_num] gradient=(x_random.T)*(np.dot(x_random,self._w)-y_random) #如果收敛,那么停止迭代
if (np.abs(self._w-lr*gradient)<epsilon).all():
break
#否则,更新w
else:
self._w =self._w-lr*gradient return self._w def print_results(self):
print("参数w:{}".format(self._w))
print("回归拟合线:y={}x+{}".format(self._w[0],self._w[1])) def predict(self,x):
x=np.asarray(x, np.float32)
x=x.reshape(x.shape[0],1)
x=np.hstack((x,np.ones((x.shape[0],1))))
return np.dot(x,self._w)

训练并保存模型:

import pickle#创建数据
x=np.linspace(0,100,10).reshape(10,1)
rng=np.random.RandomState(4)
noise=rng.randint(-10,10,size=(10,1))*4
y=4*x+4+noisemodel=Linear_Regression()
model.fit(x,y,lr=0.0001,epsilon=0.001,epoch=20)with open('model.pickle', 'wb') as file:
pickle.dump(model, file)

然后调取模型并进行预测和打印结果:

with open('model.pickle', 'rb') as file:
model=pickle.load(file)
print(model.predict([50]))
model.print_results()

输出:

[[208.73892002]]
参数w:[[4.17372929]
[0.05245564]]
回归拟合线:y=[4.17372929]x+[0.05245564]

model是保存在磁盘上的一个python对象:

<__main__.Linear_Regression object at 0x0000009FA44B2F98>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919