基于回归算法的心理健康预测(EDA + 预测)

news2025/6/7 23:26:15

   

      心理健康涵盖情感、心理与社会福祉,影响认知、情绪和行为模式,决定压力应对、人际交往及健康决策,且在生命各阶段(从童年至成年)均至关重要。心理健康与身体健康同为整体健康的核心要素:抑郁会增加糖尿病、心脏病等慢性病风险,而慢性疾病也可能诱发精神疾病。本笔记本将先用 Plotly 库全面分析多组数据,再以回归算法选定目标变量建模,聚类分析则留待下一笔记完成,现正式开启分析。

1- Import Libraries

#import important libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn import preprocessing
from sklearn import metrics
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from plotly.offline import init_notebook_mode
init_notebook_mode(connected=True)
import warnings
warnings.filterwarnings("ignore")

2- Call Datasets

Data1 = pd.read_csv("/kaggle/input/mental-health/1- mental-illnesses-prevalence.csv")
Data2 = pd.read_csv("/kaggle/input/mental-health/4- adult-population-covered-in-primary-data-on-the-prevalence-of-mental-illnesses.csv")
Data3 = pd.read_csv("/kaggle/input/mental-health/6- depressive-symptoms-across-us-population.csv")
Data4 = pd.read_csv("/kaggle/input/mental-health/7- number-of-countries-with-primary-data-on-prevalence-of-mental-illnesses-in-the-global-burden-of-disease-study.csv")
df1 = pd.DataFrame(Data1)
df2 = pd.DataFrame(Data2)
df3 = pd.DataFrame(Data3)
df4 = pd.DataFrame(Data4)

3- Functional Describe of All Datasets

def describe(df):
    
    
    variables = []
    dtypes = []
    count = []
    unique = []
    missing = []
    
    
    for item in df.columns:
        variables.append(item)
        dtypes.append(df[item].dtype)
        count.append(len(df[item]))
        unique.append(len(df[item].unique()))
        missing.append(df[item].isna().sum())
        

    output = pd.DataFrame({
        'variable': variables, 
        'dtype': dtypes,
        'count': count,
        'unique': unique,
        'missing value': missing
    })    
        
    return output
class color:
   BLUE = '\033[94m'
   BOLD = '\033[1m'
   UNDERLINE = '\033[4m'
   END = '\033[0m'

代码提供了两个数据处理和可视化工具:describe(df)函数通过遍历 DataFrame 各列,收集列名、数据类型、总行数、唯一值数量和缺失值数量,生成包含这些基本统计信息的新 DataFrame,用于快速了解数据集结构;color类则封装了 ANSI 转义序列,可在支持该序列的终端环境中对文本进行蓝色、加粗、下划线等样式格式化,二者结合可辅助数据探索阶段的数据清洗和特征工程工作,并增强关键信息的可视化效果。

4- Output of Describes(数据输出)

print(color.BOLD + color.BLUE + color.UNDERLINE +
      '"The describe table of df1 : Mental illness dataframe"' + color.END)
print(describe(df1))
print("\n")
print(color.BOLD + color.BLUE + color.UNDERLINE +
      '"The describe table of df2 : Adult population, mental illnesses"' + color.END)
print(describe(df2))
print("\n")
print(color.BOLD + color.BLUE + color.UNDERLINE +
      '"The describe table of df3 : Depressive"' + color.END)
print(describe(df3))
print("\n")
print(color.BOLD + color.BLUE + color.UNDERLINE +
      '"The describe table of df4 : Number of countries"' + color.END)
print(describe(df4))
"The describe table of df1 : Mental illness dataframe"
                                            variable    dtype  count  unique  \
0                                             Entity   object   6420     214   
1                                               Code   object   6420     206   
2                                               Year    int64   6420      30   
3  Schizophrenia disorders (share of population) ...  float64   6420    6406   
4  Depressive disorders (share of population) - S...  float64   6420    6416   
5  Anxiety disorders (share of population) - Sex:...  float64   6420    6417   
6  Bipolar disorders (share of population) - Sex:...  float64   6420    6385   
7  Eating disorders (share of population) - Sex: ...  float64   6420    6417   

   missing value  
0              0  
1            270  
2              0  
3              0  
4              0  
5              0  
6              0  
7              0  
"The describe table of df2 : Adult population, mental illnesses"
            variable    dtype  count  unique  missing value
0             Entity   object     22      22              0
1               Code   object     22       2             21
2               Year    int64     22       1              0
3   Major depression  float64     22      18              0
4   Bipolar disorder  float64     22      14              0
5   Eating disorders  float64     22      11              0
6          Dysthymia  float64     22      14              0
7      Schizophrenia   object     22      14              0
8  Anxiety disorders  float64     22      18              0


"The describe table of df3 : Depressive"
                  variable    dtype  count  unique  missing value
0                   Entity   object     10      10              0
1                     Code  float64     10       1             10
2                     Year    int64     10       1              0
3         Nearly every day  float64     10       9              0
4  More than half the days  float64     10      10              0
5             Several days  float64     10      10              0
6               Not at all  float64     10      10              0


"The describe table of df4 : Number of countries"
                                            variable    dtype  count  unique  \
0                                             Entity   object     15      15   
1                                               Code  float64     15       1   
2                                               Year    int64     15       1   
3  Number of countries with primary data on preva...    int64     15      11   

   missing value  
0              0  
1             15  
2              0  
3              0  

一、数据集整体概况

数据集名称行数列数核心数据类型主要分析方向
df1(精神疾病数据)64208float(患病率)、object疾病趋势、地理分布
df2(成年人口与精神疾病)229float(患病率)、object群体患病率对比
df3(抑郁相关数据)107float(频率评分)、object抑郁症状分布
df4(国家数量数据)155int(国家数)、object数据覆盖范围评估

5- Some Visualizations with Plotly

Plotly 是一个基于 Python、JavaScript、R 等编程语言的 开源数据可视化库,用于创建 交互式、可分享的动态图表。它支持多种图表类型,适用于数据分析、报告展示和交互式仪表盘开发。

# 按"Major depression"(重度抑郁症)列的值升序排序df2(inplace=True表示直接修改原数据框)
df2.sort_values(by="Major depression", inplace=True)

# 设置matplotlib图形的分辨率为200dpi(此设置对Plotly图表无效,但保留可能用于后续其他图表)
plt.figure(dpi=200)

# 使用Plotly Express创建水平条形图
fig = px.bar(
    df2,                      # 数据源
    x="Major depression",     # x轴:重度抑郁症患病率(数值型)
    y="Entity",               # y轴:实体(如国家、地区,类别型)
    orientation='h',          # 水平条形图(horizontal)
    color='Bipolar disorder'  # 颜色映射:双相情感障碍患病率(数值型)
)

# 显示图表(在Jupyter Notebook中会内嵌显示,在脚本中会打开浏览器窗口)
fig.show()

 该图是关于不同地区 “Major depression”(重度抑郁症)患病率的水平条形图,同时以颜色映射展示 “Bipolar disorder”(双相情感障碍)患病率。可以看出,North America 和 Australasia 的重度抑郁症患病率相对较高,在图中处于较长条形位置;而如 Central Asia、Andean Latin America 等地区重度抑郁症患病率较低。颜色方面,颜色越偏向黄色,双相情感障碍患病率越高,如 North America 和 Australasia;颜色越偏向深蓝色,双相情感障碍患病率越低。

表格呈现

地区重度抑郁症患病率情况双相情感障碍患病率趋势
North America较高
Australasia较高
Asia Pacific中等偏高中等
Western Europe中等偏高中等
Central Latin America中等中等偏低
North Africa/Middle East中等中等偏低
West Sub - Saharan Africa中等中等偏低
World中等中等
Eastern Europe中等偏低中等偏低
Latin America中等偏低
Southern America中等偏低
Central Europe中等偏低
Southeast Asia中等偏低
East Asia中等偏低
Tropical Latin American
Caribbean
South Asia
East Sub - Saharan Africa
Southern Sub - Saharan Africa
Oceania
Central Sub - Saharan Africa
Central Asia
Andean Latin America
df2.sort_values(by= "Eating disorders" ,inplace=True)
plt.figure(dpi=200)
fig = px.bar(df2, x="Eating disorders", y="Entity", orientation='h',color='Dysthymia')
fig.show()

该图为不同地区 “Eating disorders”(饮食失调症)患病率的水平条形图,并用颜色映射表示 “Dysthymia”(心境恶劣)患病率。可见,North America 的饮食失调症患病率最高,在图中条形最长;Central Latin America 次之。Western Europe、Asia Pacific 等地区处于中等水平。颜色上,颜色越黄代表心境恶劣患病率越高,如 North America、Australasia;颜色越偏向深蓝色,心境恶劣患病率越低。部分地区如 Central Sub - Saharan Africa、Oceania 等在图中未显示饮食失调症数据。

表格呈现

地区饮食失调症患病率情况心境恶劣患病率趋势
North America
Central Latin America较高中等
Western Europe中等中等
Asia Pacific中等中等
Tropical Latin America中等偏低中等偏低
Central Europe中等偏低中等偏低
Australasia中等偏低
World中等偏低中等
East Asia中等偏低
East Sub - Saharan Africa
South Asia
Central Asia
Central Sub - Saharan Africa无数据
Oceania无数据
Southern Sub - Saharan Africa无数据
Southeast Asia无数据
Caribbean无数据
Southern Latin America无数据
Eastern Europe无数据
West Sub - Saharan Africa无数据
North Africa/Middle East无数据
Andean Latin America无数据

  这段代码对 df2 数据集进行了数据预处理和可视化操作,主要目的是分析不同地区精神分裂症(Schizophrenia)与焦虑症(Anxiety disorders)患病率之间的关系。以下是带注释的代码析: 

# 数据清洗:将所有"<0.1"格式的值替换为0.1(处理数据中的小于符号)
# regex=True表示使用正则表达式匹配,确保所有类似"<0.1"的字符串都被替换
df2.replace(to_replace="<0.1", value=0.1, regex=True, inplace=True)

# 数据类型转换:将'Schizophrenia'列从object类型转换为float类型
# 确保后续排序和绘图操作能正确处理数值
df2['Schizophrenia'] = df2['Schizophrenia'].astype(float)

# 数据排序:按'Schizophrenia'列的值升序排列数据框
# inplace=True表示直接修改原数据框,不创建新对象
df2.sort_values(by="Schizophrenia", inplace=True)

# 设置图形分辨率(此设置对Plotly图表无效,但可能影响后续matplotlib图表)
plt.figure(dpi=200)

# 创建水平条形图:
# x轴:精神分裂症患病率
# y轴:地区/实体名称
# orientation='h':水平方向的条形图
# color='Anxiety disorders':使用焦虑症患病率作为颜色映射变量
fig = px.bar(df2, x="Schizophrenia", y="Entity", orientation='h', color='Anxiety disorders')

# 显示交互式图表(支持悬停查看详情、缩放、保存等功能)
fig.show()

该图是展示不同地区 “Schizophrenia”(精神分裂症)患病率的水平条形图,同时以颜色映射呈现 “Anxiety disorders”(焦虑症)患病率。North America 和 Australasia 的精神分裂症患病率相对较高,在图中条形较长;Caribbean、East Asia 等地区处于中等水平。颜色方面,颜色越偏向黄色,焦虑症患病率越高,如 North America 和 Australasia;颜色越偏向深蓝色,焦虑症患病率越低。部分地区如 Southeast Asia、Southern Sub - Saharan Africa 等在图中精神分裂症患病率较低。

表格呈现

地区精神分裂症患病率情况焦虑症患病率趋势
North America
Australasia
Asia Pacific较高较高
Caribbean中等中等
East Asia中等中等
World中等中等
Western Europe中等中等
East Sub - Saharan Africa中等偏低中等偏低
South Asia中等偏低中等偏低
Eastern Europe中等偏低中等偏低
Central Latin America
Oceania
Southeast Asia
Southern Sub - Saharan Africa
North Africa/Middle East
West Sub - Saharan Africa
Southern Latin America
Central Asia
Central Sub - Saharan Africa
Central Europe
Tropical Latin America
Andean Latin America

6- Amazing Dynamik Subplot with Plotly and go

使用 Plotly 和 go 实现的动态子图,这段代码使用 Plotly 创建了一个包含双相情感障碍(Bipolar disorder)柱状图和重度抑郁症(Major depression)折线图的横向并排子图,用于对比不同地区两种精神疾病的患病率。

# 创建1行2列的子图布局,共享y轴(地区名称),x轴独立
fig = make_subplots(
    rows=1, cols=2, 
    specs=[[{}, {}]],  # 两个空字典表示默认配置
    shared_xaxes=True,  # 共享x轴刻度
    shared_yaxes=False,  # 不共享y轴刻度
    vertical_spacing=0.001  # 垂直间距极小
)

# 定义地区名称列表(按患病率排序)
x1 = ["Andean Latin America", "West Sub-Saharan Africa", "Tropical Latin America", "Central Asia", "Central Europe",
    "Central Sub-Saharan Africa", "Southern Latin America", "North Africa/Middle East", "Southern Sub-Saharan Africa",
    "Southeast Asia", "Oceania", "Central Latin America", "Eastern Europe", "South Asia", "East Sub-Saharan Africa",
    "Western Europe", "World", "East Asia", "Caribbean", "Asia Pacific", "Australasia", "North America"]

# 左侧子图:双相情感障碍患病率柱状图
fig.append_trace(go.Bar(
    x=df2["Bipolar disorder"],  # x轴:患病率数值
    y=x1,  # y轴:地区名称
    marker=dict(  # 柱状图样式
        color='rgba(50, 171, 96, 0.6)',  # 半透明绿色
        line=dict(color='rgba(20, 10, 56, 1.0)', width=0)  # 边框颜色和宽度
    ),
    name='Bipolar disorder in Mental Health',  # 图例名称
    orientation='h',  # 水平方向柱状图
), 1, 1)  # 第1行第1列

# 右侧子图:重度抑郁症患病率折线图
fig.append_trace(go.Scatter(
    x=df2["Major depression"], y=x1,  # x轴:患病率,y轴:地区名称
    mode='lines+markers',  # 同时显示线和标记点
    line_color='rgb(40, 0, 128)',  # 紫色线条
    name='Major depression in Mental Health',  # 图例名称
), 1, 2)  # 第1行第2列

# 更新整体布局
fig.update_layout(
    title='Major depression and Bipolar disorder',  # 图表标题
    yaxis=dict(  # 左侧y轴配置
        showgrid=False,  # 不显示网格线
        showline=False,  # 不显示轴线
        showticklabels=True,  # 显示刻度标签
        domain=[0, 0.85],  # 显示区域占比(底部留出空间)
    ),
    yaxis2=dict(  # 右侧y轴配置
        showgrid=False,  # 不显示网格线
        showline=True,  # 显示轴线
        showticklabels=False,  # 不显示刻度标签(与左侧共用)
        linecolor='rgba(102, 102, 102, 0.8)',  # 轴线颜色
        linewidth=5,  # 轴线宽度
        domain=[0, 0.85],  # 显示区域占比
    ),
    xaxis=dict(  # 左侧x轴配置
        zeroline=False,  # 不显示零线
        showline=False,  # 不显示轴线
        showticklabels=True,  # 显示刻度标签
        showgrid=True,  # 显示网格线
        domain=[0, 0.45],  # 显示区域占比(左侧45%)
    ),
    xaxis2=dict(  # 右侧x轴配置
        zeroline=False,  # 不显示零线
        showline=False,  # 不显示轴线
        showticklabels=True,  # 显示刻度标签
        showgrid=True,  # 显示网格线
        domain=[0.47, 1],  # 显示区域占比(右侧53%,留出间隔)
        side='top',  # 刻度标签显示在顶部
        dtick=10000,  # 刻度间隔(此处可能有误,应为更小值)
    ),
    legend=dict(x=0.029, y=1.038, font_size=10),  # 图例位置和字体大小
    margin=dict(l=100, r=20, t=70, b=70),  # 边距设置
    paper_bgcolor='rgb(248, 248, 255)',  # 背景色
    plot_bgcolor='rgb(248, 248, 255)',  # 绘图区域背景色
)

# 添加数据标签
annotations = []

# 为每个数据点添加标签
for ydn, yd, xd in zip(df2["Major depression"], df2["Bipolar disorder"], x1):
    # 为折线图添加标签(右侧)
    annotations.append(dict(
        xref='x2', yref='y2',  # 引用右侧子图
        y=xd, x=ydn+10,  # 标签位置(x值偏移10)
        text='{:,}'.format(ydn) + '%',  # 标签文本(百分比)
        font=dict(family='Arial', size=10, color='rgb(128, 0, 128)'),  # 字体样式
        showarrow=False  # 不显示箭头
    ))
    # 为柱状图添加标签(左侧)
    annotations.append(dict(
        xref='x1', yref='y1',  # 引用左侧子图
        y=xd, x=yd+10,  # 标签位置(x值偏移10)
        text=str(yd) + '%',  # 标签文本(百分比)
        font=dict(family='Arial', size=10, color='rgb(50, 171, 96)'),  # 字体样式
        showarrow=False  # 不显示箭头
    ))

# 添加数据源注释
annotations.append(dict(
    xref='paper', yref='paper',  # 相对于整个图表
    x=-0.2, y=-0.109,  # 位置(底部左侧)
    text="Mental health visualization",  # 文本内容
    font=dict(family='Arial', size=20, color='rgb(150,150,150)'),  # 字体样式
    showarrow=False  # 不显示箭头
))

# 更新图表注释
fig.update_layout(annotations=annotations)

# 显示交互式图表
fig.show()

该图为展示不同地区 “Major depression”(重度抑郁症)和 “Bipolar disorder”(双相情感障碍)患病率的组合图表。绿色柱状代表双相情感障碍患病率,紫色折线代表重度抑郁症患病率。从图中可知,Australasia 的双相情感障碍患病率达 100%,North America 为 89.8% ,处于较高水平;在重度抑郁症方面,部分地区有相应的数值体现,如某些地区显示为 73.6%、35.4% 等 。不同地区两种疾病的患病率呈现出明显差异。

表格呈现

地区双相情感障碍患病率重度抑郁症患病率
North America89.8%有对应数值(图中标识)
Australasia100.0%有对应数值(图中标识)
Asia Pacific3.8%有对应数值(图中标识)
Caribbean0.0%有对应数值(图中标识)
East Asia8.4%有对应数值(图中标识)
World12.9%有对应数值(图中标识)
Western Europe19.0%有对应数值(图中标识)
East Sub - Saharan Africa0.9%有对应数值(图中标识)
South Asia0.0%有对应数值(图中标识)
Eastern Europe1.7%有对应数值(图中标识)
Central Latin America34.5%有对应数值(图中标识)
Oceania0.0%有对应数值(图中标识)
Southeast Asia0.0%有对应数值(图中标识)
Southern Sub - Saharan Africa0.0%有对应数值(图中标识)
North Africa/Middle East14.5%有对应数值(图中标识)
Southern Latin America47.0%有对应数值(图中标识)
Central Sub - Saharan Africa11.6%有对应数值(图中标识)
Central Europe0.0%有对应数值(图中标识)
Central Asia0.0%有对应数值(图中标识)
Tropical Latin America0.0%有对应数值(图中标识)
West Sub - Saharan Africa6.4%有对应数值(图中标识)
Andean Latin America0.0%有对应数值(图中标识)

7- Multiple Analysis(多远分析)

 使用 Plotly 创建了一个多线图,用于展示美国人群中不同抑郁症状在不同频率下的分布情况。以下是带注释的代码解析:

# 定义抑郁症状列表(x轴标签)
x = ["Appetite change", "Average across symptoms", "Depressed mood", "Difficulty concentrating", 
     "Loss of interest", "Low energy", "Low self-esteem", "Psychomotor agitation", 
     "Psychomotor agitation", "Sleep problems", "Suicidal ideation"]

# 创建图表对象
fig = go.Figure()

# 添加第一条线:"几乎每天"出现的症状频率
fig.add_trace(go.Scatter(
    x=x,  # x轴:症状类型
    y=df3["Nearly every day"],  # y轴:频率值
    name='Nearly every day',  # 图例名称
    line=dict(color='firebrick', width=4)  # 线条样式:火砖红色,线宽4
))

# 添加第二条线:"超过半数天数"出现的症状频率
fig.add_trace(go.Scatter(
    x=x, 
    y=df3["More than half the days"], 
    name='More than half the days',
    line=dict(color='royalblue', width=4)  # 线条样式:皇家蓝色,线宽4
))

# 添加第三条线:"数天"出现的症状频率
fig.add_trace(go.Scatter(
    x=x, 
    y=df3["Several days"], 
    name='Several days',
    line=dict(
        color='black',  # 黑色线条
        width=4,  # 线宽4
        dash='dashdot'  # 线型:点划线
    )
))

# 更新图表布局
fig.update_layout(
    title='Depressive symptoms across US population',  # 图表标题
    xaxis_title='Entity',  # x轴标题(此处应为"Symptoms"更合适)
    yaxis_title='Types of days'  # y轴标题(表示频率类型)
)

# 显示交互式图表
fig.show()

展示了 “Appetite change”(食欲改变)、“Depressed mood”(情绪低落)等多种抑郁症状在 “Nearly every day”(几乎每天)、“More than half the days”(超过半数天数)、“Several days”(数天)三种频率下的分布情况。可以看出,“Low energy”(精力不足)在 “Several days” 频率下数值最高,在 “Nearly every day” 和 “More than half the days” 频率下,“Low self - esteem”(低自尊)等症状也有相对较高的数值,不同症状在各频率下呈现出不同的表现。

表格呈现

抑郁症状Nearly every day(几乎每天)More than half the days(超过半数天数)Several days(数天)
Appetite change(食欲改变)较低值较低值相对较高值
Average across symptoms(症状平均值)较低值较低值中等值
Depressed mood(情绪低落)较低值较低值中等值
Difficulty concentrating(注意力不集中)较低值中等值较高值
Loss of interest(兴趣减退)中等值中等值较高值
Low energy(精力不足)中等值中等值最高值
Low self - esteem(低自尊)较高值较高值中等值
Psychomotor agitation(精神运动性激越)较低值较低值中等值
Sleep problems(睡眠问题)较低值较低值

 使用 Plotly 创建了一个折线图,展示了全球疾病负担研究中不同精神疾病的患病率数据覆盖国家数量。以下是带注释的代码解析:

# 定义精神疾病列表(x轴标签)
x = ["Alcohol use disorders", "Amphetamine use disorders", "Anorexia nervosa", "Anxiety disorders",
     "Attention-deficit hyperactivity disorder", "Autism spectrum disorders", "Bipolar disorder",
     "Bulimia nervosa", "Cannabis use disorders", "Cocaine use disorders", "Dysthymia", "Major depressive disorder",
     "Opioid use disorders", "Other drug use disorders", "Personality disorders"]

# 创建图表对象
fig = go.Figure()

# 添加数据轨迹:拥有该疾病患病率原始数据的国家数量
fig.add_trace(go.Scatter(
    x=x,  # x轴:精神疾病类型
    y=df4["Number of countries with primary data on prevalence of mental disorders"],  # y轴:国家数量
    name='Nearly every day',  # 图例名称(此处可能有误,应为更合适的名称如"Data Coverage")
    line=dict(color='firebrick', width=4)  # 线条样式:火砖红色,线宽4
))

# 更新图表布局
fig.update_layout(
    title='mental illnesses in the global burden of disease study',  # 图表标题
    xaxis_title='illnesses',  # x轴标题:疾病类型
    yaxis_title='Number of countries'  # y轴标题:国家数量
)

# 显示交互式图表
fig.show()

 该图是关于全球疾病负担研究中精神疾病的折线图,展示了不同精神疾病(如 “Alcohol use disorders” 酒精使用障碍、“Anxiety disorders” 焦虑症等)拥有患病率原始数据的国家数量。可以看出,“Anxiety disorders”(焦虑症)和 “Bipolar disorder”(双相情感障碍)等对应的国家数量较多,处于折线的高峰位置;而 “Opioid use disorders”(阿片类药物使用障碍)和 “Other drug use disorders”(其他药物使用障碍)等对应的国家数量较少,折线处于较低位置,不同精神疾病的数据覆盖国家数量差异明显。

表格呈现

精神疾病拥有患病率原始数据的国家数量大致情况
Alcohol use disorders(酒精使用障碍)中等偏上
Amphetamine use disorders(苯丙胺使用障碍)中等偏下
Anorexia nervosa(神经性厌食症)中等
Anxiety disorders(焦虑症)
Attention - deficit hyperactivity disorder(注意缺陷多动障碍)中等
Autism spectrum disorders(自闭症谱系障碍)中等偏下
Bipolar disorder(双相情感障碍)
Bulimia nervosa(神经性贪食症)中等偏上
Cannabis use disorders(大麻使用障碍)中等
Cocaine use disorders(可卡因使用障碍)中等
Dysthymia(心境恶劣)中等偏上
Major depressive disorder(重度抑郁症)中等偏上
Opioid use disorders(阿片类药物使用障碍)
Other drug use disorders(其他药物使用障碍)
Personality disorders(人格障碍)

获取 DataFrame df1的所有列名,并将这些列名存储在列表df1_column_names中,最后打印该列表。

8- Rename Columns

df1_column_names = list(df1.columns.values)
df1_column_names
['Entity',
 'Code',
 'Year',
 'Schizophrenia disorders (share of population) - Sex: Both - Age: Age-standardized',
 'Depressive disorders (share of population) - Sex: Both - Age: Age-standardized',
 'Anxiety disorders (share of population) - Sex: Both - Age: Age-standardized',
 'Bipolar disorders (share of population) - Sex: Both - Age: Age-standardized',
 'Eating disorders (share of population) - Sex: Both - Age: Age-standardized']
df1 = df1.rename(columns={'Schizophrenia disorders (share of population) - Sex: Both - Age: Age-standardized': 'Schizophrenia disorders', 
                          'Depressive disorders (share of population) - Sex: Both - Age: Age-standardized': 'Depressive disorders',
                         'Anxiety disorders (share of population) - Sex: Both - Age: Age-standardized':'Anxiety disorders',
                         'Bipolar disorders (share of population) - Sex: Both - Age: Age-standardized':'Bipolar disorders',
                         'Eating disorders (share of population) - Sex: Both - Age: Age-standardized':'Eating disorders'})
EntityCodeYearSchizophrenia disordersDepressive disordersAnxiety disordersBipolar disordersEating disorders
0AfghanistanAFG19900.2232064.9961184.7133140.7030230.127700
1AfghanistanAFG19910.2224544.9892904.7021000.7020690.123256
2AfghanistanAFG19920.2217514.9813464.6837430.7007920.118844
3AfghanistanAFG19930.2209874.9769584.6735490.7000870.115089
4AfghanistanAFG19940.2201834.9777824.6708100.6998980.111815
...........................
6415ZimbabweZWE20150.2010423.4076243.1840120.5385960.095652
6416ZimbabweZWE20160.2013193.4107553.1871480.5385930.096662
6417ZimbabweZWE20170.2016393.4119653.1884180.5385890.097330
6418ZimbabweZWE20180.2019763.4069293.1721110.5385850.097909
6419ZimbabweZWE20190.2024823.3954763.1370170.5385800.098295

输出结果:表格展示了全球疾病负担研究中精神疾病患病率的面板数据,涵盖 1990-2019 年期间多个国家的五种精神疾病(精神分裂症、抑郁症、焦虑症、双相情感障碍和饮食失调症)的标准化患病率数据。

df1_variables = df1[["Schizophrenia disorders","Depressive disorders","Anxiety disorders","Bipolar disorders",
                       "Eating disorders"]]
df1_variables
Schizophrenia disordersDepressive disordersAnxiety disordersBipolar disordersEating disorders
00.2232064.9961184.7133140.7030230.127700
10.2224544.9892904.7021000.7020690.123256
20.2217514.9813464.6837430.7007920.118844
30.2209874.9769584.6735490.7000870.115089
40.2201834.9777824.6708100.6998980.111815
..................
64150.2010423.4076243.1840120.5385960.095652
64160.2013193.4107553.1871480.5385930.096662
64170.2016393.4119653.1884180.5385890.097330
64180.2019763.4069293.1721110.5385850.097909
64190.2024823.3954763.1370170.5385800.098295

代码输出的表格分析:精神疾病患病率趋势与分布特征

这个表格展示了 1990-2019 年期间多个国家五种精神疾病的年龄标准化患病率数据。数据特点和关键发现如下:

1. 数据结构与范围

  • 疾病类型
    • 精神分裂症(Schizophrenia)
    • 抑郁症(Depressive Disorders)
    • 焦虑症(Anxiety Disorders)
    • 双相情感障碍(Bipolar Disorders)
    • 饮食失调症(Eating Disorders)
  • 时间跨度:30 年(1990-2019)
  • 地理覆盖:包含阿富汗(示例前 5 行)到津巴布韦(示例后 5 行)等 200 + 国家 / 地区

2. 患病率总体特征

疾病类型平均患病率(示例数据)特点
抑郁症~4-5%患病率最高,波动范围较大(阿富汗从 4.99% 降至 3.39%)
焦虑症~3-4%患病率次高,与抑郁症趋势接近但略低
双相情感障碍~0.5-0.7%患病率中等,波动较小(如阿富汗从 0.703% 降至 0.538%)
精神分裂症~0.2-0.3%患病率较低,长期稳定(阿富汗从 0.223% 降至 0.202%)
饮食失调症~0.1%患病率最低,但部分国家呈上升趋势(如津巴布韦从 0.095% 升至 0.098%)

9- Correlation(热力图分析)

Corrmat = df1_variables.corr()
plt.figure(figsize=(10, 5), dpi=200)
sns.heatmap(Corrmat, annot=True,fmt=".2f", linewidth=.5)

热力图展示了精神分裂症(Schizophrenia disorders)、抑郁症(Depressive disorders)、焦虑症(Anxiety disorders)、双相情感障碍(Bipolar disorders)和饮食失调症(Eating disorders)这五种精神疾病患病率相关性的热力图。颜色越接近白色,相关性越强且为正相关;颜色越接近黑色,相关性越强且为负相关。可以看出,精神分裂症与抑郁症呈较强负相关(-0.47 ),焦虑症与双相情感障碍、饮食失调症等存在一定正相关(分别为 0.58、0.59 ) ,不同疾病间相关性表现出多样特征。

10- Scatter and Box plot

使用 Matplotlib 和 Seaborn 创建了一个包含四个子图的可视化,用于探索不同精神疾病与饮食失调症之间的关系。以下是带注释的代码解析:

 分别展示了精神分裂症、抑郁症、焦虑症、双相情感障碍与饮食失调症患病率之间的关系。从图中可见,各散点分布较为分散,难以直接看出明显的线性关系。在精神分裂症 - 饮食失调症散点图中,散点集中在精神分裂症患病率 0.2 - 0.4 之间,饮食失调症患病率 0 - 0.6 之间;抑郁症 - 饮食失调症散点图里,散点在抑郁症患病率 2 - 7 之间,饮食失调症患病率 0 - 0.8 间分布;焦虑症 - 饮食失调症散点图中,散点主要在焦虑症患病率 2 - 8 之间,饮食失调症患病率 0 - 0.6 间;双相情感障碍 - 饮食失调症散点图内,散点在双相情感障碍患病率 0.2 - 1.2 之间,饮食失调症患病率 0 - 0.8 间,表明这些精神疾病与饮食失调症患病率的关联可能较为复杂。

Numerical = ['Schizophrenia disorders', 'Depressive disorders','Anxiety disorders','Bipolar disorders','Eating disorders']
i = 0
while i < 5:
    fig = plt.figure(figsize = [30,3], dpi=200)
    plt.subplot(2,2,1)
    sns.boxplot(x = Numerical[i], data = df1_variables)
    i += 1
    plt.show()

11- Normalize(标准化)

features = ['Schizophrenia disorders', 'Depressive disorders','Anxiety disorders','Bipolar disorders']
X_model = df1[features]
y_model = df1["Eating disorders"]
scaler = preprocessing.MinMaxScaler()
X_model_norm = scaler.fit_transform(X_model)
X_model_norm
array([[0.12714204, 0.56728135, 0.42008448, 0.39345779],
       [0.12439376, 0.56616628, 0.41842183, 0.39273757],
       [0.1218262 , 0.56486898, 0.41570011, 0.39177399],
       ...,
       [0.04832425, 0.30858363, 0.19399437, 0.26936249],
       [0.0495569 , 0.30776117, 0.19157658, 0.26935944],
       [0.05140367, 0.30589079, 0.1863733 , 0.26935592]])

12- Simple Linear Regression

print("Mean Absolute Error of Model is: ", metrics.mean_absolute_error(y_test,y_pred))
print("Mean Squared Error of Model is: ", metrics.mean_squared_error(y_test,y_pred))
print("Root Mean Squared of Model is: ", np.sqrt(metrics.mean_squared_error(y_test,y_pred)))
print("R2 Score of Model is: ", metrics.r2_score(y_test,y_pred))
Mean Absolute Error of Model is:  0.08003250281357932
Mean Squared Error of Model is:  0.02178632883846133
Root Mean Squared of Model is:  0.14760192694697902
R2 Score of Model is:  0.6289967829652676

In [32]:

linkcode

k_fold = KFold(10)
print (cross_val_score(Model, X_model_norm, y_model.ravel(), cv=k_fold, n_jobs=1))
[0.67019159 0.30224538 0.34774549 0.6311535  0.62898747 0.59061848
 0.66269011 0.57389516 0.64517085 0.84017723]

13- Higher Dimension Linear Regression

定义了一个名为check的函数,用于通过多项式特征扩展来优化线性回归模型的性能。

def check(Dimension, testsize):
    """
    通过添加多项式特征来优化线性回归模型
    
    参数:
    Dimension: 多项式的次数(如2表示平方项)
    testsize: 测试集占比(用于train_test_split)
    """
    r2 = 0.6289  # 初始化R²分数阈值(基准值)
    
    # 遍历特征矩阵中的每个原始特征
    for column in X_model:
        # 创建新特征名称(原始特征名+维度)
        New_Col_name = column + str(Dimension)
        # 计算新特征值(原始特征值的Dimension次幂)
        New_Col_value = X_model[column]**Dimension
        
        # 在特征矩阵的第0列插入新特征
        X_model.insert(0, New_Col_name, New_Col_value)
        
        # 划分训练集和测试集
        X_train, X_test, y_train, y_test = train_test_split(
            X_model, y_model, test_size=testsize, random_state=0
        )
        
        # 训练新的线性回归模型
        New_model = LinearRegression()
        New_model.fit(X_train, y_train)
        
        # 在测试集上预测并计算R²分数
        y_pred = New_model.predict(X_test)
        r2_new = metrics.r2_score(y_test, y_pred)
        
        # 如果新特征导致R²分数下降,则删除该特征
        if r2_new < r2:
            X_model.drop([New_Col_name], axis=1, inplace=True)
        else:
            r2 = r2_new  # 更新最佳R²分数
            
    print("R2 score is: ", r2)  # 输出最终优化后的R²分数

# 调用函数:添加二次项特征,测试集占20%
check(2, 0.2)
Bipolar disorders2Anxiety disorders2Depressive disorders2Schizophrenia disorders2Schizophrenia disordersDepressive disordersAnxiety disordersBipolar disorders
00.49424222.21532924.9611950.0498210.2232064.9961184.7133140.703023
10.49290122.10974424.8930130.0494860.2224544.9892904.7021000.702069
20.49110921.93744824.8138050.0491740.2217514.9813464.6837430.700792
30.49012221.84205724.7701140.0488350.2209874.9769584.6735490.700087
40.48985721.81646624.7783140.0484810.2201834.9777824.6708100.699898
...........................
64150.29008510.13793411.6119010.0404180.2010423.4076243.1840120.538596
64160.29008210.15791011.6332500.0405290.2013193.4107553.1871480.538593
64170.29007810.16601011.6415080.0406580.2016393.4119653.1884180.538589
64180.29007410.06228811.6071650.0407940.2019763.4069293.1721110.538585
64190.2900699.84087411.5292550.0409990.2024823.3954763.1370170.538580

表格呈现了精神分裂症、抑郁症、焦虑症、双相情感障碍的原始患病率数据及其平方项数据,反映了不同地区和时间这些疾病患病率及其变化趋势。

15- Display Model's Output

a = X_test["Bipolar disorders"]
b = y_test
c = X_test["Bipolar disorders"]
d = y_pred
font1 = {'family':'fantasy','color':'blue','size':20}
font2 = {'family':'serif','color':'darkred','size':20}
font3 = {'family':'cursive','color':'green','size':20}
plt.figure(figsize= (20,10), dpi=200)
plt.title("Bipolar Prediction",fontdict=font2)
plt.xlabel("Bipolar",fontdict= font3)
plt.ylabel("Eating",fontdict=font1)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.scatter(a,b, color = 'blue', label = "Real Values")
plt.scatter(c,d, color = 'maroon', label = "Predicted Values", marker="H", s=80)
plt.legend(fontsize=15)
plt.show()

a1 = X_test["Schizophrenia disorders"]
b1 = y_test
c1 = X_test["Schizophrenia disorders"]
d1 = y_pred
plt.figure(figsize= (20,10), dpi=200)
plt.title("Schizophrenia Prediction",fontdict=font2)
plt.xlabel("Schizophrenia",fontdict= font3)
plt.ylabel("Eating",fontdict=font1)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.scatter(a1,b1, color = 'blue', label = "Real Values")
plt.scatter(c1,d1, color = 'Orange', label = "Predicted Values", marker="H", s=80)
plt.legend(fontsize=15)
plt.show()

 

a2 = X_test["Anxiety disorders"]
b2 = y_test
c2 = X_test["Anxiety disorders"]
d2 = y_pred
plt.figure(figsize= (20,10), dpi=200)
plt.title("Anxiety Prediction",fontdict=font2)
plt.xlabel("Anxiety",fontdict= font3)
plt.ylabel("Eating",fontdict=font1)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.scatter(a2,b2, color = 'blue', label = "Real Values")
plt.scatter(c2,d2, color = 'indigo', label = "Predicted Values", marker="H", s=80)
plt.legend(fontsize=15)
plt.show()

a3 = X_test["Depressive disorders"]
b3 = y_test
c3 = X_test["Depressive disorders"]
d3 = y_pred
plt.figure(figsize= (20,10), dpi=200)
plt.title("Depressive Prediction",fontdict=font2)
plt.xlabel("Depressive",fontdict= font3)
plt.ylabel("Eating",fontdict=font1)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.scatter(a3,b3, color = 'blue', label = "Real Values")
plt.scatter(c3,d3, color = 'green', label = "Predicted Values", marker="H", s=80)
plt.legend(fontsize=15)
plt.show()

16- Conclusion

如我们所见,该模型的最大回归准确率接近 70%。由于在回归项目中变量之间的相关性非常重要,或许该数据集中缺乏所需的相关性。我认为使用聚类分析、主成分分析(PCA)甚至自组织映射(SOM)可能会在这个数据集上取得良好的效果。感谢您的关注。如果本笔记本对您有用,多多关注。

-------本笔记写于2025年6月2日凌晨1:41分。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2401837.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【新品解读】一板多能,AXRF49 定义新一代 RFSoC FPGA 开发平台

“硬件系统庞杂、调试周期长” “高频模拟前端不稳定&#xff0c;影响采样精度” “接收和发射链路难以同步&#xff0c;难以扩展更多通道” “数据流量大&#xff0c;处理与存储跟不上” 这些是大部分客户在构建多通道、高频宽的射频采样链路时&#xff0c;面临的主要问题。…

贪心算法应用:线性规划贪心舍入问题详解

贪心算法应用&#xff1a;线性规划贪心舍入问题详解 贪心算法是一种在每一步选择中都采取当前状态下最优的选择&#xff0c;从而希望导致结果是全局最优的算法策略。在线性规划问题中&#xff0c;贪心算法特别是贪心舍入技术有着广泛的应用。下面我将全面详细地讲解这一主题。…

YOLO在C#中的完整训练、验证与部署方案

YOLO在C#中的完整训练、验证与部署方案 C# 在 YOLO 部署上优势明显&#xff08;高性能、易集成&#xff09;&#xff0c;但训练能力较弱&#xff0c;通常需结合 Python 实现。若项目对开发效率要求高且不依赖 C# 生态&#xff0c;建议全程使用 Python&#xff1b;若需深度集成…

洛谷题目:P2761 软件补丁问题 (本题简单)

个人介绍: 题目传送门: P2761 软件补丁问题 - 洛谷 (luogu.com.cn) 前言: 这道题是一个典型的状态搜索问题,核心目标就是利用给定d额多个补丁程序,将包含若干错误的软件修复成没有错误的状态,并且要使得修复过程当中的总耗时最少。下面是小亦为大家阐述滴思路: 1、状态…

智慧园区数字孪生全链交付方案:降本增效30%,多案例实践驱动全周期交付

在智慧园区建设浪潮中&#xff0c;数字孪生技术正成为破解传统园区管理难题的核心引擎。通过构建与物理园区1:1映射的数字模型&#xff0c;实现数据集成、状态同步与智能决策&#xff0c;智慧园区数字孪生全链交付方案已在多个项目中验证其降本增效价值——某物流园区通过该方案…

【OpenGL学习】(四)统一着色和插值着色

文章目录 【OpenGL学习】&#xff08;四&#xff09;统一着色和插值着色统一着色&#xff08;Flat/Uniform Shading&#xff09;插值着色&#xff08;Interpolated Shading&#xff09; 【OpenGL学习】&#xff08;四&#xff09;统一着色和插值着色 着色器介绍&#xff1a; h…

在 CentOS 上安装 Docker 和 Docker Compose 并配置使用国内镜像源

在 CentOS 上安装 Docker 和 Docker Compose 并配置使用国内镜像源&#xff0c;可以加速镜像下载速度。以下是详细的步骤&#xff1a; 一、安装 Docker 移除旧版本的 Docker&#xff08;如果有&#xff09;&#xff1a; sudo yum remove docker \docker-client \docker-client…

Docker慢慢学

1、Docker DeskTop 2、N8N下载 docker run -p 8888:5678 n8nio/n8n 3、Kafka kafka依赖zookeeper,先启动zookeeper docker pull zookeeper docker run -d --name zookeeper -p 2181:2181 -e ALLOW_ANONYMOUS_LOGINyes zookeeper 启动kafka docker pull confluentinc/cp…

cursor-free-vip使用

一、项目简介 Cursor-Free-VIP 是一个开源项目&#xff0c;旨在帮助用户免费使用 Cursor AI 的高级功能。它通过自动注册 Cursor 账号、重置机器 ID 和完成 Auth 验证等操作&#xff0c;解决 Cursor AI 中常见的限制提示。 二、系统准备 1…cursor需要更新到最新的版本 三、…

使用SSH tunnel访问内网的MySQL

文章目录 环境背景方法参考 注&#xff1a;本文是使用SSH tunnel做端口转发的一个示例。有关SSH端口转发&#xff0c;可参考我的几篇文档 https://blog.csdn.net/duke_ding2/article/details/106878081https://blog.csdn.net/duke_ding2/article/details/135627263https://blo…

Redis持久化模式RDB与AOF

RDB持久化 RDB也被叫做Redis数据快照。简单来说就是把内存中的所有数据记录到磁盘中。当Redis实例故障重启后重磁盘中读取快照文件进行数据恢复(快照文件默认保存在当前运行目录)&#xff1b; 演示Redis正常停机自动执行一次RDB操作 配置Redis触发RDB机制 RDB其它配置也可在red…

【数据结构】树形结构--二叉树(二)

【数据结构】树形结构--二叉树&#xff08;二&#xff09; 一.二叉树的实现1.求二叉树结点的个数2.求二叉树叶子结点的个数3.求二叉树第k层结点的个数4.求二叉树的深度&#xff08;高度&#xff09;5.在二叉树中查找值为x的结点6.判断二叉树是否为完全二叉树7.二叉树的销毁 一.…

深度学习题目1

梯度下降法的正确步骤是什么&#xff1f; a.计算预测值和真实值之间的误差 b.重复迭代&#xff0c;直至得到网络权重的最佳值 c.把输入传入网络&#xff0c;得到输出值 d.用随机值初始化权重和偏差 e.对每一个产生误差的神经元&#xff0c;调整相应的&#xff08;权重&#xff…

【Oracle】锁

个人主页&#xff1a;Guiat 归属专栏&#xff1a;Oracle 文章目录 1. 锁基础概述1.1 锁的概念与作用1.2 锁的工作原理1.3 Oracle锁的分类 2. 行级锁 (Row-Level Locks)2.1 行级锁的基本概念2.1.1 TX锁&#xff08;事务锁&#xff09;2.1.2 行级锁的工作机制 2.2 行级锁的类型2.…

JS逆向爬虫教程与实战技巧

想要一个关于爬虫JS逆向的详细教程。这是一个很专业的技术需求&#xff0c;最近有个可能是正在学习爬虫技术的开发者或者数据分析师&#xff0c;遇到了需要破解JavaScript加密的反爬机制的问题&#xff0c;想让我出一期实战教程&#xff0c;话不多说&#xff0c;开干。 以下是我…

【Redis】Redis 的常见客户端汇总

目录 一、命令行客户端 二、图形界面的客户端 三、Java 客户端 3.1 SpringDataRedis 3.2 Jedis 3.2.1 连接池的配置 3.3 Lettuce 3.3.1 RedisTemplate 工具类实现 3.3.2 自定义序列化器 3.3.3 StringRedisTemplate 3.3.4 集群配置 3.3.4.1 刷新节点集群拓扑动态感应…

关于akka官方quickstart示例程序(scala)的记录

参考资料 https://doc.akka.io/libraries/akka-core/current/typed/actors.html#first-example 关于scala语法的注意事项 extends App是个语法糖&#xff0c;等同于直接在伴生对象中编写main 方法对象是通过apply方法创建的&#xff0c;也可以通过对象的名称单独创建&#x…

2025年渗透测试面试题总结-腾讯[实习]玄武实验室-安全工程师(题目+回答)

安全领域各种资源&#xff0c;学习文档&#xff0c;以及工具分享、前沿信息分享、POC、EXP分享。不定期分享各种好玩的项目及好用的工具&#xff0c;欢迎关注。 目录 腾讯[实习]玄武实验室-安全工程师 1. 自我介绍 2. CSRF原理 3. Web安全入门时间 4. 学习Web安全的原因 …

网站首页菜单两种布局vue+elementui顶部和左侧栏导航

顶部菜单实现 <!DOCTYPE html> <html lang"zh-CN"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Vue.js Element UI 路由导航</…

@Builder的用法

Builder 是 Lombok 提供的一个注解&#xff0c;用于简化 Java 中构建对象的方式&#xff08;Builder 模式&#xff09;。它可以让你以更加简洁、链式的方式来创建对象&#xff0c;尤其适用于构造参数较多或部分可选的类。