python: 熵权法、理想解、贴近度

安装依赖

安装pandas时,顺便也装了numpy

## 安装依赖
conda activate assembly
python3 -m pip install pandas

输入

引包,读表

##
import pandas as pd
import numpy as np

name="YM"
name="BT"
name="TG"
name="Industry"
name="JC"
name="JC2"
name="add"

df = pd.read_csv(name+".txt", index_col=0, sep="\t")
# 变量应为表头,利用 index column 转置
df = pd.DataFrame(df.values.T, 
                    index = df.columns, 
                    columns = df.index)

1 正向指标取倒数

或者是理想解取反极值

df.iloc[:,0] = 1/df.iloc[:,0]
df.iloc[:,1] = 1/df.iloc[:,1]
df.iloc[:,3] = 1/df.iloc[:,3]
df.iloc[:,4] = 1/df.iloc[:,4]
df.iloc[:,5] = 1/df.iloc[:,5]
df.iloc[:,6] = 1/df.iloc[:,6]
df.iloc[:,7] = 1/df.iloc[:,7]
#:1: RuntimeWarning: divide by zero encountered in log
#:1: RuntimeWarning: invalid value encountered in multiply

2 标准化
linalg.norm或者用极值

#data = (df - df.min())/(df.max() - df.min()) # max min 列为单位
m,n = df.shape
df_matrix = df.values

data = np.zeros((m, n))
for i in range(0, n):
    data[:, i] = df_matrix[:, i]/np.linalg.norm(df_matrix[:, i])

3 计算熵值:ej

yij = data.sum(axis=0) # 列和
pij = data/yij
test = pij * np.log(pij)
test = np.nan_to_num(test)

k = 1/np.log(m)
ej = -k*(test.sum(axis=0))

4 计算权重:wj

wj = (1-ej)/np.sum(1-ej)

5 加权规范化矩阵

mt = data * wj  # .T 矩阵转置

6 正理想解,负理想解

pos = mt.max(axis=0) # 0列,1行
neg = mt.min(axis=0)

7 各样本到正负理想解的欧式距离
Euclidean distance 欧几里德距离

dis_pos = np.zeros((1, m))
dis_neg = np.zeros((1, m))
for i in range(0, mt.shape[0]):
    dis_pos[:, i] = np.linalg.norm(mt[i, :] - pos) 
    dis_neg[:, i] = np.linalg.norm(mt[i, :] - neg)

8 贴近度

close = dis_neg/(dis_pos + dis_neg)

9 整理结果

out1 = dis_pos.T
out1 = np.column_stack((out1, dis_neg.T))
out1 = np.column_stack((out1, close.T))

out1 = pd.DataFrame(out1, 
                  index = df.index, 
                  columns = ['dis_pos','dis_neg', 'closeness'])

out1.to_csv(name+"_out1.csv", sep=',', index = True)

out2 = ej.T
out2 = np.column_stack((out2, wj.T))
out2 = np.column_stack((out2, pos.T))
out2 = np.column_stack((out2, neg.T))

out2 = pd.DataFrame(out2, 
                  index = df.columns, 
                  columns = ['e','w', 'pos', 'neg'])

out2.to_csv(name+"_out2.csv", sep=',', index = True)

更多:
一个简单实用的评价模型——TOPSIS理想解法
熵权法的python实现
Python学习笔记——熵权—TOPSIS
推荐系统-- 欧式距离和相似度
对身高和体重两个单位不同的指标使用欧式距离可能使结果失效,所以一般需要做数据标准化

你可能感兴趣的:(python: 熵权法、理想解、贴近度)