You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中为3D散点图实现普通最小二乘线性回归预测与绘图

3D散点图模型拟合与3D回归线绘制

任务说明

完成线性回归模型拟合后,需利用给定的x_fit和y_fit,通过模型的predict()方法预测对应的z_fit值,要求将x_fit和y_fit组合为DataFrame传入。

已完成的模型拟合代码

features = df[['x', 'y']]
response = df['z']

# 执行线性回归模型拟合
from sklearn.linear_model import LinearRegression

model = LinearRegression().fit(features, response)

print("Model Coefficients: ", model.coef_)
print("Model Intercept : ", model.intercept_)

模型输出结果

Model Coefficients:  [ 8.02602396 15.95639323]
Model Intercept :  -8.632876775060822

待补充的代码片段

需要补充以下代码,实现z_fit的预测以及3D回归线的绘制:

# Plot Curve Fit
x_fit = np.linspace(0,21,1000)
y_fit = x_fit

#ENTER CODE HERE#

完整补充代码

# 导入必要库
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 将拟合用的x、y组合为DataFrame,列名需与训练时的特征列名一致
fit_features = pd.DataFrame({'x': x_fit, 'y': y_fit})

# 预测z_fit值
z_fit = model.predict(fit_features)

# 创建3D绘图对象
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')

# 绘制原始数据散点图(可选,用于对比)
ax.scatter(df['x'], df['y'], df['z'], label='原始数据', alpha=0.6)

# 绘制拟合的3D回归线
ax.plot(x_fit, y_fit, z_fit, color='#ff3333', linewidth=3, label='拟合回归线')

# 设置坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

# 添加图例
ax.legend()

# 显示图形
plt.show()

内容的提问来源于stack exchange,提问作者MCly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:05:53