-
Notifications
You must be signed in to change notification settings - Fork 0
/
kMeans20221004.py
89 lines (84 loc) · 2.61 KB
/
kMeans20221004.py
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
import copy
import gurobipy as gp
from gurobipy import GRB
import numpy as np
from matplotlib import pyplot as plt
import xlrd
# k-means clustering: generate xi for my sddp
# 20221004
# temperature /= 10
# elec load (total): 1.6-5.4MW
# heat load (total): 3-5MW
# water load (total): 3.5-5.5 hundred_t/h
T = 24
Ss,S = 80,240
clsN = 3 # classfied into 3 classes
feaN = 4 # dimension of features
xi = np.zeros((3,T,feaN)) # used directly in sddp
bk = xlrd.open_workbook('xi.xls')
sh = bk.sheet_by_name("tems")
tems = np.zeros((T, S), dtype=np.float64)
for t in range(T):
for s in range(S):
tems[t,s] = sh.cell_value(t+1,s+1)
sh = bk.sheet_by_name("elds")
elds = np.zeros((T, S), dtype=np.float64)
for t in range(T):
for s in range(S):
elds[t,s] = sh.cell_value(t+1,s+1)
sh = bk.sheet_by_name("hlds")
hlds = np.zeros((T, S), dtype=np.float64)
for t in range(T):
for s in range(S):
hlds[t,s] = sh.cell_value(t+1,s+1)
sh = bk.sheet_by_name("wlds")
wlds = np.zeros((T, S), dtype=np.float64)
for t in range(T):
for s in range(S):
wlds[t,s] = sh.cell_value(t+1,s+1)
d = np.zeros((feaN, T, S),dtype=np.float64)
d[0],d[1],d[2],d[3] = tems,elds,hlds,wlds
xik = np.zeros((clsN,feaN),dtype=np.float64) # 3 centers, every vector 4 components
for t in range(T):
for dim in range(feaN):
tmp = np.sort(d[dim, t, :])
for c in range(clsN):
xik[c,dim] = np.average(tmp[c*Ss:(c+1)*Ss])
for g in range(10):
totDist = 0
dist = np.zeros(clsN,dtype=np.float64) # a sample point's dist to 3 ref points
cls = np.zeros(S) # record each sample's class Num
for s in range(S):
sp = d[:, t, s] # sample point
for c in range(clsN):
dist[c] = np.linalg.norm(sp - xik[c,:])
cls[s] = np.argmin(dist)
totDist += np.min(dist)
N0,N1,N2 = 0,0,0
sm0 = np.zeros(4,dtype=np.float64)
sm1 = np.zeros(4,dtype=np.float64)
sm2 = np.zeros(4,dtype=np.float64)
for s in range(S):
if cls[s] == 0:
N0 += 1
sm0 += d[:,t,s]
elif cls[s] == 1:
N1 += 1
sm1 += d[:,t,s]
elif cls[s] == 2:
N2 += 1
sm2 += d[:,t,s]
# print('%4d|%8g'%(g,totDist))
# print(xik)
# print(N0, N1, N2)
xik[0,:] = sm0/N0
xik[1,:] = sm1/N1
xik[2,:] = sm2/N2
for level in range(clsN):
xi[level,t,:] = xik[level,:]
print(xi)
for t in range(T):
print('t=',t)
for level in range(clsN):
print(xi[level,t,:])
np.save('myxi.npy',xi)