我在Jupyter中运行一个分类算法,使用的是sklearn。由于我的一个组别(组1)仅占其他两个组的35%,我想对这个组进行过采样。我知道SMOTE脚本,但不知道如何将其整合到我的脚本中。请问如何操作?
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split (X, y, test_size = 0.1) from sklearn.preprocessing import StandardScalersc = StandardScaler()X_train = sc.fit_transform(X_train)X_test = sc.transform (X_test)from sklearn.svm import SVCclf = SVC(kernel = 'linear')clf.fit (X_train, y_train.ravel())y_pred = clf.predict(X_test)from sklearn.metrics import confusion_matrixcm = confusion_matrix (y_test, y_pred)from sklearn.model_selection import cross_val_scoreaccuracies = cross_val_score (estimator = clf, X = X_train, y = y_train, cv = 10)accuracies.mean()accuracies.std()from sklearn.model_selection import GridSearchCVparameters = [{'C':[1, 10, 100], 'kernel':['linear']}, {'C':[1, 10, 100], 'kernel':['rbf'], 'gamma': [0.05, 0.001, 0.005]}]grid_search = GridSearchCV (estimator = clf, param_grid = parameters, scoring = 'accuracy', cv = 10)grid_search = grid_search.fit (X_train,y_train)best_accuracy = grid_search.best_score_ print (best_accuracy)best_parameters = grid_search.best_params_print (best_parameters)
回答:
你需要对数据集应用SMOTE,并使用生成的平衡数据集来训练你的模型。
因此,你需要像代码中所示的那样加载数据(问题中未显示的部分),然后对其应用SMOTE。
代码实现如下:
X = # 训练数据y = # 训练标签# 应用SMOTEfrom imblearn.over_sampling import SMOTEsm = SMOTE(random_state=42)X_balanced, y_balanced = sm.fit_sample(X, y)from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split (X_balanced, y_balanced, test_size = 0.1) from sklearn.preprocessing import StandardScalersc = StandardScaler()X_train = sc.fit_transform(X_train)X_test = sc.transform (X_test)from sklearn.svm import SVCclf = SVC(kernel = 'linear')clf.fit (X_train, y_train.ravel())y_pred = clf.predict(X_test)from sklearn.metrics import confusion_matrixcm = confusion_matrix (y_test, y_pred)from sklearn.model_selection import cross_val_scoreaccuracies = cross_val_score (estimator = clf, X = X_train, y = y_train, cv = 10)accuracies.mean()accuracies.std()from sklearn.model_selection import GridSearchCVparameters = [{'C':[1, 10, 100], 'kernel':['linear']}, {'C':[1, 10, 100], 'kernel':['rbf'], 'gamma': [0.05, 0.001, 0.005]}]grid_search = GridSearchCV (estimator = clf, param_grid = parameters, scoring = 'accuracy', cv = 10)grid_search = grid_search.fit (X_train,y_train)best_accuracy = grid_search.best_score_ print (best_accuracy)best_parameters = grid_search.best_params_print (best_parameters)