forked from tyh0123/NN_model_meta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNN_predict.py
178 lines (131 loc) · 5.04 KB
/
NN_predict.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
from __future__ import print_function
import argparse
import torch
import torch.utils.data
from torch import nn, optim
from torch.nn import functional as F
from torchvision import datasets, transforms
from torchvision.utils import save_image
import os
from scipy.io import loadmat
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import scipy.io as sio
import scipy.stats
import h5py
import pandas as pd
from dataset_NN import HVDataset
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
parser = argparse.ArgumentParser(description='NN_code')
parser.add_argument('--batch-size', type=int, default=128, metavar='N',
help='input batch size for training (default: 128)')
parser.add_argument('--epochs', type=int, default=15, metavar='N',
help='number of epochs to train (default: 10)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='enables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
#comment out this line to enable the random seed
# torch.manual_seed(args.seed)
device = torch.device("cuda" if args.cuda else "cpu")
kwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}
##load the file
cwd = os.getcwd()
filename = 'data_radius.mat' ##load the .mat file to the current directory and change the name here
dir = os.path.join(cwd,filename)
HV_input = 'radius' ##variable name for the HV in the .mat.file
label_input = 'T' ##variable name for the label in the .mat file
train = HVDataset(dir, HV_input, label_input, transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(train,batch_size=args.batch_size, shuffle=True, **kwargs)
##NN network
class NN_network(nn.Module):
def __init__(self):
super(NN_network, self).__init__()
# encoder graph
self.layer1 = nn.Sequential(
nn.Linear(4, 16),
nn.ReLU())
self.layer2 = nn.Sequential(
nn.Linear(16, 128),
nn.ReLU())
self.layer3 = nn.Sequential(
nn.Linear(128, 1024),
nn.ReLU())
self.layer4 = nn.Sequential(
nn.Linear(1024, 1024),
nn.ReLU())
self.layer5 = nn.Sequential(
nn.Linear(1024, 512),
nn.ReLU())
self.layer6 = nn.Sequential(
nn.Linear(512, 200),
nn.Sigmoid())
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = self.layer5(out)
out = self.layer6(out)
return out
model = NN_network().to(device)
print(model)
optimizer = optim.Adam(model.parameters(), lr=1e-3)
##loss function for the adversarial block
def loss_function(c_bar, c):
loss = F.mse_loss(c_bar,c,reduction='mean')
return loss
###training
def predict(net,epoch):
loss_record = []
train_loss = 0
for batch_idx, (data, labels) in enumerate(train_loader):
data = torch.unsqueeze(data, 1)
data = data.to(device)
labels = labels.to(device)
outp = net(data)
loss = loss_function(outp, labels)
loss.backward()
train_loss += loss.item()
loss_record = np.append(loss_record,loss.item()/len(data))
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader),
loss.item()))
return data, outp, labels
def plot_loss(total):
plt.plot(l1, label='TOTAL_LOSS')
plt.legend()
plt.show()
if __name__ == "__main__":
net = torch.load('NN_model.pkl')
data, outp, labels = predict(net,1)
data = data.cpu().detach().numpy()
labels = labels.cpu().detach().numpy()
outp = outp.view(-1, 200)
outp = outp.cpu().detach().numpy()
plt.plot(outp[10, :], marker='o', markerfacecolor='blue', markersize=5, color='skyblue', linewidth=4,
label="predicted")
plt.plot(labels[10, :], marker='*', markerfacecolor='yellow', markersize=5, color='skyblue', linewidth=4,
label="actual")
plt.legend()
plt.show()
plt.plot(outp[60, :], marker='o', markerfacecolor='blue', markersize=5, color='skyblue', linewidth=4,
label="predicted")
plt.plot(labels[60, :], marker='*', markerfacecolor='yellow', markersize=5, color='skyblue', linewidth=4,
label="actual")
plt.legend()
plt.show()
print(1)
##save the model