-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlong_and_short_memory_task_time_fixed.py
135 lines (115 loc) · 6 KB
/
long_and_short_memory_task_time_fixed.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
import argparse
import os
from datetime import datetime
import numpy as np
import pytz
import torch
import torch.optim as optim
import torch.utils.data
from dataset import make_lsm_signals
from model.model import RecurrentNetTimeFixed
def train(model, device, optimizer, stim_dur, each_episodes, resp_dur, n_stim, epoch, batch_size, n_hid):
model.train()
signals = []
targets = []
for i in range(batch_size):
signal, target = make_lsm_signals.lsm_signals(n_episodes=500, stim_dur=stim_dur,
sig1_stim_dur=stim_dur, resp_dur=resp_dur,
each_episodes=each_episodes, spon_rate=0.01)
signals.append(signal)
targets.append(target)
signals = np.array(signals)
targets = np.array(targets)
signals = torch.from_numpy(signals)
targets = torch.from_numpy(targets)
hidden = torch.zeros(batch_size, n_hid, requires_grad=True)
hidden = hidden.to(device)
one_learning_length = n_stim * (resp_dur + stim_dur)
for episodes in range(batch_size):
batched_signals = \
signals[:, episodes * one_learning_length * each_episodes:
(episodes + 1) * one_learning_length * each_episodes, :]
batched_targets = \
targets[:, episodes * one_learning_length * each_episodes:
(episodes + 1) * one_learning_length * each_episodes, :]
batched_signals = batched_signals.float()
batched_targets = batched_targets.float()
batched_signals.requires_grad = True
batched_signals, batched_targets = batched_signals.to(device), batched_targets.to(device)
optimizer.zero_grad()
hidden = hidden.detach()
_, output, hidden = model(batched_signals, hidden)
loss = torch.nn.MSELoss()(output[:, n_stim * stim_dur:one_learning_length, :],
batched_targets[:, n_stim * stim_dur:one_learning_length, :])
for i in range(each_episodes - 1):
loss += torch.nn.MSELoss()(output[:, n_stim * stim_dur + (i + 1) * one_learning_length:
one_learning_length * (i + 2), :],
batched_targets[:, n_stim * stim_dur + (i + 1) * one_learning_length:
one_learning_length * (i + 2), :])
loss.backward()
optimizer.step()
print("target: ", end=" ")
for i in range(n_stim, 0, -1):
print(batched_targets.cpu().data[0][-int(resp_dur * i)].numpy()[0], end=" ")
print('\n')
print("output: ", end=" ")
for i in range(n_stim, 0, -1):
print(output.cpu().data[0][-int(resp_dur * i)].numpy()[0], end=" ")
print("\n")
print('Train Epoch: {}, Episode: {}, Loss: {:.6f}'.format(
epoch, episodes, loss.item()))
def main():
use_cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
print(device)
os.makedirs("./trained_models", exist_ok=True)
alpha = [0.08]*80+[0.4]*420
# alpha = [0.4] * 500
model = RecurrentNetTimeFixed(n_in=200, n_hid=args.network_size, n_out=1,
use_cuda=use_cuda, alpha_weight=alpha).to(device)
if args.trained_model:
model.load_state_dict(
torch.load(args.trained_model))
print(model)
optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr)
for epoch in range(1, args.epochs + 1):
train(model=model, device=device, optimizer=optimizer, stim_dur=args.stim_dur, each_episodes=args.each_episodes,
resp_dur=args.resp_dur, n_stim=args.n_stim, epoch=epoch, batch_size=args.batch_size,
n_hid=args.network_size)
if args.save_model and (epoch - 1) % args.savepoint == 0:
time_stamp = datetime.strftime(datetime.now(pytz.timezone('Japan')), '%m%d%H%M')
torch.save(
model.state_dict(),
"./trained_models/{}_008_80_04_420_epoch_{}_id_{}.pth"
.format(time_stamp, epoch, args.model_id))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='PyTorch RNN training')
parser.add_argument('--batch_size', type=int, default=50, metavar='N',
help='input batch size for training (default: 50)')
parser.add_argument('--n_stim', type=int, default=3)
parser.add_argument('--each_episodes', type=int, default=5)
parser.add_argument('--stim_dur', type=int, default=15)
parser.add_argument('--resp_dur', type=int, default=10)
parser.add_argument('--t_constant', type=float, default=0.2)
parser.add_argument('--network_size', type=int, default=500)
parser.add_argument('--test_batch_size', type=int, default=50, metavar='N',
help='input batch size for testing (default: 50)')
parser.add_argument('--savepoint', type=int, default=10)
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.0005, metavar='LR',
help='learning rate (default: 0.0005)')
parser.add_argument('--no_cuda', action='store_true', default=False,
help='disables 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')
parser.add_argument('--save_model', action='store_true', default=False,
help='For Saving the current Model')
parser.add_argument('--trained_model', type=str, default=None)
parser.add_argument('--model_id', type=str)
args = parser.parse_args()
print(args)
main()