0
$\begingroup$

I am trying to use linear regression that takes two variables "Idade" and "LF" and tries to predict a third one, "DGAF". I'm trying to both do the scatterplot with the observations and the model prediction on the same graph. Bellow is the code I used (using Python).

X = df[["Idade","LF"]]
y = df["DGAF"].values.reshape(len(df["DGAF"]),1)

reg = LinearRegression()
reg.fit(X, y)

fig = plt.figure()
ax = Axes3D(fig)

ax.scatter(X['Idade'],X['LF'], y,s=10)

x_pred = np.linspace(0,100,1000)
y_pred = np.linspace(0,100,1000)
xx_pred, yy_pred = np.meshgrid(x_pred, y_pred)

model_viz = np.array([xx_pred.flatten(), yy_pred.flatten()]).T

ax.set_xlabel('Years since oil change')
ax.set_ylabel('LF')
ax.set_zlabel('DGA Score')

ax.plot(model_viz[0], model_viz[1], reg.predict(model_viz),color='red')
plt.show()

I get this error:

ValueError: input operand has more dimensions than allowed by the axis remapping

I am able to do the scatterplot, the issue seems to be with plotting the prediction. How can I solve this?

$\endgroup$
3
  • 1
    $\begingroup$ Why are you using ax.plot instead of ax.scatter as your did in the first part or ax.plot_surface to plot the surface ? these should work with your input arguments. $\endgroup$ – Ubikuity May 10 at 19:15
  • $\begingroup$ @Ubikuity, thank you for your suggestion. After trying to use scatter I found out that there were some issues with the matrix transposition as well $\endgroup$ – J. Dionisio May 10 at 21:45
  • 1
    $\begingroup$ Perfect, glad that one worked out. Was not sure at all about these 3D plots since I rarely use them, in spite of how badass they are. $\endgroup$ – Ubikuity May 10 at 22:37
1
$\begingroup$

Following the suggestion given by @Ubikuity, I changed the ax.plot to ax.scatter, but there were still some issues with the dimensions. It was due to the transposition of the matrices, that was being done in the wrong place. The code below works correctly.

X = df[["Idade","LF"]]
y = df["DGAF"].values.reshape(len(df["DGAF"]),1)

reg = LinearRegression()
reg.fit(X, y)

fig = plt.figure()
ax = Axes3D(fig)

ax.scatter(X['Idade'],X['LF'], y,s=10)

x_pred = np.linspace(0,100,100)
y_pred = np.linspace(0,100,100)
xx_pred, yy_pred = np.meshgrid(x_pred, y_pred)

model_viz = np.array([xx_pred.flatten(), yy_pred.flatten()])

ax.set_xlabel('Years since oil change')
ax.set_ylabel('LF')
ax.set_zlabel('DGA Score')

ax.scatter(model_viz[0], model_viz[1], reg.predict(model_viz.T),color='red')
plt.show()
```
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.