-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDDPG_VC_S_random_train.py
More file actions
1676 lines (1436 loc) · 65.8 KB
/
Copy pathDDPG_VC_S_random_train.py
File metadata and controls
1676 lines (1436 loc) · 65.8 KB
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
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 13 10:41:53 2021
@author: admin
Implementation of Deep Deterministic Policy Gradients (DDPG) with pytorch
riginal paper: https://arxiv.org/abs/1509.02971
Not the author's implementation !
"""
import argparse
import os
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from tensorboardX import SummaryWriter
from scipy.fftpack import fft
import matplotlib.pyplot as plt
import random
import openpyxl
from torchsummary import summary
# %% 超参数
parser = argparse.ArgumentParser()
parser.add_argument('--mode', default='test', type=str) # mode = 'train' or 'test'
parser.add_argument('--load_nn', default=False, type=bool) # 是否导入已有网络
parser.add_argument('--tau', default=0.005, type=float) # target smoothing coefficient
parser.add_argument('--lr_A', default=3e-4, type=float) # A网络学习率1e-5
parser.add_argument('--lr_C', default=3e-4, type=float) # C网络学习率1e-4
# parser.add_argument('--tau', default=0.002, type=float) # target smoothing coefficient
# parser.add_argument('--lr_A', default=1e-5, type=float) # A网络学习率1e-5
# parser.add_argument('--lr_C', default=1e-4, type=float) # C网络学习率1e-4
parser.add_argument('--gamma', default=0.99, type=int) # discounted factor
parser.add_argument('--capacity', default=2000, type=int) # replay buffer size
parser.add_argument('--batch_size', default=128, type=int) # mini batch size
parser.add_argument('--episode_length', default=300, type=int) # 回合长度
parser.add_argument('--save_interval', default=1, type=int) # 相隔n回合存储一次网络参数
parser.add_argument('--max_episode', default=10001, type=int) # 回合数
parser.add_argument('--update_iteration', default=300, type=int) # 每回合更新网络参数的次数 300
parser.add_argument('--exploration_noise', default=0.3, type=float) # 探索噪声初值
parser.add_argument('--state_scale_factor', default=0.1, type=float) # 状态放大系数(放大之后输入网络) 10
parser.add_argument('--action_scale_factor', default=0.02, type=float) # 动作放大系数(2网络输出后放大) 2
parser.add_argument('--test_num', default=300, type=int) # 训练样本长度
# args = parser.parse_args()
# os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# device = 'cuda' if torch.cuda.is_available() else 'cpu'
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(device)
# device = torch.device('cpu')
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
# %%路径
path = os.getcwd()
path1 = path + '\\pic2\\'
if not os.path.exists(path1) == True:
os.mkdir(path1)
directory = path + '\\nn2\\'
if not os.path.exists(directory) == True:
os.mkdir(directory)
# %%读取传递通道模型参数
df = pd.read_excel('Wts0415.xlsx', sheet_name='Sheet1', header=None)#[]
# df = pd.read_excel('Wts0126.xlsx',sheet_name='Sheet1', header=None)
data = df.values
W01 = data[:, 0]
W02 = data[:, 1]
W03 = data[:, 2]
W04 = data[:, 3]
W11 = data[:, 4]
W12 = data[:, 5]
W13 = data[:, 6]
W14 = data[:, 7]
W21 = data[:, 8]
W22 = data[:, 9]
W23 = data[:, 10]
W24 = data[:, 11]
W31 = data[:, 12]
W32 = data[:, 13]
W33 = data[:, 14]
W34 = data[:, 15]
W41 = data[:, 16]
W42 = data[:, 17]
W43 = data[:, 18]
W44 = data[:, 19]
W01r = W01[::-1]
W02r = W02[::-1]
W03r = W03[::-1]
W04r = W04[::-1]
W11r = W11[::-1]
W12r = W12[::-1]
W13r = W13[::-1]
W14r = W14[::-1]
W21r = W21[::-1]
W22r = W22[::-1]
W23r = W23[::-1]
W24r = W24[::-1]
W31r = W31[::-1]
W32r = W32[::-1]
W33r = W33[::-1]
W34r = W34[::-1]
W41r = W41[::-1]
W42r = W42[::-1]
W43r = W43[::-1]
W44r = W44[::-1]
df1 = pd.read_excel('motor0on0415.xlsx', sheet_name='data', header=None)
# df1 = pd.read_excel('motor0on.xlsx',sheet_name='Data', header=None)
ii = 20000
x0_array = df1.values[1:50001, 0]
# %% 定义环境
class Env():
def __init__(self):
# 振源、电机的输入均是长度300的向量()
self.X0 = 300 * [0]
self.X1 = 300 * [0]
self.X2 = 300 * [0]
self.X3 = 300 * [0]
self.X4 = 300 * [0]
self.tau = 0.001
self.max_size = 100
self.ptr = 0
self.state_memory = []
def push(self, data):
if len(self.state_memory) == self.max_size:
self.state_memory[int(self.ptr)] = data
self.ptr = (self.ptr + 1) % self.max_size
else:
self.state_memory.append(data)
def step(self, x0, x1, x2, x3, x4):
# x0是振源, x1,x2,x3,x4电机当前输入值、也是Action
# 更新输入向量
self.X0.append(x0)
self.X0.pop(0)
self.X1.append(x1)
self.X1.pop(0)
self.X2.append(x2)
self.X2.pop(0)
self.X3.append(x3)
self.X3.pop(0)
self.X4.append(x4)
self.X4.pop(0)
# 更新传感器的输出
self.y1 = np.array(self.X0).dot(W01r) + \
np.array(self.X1).dot(W11r) + \
np.array(self.X2).dot(W21r) + \
np.array(self.X3).dot(W31r) + \
np.array(self.X4).dot(W41r)
self.y2 = np.array(self.X0).dot(W02r) + \
np.array(self.X1).dot(W12r) + \
np.array(self.X2).dot(W22r) + \
np.array(self.X3).dot(W32r) + \
np.array(self.X4).dot(W42r)
self.y3 = np.array(self.X0).dot(W03r) + \
np.array(self.X1).dot(W13r) + \
np.array(self.X2).dot(W23r) + \
np.array(self.X3).dot(W33r) + \
np.array(self.X4).dot(W43r)
self.y4 = np.array(self.X0).dot(W04r) + \
np.array(self.X1).dot(W14r) + \
np.array(self.X2).dot(W24r) + \
np.array(self.X3).dot(W34r) + \
np.array(self.X4).dot(W44r)
self.y1 = self.y1*10
self.y2 = self.y2*10
self.y3 = self.y3*10
self.y4 = self.y4*10
self.state = np.array([self.y1, self.y2, self.y3, self.y4])
self.push(self.state)
def get_reward_long(state_memory):#单独 fft reward: -30.914620265197595 i_episode: 209 percetage: 4.543583055397503
states = np.array(state_memory)#-2.8615173766170274 i_episode: 905 percetage: 7.1520547272691815
S1 = states[:, 0]
#S1c = fft(S1, S1.shape[0])
P1c = abs(S1 / S1.shape[0]).mean()
S2 = states[:, 1]
#S2c = fft(S2, S2.shape[0])
P2c = abs(S2 / S2.shape[0]).mean()
S3 = states[:, 2]
#S3c = fft(S3, S3.shape[0])
P3c = abs(S3 / S3.shape[0]).mean()
S4 = states[:, 3]
#S4c = fft(S4, S3.shape[0])
P4c = abs(S4 / S3.shape[0]).mean()
return -P1c - P2c - P3c - P4c
def get_reward_long_RMS(state_memory):#均方根 reward: -316.16772874892774 i_episode: 1187 percetage: 8.678076008634521
states = np.array(state_memory)
S1 = states[:, 0]
S1 = np.power(S1, 2).sum() / S1.shape[0]
P1c = np.sqrt(S1)
S2 = states[:, 1]
S2 = np.power(S2, 2).sum() / S2.shape[0]
P2c = np.sqrt(S2)
S3 = states[:, 2]
S3 = np.power(S3, 2).sum() / S3.shape[0]
P3c = np.sqrt(S3)
S4 = states[:, 3]
S4 = np.power(S4, 2).sum() / S4.shape[0]
P4c = np.sqrt(S4)
return -P1c - P2c - P3c - P4c
def get_reward_long_var(state_memory):#方差 reward: -80.0331602813426 i_episode: 593 percetage: 6.857826866268242
states = np.array(state_memory)
S1 = states[:, 0]
mean1 = S1.mean()
var1 = np.power(S1 - mean1, 2).sum() / S1.shape[0]
S2 = states[:, 1]
mean2 = S2.mean()
var2 = np.power(S2 - mean2, 2).sum() / S2.shape[0]
S3 = states[:, 2]
mean3 = S3.mean()
var3 = np.power(S3 - mean3, 2).sum() / S3.shape[0]
S4 = states[:, 3]
mean4 = S4.mean()
var4 = np.power(S4 - mean4, 2).sum() / S4.shape[0]
return -var1 - var2 - var3 - var4
#long_reward = get_reward_long(self.state_memory)
#long_reward = get_reward_long_RMS(self.state_memory)
long_reward_v = get_reward_long_var(self.state_memory)
self.done = 0
# 定义reward
#self.reward = (-(self.y1) ** 2 - (self.y2) ** 2 - (self.y3) ** 2 - (self.y4) ** 2)
self.reward = long_reward_v
return self.state, self.reward, self.done
def reset(self):
self.state_memory = []
self.X0 = 300 * [0]
self.X1 = 300 * [0]
self.X2 = 300 * [0]
self.X3 = 300 * [0]
self.X4 = 300 * [0]
self.state = np.array([0.0, 0.0, 0.0, 0.0])
return self.state
# %% 定义智能体
class Replay_buffer():
'''
Code based on:
https://github.com/openai/baselines/blob/master/baselines/deepq/replay_buffer.py
Expects tuples of (state, next_state, action, reward, done)
'''
def __init__(self, max_size=args.capacity):
self.storage = []
self.max_size = max_size
self.ptr = 0
def push(self, data):
if len(self.storage) == self.max_size:
self.storage[int(self.ptr)] = data
self.ptr = (self.ptr + 1) % self.max_size
else:
self.storage.append(data)
def sample(self, batch_size):
ind = np.random.randint(0, len(self.storage), size=batch_size)
x, y, u, r, d = [], [], [], [], []
for i in ind:
X, Y, U, R, D = self.storage[i]
x.append(np.array(X, copy=False))
y.append(np.array(Y, copy=False))
u.append(np.array(U, copy=False))
r.append(np.array(R, copy=False))
d.append(np.array(D, copy=False))
return np.array(x), np.array(y), np.array(u), np.array(r).reshape(-1, 1), np.array(d).reshape(-1, 1)
class RSBU_CW(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, down_sample=False):
super().__init__()
self.down_sample = down_sample
self.in_channels = in_channels
self.out_channels = out_channels
stride = 1
if down_sample:
stride = 2
self.BRC = nn.Sequential(
#nn.BatchNorm1d(in_channels),
nn.ReLU(inplace=True),
nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride,
padding=1),
#nn.BatchNorm1d(out_channels),
nn.ReLU(inplace=True),
nn.Conv1d(in_channels=out_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1,
padding=1)
)
self.global_average_pool = nn.AdaptiveAvgPool1d(1)
self.FC = nn.Sequential(
nn.Linear(in_features=out_channels, out_features=out_channels),
#nn.BatchNorm1d(out_channels),
nn.ReLU(inplace=True),
nn.Linear(in_features=out_channels, out_features=out_channels),
nn.Sigmoid()
)
self.flatten = nn.Flatten()
self.average_pool = nn.AvgPool1d(kernel_size=1, stride=2)
def forward(self, input):
x = self.BRC(input)
x_abs = torch.abs(x)
#print(x_abs.shape)
gap = self.global_average_pool(x_abs)
#print(gap.shape)
gap = gap.view(gap.shape[0],gap.shape[1]*gap.shape[2])
#print("gap.shape:",gap.shape)
alpha = self.FC(gap)
threshold = torch.mul(gap, alpha)
threshold = torch.unsqueeze(threshold, 2)
# 软阈值化
sub = x_abs - threshold
zeros = sub - sub
n_sub = torch.max(sub, zeros)
x = torch.mul(torch.sign(x), n_sub)
if self.down_sample: # 如果是下采样,则对输入进行平均池化下采样
input = self.average_pool(input)
if self.in_channels != self.out_channels: # 如果输入的通道和输出的通道不一致,则进行padding,直接通过复制拼接矩阵进行padding,原代码是通过填充0
zero_padding = torch.zeros(input.shape).cuda()
input = torch.cat((input, zero_padding), dim=1)
result = x + input
#print(result.shape)
return result
# class Actor1(torch.nn.Module):
# def __init__(self, state_dim, action_dim, max_action):
# super().__init__()
# self.conv1 = nn.Conv1d(in_channels=1, out_channels=4, kernel_size=3, stride=2, padding=1)
# self.bn = nn.BatchNorm1d(16)
# self.relu = nn.Tanh()
# self.softmax = nn.Softmax(dim=1)
# self.global_average_pool = nn.AdaptiveAvgPool1d(1)
# self.flatten = nn.Flatten()
# self.linear6_8 = nn.Linear(in_features=state_dim, out_features=128)
# self.linear8_4 = nn.Linear(in_features=128, out_features=64)
# self.linear4_2 = nn.Linear(in_features=64, out_features=32)
# self.output_center_pos = nn.Linear(in_features=32, out_features=1)
# self.output_width = nn.Linear(in_features=32, out_features=1)
#
# self.linear = nn.Linear(in_features=16, out_features=8)
# self.output_class = nn.Linear(in_features=8, out_features=action_dim)
# self.max_action = max_action
# def forward(self, input): # 1*256
# input = input.view(input.shape[0], 1, (input.shape[1]))
# x = self.conv1(input) # 4*128
# #print(x.shape)
# x = RSBU_CW(in_channels=4, out_channels=4, kernel_size=3, down_sample=True).cuda()(x) # 4*64
# x = RSBU_CW(in_channels=4, out_channels=4, kernel_size=3, down_sample=False).cuda()(x) # 4*64
# x = RSBU_CW(in_channels=4, out_channels=8, kernel_size=3, down_sample=True).cuda()(x) # 8*32
# x = RSBU_CW(in_channels=8, out_channels=8, kernel_size=3, down_sample=False).cuda()(x) # 8*32
# x = RSBU_CW(in_channels=8, out_channels=16, kernel_size=3, down_sample=True).cuda()(x) # 16*16
# x = RSBU_CW(in_channels=16, out_channels=16, kernel_size=3, down_sample=False).cuda()(x) # 16*16
# x = self.bn(x)
# x = self.relu(x)
# gap = self.global_average_pool(x) # 16*1
# gap = self.flatten(gap) # 1*16
# linear1 = self.linear(gap) # 1*8
# output_class = self.output_class(linear1) # 1*3
# #output_class = self.softmax(output_class) # 1*3
# #print(output_class.shape)
# #print(output_class)
# return output_class
# class Actor1(nn.Module):
# def __init__(self, state_dim, action_dim, max_action):
# super(Actor1, self).__init__()
# self.l1 = nn.Linear(state_dim, 256)
# self.l2 = nn.Linear(256, 256)
# self.l3 = nn.Linear(256, action_dim)
#
# self.max_action = max_action
#
# def forward(self, state):
# a = F.relu(self.l1(state))
# a = F.relu(self.l2(a))
# return self.max_action * torch.tanh(self.l3(a))
class Actor1(nn.Module):
def __init__(self, state_dim, action_dim, max_action):
super(Actor1, self).__init__()
self.l1 = nn.Linear(state_dim, 256)
self.l2 = nn.Linear(256, 256)
self.l3 = nn.Linear(256, action_dim)
self.max_action = max_action
def forward(self, state):
a = F.relu(self.l1(state))
a = F.relu(self.l2(a))
return self.max_action * torch.tanh(self.l3(a))
class Critic1(nn.Module):
def __init__(self, state_dim, action_dim):
super(Critic1, self).__init__()
# Q1 architecture
self.l1 = nn.Linear(state_dim + action_dim, 256)
self.l2 = nn.Linear(256, 256)
self.l3 = nn.Linear(256, 1)
# Q2 architecture
self.l4 = nn.Linear(state_dim + action_dim, 256)
self.l5 = nn.Linear(256, 256)
self.l6 = nn.Linear(256, 1)
def forward(self, state, action):
sa = torch.cat([state, action], 1)
q1 = F.relu(self.l1(sa))
q1 = F.relu(self.l2(q1))
q1 = self.l3(q1)
q2 = F.relu(self.l4(sa))
q2 = F.relu(self.l5(q2))
q2 = self.l6(q2)
return q1, q2
def Q1(self, state, action):
sa = torch.cat([state, action], 1)
q1 = F.relu(self.l1(sa))
q1 = F.relu(self.l2(q1))
q1 = self.l3(q1)
return q1
# class Critic1(nn.Module):
# def __init__(self, state_dim, action_dim):
# super(Critic1, self).__init__()
# # Q1 architecture
# self.conv1 = nn.Conv1d(in_channels=1, out_channels=4, kernel_size=3, stride=2, padding=1)
# self.bn = nn.BatchNorm1d(16)
# self.relu = nn.Tanh()
# self.softmax = nn.Softmax(dim=1)
# self.global_average_pool = nn.AdaptiveAvgPool1d(1)
# self.flatten = nn.Flatten()
# self.linear6_8 = nn.Linear(in_features=state_dim, out_features=128)
# self.linear8_4 = nn.Linear(in_features=128, out_features=64)
# self.linear4_2 = nn.Linear(in_features=64, out_features=32)
# self.output_center_pos = nn.Linear(in_features=32, out_features=1)
# self.output_width = nn.Linear(in_features=32, out_features=1)
#
# self.linear = nn.Linear(in_features=16, out_features=8)
# self.output_class = nn.Linear(in_features=8, out_features=action_dim)
#
# # Q2 architecture
# self.conv1_2 = nn.Conv1d(in_channels=1, out_channels=4, kernel_size=3, stride=2, padding=1)
# self.bn_2 = nn.BatchNorm1d(16)
# self.relu_2 = nn.Tanh()
# self.softmax_2 = nn.Softmax(dim=1)
# self.global_average_pool_2 = nn.AdaptiveAvgPool1d(1)
# self.flatten_2 = nn.Flatten()
# self.linear6_8_2 = nn.Linear(in_features=state_dim, out_features=128)
# self.linear8_4_2 = nn.Linear(in_features=128, out_features=64)
# self.linear4_2_2 = nn.Linear(in_features=64, out_features=32)
# self.output_center_pos_2 = nn.Linear(in_features=32, out_features=1)
# self.output_width_2 = nn.Linear(in_features=32, out_features=1)
#
# self.linear_2 = nn.Linear(in_features=16, out_features=8)
# self.output_class_2 = nn.Linear(in_features=8, out_features=action_dim)
#
# def forward(self, state, action):
# input = torch.cat([state, action], 1)
#
# input = input.view(input.shape[0], 1, (input.shape[1]))
# q1 = self.conv1(input) # 4*128
# # print(x.shape)
# q1 = RSBU_CW(in_channels=4, out_channels=4, kernel_size=3, down_sample=True).cuda()(q1) # 4*64
# q1 = RSBU_CW(in_channels=4, out_channels=4, kernel_size=3, down_sample=False).cuda()(q1) # 4*64
# q1 = RSBU_CW(in_channels=4, out_channels=8, kernel_size=3, down_sample=True).cuda()(q1) # 8*32
# q1 = RSBU_CW(in_channels=8, out_channels=8, kernel_size=3, down_sample=False).cuda()(q1) # 8*32
# q1 = RSBU_CW(in_channels=8, out_channels=16, kernel_size=3, down_sample=True).cuda()(q1) # 16*16
# q1 = RSBU_CW(in_channels=16, out_channels=16, kernel_size=3, down_sample=False).cuda()(q1) # 16*16
# q1 = self.bn(q1)
# q1 = self.relu(q1)
# q1 = self.global_average_pool(q1) # 16*1
# q1 = self.flatten(q1) # 1*16
# q1 = self.linear(q1) # 1*8
# q1 = self.output_class(q1) # 1*3
#
# q2 = self.conv1(input) # 4*128
# # print(x.shape)
# q2 = RSBU_CW(in_channels=4, out_channels=4, kernel_size=3, down_sample=True).cuda()(q2) # 4*64
# q2 = RSBU_CW(in_channels=4, out_channels=4, kernel_size=3, down_sample=False).cuda()(q2) # 4*64
# q2 = RSBU_CW(in_channels=4, out_channels=8, kernel_size=3, down_sample=True).cuda()(q2) # 8*32
# q2 = RSBU_CW(in_channels=8, out_channels=8, kernel_size=3, down_sample=False).cuda()(q2) # 8*32
# q2 = RSBU_CW(in_channels=8, out_channels=16, kernel_size=3, down_sample=True).cuda()(q2) # 16*16
# q2 = RSBU_CW(in_channels=16, out_channels=16, kernel_size=3, down_sample=False).cuda()(q2) # 16*16
# q2 = self.bn_2(q2)
# q2 = self.relu_2(q2)
# q2 = self.global_average_pool_2(q2) # 16*1
# q2 = self.flatten_2(q2) # 1*16
# q2 = self.linear_2(q2) # 1*8
# q2 = self.output_class_2(q2) # 1*3
# # print(q1)
# # print(q2)
# return q1, q2
#
# def Q1(self, state, action):
# input = torch.cat([state, action], 1)
#
# input = input.view(input.shape[0], 1, (input.shape[1]))
# q1 = self.conv1(input) # 4*128
# # print(x.shape)
# q1 = RSBU_CW(in_channels=4, out_channels=4, kernel_size=3, down_sample=True).cuda()(q1) # 4*64
# q1 = RSBU_CW(in_channels=4, out_channels=4, kernel_size=3, down_sample=False).cuda()(q1) # 4*64
# q1 = RSBU_CW(in_channels=4, out_channels=8, kernel_size=3, down_sample=True).cuda()(q1) # 8*32
# q1 = RSBU_CW(in_channels=8, out_channels=8, kernel_size=3, down_sample=False).cuda()(q1) # 8*32
# q1 = RSBU_CW(in_channels=8, out_channels=16, kernel_size=3, down_sample=True).cuda()(q1) # 16*16
# q1 = RSBU_CW(in_channels=16, out_channels=16, kernel_size=3, down_sample=False).cuda()(q1) # 16*16
# q1 = self.bn(q1)
# q1 = self.relu(q1)
# q1 = self.global_average_pool(q1) # 16*1
# q1 = self.flatten(q1) # 1*16
# q1 = self.linear(q1) # 1*8
# q1 = self.output_class(q1) # 1*3
# return q1
# class Composition(nn.Module):
# def __init__(self,in_channels=256,ch1=64,ch3_reduce=96,ch3=128,ch5_reduce=16,ch5=32,pool_pro=32):#
# super(Composition, self).__init__()
# self.branch1 = torch.nn.Conv1d(in_channels,ch1,kernel_size=1)
# self.branch3 = torch.nn.Sequential(
# torch.nn.Conv1d(in_channels,ch3_reduce,kernel_size=1),
# torch.nn.Conv1d(ch3_reduce,ch3,kernel_size=3,padding=1)
# )
# self.branch5 = torch.nn.Sequential(
# torch.nn.Conv1d(in_channels,ch5_reduce,kernel_size=1),
# torch.nn.Conv1d(ch5_reduce,ch5,kernel_size=5,padding=2)
# )
# self.branch_pool = torch.nn.Sequential(
# torch.nn.MaxPool1d(kernel_size=3,stride=1,padding=1),
# torch.nn.Conv1d(in_channels,pool_pro,kernel_size=1)
# )
# def forward(self,x):
# return torch.cat([self.branch1(x),self.branch3(x),self.branch5(x),self.branch_pool(x)],1)
#
# class BasicConv1d(nn.Module):
# def __init__(self, in_channels, out_channels, **kwargs):
# super(BasicConv1d, self).__init__()
# self.conv = torch.nn.Conv1d(in_channels, out_channels, bias=False, **kwargs)
# def forward(self, x):
# x = self.conv(x)
# return F.relu(x, inplace=True)
#
# class CompositionA(nn.Module):
# def __init__(self,in_channels=256,pool_pro=32):#
# super(CompositionA, self).__init__()
# self.branch1x1 = BasicConv1d(in_channels,64,kernel_size=1)
# self.branch5x5_1 = BasicConv1d(in_channels,48,kernel_size=1)
# self.branch5x5_2 = BasicConv1d(48, 64, kernel_size=5,padding=2)
# self.branch3x3dbl_1 = BasicConv1d(in_channels, 64, kernel_size=1)
# self.branch3x3dbl_2 = BasicConv1d(64, 96, kernel_size=3,padding=1)
# self.branch3x3dbl_3 = BasicConv1d(96, 96, kernel_size=3, padding=1)
# self.branch_pool = BasicConv1d(in_channels,pool_pro,kernel_size=1)
# def forward(self,x):
# branch1x1 = self.branch1x1(x)
# branch5x5 = self.branch5x5_1(x)
# branch5x5 = self.branch5x5_2(branch5x5)
# branch3x3dbl = self.branch3x3dbl_1(x)
# branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
# branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)
# branch_pool = F.avg_pool1d(x,kernel_size=3,stride=1,padding=1)
# branch_pool = self.branch_pool(branch_pool)
# return torch.cat([branch1x1,branch5x5,branch3x3dbl,branch_pool],1)
#
# class CompositionB(nn.Module):
# def __init__(self,in_channels=256):#
# super(CompositionB, self).__init__()
# self.branch3x3 = BasicConv1d(in_channels,384,kernel_size=3,stride=2)
# self.branch3x3dbl_1 = BasicConv1d(in_channels, 64, kernel_size=1)
# self.branch3x3dbl_2 = BasicConv1d(64, 96, kernel_size=3,padding=1)
# self.branch3x3dbl_3 = BasicConv1d(96, 96, kernel_size=3,stride=2)
# def forward(self,x):
# branch3x3 = self.branch3x3(x)
# branch3x3dbl = self.branch3x3dbl_1(x)
# branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
# branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)
# branch_pool = F.avg_pool1d(x,kernel_size=3,stride=2)
# return torch.cat([branch3x3,branch3x3dbl,branch_pool],1)
#
# class CompositionC(nn.Module):
# def __init__(self,in_channels=256):#
# super(CompositionC, self).__init__()
# self.branch3x3_1 = BasicConv1d(in_channels, 192, kernel_size=1)
# self.branch3x3_2 = BasicConv1d(192, 320, kernel_size=3, stride=2)
# self.branch7x7x3_1 = BasicConv1d(in_channels, 192, kernel_size=1)
# self.branch7x7x3_2 = BasicConv1d(192, 192, kernel_size=7, padding=3)
# self.branch7x7x3_3 = BasicConv1d(192, 192, kernel_size=7, padding=3)
# self.branch7x7x3_4 = BasicConv1d(192, 192, kernel_size=3, stride=2)
#
# def forward(self,x):
# branch3x3 = self.branch3x3_1(x)
# branch3x3 = self.branch3x3_2(branch3x3)
# branch7x7x3 = self.branch7x7x3_1(x)
# branch7x7x3 = self.branch7x7x3_2(branch7x7x3)
# branch7x7x3 = self.branch7x7x3_3(branch7x7x3)
# branch7x7x3 = self.branch7x7x3_4(branch7x7x3)
# branch_pool = F.max_pool1d(x, kernel_size=3, stride=2)
# outputs = [branch3x3, branch7x7x3, branch_pool]
# return torch.cat(outputs, 1)
#
#
# class Actor1(nn.Module):
# def __init__(self, state_dim, action_dim, max_action):
# super(Actor1, self).__init__()
# self.features = torch.nn.Sequential(
# torch.nn.Linear(100, 100),
# torch.nn.Conv1d(4, 32, kernel_size=7, stride=2, padding=3),
# torch.nn.MaxPool1d(3, 2, padding=1),
# torch.nn.Conv1d(32, 32, kernel_size=1, stride=1),
# torch.nn.Conv1d(32, 128,kernel_size=3,stride=1, padding=1),
# torch.nn.MaxPool1d(3, 2, padding=1),
# Composition(128, 64, 96, 128, 16, 32, 32),
# CompositionA(256, 64),
# CompositionB(288),
# )
# self.Linear_action = torch.nn.Sequential(
# torch.nn.Linear(4608,1024),
# torch.nn.Dropout(0.5),
# torch.nn.Tanh(),
# torch.nn.Linear(1024,512),
# torch.nn.Dropout(0.5),
# torch.nn.Tanh(),
# torch.nn.Linear(512, 128),
# torch.nn.Dropout(0.5),
# torch.nn.Tanh(),
# torch.nn.Linear(128, action_dim)
# )
# self.max_action = max_action
#
# def forward(self, x):
# #print(x.shape)[1,400]
# x = x.view(x.shape[0],1,(x.shape[1]))
# x = x.reshape(x.shape[0],4,100)
# #print(x.shape)#[1,1,400]
# x = self.features(x)
# #print(x.shape)
# x = self.Linear_action(x.view(x.shape[0],4608))
# x = self.max_action * x
# return x
#
#
#
# class Critic1(nn.Module):
# def __init__(self, state_dim, action_dim):
# super(Critic1, self).__init__()
# self.features = torch.nn.Sequential(
# torch.nn.Linear(101, 101),
# torch.nn.Conv1d(4, 32, kernel_size=7, stride=2, padding=3),
# torch.nn.MaxPool1d(3, 2, padding=1),
# torch.nn.Conv1d(32, 32, kernel_size=1,stride=1),
# torch.nn.Conv1d(32, 128, kernel_size=3, stride=1, padding=1),
# torch.nn.MaxPool1d(3, 2, padding=1),
# Composition(128, 64, 96, 128, 16, 32, 32),
# CompositionA(256, 64),
# CompositionB(288),
# )
# self.Linear_action = torch.nn.Sequential(
# torch.nn.Linear(4608, 1024),
# torch.nn.Dropout(0.5),
# torch.nn.Tanh(),
# torch.nn.Linear(1024, 512),
# torch.nn.Dropout(0.5),
# torch.nn.Tanh(),
# torch.nn.Linear(512, 128),
# torch.nn.Linear(128, 1)
# )
#
# self.features2 = torch.nn.Sequential(
# torch.nn.Linear(101, 101),
# torch.nn.Conv1d(4, 32, kernel_size=7, stride=2, padding=3),
# torch.nn.MaxPool1d(3, 2, padding=1),
# torch.nn.Conv1d(32, 32, kernel_size=1,stride=1),
# torch.nn.Conv1d(32, 128, kernel_size=3, stride=1, padding=1),
# torch.nn.MaxPool1d(3, 2, padding=1),
# Composition(128, 64, 96, 128, 16, 32, 32),
# CompositionA(256, 64),
# CompositionB(288),
#
# )
# self.Linear_action2 = torch.nn.Sequential(
# torch.nn.Linear(4608, 1024),
# torch.nn.Dropout(0.5),
# torch.nn.Tanh(),
# torch.nn.Linear(1024, 512),
# torch.nn.Dropout(0.5),
# torch.nn.Tanh(),
# torch.nn.Linear(512, 128),
# torch.nn.Dropout(0.5),
# torch.nn.Tanh(),
# torch.nn.Linear(128, 1)
# )
# def forward(self, x, u):
# u = u.view(u.shape[0], 1, u.shape[1])
# u = u.reshape(u.shape[0], 4, 1)
#
# q1 = x.view(x.shape[0], 1, x.shape[1])
# q1 = q1.reshape(q1.shape[0],4,100)
# q1 = torch.cat((q1,u),2)
# q1 = self.features(q1)
# #print(q1.shape)
# q1 = self.Linear_action(q1.view(q1.shape[0], q1.shape[1]*q1.shape[2]))
#
# q2 = x.view(x.shape[0], 1, x.shape[1])
# q2 = q2.reshape(q2.shape[0], 4, 100)
# q2 = torch.cat((q2, u), 2)
# #print(q2.shape)
# q2 = self.features2(q2)
# #print(q2.shape)
# q2 = self.Linear_action2(q2.view(q2.shape[0], q2.shape[1] * q2.shape[2]))
# return q1, q2
#
# def Q1(self, x, u):
# u = u.view(u.shape[0], 1, u.shape[1])
# u = u.reshape(u.shape[0], 4, 1)
#
# q1 = x.view(x.shape[0], 1, x.shape[1])
# q1 = q1.reshape(q1.shape[0], 4, 100)
# q1 = torch.cat((q1, u), 2)
# q1 = self.features(q1)
# q1 = self.Linear_action(q1.view(q1.shape[0], q1.shape[1] * q1.shape[2]))
# return q1
class DDPG(object):
def __init__(self, state_dim, action_dim, max_action):
self.actor = Actor1(state_dim, action_dim, max_action).to(device)
self.actor_target = Actor1(state_dim, action_dim, max_action).to(device)
self.actor_target.load_state_dict(self.actor.state_dict())
self.actor_optimizer = optim.Adam(self.actor.parameters(), lr=args.lr_A)
self.critic = Critic1(state_dim, action_dim).to(device)
self.critic_target = Critic1(state_dim, action_dim).to(device)
self.critic_target.load_state_dict(self.critic.state_dict())
self.critic_optimizer = optim.Adam(self.critic.parameters(), lr=args.lr_C)
self.replay_buffer = Replay_buffer()
self.writer = SummaryWriter(directory)
self.num_critic_update_iteration = 0
self.num_actor_update_iteration = 0
self.num_training = 0
self.loss_c_list = []
self.loss_a_list = []
self.t_q_list = []
self.c_q_list = []
self.episode = 0
self.reward = -100000
self.i_episode = 0
self.percentage = -1
def select_action(self, state):
state = torch.FloatTensor(state.reshape(1, -1)).to(device)
return self.actor(state).cpu().data.numpy().flatten()
def update(self):
for it in range(args.update_iteration):
# Sample replay buffer
x, y, u, r, d = self.replay_buffer.sample(args.batch_size)
state = torch.FloatTensor(x).to(device)
action = torch.FloatTensor(u).to(device)
next_state = torch.FloatTensor(y).to(device)
done = torch.FloatTensor(1 - d).to(device)
reward = torch.FloatTensor(r).to(device)
# Select action according to policy and add clipped noise
noise = (
torch.randn_like(action) * 0.2
).clamp(-0.5, 0.5)
next_action = (
self.actor_target(next_state) + noise
).clamp(-self.actor.max_action, self.actor.max_action)
# print(next_state.shape)
# print(next_action.shape)
# Compute the target Q value
target_Q1, target_Q2 = self.critic_target(next_state, next_action)
target_Q = torch.min(target_Q1, target_Q2)
target_Q = reward + done * args.gamma * target_Q
# Get current Q estimates
current_Q1, current_Q2 = self.critic(state, action)
# Compute critic loss
critic_loss = F.mse_loss(current_Q1, target_Q) + F.mse_loss(current_Q2, target_Q)
self.writer.add_scalar('Loss/critic_loss', critic_loss, global_step=self.num_critic_update_iteration)
# Optimize the critic
self.critic_optimizer.zero_grad()
critic_loss.backward()
self.critic_optimizer.step()
# Compute actor loss
# actor_loss = -self.critic(state, self.actor(state)).mean()-reg_action
actor_loss = -self.critic.Q1(state, self.actor(state)).mean()
self.writer.add_scalar('Loss/actor_loss', actor_loss, global_step=self.num_actor_update_iteration)
tq_save = target_Q.cpu().data.numpy().mean()
cq_save = current_Q1.cpu().data.numpy().mean()
# Optimize the actor
self.actor_optimizer.zero_grad()
actor_loss.backward()
self.actor_optimizer.step()
self.loss_c_list.append(critic_loss.item())
self.loss_a_list.append(actor_loss.item())
self.t_q_list.append(tq_save.item())
self.c_q_list.append(cq_save.item())
# Update the frozen target models
if (it % 1 == 0):
for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):
target_param.data.copy_(args.tau * param.data + (1 - args.tau) * target_param.data)
if (it % 1 == 0):
for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):
target_param.data.copy_(args.tau * param.data + (1 - args.tau) * target_param.data)
self.num_actor_update_iteration += 1
self.num_critic_update_iteration += 1
self.episode += 1
'''
plt.figure(figsize=(16, 12))
plt.plot(range(len(self.Q_iter)), self.Q_iter, linewidth=3, color='g')
plt.ylabel('Q value', size=10)
plt.xlabel('Episode No.', size=10)
plt.savefig(path + '\\Q_value\\' + str(self.episode) + '.png')
'''
# plt.subplot(311)
#
# plt.plot(range(len(self.loss_c_list)),self.loss_c_list, linewidth=3, color='g')
# plt.ylabel('loss_critic', size=10)
# plt.xlabel('Episode No.', size=10)
#
# plt.subplot(312)
# plt.plot(range(len(self.loss_a_list)), self.loss_a_list, linewidth=3, color='b')
# plt.ylabel('loss_actor', size=10)
# plt.xlabel('Episode No.', size=10)
#
# plt.subplot(313)
# plt.plot(range(len(self.t_q_list)), self.t_q_list, linewidth=3, color='g')
# plt.plot(range(len(self.c_q_list)), self.c_q_list, linewidth=3, color='b')
# plt.ylabel('Q value', size=10)
# plt.xlabel('Episode No.', size=10)
#
# plt.savefig(os.getcwd() + '\\Loss1\\' + str(self.episode) + '.png')
def save(self):
torch.save(self.actor.state_dict(), directory + 'actor.pt')
torch.save(self.critic.state_dict(), directory + 'critic.pt')
print("====================================")
print("Model has been saved...")
print("====================================")
def load(self):
self.actor.load_state_dict(torch.load('actor.pt'))
self.critic.load_state_dict(torch.load('critic.pt'))
print("====================================")
print("model has been loaded...")
print("====================================")
df1 = pd.read_excel('motor0on0415.xlsx', sheet_name='data', header=None)
#df1 = pd.read_excel('motor0on0415_test4.xlsx', sheet_name='data', header=None)
agent = DDPG(state_dim=400, action_dim=4, max_action=1)
actor = Actor1(400,4,1)
critic = Critic1(400,1)
print(sum(param.numel() for param in actor.parameters())+sum(param.numel() for param in critic.parameters()))
env_org = Env()
env = Env()
# %%训练智能体
if args.mode == 'train':
print("============ train agent ==============")
if args.load_nn == True:
agent.load()
S_acc_current = 0
ep_reward__ = []
for i_episode in range(args.max_episode): # 2000
env.reset()
env_org.reset()
#每一个episode随机截取
start= random.randint(2, 50000 - args.episode_length)
#start = random.randint(2, 30000 - args.episode_length)
print(start)
x0_array = df1.values[start:args.episode_length + start, 0]
# %% 测试环境
acc1__ = []
acc2__ = []
acc3__ = []
acc4__ = []
j = 0
S_acc_org = 0
while j <= args.episode_length - 1:
x0 = x0_array[j]
# 电机的动作,神经网络的输出,这里关闭电机
x1 = 0
x2 = 0
x3 = 0
x4 = 0
# 状态,实际从传感器读取
env.state, reward, done = env.step(x0, x1, x2, x3, x4)
acc1__.append(env.state[0])
acc2__.append(env.state[1])
acc3__.append(env.state[2])
acc4__.append(env.state[3])
j += 1
S_acc_org1 = 0
S_acc_org2 = 0
S_acc_org3 = 0
S_acc_org4 = 0
for i in acc1__:
S_acc_org1 += i * i
for i in acc2__:
S_acc_org2 += i * i
for i in acc3__:
S_acc_org3 += i * i
for i in acc4__:
S_acc_org4 += i * i
S_acc_org1 = S_acc_org1 / len(acc1__)
S_acc_org2 = S_acc_org2 / len(acc1__)
S_acc_org3 = S_acc_org3 / len(acc1__)
S_acc_org4 = S_acc_org4 / len(acc1__)
S_acc_org = (S_acc_org1 + S_acc_org2 + S_acc_org3 + S_acc_org4) / 4
Fs = int(1 / env.tau)
nfft = 2 * Fs
fre = Fs / nfft * (np.array(range(0, int(nfft / 2))))
Y1 = fft(acc1__, nfft)