-
Notifications
You must be signed in to change notification settings - Fork 7
/
Tool_20210621.py
2617 lines (2511 loc) · 133 KB
/
Tool_20210621.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
@project: 各种提高效率的函数或类
@autor:郑煜钒
@file:Tool.py
@time:2021-06-21
@vision:1.9
"""
import pandas as pd
import numpy as np
import os
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_absolute_error,mean_squared_error,median_absolute_error,r2_score,mean_squared_log_error
import catboost as cb
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import RandomForestRegressor,BaggingRegressor,GradientBoostingRegressor,ExtraTreesRegressor,AdaBoostRegressor
from itertools import combinations
from sklearn.neural_network import MLPRegressor
import lightgbm as lgb
import xgboost as xgb
import csv
from sklearn.svm import SVR,LinearSVR
from numpy import random
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression,SGDRegressor,BayesianRidge,LogisticRegression,PassiveAggressiveRegressor,ElasticNet,Ridge,Lasso
from sklearn.gaussian_process import GaussianProcessRegressor
import joblib
from sklearn.preprocessing import MaxAbsScaler,StandardScaler,MinMaxScaler
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import davies_bouldin_score,calinski_harabasz_score,silhouette_score
# 寻找文件夹下所有文件的名字,suffix为指定后缀进行查找,如 suffix=".csv"
def file_name(file_dir,suffix=None):
L=[]
for root, dirs, files in os.walk(file_dir):
for file in files:
if(suffix==None):
L.append(os.path.join(root, file).replace("\\","/"))
else:
if (os.path.splitext(file)[1] == suffix):
L.append(os.path.join(root, file).replace("\\","/"))
return L
# ---------------------------------------分割线------------------------------------------------
# 创建文件夹
def mkdir(path):
folder = os.path.exists(path)
if not folder: #判断是否存在文件夹如果不存在则创建为文件夹
os.makedirs(path) #makedirs 创建文件时如果路径不存在会创建这个路径
print("--- new folder... ---")
print("--- OK ---")
else:
print("--- There is this folder! ---")
# ---------------------------------------分割线------------------------------------------------
'''
将正常数据集转换为时间序列数据
Input:
data:原始数据(按时间排序);使用num天的数据去预测later天后的值,type:DataFrame;
ignore:不对其进行时间序列操作的列名,如一些固化不变(不随时间变化)的特征(经纬度),type:List;
y:预测目标的列名,type:string;
drop_c:需要在操作前删除的列,type:List;
is_sum:预测的时间单位的大小,默认是1,如代表预测某一天。若为7,则代表预测连续7天的累计值。
Output:
seq:创建好重构后的时间序列格式数据。
'''
def create_time_seq(data,num=2,later=1,ignore=None,y=None,drop_c=None,is_sum=1):
if(drop_c!=None):
data = data.drop(columns=drop_c)
later = later-1
if(isinstance(data,pd.DataFrame)): # 先判断类型是否是pd.DataFrame,不是的话直接退出
if(ignore!=None and y!=None):
print("1")
# ingure 和 y 都有指定
# 取出y值
if(is_sum==1):
seq = pd.DataFrame(data[y].values[num+later+is_sum:].tolist(),columns=["Y"])
else:
sy = []
for n in range(data.shape[0]-later-is_sum-num):
sy.append(np.sum(data[y].iloc[n+later+num+1:n+is_sum+later+num+1].values))
seq = pd.DataFrame(sy,columns=["Y"])
for c in data.columns: # 遍历所有的列名
if c not in ignore: # 判断列名是否在ignore里
cl = data[c].values # 取出相应列名的列
cl_time = np.array([cl[n:n+num] for n in range(cl.shape[0]-num-later-is_sum)]) # 按每次取num行出来,直到倒数第num+later+1行结束
cl_name = [c+"_"+str(i+1) for i in range(num)] # 取列名
data2 = pd.DataFrame(cl_time.reshape(-1,num),columns=cl_name)
seq = pd.concat([data2,seq],axis=1) # 跟之前存在的数据进行拼接
else:
seq[c] = data[c].values[num+later+is_sum:]
elif(ignore!=None and y==None):
print("2")
# ingure有指定,但是y没指定,则取最后一列
# 取出y值
y = -1
if(is_sum==1):
seq = pd.DataFrame(data.iloc[num+later+is_sum:,-1].values.tolist(),columns=["Y"])
else:
sy = []
for n in range(data.shape[0]-later-is_sum-num):
sy.append(np.sum(data[y].iloc[n+later+num+1:n+is_sum+later+num+1].values))
seq = pd.DataFrame(sy,columns=["Y"])
for c in data.columns:
if c not in ignore:
cl = data[c].values
cl_time = np.array([cl[n:n+num] for n in range(cl.shape[0]-num-later-is_sum)])
cl_name = [c+"_"+str(i+1) for i in range(num)]
data2 = pd.DataFrame(cl_time.reshape(-1,num),columns=cl_name)
seq = pd.concat([data2,seq],axis=1)
else:
seq[c] = data[c].values[num+later+is_sum:]
elif(ignore==None and y!=None):
print("3")
# y有指定,但是ingure没指定,则取除去y列剩下的所有
# 取出y值
if(is_sum==1):
seq = pd.DataFrame(data[y].values[num+later+is_sum:].tolist(),columns=["Y"])
else:
sy = []
for n in range(data.shape[0]-later-is_sum-num):
sy.append(np.sum(data[y].iloc[n+later+num+1:n+is_sum+later+num+1].values))
seq = pd.DataFrame(sy,columns=["Y"])
for c in data.columns:
cl = data[c].values
cl_time = np.array([cl[n:n+num] for n in range(cl.shape[0]-num-later-is_sum)])
cl_name = [c+"_"+str(i+1) for i in range(num)]
data2 = pd.DataFrame(cl_time.reshape(-1,num),columns=cl_name)
print(data2.shape[0])
seq = pd.concat([data2,seq],axis=1)
elif(ignore==None and y==None):
print("4")
# y , ingure都没指定,则取最后一列为y,其他所有特征都做成时序数据
# 取出y值
if(is_sum==1):
seq = pd.DataFrame(data.iloc[num+later+is_sum:,-1].values.tolist(),columns=["Y"])
else:
sy = []
for n in range(data.shape[0]-later-is_sum-num):
sy.append(np.sum(data[y].iloc[n+later+num+1:n+is_sum+later+num+1].values))
seq = pd.DataFrame(sy,columns=["Y"])
for c in data.columns:
cl = data[c].values
cl_time = np.array([cl[n:n+num] for n in range(cl.shape[0]-num-later-is_sum)])
cl_name = [c+"_"+str(i+1) for i in range(num)]
data2 = pd.DataFrame(cl_time.reshape(-1,num),columns=cl_name)
seq = pd.concat([data2,seq],axis=1)
print("shape:{}".format(seq.shape))
else:
print("Error: type is not pd.DataFrame.")
return
return seq
# ---------------------------------------分割线------------------------------------------------
# 7z 压缩数据
import subprocess as sp
import re
import os
_SZIP_PATH = 'C:/Program Files/7-Zip/7z.exe'
_SZ_LIST_PTTRN = re.compile(r'testing +[\w\\./ &!#@]+', re.I)
_SZ_LIST_STRIP = re.compile(r'Testing +', re.I)
comp7z = '7z'
compZip = 'zip'
class SevenZipError(Exception):
def __init__(self, msg='7z: unknown error'):
self.value = msg
def __str__(self):
return repr(self.value)
class FatalError(SevenZipError):
def __init__(self, msg='7z: fatal error'):
self.value = msg
class CommandLineError(SevenZipError):
def __init__(self, msg='7z: command line error'):
self.value = msg
class MemError(SevenZipError):
def __init__(self, msg='7z: not enough memory to perform this operation'):
self.value = msg
class UserInterrupt(SevenZipError):
def __init__(self, msg='7z: process interrupted by user'):
self.value = msg
def unpack(path, targetdir=os.getcwd(), fullpaths=True):
if not os.path.exists(path):
raise IOError('Could not find file/directory at path')
args = [_SZIP_PATH, 'x', path, '-y', '-o' + targetdir]
if not fullpaths:
args[1] = 'e'
sub = sp.Popen(args, stdout=sp.PIPE, stdin=sp.PIPE)
res = sub.wait()
if res == 0:
return True
elif res == 1:
return False
elif res == 2:
raise FatalError
elif res == 7:
raise CommandLineError
elif res == 8:
raise MemError
elif res == 255:
raise UserInterrupt
else:
raise SevenZipError
def unpack_no_full_paths(path, targetdir=os.getcwd()):
return unpack(path, targetdir, False)
def pack(path, archivepath, compression_level=5, compression_type='7z', password=None):
if not os.path.exists(path):
raise IOError('Could not find file/directory at path')
args = [_SZIP_PATH, 'a', archivepath, path, '-t' + compression_type, '-mx' + str(compression_level)]
if password:
args.append('-p' + password)
sub = sp.Popen(args, stdin=sp.PIPE, stdout=sp.PIPE)
res = sub.wait()
if res == 0:
return True
elif res == 1:
return False
elif res == 2:
raise FatalError
elif res == 7:
raise CommandLineError
elif res == 8:
raise MemError
elif res == 255:
raise UserInterrupt
else:
raise SevenZipError
def test(archivepath):
if not os.path.exists(archivepath):
raise IOError('Could not find file/directory at path')
args = [_SZIP_PATH, 't', archivepath, '-r']
sub = sp.Popen(args, stdout=sp.PIPE, stdin=sp.PIPE)
res = sub.wait()
if res == 0:
return True
elif res == 1 or res == 2:
return False
elif res == 7:
raise CommandLineError
elif res == 8:
raise MemError
elif res == 255:
raise UserInterrupt
else:
raise SevenZipError
def list(archivepath):
'''Return a list of all files in the archive.'''
if not os.path.exists(archivepath):
raise IOError('Could not find file/directory at path')
args = [_SZIP_PATH, 't', archivepath, '-r']
sub = sp.Popen(args, stdout=sp.PIPE, stdin=sp.PIPE)
stdout = sub.communicate()[0]
tmp = re.findall(_SZ_LIST_PTTRN, stdout)
li = []
for i in tmp:
li.append(re.sub(_SZ_LIST_STRIP, '', i))
res = sub.returncode
if res == 0 or res == 1:
return li
elif res == 2:
raise FatalError
elif res == 7:
raise CommandLineError
elif res == 8:
raise MemError
elif res == 255:
raise UserInterrupt
else:
raise SevenZipError
def move_to_archive(path, archive_name):
import shutil
tmp = path + '-' + archive_name
os.rename(path, tmp)
if not os.path.exists(path):
os.makedirs(path)
pack(tmp, path + '-' + archive_name + '.7z')
shutil.rmtree(tmp)
# ---------------------------------------分割线------------------------------------------------
# 将BLS模型封装成类
# 回归
class BLSregressor:
def __init__(self,s,C,NumFea,NumWin,NumEnhan):
self.s = s
self.C = C
self.NumFea = NumFea
self.NumEnhan = NumEnhan
self.NumWin = NumWin
def shrinkage(self,a,b):
z = np.maximum(a - b, 0) - np.maximum( -a - b, 0)
return z
def tansig(self,x):
return (2/(1+np.exp(-2*x)))-1
def pinv(self,A,reg):
return np.mat(reg*np.eye(A.shape[1])+A.T.dot(A)).I.dot(A.T)
def sparse_bls(self,A,b):
lam = 0.001
itrs = 50
AA = np.dot(A.T,A)
m = A.shape[1]
n = b.shape[1]
wk = np.zeros([m,n],dtype = 'double')
ok = np.zeros([m,n],dtype = 'double')
uk = np.zeros([m,n],dtype = 'double')
L1 = np.mat(AA + np.eye(m)).I
L2 = np.dot(np.dot(L1,A.T),b)
for i in range(itrs):
tempc = ok - uk
ck = L2 + np.dot(L1,tempc)
ok = self.shrinkage(ck + uk, lam)
uk += ck - ok
wk = ok
return wk
def fit(self,train_x,train_y):
train_y = train_y.reshape(-1,1)
u = 0
WF = list()
for i in range(self.NumWin):
random.seed(i+u)
WeightFea=2*random.randn(train_x.shape[1]+1,self.NumFea)-1
WF.append(WeightFea)
random.seed(100)
WeightEnhan=2*random.randn(self.NumWin*self.NumFea+1,self.NumEnhan)-1
H1 = np.hstack([train_x, 0.1 * np.ones([train_x.shape[0],1])])
y = np.zeros([train_x.shape[0],self.NumWin*self.NumFea])
WFSparse = list()
distOfMaxAndMin = np.zeros(self.NumWin)
meanOfEachWindow = np.zeros(self.NumWin)
for i in range(self.NumWin):
WeightFea = WF[i]
A1 = H1.dot(WeightFea)
scaler1 = preprocessing.MinMaxScaler(feature_range=(-1, 1)).fit(A1)
A1 = scaler1.transform(A1)
WeightFeaSparse = self.sparse_bls(A1,H1).T
WFSparse.append(WeightFeaSparse)
T1 = H1.dot(WeightFeaSparse)
meanOfEachWindow[i] = T1.mean()
distOfMaxAndMin[i] = T1.max() - T1.min()
T1 = (T1 - meanOfEachWindow[i])/distOfMaxAndMin[i]
y[:,self.NumFea*i:self.NumFea*(i+1)] = T1
H2 = np.hstack([y,0.1 * np.ones([y.shape[0],1])])
T2 = H2.dot(WeightEnhan)
T2 = self.tansig(T2)
T3 = np.hstack([y,T2])
WeightTop = self.pinv(T3,self.C).dot(train_y)
self.WeightTop = WeightTop
self.WFSparse = WFSparse
self.meanOfEachWindow = meanOfEachWindow
self.distOfMaxAndMin = distOfMaxAndMin
self.WeightEnhan = WeightEnhan
return self
def predict(self,test_x):
HH1 = np.hstack([test_x, 0.1 * np.ones([test_x.shape[0],1])])
yy1=np.zeros([test_x.shape[0],self.NumWin*self.NumFea])
for i in range(self.NumWin):
WeightFeaSparse = self.WFSparse[i]
TT1 = HH1.dot(WeightFeaSparse)
TT1 = (TT1 - self.meanOfEachWindow[i])/self.distOfMaxAndMin[i]
yy1[:,self.NumFea*i:self.NumFea*(i+1)] = TT1
HH2 = np.hstack([yy1, 0.1 * np.ones([yy1.shape[0],1])])
TT2 = self.tansig(HH2.dot(self.WeightEnhan))
TT3 = np.hstack([yy1,TT2])
NetoutTest = TT3.dot(self.WeightTop)
NetoutTest = np.array(NetoutTest).reshape(1,-1)
return NetoutTest
def set_params(self, **parameters):
for parameter, value in parameters.items():
setattr(self, parameter, value)
return self
def get_params(self,deep = False):
return {
's':self.s,
'C':self.C,
'NumFea':self.NumFea,
'NumWin':self.NumWin,
'NumEnhan':self.NumEnhan
}
# 分类
class BLSclassification:
def __init__(self, s, C, NumFea, NumWin, NumEnhan):
self.s = s
self.C = C
self.NumFea = NumFea
self.NumEnhan = NumEnhan
self.NumWin = NumWin
self.onehot = None
self.label_size = None
def shrinkage(self, a, b):
z = np.maximum(a - b, 0) - np.maximum(-a - b, 0)
return z
def tansig(self, x):
return (2 / (1 + np.exp(-2 * x))) - 1
def pinv(self, A, reg):
return np.mat(reg * np.eye(A.shape[1]) + A.T.dot(A)).I.dot(A.T)
def sparse_bls(self, A, b):
lam = 0.001
itrs = 50
AA = np.dot(A.T, A)
m = A.shape[1]
n = b.shape[1]
wk = np.zeros([m, n], dtype='double')
ok = np.zeros([m, n], dtype='double')
uk = np.zeros([m, n], dtype='double')
L1 = np.mat(AA + np.eye(m)).I
L2 = np.dot(np.dot(L1, A.T), b)
for i in range(itrs):
tempc = ok - uk
ck = L2 + np.dot(L1, tempc)
ok = self.shrinkage(ck + uk, lam)
uk += ck - ok
wk = ok
return wk
def one_hot_y(self, y):
self.onehot = OneHotEncoder(sparse=False)
self.onehot.fit(y.reshape(-1, 1))
y_t = self.onehot.transform(y.reshape(-1, 1))
return y_t
def fit(self, train_x, train_y, sample_weight=None):
train_y = self.one_hot_y(train_y)
self.label_size = train_y.shape[1]
train_y = train_y.reshape(-1, self.label_size)
u = 0
WF = list()
for i in range(self.NumWin):
random.seed(i + u)
WeightFea = 2 * random.randn(train_x.shape[1] + 1, self.NumFea) - 1
WF.append(WeightFea)
WeightEnhan = 2 * random.randn(self.NumWin * self.NumFea + 1, self.NumEnhan) - 1
H1 = np.hstack([train_x, 0.1 * np.ones([train_x.shape[0], 1])])
y = np.zeros([train_x.shape[0], self.NumWin * self.NumFea])
WFSparse = list()
distOfMaxAndMin = np.zeros(self.NumWin)
meanOfEachWindow = np.zeros(self.NumWin)
for i in range(self.NumWin):
WeightFea = WF[i]
A1 = H1.dot(WeightFea)
scaler1 = preprocessing.MinMaxScaler(feature_range=(-1, 1)).fit(A1)
A1 = scaler1.transform(A1)
WeightFeaSparse = self.sparse_bls(A1, H1).T
WFSparse.append(WeightFeaSparse)
T1 = H1.dot(WeightFeaSparse)
meanOfEachWindow[i] = T1.mean()
distOfMaxAndMin[i] = T1.max() - T1.min()
T1 = (T1 - meanOfEachWindow[i]) / distOfMaxAndMin[i]
y[:, self.NumFea * i:self.NumFea * (i + 1)] = T1
H2 = np.hstack([y, 0.1 * np.ones([y.shape[0], 1])])
T2 = H2.dot(WeightEnhan)
T2 = self.tansig(T2)
T3 = np.hstack([y, T2])
WeightTop = self.pinv(T3, self.C).dot(train_y)
self.WeightTop = WeightTop
self.WFSparse = WFSparse
self.meanOfEachWindow = meanOfEachWindow
self.distOfMaxAndMin = distOfMaxAndMin
self.WeightEnhan = WeightEnhan
return self
def predict(self, test_x):
HH1 = np.hstack([test_x, 0.1 * np.ones([test_x.shape[0], 1])])
yy1 = np.zeros([test_x.shape[0], self.NumWin * self.NumFea])
for i in range(self.NumWin):
WeightFeaSparse = self.WFSparse[i]
TT1 = HH1.dot(WeightFeaSparse)
TT1 = (TT1 - self.meanOfEachWindow[i]) / self.distOfMaxAndMin[i]
yy1[:, self.NumFea * i:self.NumFea * (i + 1)] = TT1
HH2 = np.hstack([yy1, 0.1 * np.ones([yy1.shape[0], 1])])
TT2 = self.tansig(HH2.dot(self.WeightEnhan))
TT3 = np.hstack([yy1, TT2])
NetoutTest = TT3.dot(self.WeightTop)
NetoutTest = np.argmax(np.array(NetoutTest), axis=1).reshape(1, -1)[0]
return NetoutTest
def predict_proba(self, test_x):
HH1 = np.hstack([test_x, 0.1 * np.ones([test_x.shape[0], 1])])
yy1 = np.zeros([test_x.shape[0], self.NumWin * self.NumFea])
for i in range(self.NumWin):
WeightFeaSparse = self.WFSparse[i]
TT1 = HH1.dot(WeightFeaSparse)
TT1 = (TT1 - self.meanOfEachWindow[i]) / self.distOfMaxAndMin[i]
yy1[:, self.NumFea * i:self.NumFea * (i + 1)] = TT1
HH2 = np.hstack([yy1, 0.1 * np.ones([yy1.shape[0], 1])])
TT2 = self.tansig(HH2.dot(self.WeightEnhan))
TT3 = np.hstack([yy1, TT2])
NetoutTest = TT3.dot(self.WeightTop)
NetoutTest = np.array(NetoutTest).reshape(-1, self.label_size)
return NetoutTest
def set_params(self, **parameters):
for parameter, value in parameters.items():
setattr(self, parameter, value)
return self
def get_params(self, deep=False):
return {
's': self.s,
'C': self.C,
'NumFea': self.NumFea,
'NumWin': self.NumWin,
'NumEnhan': self.NumEnhan
}
# ---------------------------------------分割线------------------------------------------------
# 评估聚类的性能,内部评估指标
def calculate_cluster(X,label):
score1 = davies_bouldin_score(X,label) # 得分越低越好
score2 = calinski_harabasz_score(X,label) # 得分越高越好
score3 = silhouette_score(X,label) # 越接近于1代表越好
return [score1,score2,score3]
# ---------------------------------------分割线------------------------------------------------
# 对应model训练类的网格搜索后根据某个评估指标来寻找模型最优参数,metrics为指定的评估指标,ascending=True,最后结果为越小越好,反之,相反。
def analysiz_train_results(path,model,name,metrics,ascending=True):
path_a = path + model + "_" + name + "_assess.csv"
path_p = path + model + "_" + name + "_parameter.csv"
data_a = pd.read_csv(path_a)
data_p = pd.read_csv(path_p)
data_a = data_a.sort_values(by=metrics,ascending=ascending)
data_p = data_p.iloc[data_a.index]
return data_a[:5],data_p[:5] # 返回前五个最好的结果
# ---------------------------------------分割线------------------------------------------------
# 训练调参的类,包含各个常用的模型,每个模型的参数范围只是个例子,具体任务具体设置。
class model:
# 初始化放置结果的文件夹
def __init__(self,path_model_csv,path_model_pic,path_best_model):
print(os.getcwd())
# 创建保存结果的文件夹
self.path_model_csv = path_model_csv
folder = os.path.exists(self.path_model_csv)
if not folder:
os.makedirs(self.path_model_csv)
# 创建保存结果图片的文件夹
self.path_model_pic = path_model_pic
folder = os.path.exists(self.path_model_pic)
if not folder:
os.makedirs(self.path_model_pic)
self.path_best_model = path_best_model
# 创建保存模型的文件夹
folder = os.path.exists(self.path_best_model)
if not folder:
os.makedirs(self.path_best_model)
#self.criterion = "mse" # 保存最佳的模型的标准
print("init")
# 将参数和评估结果写入文件
def write_csv_result(self,path_1,path_2,all_metrics,all_parameter):
with open(path_1,"a",encoding="utf-8",newline="")as f:
f = csv.writer(f)
f.writerow(all_metrics)
with open(path_2,"a",encoding="utf-8",newline="")as f:
f = csv.writer(f)
f.writerow(all_parameter)
# 将训练集进行拆分,分成多个batch数据集
def create_batch_data(self,batch_size):
Train = np.c_[self.train_x,self.train_y]
data_size = Train.shape[0]
batch_data = []
# 大于batch_size再进行切分。小于等于的话,就只有一个batch data
if(data_size > batch_size):
for i in range(int(data_size/batch_size)+1):
start = i * batch_size
if((i+1)*batch_size < data_size):
end = start + batch_size
else:
end = data_size
batch_data.append([Train[start:end,:][:,:-1],Train[start:end,:][:,-1]])
else:
batch_data.append([Train[:,:][:,:-1],Train[:,:][:,-1]])
self.batch_data = batch_data
# 数据预处理,三种不同的标准化方式
def scaler(self,fun):
if(fun=="MaxAbs"):
ss = MaxAbsScaler()
ss.fit(self.train_x)
self.train_x = ss.transform(self.train_x)
self.test_x = ss.transform(self.test_x)
elif(fun=="Standard"):
ss = StandardScaler()
ss.fit(self.train_x)
self.train_x = ss.transform(self.train_x)
self.test_x = ss.transform(self.test_x)
elif(fun=="MinMax"):
ss = MinMaxScaler()
ss.fit(self.train_x)
self.train_x = ss.transform(self.train_x)
self.test_x = ss.transform(self.test_x)
else:
print("Scaler error!!!")
# 导入训练集和测试集,并且创建批量数据,导入进来的numpy的array类型数据
def load_data(self,train_x,test_x,train_y,test_y,batch_size=2048,scaler=None):
self.feature_size = test_x.shape[1]
self.train_x = train_x.reshape(-1,self.feature_size)
self.test_x = test_x.reshape(-1,self.feature_size)
if(scaler!=None):
self.scaler(fun=scaler)
self.train_y = train_y.ravel()
self.test_y = test_y.ravel()
self.test_sample_size = test_x.shape[0]
self.create_batch_data(batch_size=batch_size)
print("Train X : {}, Test X : {}, Feature size : {}".format(self.train_x.shape,self.test_x.shape,self.feature_size))
# 回归任务的评估指标,pf代表是否打印出来结果,默认不打印
def calculate(self,y_true, y_predict, n, p ,pf=False):
y_true = y_true.reshape(-1,1)
y_predict = y_predict.reshape(-1,1)
# 初始化评估结果
mse = np.inf
rmse = np.inf
mae = np.inf
r2 = np.NINF
mad = np.inf
mape = np.inf
r2_adjusted = np.NINF
rmsle = np.inf
# try except 的原因是有时候有些结果不适合用某种评估指标
try:
mse = mean_squared_error(y_true, y_predict)
except:
pass
try:
rmse = np.sqrt(mean_squared_error(y_true, y_predict))
except:
pass
try:
mae = mean_absolute_error(y_true, y_predict)
except:
pass
try:
r2 = r2_score(y_true, y_predict)
except:
pass
try:
mad = median_absolute_error(y_true, y_predict)
except:
pass
try:
mape = np.mean(np.abs((y_true - y_predict) / y_true)) * 100
except:
pass
try:
if(n>p):
r2_adjusted = 1-((1-r2)*(n-1))/(n-p-1)
except:
pass
try:
rmsle = np.sqrt(mean_squared_log_error(y_true,y_predict))
except:
pass
if(pf):
try:
print('MSE: ', mse)
except:
pass
try:
print('RMSE: ', rmse)
except:
pass
try:
print('MAE: ', mae)
except:
pass
try:
print('R2: ', r2)
except:
pass
try:
print('MAD:', mad)
except:
pass
try:
print('MAPE:', mape)
except:
pass
try:
print('R2_Adjusted: ',r2_adjusted)
except:
pass
try:
print("RMSLE: ",rmsle)
except:
pass
return mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle
# Adaboost 训练调参代码
def Ada(self,name):
path_a = self.path_model_csv + "Ada_" + name + "_" + "assess.csv"
path_p = self.path_model_csv + "Ada_" + name + "_" + "parameter.csv"
path_b = self.path_model_csv + "Ada_" + name + "_" + "best.csv"
model_path = self.path_best_model + "Ada_" + name + "_" + "best.m"
# 人工设置网格搜索的范围
n_estimators = [50,100,200,300,400,500,600,700,800]
learning_rate = [0.1,0.5,1,1.5,2]
loss = ["linear","square","exponential"]
criterion = ["mse","mae"]
splitter = ["best","random"]
max_features = ["None"]
max_leaf_nodes = ["None"]
min_samples_split = [2]
min_samples_leaf = [1]
all_nb = len(n_estimators) * len(learning_rate) * len(loss) * len(criterion) * len(splitter) * len(max_features) * len(max_leaf_nodes) * len(min_samples_leaf) * len(min_samples_split)
num = 1
# 用于重启训练模型,提高效率,不重复跑相同的实验
if(os.path.exists(path_a)):
data = pd.read_csv(path_a)
if(data.shape[0]>1):
nums = int(data.values[-1,0])
else:
nums = 0
else:
nums = 0
col_a = ['num','mse','rmse','mae','r2','mad','mape','r2_adjusted','rmsle']
col_p = ['num','n_estimators','learning_rate','loss','max_features','min_samples_split','min_samples_leaf','max_leaf_nodes','splitter','criterion']
self.write_csv_result(path_a,path_p,col_a,col_p)
# 用于保存最好的模型
if(os.path.exists(path_b)):
best_results = pd.read_csv(path_b)
if(best_results.shape[0]>1):
best_result = best_results["rmse"].values[-1]
else:
best_result = 10*10**30
else:
with open(path_b,"a",encoding="utf-8",newline="")as f:
f = csv.writer(f)
f.writerow(['num','mse','rmse','mae','r2','mad','mape','r2_adjusted','rmsle'])
best_result = 10*10**30
# 网格搜索
for n in n_estimators:
for l in learning_rate:
for lo in loss:
for mf in max_features:
for mi in min_samples_split:
for ms in min_samples_leaf:
for ml in max_leaf_nodes:
for sp in splitter:
for c in criterion:
if(nums>=num):
num = num+1
else:
print("Ada start....{}/{}".format(num,all_nb))
if(mf == "None" and ml != "None"):
model = AdaBoostRegressor(n_estimators=n,learning_rate=l,loss=lo,base_estimator=DecisionTreeRegressor(min_samples_split=mi,min_samples_leaf=ms,max_leaf_nodes=ml,splitter=sp,criterion=c))
elif(ml == "None" and mf != "None"):
model = AdaBoostRegressor(n_estimators=n,learning_rate=l,loss=lo,base_estimator=DecisionTreeRegressor(min_samples_split=mi,min_samples_leaf=ms,splitter=sp,max_features=mf,criterion=c))
elif(ml == "None" and mf == "None"):
model = AdaBoostRegressor(n_estimators=n,learning_rate=l,loss=lo,base_estimator=DecisionTreeRegressor(min_samples_split=mi,min_samples_leaf=ms,splitter=sp,criterion=c))
else:
model = AdaBoostRegressor(n_estimators=n,learning_rate=l,loss=lo,base_estimator=DecisionTreeRegressor(min_samples_split=mi,min_samples_leaf=ms,max_leaf_nodes=ml,splitter=sp,max_features=mf,criterion=c))
model.fit(self.train_x,self.train_y)
pred_test = model.predict(self.test_x)
pred_test = pred_test.reshape(-1,1)
mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle = self.calculate(self.test_y,pred_test,self.test_sample_size,self.feature_size)
all_m = [num,mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle]
all_p = [num,n,l,lo,mf,mi,ms,ml,sp,c]
self.write_csv_result(path_a,path_p,all_m,all_p)
if(rmse < best_result):
joblib.dump(model,model_path)
with open(path_b,"a",encoding="utf-8",newline="")as f:
f = csv.writer(f)
f.writerow([num,mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle])
best_result = rmse
print("current best result, mse:{},mae:{},rmse:{},mad:{},r2:{},mape:{},r2 adjusted:{},rmsle:{}".format(mse,mad,rmse,mad,r2,mape,r2_adjusted,rmsle))
print("end....",num)
num = num+1
print("--------------------------------")
# KNN 训练调参代码
def Knn(self,name):
path_a = self.path_model_csv + "Knn_" + name + "_" + "assess.csv"
path_p = self.path_model_csv + "Knn_" + name + "_" + "parameter.csv"
path_b = self.path_model_csv + "Knn_" + name + "_" + "best.csv"
model_path = self.path_best_model + "Knn_" + name + "_" + "best.m"
# 人工设置网格搜索的范围
n_neighbors = [3,5,7,9] # 默认为5
weights = ['uniform', 'distance']
algorithm = ["brute","kd_tree","ball_tree"]
leaf_size = [25,30,35] #默认是30
metric = ["euclidean","manhattan","chebyshev","minkowski","wminkowski","seuclidean","mahalanobis"]
P = [1,2] # 只在 wminkowski 和 minkowski 调
all_nb = len(n_neighbors) * len(weights) * len(algorithm) * len(leaf_size) * len(metric) * len(P)
num=1
# 用于重启训练模型,提高效率,不重复跑相同的实验
if(os.path.exists(path_a)):
data = pd.read_csv(path_a)
if(data.shape[0]>1):
nums = int(data.values[-1,0])
else:
nums = 0
else:
nums = 0
col_a = ['num','mse','rmse','mae','r2','mad','mape','r2_adjusted','rmsle']
col_p = ['num','metric','algorithm','weights','n_neighbors','leaf_size','P']
self.write_csv_result(path_a,path_p,col_a,col_p)
# 用于保存最好的模型
if(os.path.exists(path_b)):
best_results = pd.read_csv(path_b)
if(best_results.shape[0]>1):
best_result = best_results["rmse"].values[-1]
else:
best_result = 10*10**30
else:
with open(path_b,"a",encoding="utf-8",newline="")as f:
f = csv.writer(f)
f.writerow(['num','mse','rmse','mae','r2','mad','mape','r2_adjusted','rmsle'])
best_result = 10*10**30
# 网格搜索
for n in n_neighbors:
for l in leaf_size:
for p in P:
for a in algorithm:
for m in metric:
for w in weights:
if(nums>=num):
num = num+1
else:
try:
if(m=="wminkowski" or m=="minkowski"):
print("KNN start....{}/{}".format(num,all_nb))
model = KNeighborsRegressor(n_neighbors=n,leaf_size=l,p=p,weights=w,metric=m,algorithm=a)
model.fit(self.train_x,self.train_y)
pred_test = model.predict(self.test_x)
pred_test = pred_test.reshape(-1,1)
mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle = self.calculate(self.test_y,pred_test,self.test_sample_size,self.feature_size)
all_m = [num,mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle]
all_p = [num,m,a,w,n,l,p]
self.write_csv_result(path_a,path_p,all_m,all_p)
if(rmse < best_result):
joblib.dump(model,model_path)
with open(path_b,"a",encoding="utf-8",newline="")as f:
f = csv.writer(f)
f.writerow([num,mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle])
best_result = rmse
print("current best result, mse:{},mae:{},rmse:{},mad:{},r2:{},mape:{},r2 adjusted:{},rmsle:{}".format(mse,mad,rmse,mad,r2,mape,r2_adjusted,rmsle))
print("end....",num)
num = num+1
print("--------------------------------")
else:
print("KNN start....{}/{}".format(num,all_nb))
model = KNeighborsRegressor(n_neighbors=n,leaf_size=l,weights=w,metric=m,algorithm=a)
model.fit(self.train_x,self.train_y)
pred_test = model.predict(self.test_x)
pred_test = pred_test.reshape(-1,1)
mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle = self.calculate(self.test_y,pred_test,self.test_sample_size,self.feature_size)
all_m = [num,mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle]
all_p = [num,m,a,w,n,l,p]
self.write_csv_result(path_a,path_p,all_m,all_p)
if(rmse < best_result):
joblib.dump(model,model_path)
with open(path_b,"a",encoding="utf-8",newline="")as f:
f = csv.writer(f)
f.writerow([num,mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle])
best_result = rmse
print("current best result, mse:{},mae:{},rmse:{},mad:{},r2:{},mape:{},r2 adjusted:{},rmsle:{}".format(mse,mad,rmse,mad,r2,mape,r2_adjusted,rmsle))
print("end....",num)
num = num+1
print("--------------------------------")
except:
num = num+1
print("error")
#SVR训练调参代码
def Svr(self,name):
path_a = self.path_model_csv + "Svr_" + name + "_" + "assess.csv"
path_p = self.path_model_csv + "Svr_" + name + "_" + "parameter.csv"
path_b = self.path_model_csv + "Svr_" + name + "_" + "best.csv"
model_path = self.path_best_model + "Svr_" + name + "_" + "best.m"
# 人工设置网格搜索的范围
kernel = ["rbf","linear","poly","sigmoid"]
degree = [2,3,4,5,6,7,8,9,10,11,12]
gamma = ["auto","scale"]
all_nb = len(kernel) * len(degree) * len(gamma)
num=1
# 用于重启训练模型,提高效率,不重复跑相同的实验
if(os.path.exists(path_a)):
data = pd.read_csv(path_a)
if(data.shape[0]>1):
nums = int(data.values[-1,0])
else:
nums = 0
else:
nums = 0
col_a = ['num','mse','rmse','mae','r2','mad','mape','r2_adjusted','rmsle']
col_p = ['num','kernel','degree','gamma']
self.write_csv_result(path_a,path_p,col_a,col_p)
# 用于保存最好的模型
if(os.path.exists(path_b)):
best_results = pd.read_csv(path_b)
if(best_results.shape[0]>1):
best_result = best_results["rmse"].values[-1]
else:
best_result = 10*10**30
else:
with open(path_b,"a",encoding="utf-8",newline="")as f:
f = csv.writer(f)
f.writerow(['num','mse','rmse','mae','r2','mad','mape','r2_adjusted','rmsle'])
best_result = 10*10**30
# 网格搜索
for k in kernel:
if(k=="poly"):
for d in degree:
for g in gamma:
if(nums>=num):
num = num+1
else:
print("SVR start....{}/{}".format(num,all_nb))
model = SVR(kernel=k,degree=d,gamma=g)
model.fit(self.train_x,self.train_y)
pred_test = model.predict(self.test_x)
pred_test = pred_test.reshape(-1,1)
mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle = self.calculate(self.test_y,pred_test,self.test_sample_size,self.feature_size)
all_m = [num,mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle]
all_p = [num,k,d,g]
self.write_csv_result(path_a,path_p,all_m,all_p)
if(rmse < best_result):
joblib.dump(model,model_path)
with open(path_b,"a",encoding="utf-8",newline="")as f:
f = csv.writer(f)
f.writerow([num,mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle])
best_result = rmse
print("current best result, mse:{},mae:{},rmse:{},mad:{},r2:{},mape:{},r2 adjusted:{},rmsle:{}".format(mse,mad,rmse,mad,r2,mape,r2_adjusted,rmsle))
print("end....",num)
num = num+1
print("--------------------------------")
elif(k=="rbf" or k=="sigmoid"):
for g in gamma:
if(nums>=num):
num = num+1
else:
print("SVR start....{}/{}".format(num,all_nb))
model = SVR(kernel=k,gamma=g)
model.fit(self.train_x,self.train_y)
pred_test = model.predict(self.test_x)
pred_test = pred_test.reshape(-1,1)
mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle = self.calculate(self.test_y,pred_test,self.test_sample_size,self.feature_size)
all_m = [num,mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle]
all_p = [num,k,"None",g]
self.write_csv_result(path_a,path_p,all_m,all_p)
if(rmse < best_result):
joblib.dump(model,model_path)
with open(path_b,"a",encoding="utf-8",newline="")as f:
f = csv.writer(f)
f.writerow([num,mse,rmse,mae,r2,mad,mape,r2_adjusted,rmsle])
best_result = rmse
print("current best result, mse:{},mae:{},rmse:{},mad:{},r2:{},mape:{},r2 adjusted:{},rmsle:{}".format(mse,mad,rmse,mad,r2,mape,r2_adjusted,rmsle))
print("end....",num)
print("--------------------------------")
num = num+1
else:
if(nums>=num):
num = num+1
else: