对于以上代码,在保留划分后矩阵的时候不保留第一列
时间: 2024-05-14 14:15:17 浏览: 36
可以在代码中的这一行:
```
X_train, X_test, y_train, y_test = train_test_split(X[:,1:], y, test_size=0.2, random_state=0)
```
将`X[:,1:]`改为`np.delete(X, 0, axis=1)`,即删除矩阵`X`的第一列,代码如下:
```
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# 读取数据
data = pd.read_csv('data.csv')
# 划分数据集
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(np.delete(X, 0, axis=1), y, test_size=0.2, random_state=0)
# 模型训练
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# 模型预测
y_pred = regressor.predict(X_test)
# 输出结果
print("预测值:", y_pred)
print("实际值:", y_test)
```
其中,`np.delete(X, 0, axis=1)`表示删除`X`矩阵的第一列,`axis=1`表示删除列。
阅读全文