I am trying to plot results of Multiple Linear Regression model in python but the output is wrong as salary values are all zero here. Salary is a dependent variable which depends on age, Years of Experience, etc.
Salary values should be from 30000 to 50000. However, the results tell a different story. What am I missing?
# all required libraries
import pandas as pd
import warnings
import numpy as np
# For data visualizing
import seaborn as sns
#%matplotlib notebook
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#%matplotlib inline
%matplotlib widget
# For building the required model
from sklearn import linear_model
df = pd.read_csv('ml_data_salary.csv')
# Plotting a 3-D plot for visualizing the Multiple Linear Regression Model
# Preparing the data
X = df[['age', 'YearsExperience']].values.reshape(-1,2)
Y = df['Salary']
# Create range for each dimension
x = X[:, 0]
y = X[:, 1]
z = Y
xx_pred = np.linspace(25, 40, 30) # range of age values
yy_pred = np.linspace(1, 10, 30) # range of experience values
xx_pred, yy_pred = np.meshgrid(xx_pred, yy_pred)
model_viz = np.array([xx_pred.flatten(), yy_pred.flatten()]).T
# Predict using model built on previous step
ols = linear_model.LinearRegression()
model1 = ols.fit(X, Y)
predicted = model1.predict(model_viz)
# Evaluate model by using it's R^2 score
r2 = model.score(X, Y)
# Plot model visualization
plt.style.use('default')
fig = plt.figure(figsize=(12, 4))
ax1 = fig.add_subplot(131, projection='3d')
ax2 = fig.add_subplot(132, projection='3d')
ax3 = fig.add_subplot(133, projection='3d')
axes = [ax1, ax2, ax3]
for ax in axes:
ax.plot(x, y, z, color='k', zorder=15, linestyle='none', marker='o', alpha=0.5)
ax.scatter(xx_pred.flatten(), yy_pred.flatten(), predicted, facecolor=(0,0,0,0), s=20, edgecolor='#70b3f0')
ax.set_xlabel('Age', fontsize=12)
ax.set_ylabel('Experience', fontsize=12)
ax.set_zlabel('Salary', fontsize=12)
ax.locator_params(nbins=4, axis='x')
ax.locator_params(nbins=5, axis='x')
ax1.view_init(elev=27, azim=112)
ax2.view_init(elev=16, azim=-51)
ax3.view_init(elev=60, azim=165)
fig.suptitle('Multi-Linear Regression Model Visualization ($R^2 = %.2f$)' % r2, fontsize=15, color='k')
fig.tight_layout()
The data I was using was messed up. I used the Kaggle dataset and it worked fine. Thank you ands.