首页 > 解决方案 > 如何使用 matplotlib 绘制具有 2 个特征的 3D 多重线性回归?

问题描述

我需要在 matplotlib 中绘制具有 2 个特征的多重线性回归的 3D 图。我怎样才能做到这一点?

这是我的代码:

import pandas
from sklearn import linear_model

df = pandas.read_csv("cars.csv")

X = df[['Weight', 'Volume']]
y = df['CO2']

regr = linear_model.LinearRegression()

predictedCO2 = regr.predict([scaled[0]])
print(predictedCO2)

标签: pythonmatplotlibmplot3d

解决方案


因此,您想绘制回归模型结果的 3d 图。在您的 3d 图中,对于每个点,您都有 (x, y, z) = (Weight, Volume, PredictedCO2)。

现在您可以使用以下方法绘制它:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import random

# dummy variables for demonstration
x = [random.random()*100 for _ in range(100)]
y = [random.random()*100 for _ in range(100)]
z = [random.random()*100 or _ in range(100)]

# build the figure instance
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c='blue', marker='o')

# set your labels
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

这会给你一个这样的情节:

在此处输入图像描述


推荐阅读