1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| import itertools import math import bisect
XIE_LV = -2
INIT_PRICE = 500
def calculate_y(x): return x * (XIE_LV*x + INIT_PRICE)
def calcuate_total_value(X=[1, 2, 3, 4, 5, 6, 7, 8]): combinations = [] for i in range(1, len(X) + 1): combinations.extend(itertools.combinations(X, i))
total = [] for combination in combinations: sum_x = sum(combination) y_values = calculate_y(sum_x) print(f"For combination {combination}, y values are {y_values}") total.append(y_values) return total
def power_set(List): PS = [list(j) for i in range(len(List)) for j in itertools.combinations(List, i+1)] return PS
def calculate_shapley(X=[1, 2, 3, 4, 5, 6, 7, 8]): """
Args: X (): 代表每个用户提供的电量
Returns:
""" X_length = len(X) tempList = list([i for i in range(X_length)]) zuhe = power_set(tempList) total_prices = calcuate_total_value(X)
assert len(zuhe) == len(total_prices), "组合的数量和组合的收益的数量一定相等" shapley_values = [] for i in range(X_length): shapley = 0 for j in zuhe: if i not in j: Cui = j[:] bisect.insort_left(Cui,i) l = zuhe.index(j) total_l_price = float(total_prices[l]) elif i in j and len(j) == 1: Cui = j[:] total_l_price = 0 else: continue k = zuhe.index(Cui) cmod = len(Cui) chazhi = float(float(total_prices[k]) - total_l_price) jiecheng_jisuan = float(math.factorial(cmod-1) * math.factorial(X_length - cmod)) chushu_jiecheng = float(math.factorial(X_length)) temp = chazhi * jiecheng_jisuan / chushu_jiecheng shapley += temp cmod = 0 Cui = [i] k = zuhe.index(Cui) temp = float(total_prices[k]) * float(math.factorial(cmod) * math.factorial(X_length - cmod - 1)) / float(math.factorial(X_length)) shapley += temp shapley_values.append(shapley) print(shapley_values)
if __name__ == '__main__': calculate_shapley(X=[12,15,19,40,90])
|