创业者焦虑与转型决策分析
- SEM/fsQCA融合:结合定量(SEM)与定性(fsQCA)方法,揭示复杂因果关系
- 调节效应分析:量化F_WC/EIC对焦虑-转型路径的影响
将SEM和fsQCA方法转化为可交互的决策支持系统,为创业者、研究者和咨询机构提供参考
import streamlit as st
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.graph_objects as go
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LinearRegression
import matplotlib as mpl# 设置中文字体支持
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'Microsoft YaHei', 'WenQuanYi Micro Hei']
plt.rcParams['axes.unicode_minus'] = False# 页面初始化
st.set_page_config(layout="wide",page_title="创业者焦虑与转型决策分析系统",page_icon="📊"
)
st.title("创业者焦虑与转型决策分析系统")
st.subheader("基于混合方法(SEM+fsQCA)的模拟分析工具")# 侧边栏 - 参数配置
with st.sidebar:st.header("模型参数配置")# 核心变量设置st.subheader("核心变量范围")anxiety = st.slider("创业者焦虑水平(0-10)", 0.0, 10.0, 7.0, 0.1)fwc = st.slider("家庭工作冲突(F_WC, 0-10)", 0.0, 10.0, 6.0, 0.1)eic = st.slider("创业身份中心性(EIC, 0-10)", 0.0, 10.0, 8.0, 0.1)# 路径系数调整st.subheader("路径系数设置")anx_cd = st.slider("焦虑→认知失调(β1)", 0.0, 1.0, 0.35, 0.05)cd_ti = st.slider("认知失调→转型意向(β2)", 0.0, 1.0, 0.42, 0.05)fwc_mod = st.slider("F_WC调节强度(β3)", 0.0, 1.0, 0.28, 0.05)eic_mod = st.slider("EIC调节强度(β4)", 0.0, 1.0, 0.31, 0.05)# fsQCA分析阈值st.subheader("fsQCA分析设置")consistency = st.slider("一致性阈值(0.7-1.0)", 0.7, 1.0, 0.8, 0.01)coverage = st.slider("覆盖度阈值(0.5-1.0)", 0.5, 1.0, 0.65, 0.01)# 样本设置sample_size = st.number_input("模拟样本量", 100, 1000, 500)# 数据导出选项st.subheader("数据导出")export_format = st.selectbox("导出格式", ["CSV", "Excel"])st.caption("注:参数基于创业行为研究领域经典文献")# 模型核心功能
def calculate_transformation(anxiety, fwc, eic, anx_cd, cd_ti, fwc_mod, eic_mod):"""计算转型意向的核心模型"""# 计算认知失调(受家庭工作冲突调节)cognitive_dissonance = anxiety * anx_cd + anxiety * fwc * fwc_mod# 计算转型意向(受创业身份中心性调节)transformation_intention = cognitive_dissonance * cd_ti + cognitive_dissonance * eic * eic_mod# 加入随机噪声使模型更真实noise = np.random.normal(0, 0.15)return max(0, min(10, transformation_intention + noise)), cognitive_dissonancedef generate_sample_data(size, params):"""生成模拟样本数据集"""data = []for _ in range(size):# 生成随机变量(围绕输入值波动)anxiety_val = np.random.normal(params['anxiety'], 1.2)fwc_val = np.random.normal(params['fwc'], 1.1)eic_val = np.random.normal(params['eic'], 1.0)ti, cd = calculate_transformation(anxiety_val, fwc_val, eic_val,params['anx_cd'], params['cd_ti'],params['fwc_mod'], params['eic_mod'])# 转换为0-10评分data.append({'anxiety': max(0, min(10, anxiety_val)),'fwc': max(0, min(10, fwc_val)),'eic': max(0, min(10, eic_val)),'cognitive_dissonance': cd,'transformation_intention': ti,'high_ti': 1 if ti > 6.5 else 0 # 高转型意向阈值})return pd.DataFrame(data)# 页面主区域
tab1, tab2, tab3, tab4, tab5 = st.tabs(["核心路径分析","关系可视化","组态分析(fsQCA)","决策建议","数据导出"
])# 准备模型参数
model_params = {'anxiety': anxiety,'fwc': fwc,'eic': eic,'anx_cd': anx_cd,'cd_ti': cd_ti,'fwc_mod': fwc_mod,'eic_mod': eic_mod
}# 标签1: 核心路径分析
with tab1:st.header("结构方程模型(SEM)路径分析")# 计算当前输入的转型意向ti, cd = calculate_transformation(anxiety, fwc, eic, anx_cd, cd_ti, fwc_mod, eic_mod)# 展示路径图col1, col2 = st.columns([1, 2])with col1:st.subheader("实时预测结果")st.metric("认知失调水平", f"{cd:.2f}/10.0", delta=f"{(cd - 5):.1f}" if cd > 5 else f"{(cd - 5):.1f}",delta_color="inverse" if cd < 5 else "normal")st.metric("转型决策倾向", f"{ti:.2f}/10.0", delta=f"{(ti - 5):.1f}" if ti > 5 else f"{(ti - 5):.1f}")# 评估决策水平if ti < 3.5:decision_level = "低转型意向"color = "green"elif ti < 6.5:decision_level = "中等转型意向"color = "orange"else:decision_level = "高转型意向"color = "red"st.markdown(f"**决策评估**: :{color}[{decision_level}]")st.progress(ti / 10, text=f"转型意向强度 ({ti:.1f}/10)")with col2:# 使用Plotly绘制交互式路径图st.subheader("模型路径关系图")# 创建网络图数据nodes = [{"name": "焦虑", "group": 1},{"name": "认知失调", "group": 2},{"name": "转型意向", "group": 3},{"name": "F_WC", "group": 4},{"name": "EIC", "group": 5}]edges = [{"source": "焦虑", "target": "认知失调", "value": anx_cd * 100, "color": "#1f77b4"},{"source": "认知失调", "target": "转型意向", "value": cd_ti * 100, "color": "#ff7f0e"},{"source": "F_WC", "target": "焦虑", "value": fwc_mod * 100, "color": "#d62728"},{"source": "EIC", "target": "转型意向", "value": eic_mod * 100, "color": "#9467bd"}]fig = go.Figure(data=[go.Scatter(x=[0.1, 0.3, 0.5, 0.2, 0.4],y=[0.9, 0.5, 0.1, 0.7, 0.3],text=[node['name'] for node in nodes],mode='markers+text',marker=dict(size=50,color=[node['group'] for node in nodes],colorscale='Viridis'),textposition="middle center",hoverinfo='text'),go.Scatter(x=[0.1, 0.3, 0.3, 0.5, 0.1, 0.2, 0.4, 0.5],y=[0.9, 0.5, 0.5, 0.1, 0.9, 0.7, 0.3, 0.1],mode='lines',line=dict(width=4),hoverinfo='none')])fig.update_layout(showlegend=False,xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),margin=dict(l=0, r=0, b=0, t=0),height=400)st.plotly_chart(fig, use_container_width=True)# 标签2: 关系可视化
with tab2:st.header("变量关系可视化分析")# 生成样本数据df = generate_sample_data(sample_size, model_params)# 选项卡布局vis_tab1, vis_tab2, vis_tab3 = st.tabs(["回归分析", "相关系数矩阵", "三维关系"])with vis_tab1:col1, col2 = st.columns(2)with col1:# 焦虑与转型意向关系fig, ax = plt.subplots(figsize=(8, 5))sns.regplot(x=df['anxiety'], y=df['transformation_intention'],scatter_kws={'alpha': 0.4}, line_kws={'color': 'red'}, ax=ax)ax.set(xlabel="焦虑水平", ylabel="转型意向", title="焦虑对转型意向的影响")st.pyplot(fig)# 中介效应分析df['anxiety_group'] = pd.cut(df['anxiety'], [0, 5, 10], labels=['低焦虑', '高焦虑'])fig, ax = plt.subplots(figsize=(8, 5))sns.boxplot(x='anxiety_group', y='transformation_intention', data=df,palette="Set2", ax=ax)ax.set(xlabel="焦虑分组", ylabel="转型意向", title="不同焦虑水平下的转型意向分布")st.pyplot(fig)with col2:# 调节效应分析st.subheader("调节效应分析")moderator = st.radio("选择调节变量", ["家庭工作冲突(F_WC)", "创业身份中心性(EIC)"])if moderator == "家庭工作冲突(F_WC)":fig, ax = plt.subplots(figsize=(8, 5))sns.scatterplot(data=df, x='anxiety', y='transformation_intention',hue='fwc', palette='viridis', size='fwc', sizes=(20, 200),alpha=0.7, ax=ax)ax.set(xlabel="焦虑水平", ylabel="转型意向",title="F_WC对焦虑-转型关系的调节效应")st.pyplot(fig)else:fig, ax = plt.subplots(figsize=(8, 5))sns.scatterplot(data=df, x='cognitive_dissonance',y='transformation_intention',hue='eic', palette='plasma', size='eic', sizes=(20, 200),alpha=0.7, ax=ax)ax.set(xlabel="认知失调", ylabel="转型意向",title="EIC对认知失调-转型关系的调节效应")st.pyplot(fig)with vis_tab2:st.subheader("变量间相关关系")# 计算相关系数矩阵corr_cols = ['anxiety', 'fwc', 'eic', 'cognitive_dissonance', 'transformation_intention']corr_matrix = df[corr_cols].corr()# 创建热力图fig, ax = plt.subplots(figsize=(10, 7))sns.heatmap(corr_matrix, annot=True, fmt=".2f", cmap='coolwarm',square=True, linewidths=.5, cbar_kws={"shrink": .75}, ax=ax)ax.set_xticklabels(['焦虑', 'F_WC', 'EIC', '认知失调', '转型意向'], rotation=45)ax.set_yticklabels(['焦虑', 'F_WC', 'EIC', '认知失调', '转型意向'], rotation=0)ax.set_title("变量相关系数矩阵", fontsize=14)st.pyplot(fig)# 相关系数解释st.markdown("**相关系数解读:**")st.markdown("- |r| ≥ 0.8: 极强相关")st.markdown("- 0.6 ≤ |r| < 0.8: 强相关")st.markdown("- 0.4 ≤ |r| < 0.6: 中度相关")st.markdown("- |r| < 0.4: 弱相关")with vis_tab3:st.subheader("三维交互关系")# 使用Plotly创建3D散点图fig = go.Figure(data=[go.Scatter3d(x=df['anxiety'],y=df['fwc'],z=df['transformation_intention'],mode='markers',marker=dict(size=6,color=df['eic'],colorscale='Viridis',opacity=0.8))])fig.update_layout(scene=dict(xaxis_title='焦虑水平',yaxis_title='家庭工作冲突',zaxis_title='转型意向'),margin=dict(l=0, r=0, b=0, t=0),height=600)st.plotly_chart(fig, use_container_width=True)# 标签3: fsQCA组态分析
with tab3:st.header("模糊集定性比较分析(fsQCA)")st.info("该方法识别导致高转型意向的多重因果组合路径")# 处理数据df = generate_sample_data(sample_size, model_params)# 定义高水平的阈值df['high_anxiety'] = (df['anxiety'] > 6.5).astype(int)df['high_fwc'] = (df['fwc'] > 6.5).astype(int)df['high_eic'] = (df['eic'] > 6.5).astype(int)df['high_cd'] = (df['cognitive_dissonance'] > 5).astype(int)# 计算组合路径def calc_consistency(outcome, condition):"""计算组态路径的一致性"""consistent_cases = df[(condition == 1) & (outcome == 1)].shape[0]condition_cases = df[condition == 1].shape[0]return consistent_cases / condition_cases if condition_cases > 0 else 0def calc_coverage(outcome, condition):"""计算组态路径的覆盖度"""covered_cases = df[(condition == 1) & (outcome == 1)].shape[0]outcome_cases = df[outcome == 1].shape[0]return covered_cases / outcome_cases if outcome_cases > 0 else 0# 路径1: 身份驱动型path1 = df['high_anxiety'] & df['high_fwc'] & df['high_eic']cons1 = calc_consistency(df['high_ti'], path1)cov1 = calc_coverage(df['high_ti'], path1)# 路径2: 认知失调驱动型path2 = df['high_anxiety'] & df['high_fwc'] & df['high_cd']cons2 = calc_consistency(df['high_ti'], path2)cov2 = calc_coverage(df['high_ti'], path2)# 路径3: 综合路径path3 = (df['high_anxiety'] | df['high_fwc']) & (df['high_eic'] | df['high_cd'])cons3 = calc_consistency(df['high_ti'], path3)cov3 = calc_coverage(df['high_ti'], path3)# 显示结果st.subheader("组态路径分析结果")col1, col2, col3 = st.columns(3)def create_path_card(title, formula, cons, cov, thresholds):"""创建路径结果卡片"""meets_threshold = cons > thresholds['consistency'] and cov > thresholds['coverage']status = "显著路径 ✓" if meets_threshold else "非显著路径"color = "green" if meets_threshold else "gray"card = st.container(border=True)card.markdown(f"#### {title}")card.markdown(f"**逻辑公式**: `{formula}`")card.markdown(f"**一致性**: {cons:.3f} (阈值={thresholds['consistency']:.2f})")card.markdown(f"**覆盖度**: {cov:.3f} (阈值={thresholds['coverage']:.2f})")card.markdown(f"**状态**: :{color}[{status}]")return cardthresholds = {'consistency': consistency, 'coverage': coverage}with col1:create_path_card("身份驱动型","高焦虑 & 高F_WC & 高EIC",cons1, cov1, thresholds)with col2:create_path_card("认知失调驱动型","高焦虑 & 高F_WC & 高认知失调",cons2, cov2, thresholds)with col3:create_path_card("综合路径","(高焦虑|高F_WC) & (高EIC|高认知失调)",cons3, cov3, thresholds)# 绘制结果矩阵st.subheader("高转型案例分布图")# 仅选取高转型案例high_ti_df = df[df['high_ti'] == 1]if not high_ti_df.empty:# 创建散点图矩阵fig = sns.pairplot(high_ti_df[['anxiety', 'fwc', 'eic', 'cognitive_dissonance']],diag_kind='kde',plot_kws={'alpha': 0.5})st.pyplot(fig)else:st.warning("当前参数下未检测到高转型意向案例")# 标签4: 决策建议
with tab4:st.header("管理决策建议")# 计算转型意向指数ti = calculate_transformation(anxiety, fwc, eic, anx_cd, cd_ti, fwc_mod, eic_mod)[0]st.subheader("现状评估")col1, col2, col3 = st.columns([2, 1, 1])with col1:if ti < 4:status = "低转型意向"status_color = "green"status_icon = "🟢"elif ti < 7:status = "中等转型意向"status_color = "orange"status_icon = "🟠"else:status = "高转型意向"status_color = "red"status_icon = "🔴"st.markdown(f"""**当前状态**: :{status_color}[{status_icon} {status}]**焦虑水平**: {anxiety:.1f}/10.0 **家庭工作冲突**: {fwc:.1f}/10.0 **身份中心性**: {eic:.1f}/10.0 **转型意向指数**: {ti:.2f}/10.0""")with col2:st.metric("焦虑→认知失调", f"{anx_cd:.2f}")st.metric("认知失调→转型", f"{cd_ti:.2f}")with col3:st.metric("F_WC调节强度", f"{fwc_mod:.2f}")st.metric("EIC调节强度", f"{eic_mod:.2f}")# 针对性建议st.subheader("管理干预策略")container = st.container(border=True)container.markdown("### 🛠️ 焦虑管理策略")if anxiety > 7:container.markdown("""- **认知重构训练**: 每周3次引导式反思练习- **压力缓解机制**: 每日15分钟正念冥想- **导师支持**: 建立创业者互助小组- **工作分解**: 大任务分解为可管理单元""")else:container.markdown("""- **压力监测**: 使用应激反应量表每周自评- **预防性干预**: 每月1次职业心理咨询- **资源优化**: 减少非核心业务投入""")if fwc > 6:container.markdown("### 👨👩👧 家庭工作平衡策略")container.markdown("""- **时空分离**: 专用工作空间+固定家庭时间- **责任分担**: 关键家庭任务委托机制- **家人沟通**: 每周家庭会议建立共享目标- **外部支持**: 家庭托幼/家政服务""")if ti > 5:container.markdown("### 🔄 转型决策策略")if ti < 7:container.markdown("""**中等转型意向行动计划:**1. 市场验证: 构建最小可行性产品(MVP)2. 成本分析: 建立转型损益模型3. 团队动员: 开展愿景共识工作坊4. 风险预备金: 储备3-6个月运营资金""")else:container.markdown("""**高转型意向执行框架:**1. **过渡计划**: 分三阶段(试点/扩张/整合)实施2. **组织重组**: 建立转型专项团队3. **利益相关方管理**: 客户/投资人/员工沟通计划4. **退出机制**: 设定关键绩效指标(KPIs)及止损点""")# 标签5: 数据导出
with tab5:st.header("数据导出功能")# 生成样本数据df = generate_sample_data(sample_size, model_params)st.subheader("模拟数据集预览")st.dataframe(df.head())st.subheader("导出选项")# 导出全部数据st.download_button(label="下载完整数据集",data=df.to_csv().encode('utf-8'),file_name=f"entrepreneur_data_{sample_size}.csv",mime="text/csv")# 导出分析摘要summary = f"""创业者焦虑与转型分析报告
生成时间: {pd.Timestamp.now()}
参数配置:
- 焦虑水平: {anxiety}
- F_WC: {fwc}
- EIC: {eic}
- 路径系数: β1={anx_cd}, β2={cd_ti}, β3={fwc_mod}, β4={eic_mod}
样本量: {sample_size}
主要发现:
- 转型意向均值: {df['transformation_intention'].mean():.2f}
- 高转型案例占比: {(df['high_ti'].mean() * 100):.1f}%
- 焦虑-转型相关系数: {df[['anxiety', 'transformation_intention']].corr().iloc[0, 1]:.3f}"""st.download_button(label="下载分析摘要报告",data=summary.encode('utf-8'),file_name="analysis_summary.txt",mime="text/plain")# 导出当前参数配置param_config = {'核心变量': {'焦虑水平': anxiety, '家庭工作冲突': fwc, '创业身份中心性': eic},'路径系数': {'焦虑→认知失调': anx_cd,'认知失调→转型': cd_ti,'F_WC调节强度': fwc_mod,'EIC调节强度': eic_mod},'fsQCA阈值': {'一致性阈值': consistency, '覆盖度阈值': coverage}}st.download_button(label="下载当前配置",data=str(param_config).encode('utf-8'),file_name="parameter_config.json",mime="application/json")# 帮助文档
st.sidebar.markdown("---")
with st.sidebar.expander("系统帮助文档"):st.markdown("""**系统使用指南**:1. 左侧调整参数模拟不同情境2. 通过各选项卡查看分析结果3. 数据导出功能下载分析结果4. 自定义阈值可发现新组态路径**理论依据**:- SEM模型建立因果路径- fsQCA识别多重并发因果关系- 调节效应揭示条件性作用机制**适用场景**:- 创业者自我诊断- 咨询服务工具- 创业行为学术研究""")