决策工具模板¶
Decision Tools Templates
📋 决策工具概览¶
| 工具 | 用途 | 适用场景 | 复杂度 |
|---|---|---|---|
| SWOT 分析 | 战略态势分析 | 市场进入、产品定位 | ⭐ |
| PESTEL 分析 | 宏观环境分析 | 战略规划、风险评估 | ⭐ |
| 决策矩阵 | 多方案对比 | 方案选择、优先级排序 | ⭐⭐ |
| 决策树 | 风险决策分析 | 投资决策、产品决策 | ⭐⭐⭐ |
| 成本效益分析 | 经济性评估 | 项目评估、资源分配 | ⭐⭐ |
| 蒙特卡洛模拟 | 不确定性量化 | 风险评估、预测 | ⭐⭐⭐⭐ |
| 情景规划 | 战略情景分析 | 长期规划、风险管理 | ⭐⭐⭐ |
| AHP 层次分析 | 多准则决策 | 复杂决策、资源分配 | ⭐⭐⭐⭐ |
1. SWOT 分析¶
用途: 分析内部优势劣势 + 外部机会威胁
模板¶
## SWOT 分析:[项目/产品名称]
### 优势 (Strengths) - 内部
| 优势 | 说明 | 影响程度 |
|------|------|---------|
| | | 高/中/低 |
### 劣势 (Weaknesses) - 内部
| 劣势 | 说明 | 影响程度 |
|------|------|---------|
| | | 高/中/低 |
### 机会 (Opportunities) - 外部
| 机会 | 说明 | 影响程度 |
|------|------|---------|
| | | 高/中/低 |
### 威胁 (Threats) - 外部
| 威胁 | 说明 | 影响程度 |
|------|------|---------|
| | | 高/中/低 |
### 交叉策略
| 策略类型 | 策略内容 |
|---------|---------|
| SO 策略 (发挥优势,利用机会) | |
| WO 策略 (克服劣势,利用机会) | |
| ST 策略 (发挥优势,规避威胁) | |
| WT 策略 (克服劣势,规避威胁) | |
Python 可视化工具¶
import matplotlib.pyplot as plt
import numpy as np
def create_swot_matrix(swot_data):
"""
创建 SWOT 矩阵可视化
swot_data: dict with keys 'strengths', 'weaknesses', 'opportunities', 'threats'
"""
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
categories = ['内部因素', '外部因素']
# SWOT 四个象限
quadrants = [
('优势 (S)', swot_data['strengths'], 'green'),
('劣势 (W)', swot_data['weaknesses'], 'red'),
('机会 (O)', swot_data['opportunities'], 'blue'),
('威胁 (T)', swot_data['threats'], 'orange')
]
titles = [['优势 (S) - 内部', '劣势 (W) - 内部'],
['机会 (O) - 外部', '威胁 (T) - 外部']]
for idx, ((title, items, color), ax) in enumerate(zip(quadrants, axes.flatten())):
ax.set_title(title, fontsize=14, fontweight='bold', color=color)
ax.axis('off')
if items:
for i, item in enumerate(items):
ax.text(0.1, 0.9 - i * 0.15, f"• {item}",
transform=ax.transAxes, fontsize=11,
verticalalignment='top', bbox=dict(boxstyle='round',
facecolor='wheat', alpha=0.5))
plt.tight_layout()
plt.savefig('swot_analysis.png', dpi=300, bbox_inches='tight')
plt.show()
# 使用示例
swot_example = {
'strengths': ['技术领先', '团队经验丰富', '资金充足'],
'weaknesses': ['品牌知名度低', '渠道有限'],
'opportunities': ['市场需求增长', '政策支持', '新技术出现'],
'threats': ['竞争加剧', '经济下行', '人才争夺']
}
create_swot_matrix(swot_example)
2. PESTEL 分析¶
用途: 分析宏观环境六大维度
模板¶
## PESTEL 分析:[行业/市场名称]
### 政治因素 (Political)
| 因素 | 描述 | 影响 | 趋势 |
|------|------|------|------|
| | | 正面/负面/中性 | ↑/→/↓ |
### 经济因素 (Economic)
| 因素 | 描述 | 影响 | 趋势 |
|------|------|------|------|
| GDP 增长 | | | |
| 利率 | | | |
| 通货膨胀 | | | |
| 汇率 | | | |
### 社会因素 (Social)
| 因素 | 描述 | 影响 | 趋势 |
|------|------|------|------|
| 人口结构 | | | |
| 消费习惯 | | | |
| 生活方式 | | | |
### 技术因素 (Technological)
| 因素 | 描述 | 影响 | 趋势 |
|------|------|------|------|
| 技术革新 | | | |
| 自动化 | | | |
| 研发投入 | | | |
### 环境因素 (Environmental)
| 因素 | 描述 | 影响 | 趋势 |
|------|------|------|------|
| 环保法规 | | | |
| 碳排放 | | | |
| 可持续发展 | | | |
### 法律因素 (Legal)
| 因素 | 描述 | 影响 | 趋势 |
|------|------|------|------|
| 劳动法 | | | |
| 知识产权 | | | |
| 行业监管 | | | |
### 关键洞察
1.
2.
3.
3. 决策矩阵¶
用途: 多方案、多准则对比分析
模板¶
## 决策矩阵:[决策主题]
### 方案列表
1. 方案 A:
2. 方案 B:
3. 方案 C:
### 评估准则及权重
| 准则 | 权重 | 说明 |
|------|------|------|
| | 0.% | |
| | 0.% | |
| | 0.% | |
| **总计** | **100%** | |
### 评分表
| 方案 | 准则 1 (w=.) | 准则 2 (w=.) | 准则 3 (w=.) | 加权总分 |
|------|------------|------------|------------|---------|
| 方案 A | | | | |
| 方案 B | | | | |
| 方案 C | | | | |
### 评分说明
- 5 分:非常好
- 4 分:好
- 3 分:一般
- 2 分:差
- 1 分:非常差
### 决策建议
[基于加权总分的决策建议]
Python 实现¶
import pandas as pd
import numpy as np
def decision_matrix(options, criteria, weights, scores):
"""
决策矩阵分析
Args:
options: list of option names
criteria: list of criteria names
weights: dict of criteria weights (sum to 1)
scores: dict of {option: {criterion: score}}
Returns:
DataFrame with weighted scores and ranking
"""
# 创建评分 DataFrame
df = pd.DataFrame(scores).T
df.columns = criteria
# 计算加权分数
weighted_df = df.copy()
for criterion in criteria:
weighted_df[criterion] = df[criterion] * weights[criterion]
# 计算总分
df['加权总分'] = weighted_df.sum(axis=1)
# 排名
df['排名'] = df['加权总分'].rank(ascending=False, method='dense').astype(int)
df = df.sort_values('排名')
# 显示结果
print("决策矩阵分析结果")
print("=" * 60)
print(df.to_string())
print("=" * 60)
print(f"\n推荐方案:{df.index[0]} (得分:{df['加权总分'].iloc[0]:.2f})")
return df
# 使用示例:选择办公地点
options = ['地点 A', '地点 B', '地点 C']
criteria = ['成本', '交通便利', '办公环境', '周边配套']
weights = {
'成本': 0.35,
'交通便利': 0.30,
'办公环境': 0.20,
'周边配套': 0.15
}
scores = {
'地点 A': {'成本': 4, '交通便利': 3, '办公环境': 5, '周边配套': 4},
'地点 B': {'成本': 3, '交通便利': 5, '办公环境': 4, '周边配套': 5},
'地点 C': {'成本': 5, '交通便利': 4, '办公环境': 3, '周边配套': 3}
}
result = decision_matrix(options, criteria, weights, scores)
4. 决策树¶
用途: 风险环境下的序列决策分析
模板¶
## 决策树:[决策主题]
### 决策节点 1: [决策描述]
- **方案 A**: [方案描述]
- 自然状态 A1 (概率 __%): 结果 [描述],收益/成本 [数值]
- 自然状态 A2 (概率 __%): 结果 [描述],收益/成本 [数值]
- **期望值**: [计算]
- **方案 B**: [方案描述]
- 自然状态 B1 (概率 __%): 结果 [描述],收益/成本 [数值]
- 自然状态 B2 (概率 __%): 结果 [描述],收益/成本 [数值]
- **期望值**: [计算]
### 决策建议
选择方案 [X],期望值为 [数值]
### 敏感性分析
- 如果 [关键假设] 变化 __%,决策是否会改变?
- 最坏情况:[描述]
- 最好情况:[描述]
Python 实现(含可视化)¶
import graphviz
from typing import List, Dict, Tuple
class DecisionTree:
"""决策树分析类"""
def __init__(self):
self.nodes = []
def add_decision_node(self, name: str, alternatives: List[str]):
"""添加决策节点"""
node = {
'type': 'decision',
'name': name,
'alternatives': alternatives
}
self.nodes.append(node)
return len(self.nodes) - 1
def add_chance_node(self, name: str, outcomes: List[Tuple[str, float, float]]):
"""
添加机会节点
Args:
name: 节点名称
outcomes: list of (outcome_name, probability, payoff)
"""
node = {
'type': 'chance',
'name': name,
'outcomes': outcomes,
'expected_value': sum(p * payoff for _, p, payoff in outcomes)
}
self.nodes.append(node)
return len(self.nodes) - 1
def calculate_ev(self, node_idx: int) -> float:
"""计算指定期望值"""
node = self.nodes[node_idx]
if node['type'] == 'chance':
return node['expected_value']
return 0
def visualize(self, filename: str = 'decision_tree'):
"""可视化决策树"""
dot = graphviz.Digraph(comment='Decision Tree')
dot.attr(rankdir='LR')
for idx, node in enumerate(self.nodes):
if node['type'] == 'decision':
dot.node(f'd{idx}', node['name'], shape='square',
style='filled', fillcolor='lightblue')
elif node['type'] == 'chance':
dot.node(f'c{idx}', f"{node['name']}\nEV={node['expected_value']:.0f}",
shape='circle', style='filled', fillcolor='lightyellow')
# 添加连接(简化版,完整版需要记录节点间关系)
for idx in range(len(self.nodes) - 1):
dot.edge(f'd{idx}', f'c{idx+1}')
dot.render(filename, view=True)
# 使用示例:产品开发决策
tree = DecisionTree()
# 决策节点:是否开发新产品
tree.add_decision_node("产品开发决策", ["开发新产品", "改进现有产品"])
# 机会节点:开发新产品的结果
tree.add_chance_node("新产品市场反应", [
("成功", 0.6, 5000000), # 60% 概率赚 500 万
("失败", 0.4, -2000000) # 40% 概率亏 200 万
])
# 机会节点:改进现有产品的结果
tree.add_chance_node("改进产品市场反应", [
("成功", 0.8, 2000000), # 80% 概率赚 200 万
("失败", 0.2, -500000) # 20% 概率亏 50 万
])
# 计算并显示期望值
print(f"开发新产品期望值:¥{tree.calculate_ev(1):,.0f}")
print(f"改进现有产品期望值:¥{tree.calculate_ev(2):,.0f}")
print(f"推荐决策:{'开发新产品' if tree.calculate_ev(1) > tree.calculate_ev(2) else '改进现有产品'}")
# 可视化
tree.visualize('product_decision')
5. 成本效益分析¶
用途: 评估项目的经济可行性
模板¶
## 成本效益分析:[项目名称]
### 项目概述
- 项目周期: [X] 年
- 折现率:[X]%
- 评估基准:[日期]
### 成本分析
#### 一次性成本
| 成本项 | 金额 | 发生时间 |
|--------|------|---------|
| | ¥ | 第 X 年 |
| **小计** | **¥** | |
#### 年度运营成本
| 成本项 | 年金额 | 持续年数 |
|--------|--------|---------|
| | ¥ | X 年 |
| **小计** | **¥/年** | |
### 效益分析
#### 有形效益
| 效益项 | 年金额 | 计算依据 |
|--------|--------|---------|
| | ¥ | |
| **小计** | **¥/年** | |
#### 无形效益
-
-
-
### 财务指标
| 指标 | 数值 | 判断标准 |
|------|------|---------|
| 净现值 (NPV) | ¥ | >0 可行 |
| 内部收益率 (IRR) | % | >折现率可行 |
| 投资回收期 | X 年 | 越短越好 |
| 效益成本比 (BCR) | X | >1 可行 |
### 敏感性分析
| 变量 | 变化范围 | NPV 影响 |
|------|---------|---------|
| 收入 | ±20% | ¥ ~ ¥ |
| 成本 | ±20% | ¥ ~ ¥ |
| 折现率 | ±2% | ¥ ~ ¥ |
### 决策建议
[基于财务指标和敏感性分析的决策建议]
Python 实现¶
import numpy as np
def cost_benefit_analysis(initial_cost, annual_costs, annual_benefits,
discount_rate, years):
"""
成本效益分析
Args:
initial_cost: 初始投资
annual_costs: 年度运营成本列表
annual_benefits: 年度效益列表
discount_rate: 折现率
years: 项目年限
Returns:
dict with NPV, IRR, Payback Period, BCR
"""
# 计算净现金流
net_cashflows = [-initial_cost] + [b - c for b, c in
zip(annual_benefits, annual_costs)]
# 计算净现值 (NPV)
npv = sum(cf / (1 + discount_rate) ** t
for t, cf in enumerate(net_cashflows))
# 计算效益成本比 (BCR)
pv_benefits = sum(b / (1 + discount_rate) ** t
for t, b in enumerate(annual_benefits, 1))
pv_costs = initial_cost + sum(c / (1 + discount_rate) ** t
for t, c in enumerate(annual_costs, 1))
bcr = pv_benefits / pv_costs
# 计算投资回收期
cumulative = 0
payback_period = 0
for t, cf in enumerate(net_cashflows):
cumulative += cf
if cumulative >= 0:
payback_period = t
break
# 计算内部收益率 (IRR)
irr = np.irr(net_cashflows)
results = {
'NPV': npv,
'IRR': irr,
'Payback Period': payback_period,
'BCR': bcr,
'PV Benefits': pv_benefits,
'PV Costs': pv_costs
}
# 输出报告
print("成本效益分析报告")
print("=" * 60)
print(f"初始投资:¥{initial_cost:,.0f}")
print(f"折现率:{discount_rate:.1%}")
print(f"项目年限:{years} 年")
print("=" * 60)
print(f"净现值 (NPV): ¥{npv:,.0f}")
print(f"内部收益率 (IRR): {irr:.1%}")
print(f"投资回收期:{payback_period} 年")
print(f"效益成本比 (BCR): {bcr:.2f}")
print("=" * 60)
# 决策建议
if npv > 0 and bcr > 1:
print("✓ 项目可行 (NPV>0, BCR>1)")
else:
print("✗ 项目不可行")
return results
# 使用示例
cost_benefit_analysis(
initial_cost=1000000, # 初始投资 100 万
annual_costs=[200000] * 5, # 年运营成本 20 万
annual_benefits=[400000] * 5, # 年效益 40 万
discount_rate=0.10, # 折现率 10%
years=5 # 5 年期
)
6. 蒙特卡洛模拟¶
用途: 不确定性环境下的风险量化
模板¶
## 蒙特卡洛模拟:[分析主题]
### 模型设定
- 模拟次数:[10,000] 次
- 关键变量及分布:
- 变量 A: [正态分布/均匀分布/三角分布], 参数 [μ=__, σ=__]
- 变量 B: [分布类型], 参数 [__]
### 输入假设
| 变量 | 分布类型 | 参数 | 依据 |
|------|---------|------|------|
| | | μ=, σ= | |
### 模拟结果
| 统计量 | 数值 |
|--------|------|
| 均值 | |
| 标准差 | |
| P10 (悲观) | |
| P50 (中位数) | |
| P90 (乐观) | |
| 最小值 | |
| 最大值 | |
### 风险分析
- 损失概率:P(X<0) = __%
- 达到目标的概率:P(X>目标值) = __%
### 可视化
[直方图 + 累积分布图]
Python 实现(完整版)¶
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
def monte_carlo_simulation(model_func, input_distributions,
n_simulations=10000, seed=42):
"""
通用蒙特卡洛模拟框架
Args:
model_func: 输出 = f(输入变量)
input_distributions: dict of {var_name: (distribution, params)}
n_simulations: 模拟次数
seed: 随机种子
Returns:
dict with simulation results
"""
np.random.seed(seed)
# 生成随机输入
inputs = {}
for var_name, (dist_name, params) in input_distributions.items():
if dist_name == 'normal':
inputs[var_name] = np.random.normal(params['mu'], params['sigma'],
n_simulations)
elif dist_name == 'uniform':
inputs[var_name] = np.random.uniform(params['low'], params['high'],
n_simulations)
elif dist_name == 'triangular':
inputs[var_name] = np.random.triangular(params['left'],
params['mode'],
params['right'],
n_simulations)
elif dist_name == 'lognormal':
inputs[var_name] = np.random.lognormal(params['mu'], params['sigma'],
n_simulations)
# 运行模拟
outputs = model_func(inputs)
# 统计分析
results = {
'mean': np.mean(outputs),
'std': np.std(outputs),
'median': np.median(outputs),
'p10': np.percentile(outputs, 10),
'p50': np.percentile(outputs, 50),
'p90': np.percentile(outputs, 90),
'min': np.min(outputs),
'max': np.max(outputs),
'outputs': outputs,
'inputs': inputs
}
return results
def plot_monte_carlo_results(results, title="蒙特卡洛模拟结果"):
"""可视化蒙特卡洛模拟结果"""
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
outputs = results['outputs']
# 直方图
axes[0].hist(outputs, bins=50, alpha=0.7, edgecolor='black', density=True)
axes[0].axvline(results['mean'], color='red', linestyle='--',
label=f"均值:¥{results['mean']:,.0f}")
axes[0].axvline(results['p50'], color='green', linestyle='--',
label=f"中位数:¥{results['p50']:,.0f}")
axes[0].axvline(results['p10'], color='orange', linestyle=':',
label=f"P10: ¥{results['p10']:,.0f}")
axes[0].axvline(results['p90'], color='orange', linestyle=':',
label=f"P90: ¥{results['p90']:,.0f}")
axes[0].set_xlabel('结果')
axes[0].set_ylabel('概率密度')
axes[0].set_title(f'{title}\n概率分布')
axes[0].legend()
axes[0].grid(True, alpha=0.3)
# 累积分布
sorted_outputs = np.sort(outputs)
cumulative_prob = np.arange(1, len(sorted_outputs) + 1) / len(sorted_outputs)
axes[1].plot(sorted_outputs, cumulative_prob, linewidth=2)
axes[1].axhline(0.1, color='gray', linestyle='--', alpha=0.5)
axes[1].axhline(0.5, color='gray', linestyle='--', alpha=0.5)
axes[1].axhline(0.9, color='gray', linestyle='--', alpha=0.5)
axes[1].axvline(results['p10'], color='orange', linestyle=':', alpha=0.7)
axes[1].axvline(results['p50'], color='green', linestyle=':', alpha=0.7)
axes[1].axvline(results['p90'], color='orange', linestyle=':', alpha=0.7)
axes[1].set_xlabel('结果')
axes[1].set_ylabel('累积概率')
axes[1].set_title('累积分布函数 (CDF)')
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('monte_carlo_results.png', dpi=300, bbox_inches='tight')
plt.show()
# 打印统计摘要
print("蒙特卡洛模拟结果摘要")
print("=" * 60)
print(f"模拟次数:{len(outputs):,}")
print(f"均值:¥{results['mean']:,.0f}")
print(f"标准差:¥{results['std']:,.0f}")
print(f"中位数 (P50): ¥{results['p50']:,.0f}")
print(f"P10 (悲观): ¥{results['p10']:,.0f}")
print(f"P90 (乐观): ¥{results['p90']:,.0f}")
print(f"范围:[¥{results['min']:,.0f}, ¥{results['max']:,.0f}]")
print("=" * 60)
# 使用示例 1:项目成本估算
def project_cost_model(inputs):
"""项目成本 = 人力 + 设备 + 外包"""
return inputs['labor'] + inputs['equipment'] + inputs['outsourcing']
labor_dist = ('triangular', {'left': 800000, 'mode': 1000000, 'right': 1500000})
equipment_dist = ('normal', {'mu': 500000, 'sigma': 100000})
outsourcing_dist = ('uniform', {'low': 200000, 'high': 400000})
input_dists = {
'labor': labor_dist,
'equipment': equipment_dist,
'outsourcing': outsourcing_dist
}
results = monte_carlo_simulation(project_cost_model, input_dists, n_simulations=10000)
plot_monte_carlo_results(results, "项目成本蒙特卡洛模拟")
# 使用示例 2:投资回报分析
def roi_model(inputs):
"""ROI = (收入 - 成本) / 成本"""
revenue = inputs['revenue']
cost = inputs['cost']
return (revenue - cost) / cost * 100 # ROI 百分比
roi_inputs = {
'revenue': ('normal', {'mu': 2000000, 'sigma': 300000}),
'cost': ('triangular', {'left': 1000000, 'mode': 1200000, 'right': 1500000})
}
roi_results = monte_carlo_simulation(roi_model, roi_inputs, n_simulations=10000)
plot_monte_carlo_results(roi_results, "投资回报率蒙特卡洛模拟")
# 计算达到目标 ROI 的概率
target_roi = 50 # 目标 ROI 50%
prob_achieving = np.mean(roi_results['outputs'] >= target_roi)
print(f"达到{target_roi}%ROI 的概率:{prob_achieving:.1%}")
7. 情景规划¶
用途: 长期战略规划与风险管理
模板¶
## 情景规划:[战略主题]
### 关键不确定性维度
| 维度 | 极端 A | 极端 B |
|------|--------|--------|
| 维度 1 | | |
| 维度 2 | | |
### 情景矩阵
### 情景详述
#### 情景 1: [名称]
- **发生概率**: __%
- **关键特征**:
-
-
- **驱动因素**:
-
- **战略应对**:
-
#### 情景 2: [名称]
...
### 早期预警指标
| 情景 | 预警指标 | 阈值 | 监测频率 |
|------|---------|------|---------|
| 情景 1 | | | 月度/季度 |
### 战略选择评估
| 战略选项 | 情景 1 | 情景 2 | 情景 3 | 情景 4 | 鲁棒性评分 |
|---------|--------|--------|--------|--------|-----------|
| 战略 A | | | | | |
| 战略 B | | | | | |
Python 辅助工具¶
import pandas as pd
import numpy as np
def scenario_planning_framework(strategies, scenarios, payoffs):
"""
情景规划分析框架
Args:
strategies: list of strategy names
scenarios: list of scenario names
payoffs: dict of {strategy: {scenario: payoff}}
Returns:
analysis results with robustness scores
"""
# 创建收益矩阵
payoff_matrix = pd.DataFrame(payoffs).T
# 计算各战略的统计指标
analysis = pd.DataFrame(index=strategies)
analysis['最小收益'] = payoff_matrix.min(axis=1) # Maximin 准则
analysis['最大收益'] = payoff_matrix.max(axis=1) # Maximax 准则
analysis['平均收益'] = payoff_matrix.mean(axis=1) # Laplace 准则
analysis['收益标准差'] = payoff_matrix.std(axis=1) # 风险度量
analysis['最小遗憾'] = payoff_matrix.apply(
lambda row: (payoff_matrix.max(axis=1) - row).max(), axis=1
) # Minimax Regret 准则
# 计算鲁棒性评分(基于变异系数)
analysis['鲁棒性评分'] = analysis['平均收益'] / analysis['收益标准差']
# 排名
analysis['综合排名'] = analysis['鲁棒性评分'].rank(ascending=False).astype(int)
print("情景规划分析")
print("=" * 80)
print("收益矩阵:")
print(payoff_matrix.to_string())
print("\n战略分析:")
print(analysis.to_string())
print("=" * 80)
print(f"推荐战略:{analysis['综合排名'].idxmin()}")
print(f"(基于最高鲁棒性评分:{analysis['鲁棒性评分'].max():.2f})")
return analysis, payoff_matrix
# 使用示例:市场进入战略
strategies = ['快速扩张', '稳健发展', '保守观望']
scenarios = ['经济繁荣', '平稳增长', '经济衰退', '剧烈动荡']
payoffs = {
'快速扩张': {'经济繁荣': 100, '平稳增长': 60, '经济衰退': -50, '剧烈动荡': -80},
'稳健发展': {'经济繁荣': 70, '平稳增长': 50, '经济衰退': 10, '剧烈动荡': -20},
'保守观望': {'经济繁荣': 30, '平稳增长': 25, '经济衰退': 15, '剧烈动荡': 5}
}
analysis, matrix = scenario_planning_framework(strategies, scenarios, payoffs)
8. AHP 层次分析¶
用途: 复杂多准则决策
模板¶
目标层:[总目标] ├─ 准则层 1: [准则名称] │ ├─ 子准则 1.1 │ └─ 子准则 1.2 ├─ 准则层 2: [准则名称] │ ├─ 子准则 2.1 │ └─ 子准则 2.2 └─ 准则层 3: [准则名称] └─ ...方案层:[方案 A, 方案 B, 方案 C]
### 判断矩阵
#### 准则层判断矩阵
| | 准则 1 | 准则 2 | 准则 3 | 权重 |
|---|-------|-------|-------|------|
| 准则 1 | 1 | | | |
| 准则 2 | | 1 | | |
| 准则 3 | | | 1 | |
### 一致性检验
| 指标 | 数值 | 标准 |
|------|------|------|
| CI (一致性指标) | | <0.1 |
| RI (随机指标) | | |
| CR (一致性比率) | | <0.1 通过 |
### 方案排序
| 方案 | 综合得分 | 排名 |
|------|---------|------|
| | | |
Python 实现¶
import numpy as np
from scipy.linalg import eigh
def ahp_analysis(criteria_matrix, alternatives_matrices):
"""
AHP 层次分析法
Args:
criteria_matrix: 准则层判断矩阵 (n×n)
alternatives_matrices: 各准则下的方案判断矩阵列表
Returns:
dict with weights, rankings, consistency check
"""
def calculate_weights(matrix):
"""计算权重向量"""
n = matrix.shape[0]
eigenvalues, eigenvectors = eigh(matrix)
# 取最大特征值对应的特征向量
max_idx = np.argmax(eigenvalues)
weights = eigenvectors[:, max_idx]
weights = weights / weights.sum() # 归一化
return weights, eigenvalues[max_idx]
def consistency_check(matrix, eigenvalue):
"""一致性检验"""
n = matrix.shape[0]
CI = (eigenvalue - n) / (n - 1)
RI_table = {1: 0, 2: 0, 3: 0.58, 4: 0.90, 5: 1.12, 6: 1.24, 7: 1.32}
RI = RI_table.get(n, 1.49)
CR = CI / RI if RI > 0 else 0
return {'CI': CI, 'RI': RI, 'CR': CR, 'passed': CR < 0.1}
# 1. 计算准则层权重
criteria_weights, criteria_eigenvalue = calculate_weights(criteria_matrix)
criteria_consistency = consistency_check(criteria_matrix, criteria_eigenvalue)
print("准则层权重:")
for i, w in enumerate(criteria_weights):
print(f" 准则{i+1}: {w:.4f}")
print(f"一致性检验 CR={criteria_consistency['CR']:.4f} "
f"{'✓ 通过' if criteria_consistency['passed'] else '✗ 未通过'}")
# 2. 计算各准则下的方案权重
n_alternatives = alternatives_matrices[0].shape[0]
alternative_scores = np.zeros(n_alternatives)
for idx, alt_matrix in enumerate(alternatives_matrices):
alt_weights, alt_eigenvalue = calculate_weights(alt_matrix)
alt_consistency = consistency_check(alt_matrix, alt_eigenvalue)
alternative_scores += criteria_weights[idx] * alt_weights
print(f"\n准则{idx+1}下方案权重:")
for i, w in enumerate(alt_weights):
print(f" 方案{i+1}: {w:.4f}")
print(f"一致性检验 CR={alt_consistency['CR']:.4f} "
f"{'✓ 通过' if alt_consistency['passed'] else '✗ 未通过'}")
# 3. 综合排序
ranking = np.argsort(-alternative_scores)
print("\n" + "=" * 60)
print("方案综合排名:")
for i, idx in enumerate(ranking, 1):
print(f" {i}. 方案{idx+1}: {alternative_scores[idx]:.4f}")
print("=" * 60)
return {
'criteria_weights': criteria_weights,
'alternative_scores': alternative_scores,
'ranking': ranking,
'best_alternative': ranking[0],
'criteria_consistency': criteria_consistency
}
# 使用示例:选择供应商
# 准则层判断矩阵(成本、质量、服务、交付)
criteria_matrix = np.array([
[1, 1/3, 3, 2], # 成本
[3, 1, 5, 4], # 质量
[1/3, 1/5, 1, 1/2], # 服务
[1/2, 1/4, 2, 1] # 交付
])
# 各准则下的方案判断矩阵(3 个供应商)
alt_matrices = [
# 成本准则下的比较
np.array([
[1, 3, 5],
[1/3, 1, 2],
[1/5, 1/2, 1]
]),
# 质量准则下的比较
np.array([
[1, 1/2, 1/4],
[2, 1, 1/2],
[4, 2, 1]
]),
# 服务准则下的比较
np.array([
[1, 1, 2],
[1, 1, 2],
[1/2, 1/2, 1]
]),
# 交付准则下的比较
np.array([
[1, 2, 1],
[1/2, 1, 1/2],
[1, 2, 1]
])
]
results = ahp_analysis(criteria_matrix, alt_matrices)
print(f"\n推荐供应商:方案{results['best_alternative']+1}")
📚 使用说明¶
工具选择指南¶
| 决策场景 | 推荐工具 |
|---|---|
| 快速定性分析 | SWOT、PESTEL |
| 多方案对比 | 决策矩阵 |
| 风险决策 | 决策树 |
| 项目评估 | 成本效益分析 |
| 不确定性高 | 蒙特卡洛模拟 |
| 长期战略 | 情景规划 |
| 复杂多准则 | AHP 层次分析 |
使用流程¶
- 明确决策问题: 定义决策目标、约束条件
- 选择合适工具: 根据决策类型选择上述工具
- 收集数据: 准备所需输入数据
- 应用工具: 使用模板或代码进行分析
- 敏感性检验: 验证结论的稳健性
- 做出决策: 基于分析结果决策
- 记录与复盘: 记录决策依据,事后复盘
最后更新: 2026-06-01
相关文档: - decision-making-methodology.md - 决策方法论 - decision-science-resources.md - 决策科学资源
**决策工具模板 | 让决策更科学、更理性**
[返回顶部](#决策工具模板)