pandas

用处:Pandas 的主要数据结构是 Series (一维数据)与 DataFrame(二维数据),这两种数据结构足以处理金融、统计、社会科学、工程等领域里的大多数典型用例。

![](2022-07-08 ML-BrainWave代码初读.assets/2022-07-08-pd.read_csv.png)

1
2
3
# 读取数据
train_images = pd.read_csv('D:/_Codes/PyChram/BrainWave/datas/Enrollment_Info.csv')
val_images = pd.read_csv('D:/_Codes/PyChram/BrainWave/datas/Calibration_Info.csv')

shuffle()

方法将序列的所有元素随机排序。

![](2022-07-08 ML-BrainWave代码初读.assets/2022-07-08-shuffle.png)

1
2
3
# 意思应该是训练时完全随机
train_images = shuffle(train_images, random_state=0)
val_images = shuffle(val_images)

dwt

在数字图像处理中,需要将连续的小波及其小波变换离散化。一般计算机实现中使用二进制离散处理,将经过这种离散化的小波及其相应的小波变换成为离散小波变换(简称DWT)。实际上,离散小波变换是对连续小波变换的尺度、位移按照2的幂次进行离散化得到的,所以也称之为二进制小波变换。

虽然经典的傅里叶变换可以反映出信号的整体内涵,但表现形式往往不够直观,并且噪声会使得信号频谱复杂化。在信号处理领域一直都是使用一族带通滤波器将信号分解为不同频率分量,即将信号f(x)送到带通滤波器族Hi(x)中。

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
# 小波变换

# 传参是paddle.nn的layer
"""
class paddle.nn.Layer ( name_scope=None, dtype=’float32’ ) [源代码]
基于OOD实现的动态图Layer,包含该Layer的参数、前序运行的结构等信息。

参数:
name_scope (str,可选) - 为Layer内部参数命名而采用的名称前缀。如果前缀为“mylayer”,在一个类名为MyLayer的Layer中,参数名为“mylayer_0.w_n”,其中w是参数的名称,n为自动生成的具有唯一性的后缀。如果为None,前缀名将为小写的类名。默认值为None。
dtype (str可选) - Layer中参数数据类型。如果设置为str,则可以是“bool”,“float16”,“float32”,“float64”,“int8”,“int16”,“int32”,“int64”,“uint8”或“uint16”。默认值为 “float32”。

返回:无
"""

class MyNet_dwt(nn.Layer):

def __init__(self, num_classes=1000):
super(MyNet_dwt, self).__init__()
self.num_classes = num_classes

self._conv1 = Conv1D(
65,
128,
3,
stride=2,
padding=1,
)

self._conv2_1 = Conv1D(
128,
256,
3,
stride=2,
padding=1,
)
self._conv3_1 = Conv1D(
256,
512,
3,
stride=2,
padding=1,
)
self._conv4_1 = Conv1D(
512,
256,
3,
stride=2,
padding=1,
)

self._conv2_2 = Conv1D(
128,
256,
3,
stride=2,
padding=1,
)
self._conv3_2 = Conv1D(
256,
512,
3,
stride=2,
padding=1,
)

self._conv4_2 = Conv1D(
512,
256,
3,
stride=2,
padding=1,
)

self._fc8 = Linear(
in_features=16384,
out_features=num_classes,
)

def forward(self, inputs):
x = self._conv1(inputs)
x = paddle.to_tensor(pywt.dwt(x.numpy(), 'haar'), dtype='float32')
x1, x2 = x.split(2)

x1 = x1.squeeze(axis=0)
x2 = x2.squeeze(axis=0)
x1 = self._conv2_1(x1)
x1 = self._conv3_1(x1)
x1 = F.relu(x1)
x1 = self._conv4_1(x1)
x1 = F.relu(x1)

x2 = self._conv2_2(x2)
x2 = self._conv3_2(x2)
x2 = F.relu(x2)
x2 = self._conv4_2(x2)
x2 = F.relu(x2)

x = paddle.concat(x=[x1, x2], axis=2)
x = paddle.flatten(x, start_axis=1, stop_axis=-1)
x = self._fc8(x)
return x

模型封装

转化为paddle的model

1
model = paddle.Model(model_res)

定义优化器

优化器:在深度学习反向传播过程中,指引损失函数(目标函数)的各个参数往正确的方向更新合适的大小,使得更新后的各个参数让损失函数(目标函数)值不断逼近全局最小。

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
# 定义优化器
class Cosine(CosineAnnealingDecay):
"""
Cosine learning rate decay
lr = 0.05 * (math.cos(epoch * (math.pi / epochs)) + 1)

Args:
lr(float): initial learning rate
step_each_epoch(int): steps each epoch
epochs(int): total training epochs
"""

def __init__(self, lr, step_each_epoch, epochs, **kwargs):
super(Cosine, self).__init__(
learning_rate=lr,
T_max=step_each_epoch * epochs, )

self.update_specified = False

class CosineWarmup(LinearWarmup):
"""
Cosine learning rate decay with warmup
[0, warmup_epoch): linear warmup
[warmup_epoch, epochs): cosine decay

Args:
lr(float): initial learning rate
step_each_epoch(int): steps each epoch
epochs(int): total training epochs
warmup_epoch(int): epoch num of warmup
"""

def __init__(self, lr, step_each_epoch, epochs, warmup_epoch=5, **kwargs):
assert epochs > warmup_epoch, "total epoch({}) should be larger than warmup_epoch({}) in CosineWarmup.".format(
epochs, warmup_epoch)
warmup_step = warmup_epoch * step_each_epoch
start_lr = 0.0
end_lr = lr
lr_sch = Cosine(lr, step_each_epoch, epochs - warmup_epoch)

super(CosineWarmup, self).__init__(
learning_rate=lr_sch,
warmup_steps=warmup_step,
start_lr=start_lr,
end_lr=end_lr)

self.update_specified = False

scheduler = CosineWarmup(
lr=0.00125, step_each_epoch=226, epochs=24, warmup_steps=20, start_lr=0, end_lr=0.00125, verbose=True)
optim = paddle.optimizer.Adam(learning_rate=scheduler, parameters=model.parameters())
Cosine learning rate decay

学习率不断衰减是一个提高精度的好方法。其中有step decay和cosine decay等,前者是随着epoch增大学习率不断减去一个小的数,后者是让学习率随着训练过程曲线下降。

warmup step decay

复习?

Adam

1
optim = paddle.optimizer.Adam(learning_rate=scheduler, parameters=model.parameters())

Adam优化器能够利用梯度的一阶矩估计和二阶矩估计动态调整每个参数的学习率。

VisualDL

1
callback = paddle.callbacks.VisualDL(log_dir='visualdl_log_dir_alexdwt')

VisualDL 是一个visualdl( 飞桨可视化分析工具 )的回调类。该类将训练过程中的损失值和评价指标储存至日志文件中后,启动面板即可查看可视化结果。

训练

(不太清楚细节)

1
2
3
4
5
6
7
8
9
10
pre_list = []
for i in range(len(eeg_list)):
data = load_eeg(eeg_path=eeg_list[i])
dy_x_data = np.array(data).astype('float32')
dy_x_data = dy_x_data[np.newaxis, :, :]
eeg = paddle.to_tensor(dy_x_data)
out = model_res(eeg)
res = paddle.nn.functional.softmax(out)[0] # 若模型中已经包含softmax则不用此行代码。
lab = np.argmax(out.numpy()) # argmax():返回最大数的索引
pre_list.append(int(lab) + 1)

预测并生成文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
img_test = pd.DataFrame(labeled_img_list)
img_pre = pd.DataFrame(labeled_img_list)

img_test = img_test.rename(columns={0: "EpochID"})
img_pre['SubjectID'] = pre_list
pre_info = img_pre['SubjectID'].values
test_info = test_image['SubjectID'].values

result_cnn = list()

for i, j in zip(test_info, pre_info):

if i == 'None':
result_cnn.append(j)
elif int(i[4:]) == j:
print(i[4:])
result_cnn.append(int(1))
else:
result_cnn.append(int(0))

img_test['Prediction'] = result_cnn
img_test.to_csv('result_dwt.csv', index=False)
Pandas 数据结构 - DataFrame

DataFrame 是一个表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔型值)。DataFrame 既有行索引也有列索引,它可以被看做由 Series 组成的字典(共同用一个索引)。