import pandas as pd import numpy as np from sklearn.model_selection import StratifiedKFold, KFold from sklearn.svm import SVR train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') # 分离数据集 X_train_c = train.drop(['ID', 'CLASS'], axis=1).values y_train_c = train['CLASS'].values X_test_c = test.drop(['ID'], axis=1).values nfold = 5 kf = KFold(n_splits=nfold, shuffle=True, random_state=2020) prediction1 = np.zeros((len(X_test_c),)) i = 0 for train_index, valid_index in kf.split(X_train_c, y_train_c): print("\nFold {}".format(i + 1)) X_train, label_train = X_train_c[train_index], y_train_c[train_index] X_valid, label_valid = X_train_c[valid_index], y_train_c[valid_index] clf = SVR(kernel='rbf', C=1, gamma='scale') clf.fit(X_train, label_train) x1 = clf.predict(X_valid) y1 = clf.predict(X_test_c) prediction1 += y1 / nfold i += 1 result1 = np.round(prediction1) id_ = range(210, 314) df = pd.DataFrame({'ID': id_, 'CLASS': result1}) df.to_csv("baseline.csv", index=False)
时间: 2023-07-16 21:15:48 浏览: 214
python_SVM_svrpython_SVR回归预测_SVR_svr预测.zip
3星 · 编辑精心推荐
这段代码是一个基线模型,使用了支持向量回归(SVR)算法,通过 K 折交叉验证来训练模型,并对测试集进行预测。其中,训练数据集和测试数据集均为 CSV 格式的文件,需要使用 pandas 库读取。具体的实现过程如下:
1. 读取训练集和测试集的数据,并进行预处理。
```python
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
X_train_c = train.drop(['ID', 'CLASS'], axis=1).values
y_train_c = train['CLASS'].values
X_test_c = test.drop(['ID'], axis=1).values
```
2. 定义 K 折交叉验证器,并进行模型训练和预测。
```python
nfold = 5
kf = KFold(n_splits=nfold, shuffle=True, random_state=2020)
prediction1 = np.zeros((len(X_test_c),))
i = 0
for train_index, valid_index in kf.split(X_train_c, y_train_c):
print("\nFold {}".format(i + 1))
X_train, label_train = X_train_c[train_index], y_train_c[train_index]
X_valid, label_valid = X_train_c[valid_index], y_train_c[valid_index]
clf = SVR(kernel='rbf', C=1, gamma='scale')
clf.fit(X_train, label_train)
x1 = clf.predict(X_valid)
y1 = clf.predict(X_test_c)
prediction1 += y1 / nfold
i += 1
```
3. 对测试集的预测结果进行处理,并将结果保存到 CSV 文件中。
```python
result1 = np.round(prediction1)
id_ = range(210, 314)
df = pd.DataFrame({'ID': id_, 'CLASS': result1})
df.to_csv("baseline.csv", index=False)
```
其中,`prediction1` 是对测试集的预测结果进行累加的数组,`result1` 是将累加结果四舍五入后得到的最终预测结果。最后将结果保存到 CSV 文件中,方便后续的提交。
阅读全文