min_on_training = X_train.min(axis=0) range_on_training = (X_train - min_on_training).max(axis=0) X_train_scaled = (X_train - min_on_training) / range_on_training print(("Minimum for each feature\n", X_train_scaled.min(axis=0))) print(("Maximum for each feature\n", X_train_scaled.max(axis=0))) svc = SVC(gamma='auto') SVC.fit(X_train_scaled, y_train) print("训练集精度:[:.3f]".format(svc.score(X_train_scaled, y_train))) print("训练集精度:[:.3f]".format(svc.score(X_train_scaled, y_test)))修改代码
时间: 2024-01-06 22:11:56 浏览: 36
代码中有两处小错误,应该将 `SVC.fit(X_train_scaled, y_train)` 改为 `svc.fit(X_train_scaled, y_train)`,并且在打印训练集精度时,应该将 `[:.3f]` 改为 `{:.3f}`。修改后的代码如下:
```
min_on_training = X_train.min(axis=0)
range_on_training = (X_train - min_on_training).max(axis=0)
X_train_scaled = (X_train - min_on_training) / range_on_training
print("Minimum for each feature:\n", X_train_scaled.min(axis=0))
print("Maximum for each feature:\n", X_train_scaled.max(axis=0))
svc = SVC(gamma='auto')
svc.fit(X_train_scaled, y_train)
print("训练集精度:{:.3f}".format(svc.score(X_train_scaled, y_train)))
print("测试集精度:{:.3f}".format(svc.score(X_test, y_test)))
```
注意,在打印精度时,第二个应该是测试集的精度,所以将 `X_train_scaled` 改成了 `X_test`。
相关问题
翻译这段代码:print("start:") start = time.time() K = 9 skf = StratifiedKFold(n_splits=K,shuffle=True,random_state=2018) auc_cv = [] pred_cv = [] for k,(train_in,test_in) in enumerate(skf.split(X,y)): X_train,X_test,y_train,y_test = X[train_in],X[test_in],\ y[train_in],y[test_in] # The data structure 数据结构 lgb_train = lgb.Dataset(X_train, y_train) lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train) # Set the parameters 设置参数 params = { 'boosting': 'gbdt', 'objective':'binary', 'verbosity': -1, 'learning_rate': 0.01, 'metric': 'auc', 'num_leaves':17 , 'min_data_in_leaf': 26, 'min_child_weight': 1.12, 'max_depth': 9, "feature_fraction": 0.91, "bagging_fraction": 0.82, "bagging_freq": 2, } print('................Start training..........................') # train gbm = lgb.train(params, lgb_train, num_boost_round=2000, valid_sets=lgb_eval, early_stopping_rounds=100, verbose_eval=100) print('................Start predict .........................') # Predict y_pred = gbm.predict(X_test,num_iteration=gbm.best_iteration) # Evaluate tmp_auc = roc_auc_score(y_test,y_pred) auc_cv.append(tmp_auc) print("valid auc:",tmp_auc) # Test pred = gbm.predict(X, num_iteration = gbm.best_iteration) pred_cv.append(pred) # the mean auc score of StratifiedKFold StratifiedKFold的平均auc分数 print('the cv information:') print(auc_cv) lgb_mean_auc = np.mean(auc_cv) print('cv mean score',lgb_mean_auc) end = time.time() lgb_practice_time=end-start print("......................run with time: {} s".format(lgb_practice_time) ) print("over:*") # turn into array 变为阵列 res = np.array(pred_cv) print("rusult:",res.shape) # mean the result 平均结果 r = res.mean(axis = 0) print('result shape:',r.shape) result = pd.DataFrame() result['company_id'] = range(1,df.shape[0]+1) result['pred_prob'] = r
打印 "start:",并记录开始时间。然后进行 K 折交叉验证,其中 K=9。对于每个交叉验证的训练集和测试集,使用 LightGBM 模型进行训练和预测,并计算每个测试集的 AUC 分数。将每个测试集的预测结果和相应的 AUC 分数存储在数组中。计算 StratifiedKFold 的平均 AUC 分数,并打印出来。将所有测试集的预测结果取平均值作为最终预测结果,并将其存储在 DataFrame 中。最后打印出总运行时间。
import numpy as np import matplotlib.pyplot as plt from sklearn import svm from sklearn.datasets import make_blobs from sklearn import model_selection from sklearn.metrics import f1_score def show_svm(a, b, bt): plt.figure(bt) plt.title('SVM with ' + bt) # 建立图像坐标 axis = plt.gca() plt.scatter(a[:, 0], a[:, 1], c=b, s=30) xlim = [a[:, 0].min(), a[:, 0].max()] ylim = [a[:, 1].min(), a[:, 1].max()] # 生成两个等差数列 xx = np.linspace(xlim[0], xlim[1], 50) yy = np.linspace(ylim[0], ylim[1], 50) X, Y = np.meshgrid(xx, yy) xy = np.vstack([X.ravel(), Y.ravel()]).T Z = clf.decision_function(xy).reshape(X.shape) # 画出分界线 axis.contour(X, Y, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--']) axis.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=200, linewidths=1, facecolors='none') if __name__ == '__main__': # data = np.loadtxt('separable_data.txt', delimiter=',') # data = np.loadtxt('non_separable_data.txt', delimiter=',') # data = np.loadtxt('banknote.txt', delimiter=',') data = np.loadtxt('ionosphere.txt', delimiter=',') # data = np.loadtxt('wdbc.txt', delimiter=',') X = data[:, 0:-1] y = data[:, -1] """标签中有一类标签为1""" y = y + 1 ymin = min(y) if not (1 in set(y)): ll = max(list(set(y))) + 1 for i in range(len(y)): if y[i] == ymin: y[i] = 1 # 建立一个线性核(多项式核)的SVM clf = svm.SVC(kernel='linear') clf.fit(X, y) """显示所有数据用于训练后的可视化结果""" show_svm(X, y, 'all dataset') """divide the data into two sections: training and test datasets""" X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.1, random_state=42) """training""" clf = svm.SVC(kernel='linear')#线性内核 # clf = svm.SVC(kernel='poly')# 多项式内核 # clf = svm.SVC(kernel='sigmoid')# Sigmoid内核 clf.fit(X_train, y_train) # show_svm(X_train, y_train, 'training dataset') """predict""" pred = clf.predict(X_test) pred = np.array(pred) y_test = np.array(y_test) print(f'SVM 的预测结果 f1-score:{f1_score(y_test, pred)}') # plt.show()结果与分析
这段代码实现了一个支持向量机(SVM)分类器,并对数据进行了可视化展示。具体来说,它包括以下几个主要步骤:
1. 导入需要使用的库,如 numpy、matplotlib、sklearn 等。
2. 定义一个名为 show_svm 的函数,用于对数据进行可视化展示。函数有三个参数:a 表示数据的特征值,b 表示数据的标签,bt 表示图像的标题。
3. 在主函数中,首先读取数据,然后将标签中的一类标签设为 1,并划分数据集为训练集和测试集。
4. 建立一个线性核的 SVM 分类器,并用训练集进行训练。
5. 对训练后的模型进行可视化展示,包括所有数据集和训练数据集的分界线。
6. 对测试集进行预测,并计算预测结果的 f1-score。
7. 最后展示结果。
总的来说,这段代码的功能是对数据进行 SVM 分类,并对分类结果进行可视化和评估。其中,SVM 模型的核函数可以通过修改代码中的 kernel 参数进行更换。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)