酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

背景:某医院收集了一组关于患者健康状况的数据集,其中包含患者的年龄(age)、体重(weight)、血压(bp)和胆固醇水平(cholesterol)。 研究员希望使用线性回归模型预测胆固醇水平。 数据文件名为:health_data.csv,包含字段如下: age, weight, bp, cholesterol 请根据以下Python代码,完成相应的填空,使其能成功实现以下功能: (1)导入所需的库,并加载数据; (2)使用age、weight和bp预测cholesterol; (3)将数据集的 20% 用作测试集; (4)构建并训练线性回归模型; (5)对测试集进行预测; (6)输出模型评估结果; (7)绘制预测值与实际值的对比图。 import pandas as pd from sklearn.linear_model import ______ #填空(1) from sklearn.model_selection import ______ #填空(2) from sklearn.metrics import

完成后的代码如下: ```python import pandas as pd from sklearn.linear_model import LinearRegression #填空(1) from sklearn.model_selection import train_test_split #填空(2) from sklearn.metrics import r2_score import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'fangsong' data = pd.read_csv("health_data.csv") #填空(3) X = data[['age', 'weight', 'bp']] y = data["cholesterol"] #填空(4) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) #填空(5)和(6) model = LinearRegression() #填空(7) model.fit(X_train, y_train) #填空(8) y_pred = model.predict(X_test) #填空(9)和 填空(10) print("系数:", model.coef_) print("截距:", model.intercept_) #填空(11) print("R²分数:", r2_score(y_test, y_pred)) #填空(12) plt.scatter(y_test, y_pred, color='green') plt.xlabel("实际胆固醇") plt.ylabel("预测胆固醇") plt.title('预测值与实际值对比图' ) plt.show() ``` 额外需要注意的逻辑点: 1. 确保`health_data.csv`文件位于当前工作目录中,否则需提供完整路径。 2. 数据集中不能含有缺失值,否则在训练模型时会出错,建议提前做`data.isnull().sum()`检查。 3. 使用`LinearRegression`默认参数即可完成线性拟合,但如需更高精度或正则化,可改用`Ridge`或`Lasso`回归。 [2025-06-29 17:53:11 | AI写代码神器 | 404点数解答]

相关提问