大家好,我想问json.dump
我使用 scikit 来调整一些带有参数的方法,我想将其转储到 json,但我在这里遇到了一些错误:我有方法 KNN 的参数:
KNeighborsClassifier(algorithm=u'auto', leaf_size=30, metric=u'manhattan',
metric_params=None, n_jobs=-1, n_neighbors=300, p=2,
weights=u'distance')
但是得到这样的错误:
Traceback (most recent call last):
File "jamu.py", line 1018, in <module>
main(argv)
File "jamu.py", line 863, in main
json.dumps(meta_clf, f)
File "C:Python27libjson__init__.py", line 250, in d
sort_keys=sort_keys, **kw).encode(obj)
File "C:Python27libjsonencoder.py", line 207, in en
chunks = self.iterencode(o, _one_shot=True)
File "C:Python27libjsonencoder.py", line 270, in it
return _iterencode(o, 0)
File "C:Python27libjsonencoder.py", line 184, in de
raise TypeError(repr(o) + " is not JSON serializable"
TypeError: KNeighborsClassifier(algorithm=u'auto', leaf_s
tan',
metric_params=None, n_jobs=-1, n_neighbors=300
weights=u'distance') is not JSON serializable
我的代码有什么问题吗?
这是它在锡上所说的,KNeighborsClassifier
不能用json
序列化。
必须使用其他方式来序列化模型。例如,您可以使用joblib
:
from sklearn.external import joblib
# Suppose your KNeighborsClassifier model is called knn
joblib.dump(knn, 'some/kind/of/path/knn.joblib')
加载模型同样简单:
knn = joblib.load('some/kind/of/path/knn.joblib')
查看 joblib 文档,了解它还有什么好处。
最后我用这种方式:
meta_clf = KNeighborsClassifier(algorithm=u'auto', leaf_size=30, metric=u'manhattan',
metric_params=None, n_jobs=-1, n_neighbors=300, p=2,
weights=u'distance')
def print_to_json(meta_clf):
meta_clf_str = str(meta_clf)
meta_clf_str = meta_clf_str[meta_clf_str.index("(") + 1:meta_clf_str.rindex(")")]
meta_clf_str = meta_clf_str.replace('n ', '')
meta_clf_str = meta_clf_str.replace(' ', '')
meta_clf_str = meta_clf_str.replace('=u'', '='')
meta_clf_str = meta_clf_str.replace(''', '')
meta_clf_str_list = meta_clf_str.split(',')
meta_clf_str_list_len = len(meta_clf_str_list)
meta_clf_str_lists = []
params = {}
for x in meta_clf_str_list:
meta_clf_str_list = x.split('=')
if meta_clf_str_list[1].isdigit() == True:
meta_clf_str_list[1] = int(meta_clf_str_list[1])
meta_clf_str_lists.append(meta_clf_str_list)
params[meta_clf_str_list[0]] = meta_clf_str_list[1]
return params
这对我来说已经足够了。感谢托马斯,我很感激。