python - Python:如何加载 CSV 文件并从中提取特定列以用作数据输入?
问题描述
我有一个 CSV 文件,其中每一行都是一个病人,每一列都是一个“特征”。我想使用这个多元线性回归代码。而不是波士顿示例数据集,我想加载我的 CSV 文件并使用第 1 到 79 列作为“数据”特征矩阵 (X),第 80 列作为“目标”响应向量 (y)。我怎样才能做到这一点?我对 Python 很陌生,因此非常感谢任何建议。
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model, metrics
# load the boston dataset
boston = datasets.load_boston(return_X_y=False)
# defining feature matrix(X) and response vector(y)
X = boston.data
y = boston.target
# splitting X and y into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4,
random_state=1)
# create linear regression object
reg = linear_model.LinearRegression()
# train the model using the training sets
reg.fit(X_train, y_train)
# regression coefficients
print('Coefficients: ', reg.coef_)
# variance score: 1 means perfect prediction
print('Variance score: {}'.format(reg.score(X_test, y_test)))
# plot for residual error
## setting plot style
plt.style.use('fivethirtyeight')
## plotting residual errors in training data
plt.scatter(reg.predict(X_train), reg.predict(X_train) - y_train,
color = "green", s = 10, label = 'Train data')
## plotting residual errors in test data
plt.scatter(reg.predict(X_test), reg.predict(X_test) - y_test,
color = "blue", s = 10, label = 'Test data')
## plotting line for zero residual error
plt.hlines(y = 0, xmin = 0, xmax = 50, linewidth = 2)
## plotting legend
plt.legend(loc = 'upper right')
## plot title
plt.title("Residual errors")
## method call for showing the plot
plt.show()
解决方案
推荐阅读
- javascript - 如何垂直分离 Material UI Gridded Paper 组件?
- excel - Excel 2019 VBA SaveAs 生成运行时 1004
- jquery - 在 Laravel 中验证 yyyy-mm 输入
- python - 如何在这个 pandas 数据框中对差异进行分组、排序和计算?
- javascript - 如何为特定的 axios 调用模拟 jest.spyOn
- filter - 过滤具有相同前缀但数字后缀不同的数据表
- python - 为什么我不能导入 pygame?
- sql - 正则表达式 - 在逗号之间的序列中捕获下划线之间的数字
- r - UpsetR:如何增加图例的字体大小?
- custom-wordpress-pages - 使用密码打开只读 URL