python-多项式线性回归模型保存与重建
·
方案1- 输出模型参数重建模型
①首先获得模型参数
if return_coef:
# 返回映射函数和系数
return model, {
'coef_x': model_x.coef_.tolist(),
'intercept_x': model_x.intercept_.tolist(),
'coef_y': model_y.coef_.tolist(),
'intercept_y': model_y.intercept_.tolist(),
'degree': 3,
# 'n_features': source_data.shape[1] # 输入特征维度
}
else:
# 只返回映射函数
return model
②模型重建与预测
这里的输入数据维度为(11,9,2) 或者(9,11,2).
在真实预测时,需要转为2维的(99,2)的维度,因此,单个样本的维度为(1,2).
def rebuild_model(params):
"""从参数重建完全一致的模型"""
# 重建多项式转换器
poly = PolynomialFeatures(degree=params['degree'])
# 关键步骤:用正确维度的数据fit多项式转换器
dummy_data = np.zeros((1, 2)) # 这里是单个样本的维度,用以假fit
poly.fit(dummy_data) # 这行确保多项式转换器状态与原始一致
# 重建线性回归模型
model_x = LinearRegression()
model_x.coef_ = np.array(params['coef_x'])
model_x.intercept_ = np.array(params['intercept_x'])
model_y = LinearRegression()
model_y.coef_ = np.array(params['coef_y'])
model_y.intercept_ = np.array(params['intercept_y'])
return poly, model_x, model_y
rebuilt_poly, rebuilt_model_x, rebuilt_model_y = rebuild_model(model_coef)
# 定义预测函数
def predict_with_rebuilt_model(poly, model_x, model_y, source_data):
"""使用重建的模型进行预测"""
source_data=np.array(source_data) # 将数据转为np.arrar
origin_shape = source_data.shape # 获得输入数据的维度
source_data = source_data.reshape((-1, 2)) #将 source_data 重新整形为二维数组,其中每行有2个特征,行数自动计算 原来是三维数组么
# 分别预测x和y坐标
pred_x = model_x.predict(poly.transform(source_data))
pred_y = model_y.predict(poly.transform(source_data))
return np.column_stack((pred_x, pred_y)).reshape(origin_shape)
xy_camera_reconstruction = predict_with_rebuilt_model(rebuilt_poly,rebuilt_model_x,rebuilt_model_y,xy_module_lattice)
print(xy_camera_reconstruction-xy_camera)
方案2- 直接保存模型再读取预测
①预测函数定义同上方案1
import joblib
def save_model_complete(poly, model_x, model_y, filepath):
"""保存完整的模型对象"""
model_objects = {
'poly': poly,
'model_x': model_x,
'model_y': model_y
}
joblib.dump(model_objects, filepath)
save_model_complete(rebuilt_poly, rebuilt_model_x, rebuilt_model_y, 'model.joblib')
# 加载模型
def load_model_complete(filepath):
"""加载完整的模型对象"""
model_objects = joblib.load(filepath)
return model_objects['poly'], model_objects['model_x'], model_objects['model_y']
loaded_poly, loaded_model_x, loaded_model_y = load_model_complete('model.joblib')
xy_camera_reconstruction2 = predict_with_rebuilt_model(loaded_poly,loaded_model_x,loaded_model_y,xy_module_lattice)
print(xy_camera_reconstruction2-xy_camera)
更多推荐
所有评论(0)