Current Teaclave supports any python machine learning modules?  can I load a 
pickle-dumped machine learning model file in Teaclave and run it?
`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()` 

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/apache/incubator-teaclave/issues/463#issuecomment-768006278

Reply via email to