import pandas as pd
df=pd.read_csv(‘Predict Hair Fall.csv’)
df

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split #划分训练集和测试集
from sklearn.ensemble import RandomForestClassifier #随机森林
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report, roc_curve, auc, confusion_matrix #模型评估

from sklearn.svm import SVC #支持向量机

import warnings
warnings.filterwarnings(‘ignore’) #忽略警告信息

plt.rcParams[‘font.sans-serif’]=‘SimHei’
plt.rcParams[‘axes.unicode_minus’]=False

将列名转换成中文,便于理解

chinese_columns=[
‘遗传因素’,
‘荷尔蒙变化’,
‘医疗状况’,
‘药物及治疗’,
‘营养缺乏’,
‘压力水平’,
‘年龄’,
‘不良护发习惯’,
‘环境因素’,
‘吸烟习惯’,
‘体重减轻’,
‘脱发标记’ # 目标变量]
# 将原始数据集的列名改为:第一列为’ID’,后面依次为chinese_columns中的12个列名
df.columns = [‘ID’] + chinese_columns
df.head(5)

缺失值处理

df.replace(“No Data”,pd.NA,inplace=True)
df.head()

二值列转换

binary_cols= [‘遗传因素’, ‘荷尔蒙变化’, ‘不良护发习惯’, ‘环境因素’, ‘吸烟习惯’, ‘体重减轻’]
for col in binary_cols:
df[col]=df[col].map({‘Yes’:1,‘No’:0, pd.NA:np.nan})

df.head()

df[‘高压力’]=df[‘压力水平’].apply(lambda x:1 if x==‘High’ else 0)
df.head()

#脱发标记分布
data=df[‘脱发标记’].value_counts()

plt.figure(figsize=(8,5))
plt.pie(data,labels=[‘不脱发’,‘脱发’],autopct=‘%.2f%%’,startangle=90,shadow=True)
plt.title(‘脱发标记分布’)
plt.show()
在这里插入图片描述

年龄与脱发关系
fig=plt.figure(figsize=(10,6))
ax1=plt.subplot(111)
df.boxplot(column=‘年龄’,by=‘脱发标记’,ax=ax1,)
ax1.set_title(‘脱发人群年龄分布’,fontsize=14)
ax1.set_ylabel(‘年龄’)
plt.show()

在这里插入图片描述

#常见医疗诊断分析
plt.figure(figsize=(12, 8))
top_conditions = df[‘医疗状况’].value_counts().head(10)
plt.barh(top_conditions.index,top_conditions) #横向柱状图
plt.title(‘十大常见脱发相关医疗状况’, fontsize=14)
plt.xlabel(‘样本数量’, fontsize=12)
plt.ylabel(‘医疗状况’, fontsize=12)
plt.tight_layout()
plt.show()

在这里插入图片描述
plt.figure(figsize=(12,8))

top8_nutrition=df[‘营养缺乏’].value_counts().head(8)

plt.barh(top8_nutrition.index,top8_nutrition)
plt.title(‘常见脱发相关营养缺乏类型’, fontsize=16, pad=20)
plt.xlabel(‘样本数量’, fontsize=14)
plt.ylabel(‘营养缺乏类型’, fontsize=14)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)

plt.show()

在这里插入图片描述

二值特征与脱发关系

features = [‘遗传因素’, ‘荷尔蒙变化’, ‘不良护发习惯’, ‘环境因素’, ‘吸烟习惯’, ‘体重减轻’]

fig,axes=plt.subplots(3,2,figsize=(15,15))
axes=axes.flatten()
df[‘脱发标记’] = df[‘脱发标记’].astype(‘category’)
categories = df[‘脱发标记’].cat.categories
num_categories = len(categories)
x=np.arange(num_categories)
width=0.35

for i ,feature in enumerate(features):#枚举每个特征
if i < len(axes):
ax=axes[i]
#计算每个类别中1和0的数量
counts=df.groupby(‘脱发标记’)[feature].value_counts().unstack(fill_value=0)
rects1=ax.bar(x-width/2,counts[0],width)
rects1=ax.bar(x+width/2,counts[1],width)
ax.set_title(f’{feature}与脱发’)
#ax.set_ylable(‘数量’)
ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.legend([‘无’,‘有’])

plt.tight_layout()
plt.show()

在这里插入图片描述

特征相关性分析

corr_features = [‘遗传因素’, ‘荷尔蒙变化’, ‘高压力’, ‘不良护发习惯’, ‘吸烟习惯’, ‘体重减轻’, ‘脱发标记’]
corr = df[corr_features].corr()
plt.figure(figsize=(12, 8))
plt.imshow(corr, cmap=‘hot’,interpolation=‘nearest’,alpha=0.9)
plt.colorbar()
plt.title(‘脱发相关因素相关系数热力图’, fontsize=14)

plt.tight_layout()
plt.show()

在这里插入图片描述# " 压力水平 年龄 不良护发习惯 环境因素 吸烟习惯 体重减轻 脱发标记 \n",# 可视化遗传与医疗状况对脱发的影响
plt.figure(figsize=(12, 8))
sns.boxplot(x=‘Genetics’, y=‘Hair Loss’, hue=‘Medical Conditions’, data=df)
plt.title(‘遗传与医疗状况对脱发的影响’)
plt.xlabel(‘遗传因素(0=无, 1=有)’)
plt.ylabel(‘脱发率’)
plt.tight_layout()
plt.show()

在这里插入图片描述

缺失值处理(删除少量缺失行)

df.dropna(subset=[‘脱发标记’, ‘医疗状况’, ‘药物及治疗’, ‘营养缺乏’], inplace=True)

复合变量

遗传因素+高压力组合

df[‘遗传高压力组合’] = ((df[‘遗传因素’] == 1) & (df[‘高压力’] == 1)).astype(int)

标签编码分类变量

label_encoders = {}
categorical_cols = [‘医疗状况’, ‘药物及治疗’, ‘营养缺乏’, ‘压力水平’]
for col in categorical_cols:
le = LabelEncoder()
df[col] = le.fit_transform(df[col].astype(str))
label_encoders[col] = le
在这里插入图片描述

基于 Python 的脱发因素分析与预测## 一、引言

**脱发已成为一个普遍现象,严重影响人们的生活质量。通过系统分析脱发影响因素并建立预测模型,可以为防治工作提供科学依据。Python强大的数据分析工具库为解决这一问题提供了有效支持。

二、数据获取与预处理

(一)数据获取
*获取涵盖脱发相关因素的数据集,数据来源应包含:

  1. 专业医学数据库
  2. 健康调研平台
  3. 权威研究机构
    数据集需包含以下关键信息:
  • 人口统计学特征(如年龄)
  • 遗传因素
  • 荷尔蒙水平变化
  • 基础医疗状况
  • 营养摄入情况
  • 心理压力指标
  • 日常护发习惯
  • 环境影响因素
  • 吸烟史
  • 体重波动记录
    (二)数据预处理
    数据清洗:使用 Pandas 库检查并处理缺失值,对于少量缺失值,可采用均值、中位数或众数填充;对于大量缺失值,可考虑删除相应记录。同时,识别并处理重复数据,确保数据的唯一性。
    python
    运行
    import pandas as pd
    df = pd.read_csv(‘hair_loss_data.csv’)
    df.drop_duplicates(inplace=True)
    df.fillna(df.median(), inplace=True)

    数据转换:针对遗传(是/否)、荷尔蒙变化(有/无)等分类变量,采用LabelEncoder或One-Hot Encoding方法进行编码转换,以适配后续模型的输入要求。
    from sklearn.preprocessing import LabelEncoder
    cat_cols = [‘Genetics’, ‘Hormonal Changes’]
    le = LabelEncoder()
    for col in cat_cols:
    df[col] = le.fit_transform(df[col])
    ## 三、脱发因素分析

    (一)单因素分析
    数据分析:年龄对脱发的影响
    数据处理步骤:
  1. 使用 Pandas 进行年龄分组(分箱处理)
  2. 计算各年龄段的脱发发生率
  3. 通过 Matplotlib 绘制年龄-脱发率关系柱状图
    可视化呈现:
  • 横轴:划分的年龄段
  • 纵轴:对应年龄组的脱发比例
  • 图表直观展示年龄增长与脱发率的变化趋势
    import matplotlib.pyplot as plt
    age_bins = [0, 20, 30, 40, 50, 100]
    age_labels = [‘青少年’, ‘青年’, ‘中年前期’, ‘中年后期’, ‘老年’]
    df[‘Age_Bin’] = pd.cut(df[‘Age’], bins = age_bins, labels = age_labels)
    age_hair_loss = df.groupby(‘Age_Bin’)[‘Hair Loss’].mean()
    age_hair_loss.plot(kind=‘bar’)
    plt.title(‘年龄与脱发率关系’)
    plt.xlabel(‘年龄段’)
    plt.ylabel(‘脱发率’)
    plt.show()
    遗传因素分析:比较有家族史和无家族史人群的脱发发生率,采用卡方检验评估遗传因素与脱发风险的关联显著性。
    from scipy.stats import chi2_contingency
    genetics_hairloss = pd.crosstab(df[‘Genetics’], df[‘Hair Loss’])
    chi2, p, dof, expected = chi2_contingency(genetics_hairloss)
    print(f"卡方值: {chi2}, p值: {p}")
    (二)多因素分析
    使用 Seaborn 绘制箱线图:探究遗传因素与医疗状况对脱发率的交互影响,直观呈现不同遗传背景下各类医疗状况对应的脱发率分布情况。
    import seaborn as sns
    sns.boxplot(x=‘Genetics’, y=‘Hair Loss’, hue=‘Medical Conditions’, data=df)
    plt.title(‘遗传与医疗状况对脱发的影响’)
    plt.xlabel(‘遗传因素(0=无, 1=有)’)
    plt.ylabel(‘脱发率’)
    plt.show()
    相关性分析:采用皮尔逊相关系数评估各因素与脱发的关联程度,并通过Matplotlib热力图可视化呈现相关性强度。
    import numpy as np
    corr_matrix = df[[‘Genetics’, ‘Hormonal Changes’, ‘Medical Conditions’, ‘Hair Loss’]].corr()
    plt.imshow(corr_matrix, cmap=‘hot’, interpolation=‘nearest’)
    plt.title(‘相关性热力图’)
    plt.xticks(range(len(corr_matrix.columns)), corr_matrix.columns, rotation=90)
    plt.yticks(range(len(corr_matrix.columns)), corr_matrix.columns)
    plt.colorbar()
    plt.show()

四、脱发预测模型构建

(一)模型选择
我们采用随机森林(Random Forest)和支持向量机(SVM)等监督学习算法构建脱发预测模型。随机森林算法具有优秀的抗噪能力,对异常值和高维数据都能有效处理;而支持向量机在小样本和非线性数据预测方面表现尤为突出。
(二)模型训练与评估
数据集划分:采用 Sklearn 的 train_test_split 函数将数据分割为训练集和测试集,通常按 7:3 或 8:2 的比例进行分配。
from sklearn.model_selection import train_test_split
X = df.drop(‘Hair Loss’, axis = 1)
y = df[‘Hair Loss’]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state
= 42)
模型训练:以随机森林为例,使用训练集数据训练模型。
from sklearn.ensemble import RandomForestClassifier
rf_model = RandomForestClassifier(n_estimators = 100, random_state = 42)
rf_model.fit(X_train, y_train)

模型评估:使用测试集数据评估模型性能,采用准确率、精确率、召回率、F1 值等指标进行评价

from sklearn.metrics import accuracy_score, precision_score, recall_score, F1_score
y_pred = rf_model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = F1_score(y_test, y_pred)
print(f"准确率: {accuracy}, 精确率: {precision}, 召回率: {recall}, F1值: {f1}")

五、结论

我的Python数据分析揭示了脱发的主要影响因素,包括年龄、遗传和健康状况等,并量化了它们的影响程度和相互关系。在此基础上开发的预测模型能够有效评估个体的脱发风险。这些发现不仅为个人防脱提供了科学依据,也为医学研究和治疗方案优化提供了重要参考。后续可通过纳入更多影响因素来进一步提升模型的预测精度。

Logo

永洪科技,致力于打造全球领先的数据技术厂商,具备从数据应用方案咨询、BI、AIGC智能分析、数字孪生、数据资产、数据治理、数据实施的端到端大数据价值服务能力。

更多推荐