Skip to content

Commit 6068c4b

Browse files
committed
Lstm优化
已经可以本地运行计算正确率打了
1 parent 4656762 commit 6068c4b

1 file changed

Lines changed: 31 additions & 25 deletions

File tree

‎PyTorch/LSTM.py‎

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,14 @@
99
import os
1010
from ProcessProgram.NeurNetWorkProcess.ProceRawDataToTensor import *
1111

12-
12+
Work_Path = "F:\\PlantarPressurePredictExperiment"
13+
os.chdir(Work_Path)
14+
global x_train,x_test,y_train,y_test,train_loader,test_loader
1315
#region 预置参数
14-
BATCH_SIZE = 8
16+
BATCH_SIZE = 16
1517
Learn_Rate = 0.001
1618
EPOCH = 30
1719
tempMax = 87
18-
1920
sequenceLen = 2 #视频序列长度
2021
#endregion
2122

@@ -65,29 +66,34 @@ def TrainFormData():
6566

6667
#region lstm模型
6768
class LSTM(nn.Module):
68-
def __init__(self):
69+
def __init__(self,in_dim,hidden_dim,n_layer,n_class):
70+
'''
71+
:param in_dim: 进入维度
72+
:param hidden_dim: 隐藏层数量
73+
:param n_layer: 层数
74+
:param n_class: 分类数量
75+
'''
6976
super(LSTM,self).__init__()
70-
self.batchNorm =nn.BatchNorm2d(1260, momentum=0.1)
71-
self.lstm1 = nn.LSTM(1260,40,3,batch_first=True) #输入特征1260,输出特征50, 3层隐藏层
72-
self.out = nn.Linear(40,4)
77+
self.lstm = nn.LSTM(in_dim,hidden_dim,n_layer,batch_first=True)
78+
self.linear = nn.Linear(hidden_dim,n_class)
7379

7480
#前向函数
7581
def forward(self, x):
76-
#x = self.batchNorm(x)
77-
x = self.lstm1(x)[0]
78-
x = x.view(x.size(0), -1) #将除Batch的维度展成一维的
79-
output = self.out(x)
82+
out,_ = self.lstm(x)
83+
out = out[:,-1,:]
84+
out = self.linear(out)
85+
return out
8086
#endregion
8187

8288
#region 功能函数
8389

8490
#保存网络
8591
def savemodel(model,filename_Date_correctRate):
86-
torch.save(model,"ProcessProgram\\model\\{}".format(filename_Date_correctRate))
92+
torch.save(model,"F:\\PlantarPressurePredictExperiment\\Pytorch\\model\\{}".format(filename_Date_correctRate))
8793

8894
#提取网络
8995
def getmodel(filename_Date_correctRate):
90-
net = torch.load("ProcessProgram\\model\\{}".format(filename_Date_correctRate))
96+
net = torch.load("F:\\PlantarPressurePredictExperiment\\Pytorch\\model\\{}".format(filename_Date_correctRate))
9197
return net
9298
#endregion
9399

@@ -97,22 +103,21 @@ def TestNetWork(lstm):
97103
correct = 0
98104
test_loss = 0
99105
for step, (data, target) in enumerate(test_loader):
100-
data, target = Variable(data),Variable(target)
101-
data = data.float()
106+
data, target = Variable(data).cuda(),Variable(target).cuda()
102107
output = lstm(data)
103108
# sum up batch loss
104109
test_loss += loss_func(output, target).item()
105110
# get the index of the max log-probability
106111
pred = torch.max(output.data, 1)[1]
107-
correct += pred.eq(target.data.view_as(pred)).cpu().sum()
112+
correct += int(pred.eq(target.data.view_as(pred)).cpu().sum())
108113
test_loss /= len(test_loader.dataset)
109-
correctRate = int(100. * correct / len(test_loader.dataset))
114+
correctRate = 100. * correct / len(test_loader.dataset)
110115
print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
111116
test_loss, correct, len(test_loader.dataset),correctRate))
112117
tempMax = 85
113-
if(correctRate > tempMax):
114-
tempMax = correctRate
115-
#savemodel(cnn, "tempMaxModel\\cnn_tempMax_correct{}%.pkl".format(correctRate))
118+
# if(correctRate > tempMax):
119+
# tempMax = correctRate
120+
# #savemodel(cnn, "tempMaxModel\\cnn_tempMax_correct{}%.pkl".format(correctRate))
116121
lstm.train()
117122
return ("{:.0f}%".format(100. * correct / len(test_loader.dataset)))
118123

@@ -121,18 +126,18 @@ def TestNetWork(lstm):
121126
if __name__ == '__main__':
122127
importData()
123128
TrainFormData()
124-
lstm = LSTM()
129+
lstm = LSTM(1260,400,2,4)
125130
lstm.cuda()
126131

127132
optimizer = torch.optim.Adam(lstm.parameters(), lr=Learn_Rate)
128133
# scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.5,
129134
# last_epoch=-1) # 动态调整学习率。每10轮下降一位小数点
130135
loss_func = nn.CrossEntropyLoss()
131136

132-
for epoch in range(1,EPOCH):
137+
for epoch in range(EPOCH):
133138
for step,(x,y) in enumerate(train_loader):
134-
b_x = Variable(x)
135-
b_y = Variable(y)
139+
b_x = Variable(x).cuda()
140+
b_y = Variable(y).cuda()
136141
output = lstm(b_x)
137142
loss = loss_func(output, b_y)
138143
optimizer.zero_grad()
@@ -143,11 +148,12 @@ def TestNetWork(lstm):
143148
print('Train Epoch: {} \t [{:4d}/{:4d} ({:.0f}%)] \t\t Loss: {:.6f}'.format(
144149
epoch, step * len(x), len(train_loader.dataset),
145150
100. * step / len(train_loader), loss.data), end="\n")
151+
TestNetWork(lstm)
146152
#scheduler.step()
147153

148154
print("Final:", end="")
149155
# test
150156
Correct = TestNetWork(lstm)
151-
savemodel(lstm, "cnn9_23_0_correct{}.pkl".format(Correct))
157+
savemodel(lstm, "lstm10_3_0_correct{}.pkl".format(Correct))
152158

153159

0 commit comments

Comments
 (0)