如何将训练好的sklearn.svm.SVR模型保存为JSON而非Pickle格式?
将训练好的SVR模型保存为JSON格式的问题
我需要把训练好的SVR模型保存为JSON格式,而非Pickle格式。核心思路是捕获模型的权重及其他“拟合”属性状态,后续通过设置这些属性来完成预测。以下是我的实现方案:
模型保存代码
# 假设SVR已完成训练 regressor = SVR() regressor.fit(x_train, y_train) # 保存SVR的必要参数到JSON文件 with open(f'saved_regressor_params.json', 'w', encoding='utf-8') as outfile: json.dump(regressor.get_params(), outfile) # 筛选SVR的拟合属性(以单下划线结尾且不是双下划线结尾的属性) attrs = [i for i in dir(regressor) if i.endswith('_') and not i.endswith('__')] remove_list = ['coef_', '_repr_html_', '_repr_mimebundle_'] # 移除不必要的属性 for attr in remove_list: if attr in attrs: attrs.remove(attr) # 将NumPy数组转为列表,保存拟合属性到JSON文件 attr_dict = {i: getattr(regressor, i) for i in attrs} for k in attr_dict: if isinstance(attr_dict[k], np.ndarray): attr_dict[k] = attr_dict[k].tolist() # 写入拟合属性JSON文件 with open(f'saved_regressor_{index}.json', 'w', encoding='utf-8') as outfile: json.dump(attr_dict, outfile, separators=(',', ':'), sort_keys=True, indent=4)
生成的JSON文件示例
saved_regressor_params.json用于保存模型参数,saved_regressor.json存储拟合属性及训练值,示例如下:
{ "_dual_coef_": [ [ -1.0, -1.0, -1.0 ] ], "_intercept_": [ 1.323423423 ], ... "_n_support_": [ 3 ] }
加载模型并预测的代码
后续创建新的SVR实例,通过加载两个JSON文件设置参数与属性后调用predict方法:
predict_svr = SVR() # 加载JSON文件 obj_text = codecs.open('saved_regressor_params.json', 'r', encoding='utf-8').read() params = json.loads(obj_text) obj_text = codecs.open('saved_regressor.json', 'r', encoding='utf-8').read() attributes = json.loads(obj_text) # 设置模型参数 predict_svr.set_params(**params) # 设置拟合属性 for k in attributes: if isinstance(attributes[k], list): setattr(predict_svr, k, np.array(attributes[k])) else: setattr(predict_svr, k, attributes[k]) predict_svr.predict(...)
遇到的问题
在这个过程中,n_support_属性无法设置,即使忽略该属性也会出现其他错误。不确定是逻辑存在问题,还是遗漏了某些必要内容。
求助方向
正在寻找将SVR模型保存为JSON的其他方法或巧妙方案。曾尝试过sklearn_json等第三方库,它们对线性模型支持良好,但无法处理支持向量模型。
内容的提问来源于stack exchange,提问作者P0intMaN
相关产品推荐
相关产品推荐

