03/01 22:25

# 前言

• 5层的深度神经网络，活函数是双曲正切函数；
• 另一种方法使用的是李加索变量选择方法，这种方法思想就是挑选10个边际p值最小的像素来进行(用这些值做回归就可以了);

# 正文

## 一维信号

label分别为：0、1、2、3.

## 数据读取

import torch
import torch.utils.data as data
import scipy.io
import os
import os.path as osp


# 将原始数据转化为训练需要的数据格式
def to_tensor(data):
data = torch.from_numpy(data).type(torch.float32)
data = data.unsqueeze(0)
return data

# 读取数据类
class LineData(data.Dataset):

def __init__(self, root, name=532, train=True, transform=to_tensor):
self.root = os.path.expanduser(root)
self.name = name
self.train = train
self.transform = transform
self.classes = [0, 1, 2, 3]

if not osp.exists('datasets'):
raise FileExistsError('Missing Datasets')

if self.train:
self.train_datas = []
self.train_labels = []

dataset_dir = osp.join(self.root, 'train_{}nm.mat'.format(self.name))
data_length = len(train_data) - 1              # 161 - 1 = 160

if self.transform:

for i in range(data_length):                   # 0 - 159
self.train_datas.append(transform(train_data[i+1]))        # i+1 => 1 - 160
self.train_labels.append(self.classes[int(i / 40)])
else:
raise ValueError('We need tranform function!')

if not self.train:
self.test_datas = []
self.test_labels = []

dataset_dir = osp.join(self.root, 'test_{}nm.mat'.format(self.name))
data_length = len(test_data) - 1              # 81 - 1 = 80

if self.transform:

for i in range(data_length):                   # 0 - 79
self.test_datas.append(transform(test_data[i+1]))         # i+1 => 1 - 80
self.test_labels.append(self.classes[int(i / 20)])
else:
raise ValueError('We need tranform function!')

def __getitem__(self, index):
"""
Args:
index (int): Index

Returns:
tuple: (image, target) where target is index of the target class.
"""
if self.train:
data, target = self.train_datas[index], self.train_labels[index]
else:
data, target = self.test_datas[index], self.test_labels[index]

return data, target

def __len__(self):
if self.train:
return len(self.train_datas)
else:
return len(self.test_datas)



## 编写神经网络

每个数据的长度为168

class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv1d(1, 10, 3)    # (168 - 3)/1 + 1 = 166 (* 10)
self.pool = nn.MaxPool1d(2, 2)      # (166 - 2)/2 + 1= 83 (* 10)
self.conv2 = nn.Conv1d(10, 20, 3)   # (83 - 3)/1 + 1 = 81 (* 20)
self.fc1 = nn.Linear(81*20, 100)
self.fc2 = nn.Linear(100, 4)

def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = F.relu(self.conv2(x))
x = x.view(-1, 81*20)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x


## 训练以及测试

# 主程序页面

import torch
import torch.nn as nn
import torch.utils.data
import torch.optim as optim
from model import Net
from data_utils import LineData

root = 'datasets'    # 数据所在目录,相对目录地址
train_name = '532'   # 或者 '1064'

# device = torch.device('cuda:0')

# 读取文件类
trainset = LineData(root, name=train_name)

testset = LineData(root, name=train_name, train=False)

net = Net()
# net = net.to(device)

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

# 下面的epoch改成 2 可以达到100%的准确率
epoch_sum = 1
# 训练
for epoch in range(epoch_sum):

loss_sum = 0.0
for i, data in enumerate(trainloader, 0):

inputs, labels = data
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()

loss_sum += loss.item()
if i % 10 == 9:
print('[epoch:{} num:{}] loss:{}'.format(epoch, i, loss_sum / 20))
loss_sum = 0.0

print('Finished Training')

# 验证
correct = 0
total = 0
inputs, labels = data
outputs = net(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()

print('Accuracy of the network on the 80 test images: %d %%' % (
100 * correct / total))

pass



[epoch:0 num:9] loss:1.693671927541118e+16
[epoch:0 num:19] loss:53694975.30745087
[epoch:0 num:29] loss:6.2672371854667905e+28
[epoch:0 num:39] loss:51403236.52956776
Finished Training
Accuracy of the network on the 80 test images: 25 %


[epoch:0 num:9] loss:133432.54784755706
[epoch:0 num:19] loss:67940.00796541572
[epoch:0 num:29] loss:109.18773172795773
[epoch:0 num:39] loss:1.1358043849468231
Finished Training
Accuracy of the network on the 80 test images: 25 %


loss下降很平缓，但是epoch看起来不够导致loss下降没有彻底，准确率依然很低，让我们来调整一下epoch。

[epoch:0 num:9] loss:3024598166.2773805
[epoch:0 num:19] loss:3117157163.829549
[epoch:0 num:29] loss:258.4028107881546
[epoch:0 num:39] loss:0.6990358293056488
[epoch:1 num:9] loss:0.6830220401287079
[epoch:1 num:19] loss:66.56461009383202
[epoch:1 num:29] loss:0.7117315053939819
[epoch:1 num:39] loss:0.6977931916713714
[epoch:2 num:9] loss:0.6974189281463623
[epoch:2 num:19] loss:0.6898959457874299
[epoch:2 num:29] loss:0.7101178288459777
[epoch:2 num:39] loss:0.6914324820041656
[epoch:3 num:9] loss:0.686737447977066
[epoch:3 num:19] loss:0.6972651600837707
[epoch:3 num:29] loss:0.7028001189231873
[epoch:3 num:39] loss:0.6998239696025849
[epoch:4 num:9] loss:0.6997098863124848
[epoch:4 num:19] loss:0.6969940900802613
[epoch:4 num:29] loss:0.696108078956604
[epoch:4 num:39] loss:0.6910847663879395
Finished Training
Accuracy of the network on the 80 test images: 25 %


loss下降到一定级别没有再下降，而准确率依然很迷，有可能还是因为学习率过高而导致loss一直卡在一个范围无法彻底下降，我们再试着尝试下降一下学习率。

[epoch:0 num:9] loss:200.58453428081702
[epoch:0 num:19] loss:5.724525341391564
[epoch:0 num:29] loss:0.2976263818090047
[epoch:0 num:39] loss:0.05558242934057489
[epoch:1 num:9] loss:0.0004892532759185996
[epoch:1 num:19] loss:0.00012833428763769916
[epoch:1 num:29] loss:9.479262493137242e-05
[epoch:1 num:39] loss:3.948449189010717e-05
Finished Training
Accuracy of the network on the 80 test images: 100 %


epoch从1换成3则是：100%、100%、100%、100%、100%、100%、100%、100%、100%、100%。

class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(168, 1000)
self.fc2 = nn.Linear(1000, 100)
self.fc3 = nn.Linear(100,4)

def forward(self, x):
x = x.view(-1, 168)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x


# 撩我吧

• 如果你与我志同道合于此，老潘很愿意与你交流；
• 如果你喜欢老潘的内容，欢迎关注和支持。
• 如果你喜欢我的文章，希望点赞👍 收藏 📁 评论 💬 三连一下~

0
0 收藏

0 评论
0 收藏
0