我已经训练了一个 SVM 分类器并获得了良好的结果,现在我需要保存该模型,在需要时加载它,并预测新的未见数据。 这是我的代码,我应该添加什么
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import f_classif
from sklearn.model_selection import GridSearchCV
from sklearn.feature_selection import SelectKBest
import pandas as pd
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report, confusion_matrix
param_grid = {'C': [0.1,1, 10, 100], 'gamma': [1,0.1,0.01,0.001],'kernel': ['linear','rbf', 'poly', 'sigmoid']}
def select_features(X_train,y_train,X_test):
fs = SelectKBest(score_func=f_classif, k='all')
fs.fit(X_train, y_train)
X_train_fs = fs.transform(X_train)
X_test_fs = fs.transform(X_test)
return X_train_fs,X_test_fs,fs
data = pd.read_csv('d:/f.csv')
d=data.values
X = d[:,0:207]
y = d[:,208]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1)
X_train_fs, X_test_fs, fs =select_features(X_train,y_train,X_test)
model = GridSearchCV(SVC(),param_grid,refit=True,verbose=2,n_jobs=-1)
model.fit(X_train_fs, y_train)
y_pred = model.predict(X_test_fs)
print('Best GridSearchCV parameters: ',model.best_params_)
print("Accuracy: ",accuracy_score(y_test, y_pred))
print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))
答案 0 :(得分:0)
简答:
SVC
has 没有 load
或 save
函数。但是,参数存储在 dict
中,这意味着您可以将它们保存为 json
。之后,您可以加载 dict
并使用 set_params
方法重新实例化 SVM。
from sklearn.svm import SVC
svc = SVC()
svc.set_params(loaded_params)
这是你的问题吗?