英文:
Plotting Multiple Linear Regression Model in Python
问题
我正在尝试在Python中绘制多元线性回归模型的结果,但输出是错误的,因为这里的薪水值都是零。薪水是一个依赖于年龄、工作经验等因素的因变量。
薪水值应该在30000到50000之间。然而,结果告诉了一个不同的故事。我错过了什么?
# 所有所需的库
import pandas as pd
import warnings
import numpy as np
# 用于数据可视化
import seaborn as sns
# %matplotlib notebook
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# %matplotlib inline
%matplotlib widget
# 用于构建所需的模型
from sklearn import linear_model
df = pd.read_csv('ml_data_salary.csv')
# 绘制用于可视化多元线性回归模型的3-D图
# 准备数据
X = df[['age', 'YearsExperience']].values.reshape(-1, 2)
Y = df['Salary']
# 为每个维度创建范围
x = X[:, 0]
y = X[:, 1]
z = Y
xx_pred = np.linspace(25, 40, 30) # 年龄值的范围
yy_pred = np.linspace(1, 10, 30) # 经验值的范围
xx_pred, yy_pred = np.meshgrid(xx_pred, yy_pred)
model_viz = np.array([xx_pred.flatten(), yy_pred.flatten()]).T
# 使用前面构建的模型进行预测
ols = linear_model.LinearRegression()
model1 = ols.fit(X, Y)
predicted = model1.predict(model_viz)
# 使用模型的R^2分数来评估模型
r2 = model1.score(X, Y)
# 绘制模型可视化
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()
<details>
<summary>英文:</summary>
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()
![enter image description here](https://i.stack.imgur.com/tKW3D.png)
</details>
# 答案1
**得分**: 0
我的使用的数据混乱了。我使用了Kaggle数据集,它运行良好。谢谢。
<details>
<summary>英文:</summary>
The data I was using was messed up. I used the Kaggle dataset and it worked fine. Thank you ands.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论