X_train = X_train.iloc[:,3]
时间: 2024-01-06 07:13:29 浏览: 106
This code selects the fourth column (index 3) of the pandas DataFrame X_train and assigns it to a new DataFrame called X_train.
Note: The resulting DataFrame X_train will only have one column.
相关问题
修正代码 for k in range(self.n_fold): est=self.init_estimator() train_id, val_id=cv[k] x=pd.DataFrame(x) y=pd.DataFrame(y) # x_train, x_test = x.iloc[train_id], x.iloc[test_id] # y_train, y_test = y.iloc[train_id], y.iloc[test_id] # print(x[train_id]) x_train= x.iloc[train_id] y_train= y.iloc[train_id] est.fit(x_train, y_train) x_proba=est.predict_proba(x.iloc[val_id]) print(x_proba) print(x_probas[val_id]) y_pre=est.predict(x.iloc[val_id]) acc=accuracy_score(y.iloc[val_id],y_pre) f1=f1_score(y.iloc[val_id],y_pre,average="macro") LOGGER_2.info("{}, n_fold{},Accuracy={:.4f}, f1_macro={:.4f}".format(self.name,k,acc,f1)) x_probas[val_id]=x_proba
修正后的代码应该是这样的:
```
for k in range(self.n_fold):
est = self.init_estimator()
train_id, val_id = cv[k]
x = pd.DataFrame(x)
y = pd.DataFrame(y)
x_train = x.iloc[train_id]
y_train = y.iloc[train_id]
est.fit(x_train, y_train)
x_proba = est.predict_proba(x.iloc[val_id])
print(x_proba)
print(x_probas[val_id])
y_pre = est.predict(x.iloc[val_id])
acc = accuracy_score(y.iloc[val_id], y_pre)
f1 = f1_score(y.iloc[val_id], y_pre, average="macro")
LOGGER_2.info("{}, n_fold{},Accuracy={:.4f}, f1_macro={:.4f}".format(self.name, k, acc, f1))
x_probas[val_id] = x_proba
```
在原有代码的基础上,主要修改了以下两点:
1. 将 `x`、`y` 转化为 DataFrame 类型。
2. 将 `x_train` 和 `y_train` 的赋值方式修改为 `x_train = x.iloc[train_id]`、`y_train = y.iloc[train_id]`,以保证对应行的数据匹配。
优化这段代码 x_train_YS, y_train_YS = data.iloc[0:418+20*i,cols],data.iloc[0:418+20*i,95] x_test_YS, y_test_YS = data.iloc[418+20*i:438+20*i,cols],data.iloc[418+20*i:438+20*i,95] print(x_train_YS) x_train_YS_1,y_train_YS_1 = x_train_YS.values[0:418+20*i,1:85],y_train_YS.values[0:418+20*i,85]
可以将代码进行优化,避免多次索引和切片,可以使用数据切分函数train_test_split()来代替手动切分数据。
具体实现如下:
1. 首先需要导入train_test_split函数:from sklearn.model_selection import train_test_split
2. 对数据进行切分:
```
X = data.iloc[:, cols]
y = data.iloc[:, 95]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.05, random_state=42)
```
其中,test_size表示测试数据占比,random_state为随机种子,保证每次运行结果一致。
3. 对训练数据进行切分:
```
X_train_YS = X_train.iloc[:418+20*i, 1:85]
y_train_YS = y_train.iloc[:418+20*i]
```
4. 对测试数据进行切分:
```
X_test_YS = X_test.iloc[418+20*i:438+20*i, 1:85]
y_test_YS = y_test.iloc[418+20*i:438+20*i]
```
这样就可以得到和原代码相同的训练数据和测试数据了。
阅读全文