当我们需要评估多个决策单元(如学校、医院或企业部门)的效率时,传统方法往往需要复杂的数学计算和大量时间。数据包络分析(DEA)中的CCR模型正是为解决这类多投入多产出的效率评价问题而生。本文将带你快速掌握如何用Python的DEApy库实现CCR模型,无需深入数学原理也能轻松应用。
在开始之前,我们需要准备好Python环境和示例数据。假设我们要评估6所中学的效率,投入指标包括生均投入和非低收入家庭百分比,产出指标则是生均写作得分和生均科技得分。
首先安装必要的库:
bash复制pip install deapy pandas numpy
接着创建示例数据文件schools.csv:
csv复制school,student_cost,low_income_percent,writing_score,science_score
A,89300,64.3,250,223
B,86200,99,316,328
C,108100,99.6,273,291
D,106600,96,291,295
E,102000,96.2,306,320
F,115700,79.9,290,310
用pandas读取数据:
python复制import pandas as pd
data = pd.read_csv('schools.csv')
inputs = data[['student_cost', 'low_income_percent']].values
outputs = data[['writing_score', 'science_score']].values
DEApy库已经封装了CCR模型的复杂计算过程,我们只需几行代码即可完成效率评价:
python复制from deapy import CCR
# 创建CCR模型实例
model = CCR(inputs, outputs)
# 计算效率得分
efficiency_scores = model.efficiency()
# 将结果添加到原始数据中
data['efficiency'] = efficiency_scores
print(data.sort_values('efficiency', ascending=False))
运行后会输出类似下面的结果:
code复制 school student_cost low_income_percent writing_score science_score efficiency
B B 86200 99.0 316 328 1.000000
E E 102000 96.2 306 320 0.963107
F F 115700 79.9 290 310 0.843478
D D 106600 96.0 291 295 0.783784
C C 108100 99.6 273 291 0.722222
A A 89300 64.3 250 223 0.700000
效率得分在0到1之间,1表示完全有效,得分越低效率相对越低。从结果可以看出:
我们可以用matplotlib绘制效率分布图:
python复制import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.bar(data['school'], data['efficiency'], color='skyblue')
plt.axhline(y=1, color='r', linestyle='--')
plt.title('School Efficiency Scores (CCR Model)')
plt.ylabel('Efficiency Score')
plt.xlabel('School')
plt.show()
实际应用中,我们可能需要对模型进行更多定制化设置:
如果需要限制某些指标的权重范围,可以添加约束条件:
python复制from deapy import WeightRestriction
# 限制生均投入的权重不超过0.7
restrictions = [WeightRestriction(input_index=0, upper=0.7)]
model = CCR(inputs, outputs, weight_restrictions=restrictions)
CCR模型假设规模收益不变,如果需要分析规模收益变化,可以使用BCC模型:
python复制from deapy import BCC
bcc_model = BCC(inputs, outputs)
scale_efficiency = bcc_model.scale_efficiency()
提示:实际项目中,建议先用描述性统计和相关性分析检查数据质量,再运行DEA模型。
下面是一个完整的学校评价案例,包含数据预处理、模型运行和结果分析:
python复制import pandas as pd
from deapy import CCR
import matplotlib.pyplot as plt
# 数据准备
data = pd.DataFrame({
'school': ['A', 'B', 'C', 'D', 'E', 'F'],
'student_cost': [89300, 86200, 108100, 106600, 102000, 115700],
'low_income_percent': [64.3, 99, 99.6, 96, 96.2, 79.9],
'writing_score': [250, 316, 273, 291, 306, 290],
'science_score': [223, 328, 291, 295, 320, 310]
})
# 标准化处理(可选)
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
data[['student_cost', 'low_income_percent']] = scaler.fit_transform(data[['student_cost', 'low_income_percent']])
data[['writing_score', 'science_score']] = scaler.fit_transform(data[['writing_score', 'science_score']])
# 运行CCR模型
inputs = data[['student_cost', 'low_income_percent']].values
outputs = data[['writing_score', 'science_score']].values
model = CCR(inputs, outputs)
data['efficiency'] = model.efficiency()
# 结果分析
print("效率排名:")
print(data.sort_values('efficiency', ascending=False))
# 可视化
plt.style.use('ggplot')
fig, ax = plt.subplots(figsize=(12, 6))
bars = ax.bar(data['school'], data['efficiency'], color=['#4C72B0' if x < 1 else '#55A868' for x in data['efficiency']])
ax.axhline(1, color='#CC6677', linestyle='--')
ax.set_title('学校效率评价结果(CCR模型)', pad=20, fontsize=15)
ax.set_xlabel('学校', labelpad=10)
ax.set_ylabel('效率得分', labelpad=10)
# 添加数值标签
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.3f}',
ha='center', va='bottom')
plt.tight_layout()
plt.savefig('school_efficiency.png', dpi=300)
plt.show()
这个案例展示了从数据准备到结果可视化的完整流程。实际应用中,可以根据需要调整输入输出指标,或者尝试不同的DEA模型变体。