自学内容网 自学内容网

数据分析案例-机器学习工程师薪资数据可视化分析

 

🤵‍♂️ 个人主页:@艾派森的个人主页

✍🏻作者简介:Python学习者
🐋 希望大家多多支持,我们一起进步!😄
如果文章对你有帮助的话,
欢迎评论 💬点赞👍🏻 收藏 📂加关注+


目录

1.项目背景

2.数据集介绍

3.技术工具

4.导入数据

5.数据可视化

源代码 


1.项目背景

        在当今日新月异的科技时代,人工智能和机器学习技术的迅猛发展正推动着各行各业进行深刻的变革。作为这一变革中的核心力量,机器学习工程师的需求和关注度与日俱增。他们不仅承担着研发、优化机器学习算法的重任,更是推动企业智能化转型的关键角色。

        然而,随着机器学习工程师人才市场的竞争日趋激烈,如何准确评估这一职业群体的薪资水平,以及影响薪资的各种因素,成为了行业内外普遍关注的问题。薪资水平不仅直接反映了机器学习工程师的市场价值,也是他们职业发展、生活品质的重要体现。

        在此背景下,本实验旨在通过对机器学习工程师薪资数据进行可视化分析,揭示薪资水平的分布规律、影响因素以及行业趋势。我们收集了大量来自招聘网站、薪资调查机构等渠道的原始数据,涵盖了不同地区、不同企业规模、不同工作经验等多个维度的信息。通过对这些数据进行清洗、整理、分类和可视化处理,我们可以更加直观地了解机器学习工程师薪资的整体状况,为企业制定招聘策略、为员工提供职业规划提供参考。

        同时,本实验还尝试运用机器学习算法对数据进行深入挖掘,探索薪资水平与各种因素之间的潜在关系,为行业内的研究者和决策者提供有价值的洞见。我们相信,通过本实验的研究和分析,不仅可以为机器学习工程师的薪资问题提供更为准确的解答,还可以为整个行业的健康发展提供有力的支持。

2.数据集介绍

        本实验数据集来源于Kaggle,原始数据集中共有16494条数据,11个变量,各变量含义如下:

work_year:收集薪资数据的年份(例如,2024 年)。

experience_level:员工的经验水平(例如,MI 表示中级)。

employment_type:就业类型(例如,FT 表示全职)。

job_title:职位名称(例如数据科学家)。

salary:工资金额。

salary_currency:工资的计价货币(例如,USD 代表美元)。

salary_in_usd:转换为美元的工资金额。

employee_residence:员工居住的国家/地区(例如,AU 代表澳大利亚)。

Remote_ratio:表示远程工作级别的比率(0 表示无远程工作)。

company_location:公司的位置(例如,AU 代表澳大利亚)。

company_size:公司的规模(例如,S 表示小型)。

3.技术工具

Python版本:3.9

代码编辑器:jupyter notebook

4.导入数据

导入数据分析第三方库并加载数据集

查看数据集大小

查看数据基本信息

查看数值型变量的描述性统计

查看非数值型变量的描述性统计

统计数据集缺失值情况

统计数据集重复值情况

从结果中可以看出原始数据集不存在缺失值,但存在6401个重复数据。

删除重复数据

5.数据可视化

-工资分布似乎是右偏的,长尾倾向于更高的工资。

-大部分人的工资在101,000 - 186,000美元之间。

-工资中位数约为14.13万美元,这表明有一半的工资高于/低于此值。

-有一些异常值的薪水很高,这可能需要进一步调查。

在前20名中,最常见的职位是数据工程师,这表明对该职位的需求很高。

其他突出的职位包括数据科学家、数据分析师和机器学习工程师,这表明它们在数据集中的重要性。

排名前20的职位出现的频率各不相同,有些职位的出现频率明显高于其他职位。

中型企业的平均工资和中位数在这三类企业中是最高的。

大公司的平均工资和中位数是第二高的。

小公司的平均工资和中位数最低。

所有公司规模的工资中位数都低于平均工资,这表明工资分布略有右倾斜(即,有一些高异常值将平均值向上拉)。

按工资中位数对经验等级排序

首先,我们根据他们的工资中位数对经验水平进行排名。这让我们初步了解了不同经验水平的薪水是如何不同的。

输出结果显示,经验等级排序如下:

EX(行政人员),平均工资为18万美元

SE(高级),工资中位数为165,000美元

MI(中级),工资中位数为129,900美元

EN(入门级),工资中位数为85,750美元

源代码 

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")

df = pd.read_csv("salaries.csv")
df.head()
df.shape
df.info()
df.describe()
df.describe(include='O')
df.isnull().sum()
df.duplicated().sum()
df.drop_duplicates(inplace=True)
df.duplicated().sum()
# 工资分布直方图
plt.figure(figsize=(8, 6))
sns.histplot(data=df, x='salary_in_usd', kde=True)
plt.title('Distribution of Salaries (USD)')
plt.xlabel('Salary (USD)')
plt.ylabel('Frequency')
plt.show()
-工资分布似乎是右偏的,长尾倾向于更高的工资。
-大部分人的工资在101,000 - 186,000美元之间。
-工资中位数约为14.13万美元,这表明有一半的工资高于/低于此值。
-有一些异常值的薪水很高,这可能需要进一步调查。
# 前20个职位标题的条形图
top_20_titles = df['job_title'].value_counts().head(20)
# 为排名前20的职位创建一个条形图
plt.figure(figsize=(12, 6))
plt.bar(top_20_titles.index, top_20_titles.values)
plt.xlabel('Job Title')
plt.ylabel('Count')
plt.title('Top 20 Job Titles')
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.show()
该柱状图揭示了以下见解:
在前20名中,最常见的职位是数据工程师,这表明对该职位的需求很高。
其他突出的职位包括数据科学家、数据分析师和机器学习工程师,这表明它们在数据集中的重要性。
排名前20的职位出现的频率各不相同,有些职位的出现频率明显高于其他职位。
# 职位名称词云
top_20_titles = df['job_title'].value_counts().head(20)
title_counts = dict(top_20_titles)
from wordcloud import WordCloud
wordcloud = WordCloud(width=800, height=400, background_color='white').generate_from_frequencies(title_counts)
plt.figure(figsize=(10, 6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('Top 20 - Job Title Word Cloud')
plt.show()
# 前10名职位树图-树状图使用嵌套的矩形来表示每个职位的相对频率。
job_title_counts = df['job_title'].value_counts().head(10)
import squarify
plt.figure(figsize=(12, 6))
squarify.plot(sizes=job_title_counts, label=job_title_counts.index, alpha=0.8)
plt.axis('off')
plt.title('Job Title Treemap')
plt.show()
# 公司规模分析
# 变量
size=df['company_size']
salary=df['salary_in_usd']

#公司规模
print("Value Counts by Company Size:")
company_size_counts = df['company_size'].value_counts()
print(company_size_counts)

# 计算组均值和中位数
print("Mean Salaries by Company Size:")
print(df.groupby('company_size')['salary_in_usd'].mean().to_string(index=True))
print("\nMedian Salaries by Company Size:")
print(df.groupby('company_size')['salary_in_usd'].median().to_string(index=True))

#散点图
plt.figure(figsize=(16, 6))
plt.scatter(salary,size)
plt.xlabel('Salary in USD')
plt.ylabel('Company Size')
plt.title('Salary vs. Company Size')
plt.show()

#箱型图
plt.figure(figsize=(10, 6))
box_plot_data = [df[df['company_size'] == size]['salary_in_usd'] for size in ['S', 'M', 'L']]
box_plot = plt.boxplot(box_plot_data, patch_artist=True)
colors = ['lightblue', 'lightgreen', 'pink']
for patch, color in zip(box_plot['boxes'], colors):
    patch.set_facecolor(color)
plt.xticks([1, 2, 3], ['Small', 'Medium', 'Large'])
plt.xlabel('Company Size')
plt.ylabel('Salary (USD)')
plt.title('Salary Distribution by Company Size')
plt.legend(box_plot['boxes'], ['Small', 'Medium', 'Large'], title='Company Size', loc='upper right')
plt.show()
中型企业的平均工资和中位数在这三类企业中是最高的。
大公司的平均工资和中位数是第二高的。
小公司的平均工资和中位数最低。
所有公司规模的工资中位数都低于平均工资,这表明工资分布略有右倾斜(即,有一些高异常值将平均值向上拉)。
# 按经验水平分析工资分配
# 计算每个经验级别的工资中位数
experience_salaries = df.groupby('experience_level')['salary_in_usd'].median().reset_index()
# 按工资中位数降序排序经验水平
experience_salaries_sorted = experience_salaries.sort_values('salary_in_usd', ascending=False)
# 将经验等级与原始数据合并
df_Ranked = pd.merge(df, experience_salaries_sorted, on='experience_level')
# 创建了一个字典,将经验等级映射到他们的等级
experience_rank = {'EN': 0, 'MI': 1, 'SE': 2, 'EX': 3}
df['experience_rank'] = df['experience_level'].map(experience_rank)
print("Experience Levels Ranked by Median Salary:")
print(experience_salaries_sorted)
plt.figure(figsize=(10, 6))
sns.boxplot(data=df, x='experience_level', y='salary_in_usd')
plt.title('Salary Distribution by Experience Level')
plt.xlabel('Experience Level')
plt.ylabel('Salary (USD)')
plt.xticks([0, 1, 2, 3], ['EN', 'MI', 'SE', 'EX'])
plt.show()
按工资中位数对经验等级排序¶
首先,我们根据他们的工资中位数对经验水平进行排名。这让我们初步了解了不同经验水平的薪水是如何不同的。
输出结果显示,经验等级排序如下:
EX(行政人员),平均工资为18万美元
SE(高级),工资中位数为165,000美元
MI(中级),工资中位数为129,900美元
EN(入门级),工资中位数为85,750美元
# 按经验水平及受雇类别划分的薪金分布
plt.figure(figsize=(12, 6))
sns.set_color_codes("pastel")
sns.barplot(x='experience_level', y='salary_in_usd', hue='employment_type', data=df,)
plt.title('Salary Distribution by Experience Level and Employment Type')
plt.xlabel('Experience Level')
plt.ylabel('Salary (USD)')
plt.legend(title='Employment Type')
plt.show()
# 历年按经验水平划分的平均工资
plt.figure(figsize=(10, 6))
sns.lineplot(data=df, x='work_year', y='salary_in_usd', hue='experience_level', estimator='mean', ci=None)
plt.title('Average salaries by level of experience over the years')
plt.xlabel('Year')
plt.ylabel('Salary (USD)')
plt.legend(title='Experience level', labels=['EN', 'MI', 'SE', 'EX'])
plt.show()
# 历年的薪资趋势
plt.figure(figsize=(10, 6))
sns.lineplot(data=df, x='work_year', y='salary_in_usd', estimator='mean', ci=None)
plt.title('Salary trends over the years')
plt.xlabel('Year')
plt.ylabel('Salary (USD)')
plt.show()
# 按公司规模划分的历年平均工资
plt.figure(figsize=(10, 6))
df.groupby(['work_year', 'company_size'])['salary_in_usd'].mean().unstack().plot(kind='line', marker='o')
plt.title('Average Salaries by Company Size Over the Years')
plt.xlabel('Year')
plt.ylabel('Average salary (USD)')
plt.legend(title='Company size')
plt.show()
# 相关性分析
numeric_columns = df.select_dtypes(include=['number'])
correlation_matrix = numeric_columns.corr()
plt.figure(figsize=(12, 8))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt=".2f", linewidths=0.5)
plt.title('Correlation Matrix')
plt.show()
df.head()
new_df = df.drop(['salary','salary_currency'],axis=1)
new_df.head()
from sklearn.preprocessing import LabelEncoder

for col in new_df.describe(include='O'):
    new_df[col] = LabelEncoder().fit_transform(new_df[col])
new_df.head()
sns.boxplot(data=new_df,y='salary_in_usd')
new_df = new_df[new_df['salary_in_usd']<400000]
from sklearn.model_selection import train_test_split
X = new_df.drop('salary_in_usd',axis=1)
y = new_df['salary_in_usd']
# 划分数据集
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
import seaborn as sns
import matplotlib.pylab as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #解决中文显示
plt.rcParams['axes.unicode_minus'] = False   #解决符号无法显示
sns.set(font='SimHei')
from sklearn.metrics import r2_score,mean_absolute_error,mean_squared_error
import numpy as np
# 定义一个训练模型并对模型各个指标进行评估的函数
def train_model(ml_model):
    print("Model is: ", ml_model)
    model = ml_model.fit(X_train, y_train)
    print("Training score: ", model.score(X_train,y_train))
    predictions = model.predict(X_test)
    r2score = r2_score(y_test, predictions)
    print("r2 score is: ", r2score)
    print('MAE:', mean_absolute_error(y_test,predictions))
    print('MSE:', mean_squared_error(y_test,predictions))
    print('RMSE:', np.sqrt(mean_squared_error(y_test,predictions)))
    # 真实值和预测值的差值
    sns.distplot(y_test - predictions)
# 构建多元线性回归
from sklearn.linear_model import LinearRegression
lg = LinearRegression()
train_model(lg)
# 构建knn回归
from sklearn.neighbors import KNeighborsRegressor
knn = KNeighborsRegressor()
train_model(knn)
# 构建决策树回归
from sklearn.tree import DecisionTreeRegressor
tree = DecisionTreeRegressor()
train_model(tree)
# 构建随机森林回归
from sklearn.ensemble import RandomForestRegressor
forest = RandomForestRegressor()
train_model(forest)
# GBDT回归
from sklearn.ensemble import GradientBoostingRegressor
gbdt = GradientBoostingRegressor()
train_model(gbdt)
#打印特征重要性评分
feat_labels = X_train.columns[0:]
importances = forest.feature_importances_
indices = np.argsort(importances)[::-1]
index_list = []
value_list = []
for f,j in zip(range(X_train.shape[1]),indices):
    index_list.append(feat_labels[j])
    value_list.append(importances[j])
    print(f + 1, feat_labels[j], importances[j])
plt.figure(figsize=(10,6))
plt.barh(index_list[::-1],value_list[::-1])
plt.yticks(fontsize=12)
plt.title('各特征重要程度排序',fontsize=14)
plt.show()
# 使用随机森林模型预测并可视化
plt.figure(figsize=(10,6))  
y_pred = forest.predict(X_test)
plt.plot(range(len(y_test))[:200],y_pred[:200],'b',label='预测值')
plt.plot(range(len(y_test))[:200],y_test[:200],'r',label='真实值')
plt.legend(loc='upper right',fontsize=15)
plt.xlabel('the number of job',fontdict={'weight': 'normal', 'size': 15})
plt.ylabel('value of salary',fontdict={'weight': 'normal', 'size': 15})
plt.show()

资料获取,更多粉丝福利,关注下方公众号获取

在这里插入图片描述


原文地址:https://blog.csdn.net/m0_64336780/article/details/138705547

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!