• 用pickle保存机器学习模型


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

    如果模型的流转都在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 np
    
    class 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+noise
    
    model=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>
  • 相关阅读:
    vs2015调试慢
    阿里正式发布《Java开发手册》终极版!
    为什么听有些人讲话让人抓狂
    hibernate 映射实例 学生 课程 成绩
    hibernate 树状映射
    hibernate 一对多双向的CURD
    hibernate 多对多双向关联
    hibernate 多对多单向
    hibernate 一对多双向
    hibernate 一对多关联
  • 原文地址:https://www.cnblogs.com/HuZihu/p/10361864.html
Copyright © 2020-2023  润新知