python绘制结构方程模型SEM

结构方程模型SEM

结构方程模型(Structural Equation Modeling, SEM)是一种统计建模方法,它结合了因素分析和路径分析来检验多个变量之间的关系。SEM允许研究者同时评估测量模型(即潜变量与观测指标间的关系)和结构模型(即潜变量间的因果关系)。这种方法在社会科学、心理学、教育学、市场研究等领域得到广泛应用。

主要特点

  • 处理复杂关系:SEM能够处理多个因变量,并且可以同时考虑直接效应、间接效应以及总效应。
  • 包含误差项:在SEM中,每个观测变量都假设有一个误差项,这有助于更准确地估计模型参数。
  • 潜在变量:SEM允许使用潜在变量(或称构念),这些是不能直接观测到但可以通过一组相关联的观测变量来推断的概念。
  • 模型拟合度评价:通过一系列指标(如χ²/df比值、RMSEA、CFI等)来评估所构建模型与数据之间的拟合程度。

案例:

Qian等(2024)利用结构方程路径图探讨了多因素协调下生态调水工程(EWTP)对生态系统服务(ES)总体效益(OB)的影响。(a) EWTP 前的模拟框架,(b) EWTP 后的模拟框架。Pre 表示降水量,NDVI 表示归一化植被指数,AET 表示实际蒸散量,Tem 表示温度,SHDI 表示景观多样性指数,OB 表示生态系统服务的总体效益。EWC 代表 EWTP。蓝色箭头表示正向影响关系,红色箭头表示负向影响关系,剪切头上的数字表示影响程度,星号表示基于 P 值的统计显著性水平:"***"表示数值<0.01,结果非常显著;"**"表示数值0.01<P值<0.05,结果相对显著;"*"表示数值0.05<P值<0.1,结果不显著。
结构方程路径图

python示例代码

我用到的数据是模拟的随机数据,放在了SEM_simulated_data.csv文件中。
部分数据展示:


随机模拟数据
import semopy
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

# 读取数据
data = pd.read_csv("./SEM_simulated_data.csv")

# 定义 SEM 模型
model_desc = """
NDVI ~ Pre
Runoff ~ Pre + Tem
AET ~ NDVI
SHDI ~ NDVI + Tem
OB ~ NDVI + Runoff + Tem
"""

# 使用 semopy 拟合模型
model = semopy.Model(model_desc)
result = model.fit(data)

# 获取路径系数数据
param_df = model.inspect()

# 定义变量类别
input_vars = ["Pre", "Tem"]  # 输入变量
mediator_vars = ["NDVI", "Runoff"]  # 中介变量
output_vars = ["AET", "SHDI", "OB"]  # 输出变量

# 创建有向图
G = nx.DiGraph()

# 添加节点和颜色
node_colors = {}  # 字典存储节点颜色
for var in input_vars:
    G.add_node(var)
    node_colors[var] = "lightgreen"  # 输入变量:绿色
for var in mediator_vars:
    G.add_node(var)
    node_colors[var] = "skyblue"  # 中介变量:蓝色
for var in output_vars:
    G.add_node(var)
    node_colors[var] = "lightcoral"  # 输出变量:红色

# 添加边(路径系数)
for _, row in param_df.iterrows():
    if row["op"] == "~":  # 表示有路径
        weight = row["Estimate"]
        color = "blue" if weight > 0 else "red"  # 根据正负设置颜色
        significance = row["p-value"]  # 显著性水平
        stars = ""
        if significance < 0.001:
            stars = "***"
        elif significance < 0.01:
            stars = "**"
        elif significance < 0.05:
            stars = "*"
        label = f"{weight:.2f}{stars}"  # 加入显著性星号
        G.add_edge(row["rval"], row["lval"], weight=abs(weight), color=color, label=label)

# 绘制图形
plt.figure(figsize=(12, 8))

# 布局
pos = nx.spring_layout(G)

# 提取边的属性
edges = G.edges(data=True)
edge_colors = [attr["color"] for _, _, attr in edges]

# 修改粗细放大倍数(整体加粗)
scaling_factor = 5  # 调整此值以加粗箭头
edge_weights = [attr["weight"] * scaling_factor for _, _, attr in edges]

# 绘制节点和边
nx.draw(
    G,
    pos,
    with_labels=True,
    node_color=[node_colors[node] for node in G.nodes()],
    node_size=3000,
    edge_color=edge_colors,
    width=edge_weights,  # 加粗的边宽
    font_size=10
)

# 添加路径系数标签(带负号和显著性星号)
edge_labels = nx.get_edge_attributes(G, "label")
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

# 添加图例
legend_elements = [
    plt.Line2D([0], [0], marker="o", color="w", label="Input Variables", markerfacecolor="lightgreen", markersize=10),
    plt.Line2D([0], [0], marker="o", color="w", label="Mediator Variables", markerfacecolor="skyblue", markersize=10),
    plt.Line2D([0], [0], marker="o", color="w", label="Output Variables", markerfacecolor="lightcoral", markersize=10),
]
plt.legend(handles=legend_elements, loc="upper left")

plt.title("SEM Path Diagram with Variable Categories")
plt.show()

结果展示:
图中绿色的输入变量,蓝色的是中间变量,红色的是输出变量。红色箭头是负相关,蓝色箭头是正相关。


结构方程路径图

参考文献

Qian, K. et al. Trade-offs and synergies among ecosystem services in Inland River Basins under the influence of ecological water transfer project: A case study on the Tarim River basin. The Science of The Total Environment 908, 168248–168248 (2023).

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容