请问如何保存训练好的模型?
模型代码如下
#RM,LSTAT-->MEDV
#y=theta_0+theta_1*RM+theta_2*LSTAT+theta_3*PTRATIO+theta_4*RM^2+theta_5*RM*LSTAT+theta_6*RM*LSTAT*PTRATIO
import numpy as np
theta=np.random.rand(7,)
theta
#回归模型
def f(x):
return np.dot(theta,x.T)
#dot():返回两个数组的点积,x.T为矩阵转置
#评估函数(求均方误差)
def mse(x,y):
return np.sum((f(x)-y)**2) / len(y)
#训练模型
learning_rate = 0.00001
df['RM2'] = df['RM']**2
df['RM_LSTAT'] = df['RM']*df['LSTAT']
df['RM_LSTAT_PTRATIO'] = df['RM']*df['LSTAT']*df['PTRATIO']
train_x = df[['RM','LSTAT','PTRATIO','RM2','RM_LSTAT','RM_LSTAT_PTRATIO']]
print(train_x)
train_x = (train_x -train_x.mean()) / train_x.std()#标准化, mean()求平均值
train_x = np.insert(train_x.to_numpy(),0,1,axis=1)
train_y = df['MEDV']
for i in range(10000):
theta = theta - learning_rate * np.dot(f(train_x)-train_y,train_x)
metrics = mse(train_x,train_y)
print('第%d轮 均方误差为%.04f theta%s' % (i+1,metrics,str(theta)))