forked from xuerenlv/social-lstm-tf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
social_train.py
156 lines (132 loc) · 7.01 KB
/
social_train.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
import tensorflow as tf
import argparse
import os
import time
import pickle
import ipdb
from social_model import SocialModel
from social_utils import SocialDataLoader
from grid import getSequenceGridMask
def main():
parser = argparse.ArgumentParser()
# RNN size parameter (dimension of the output/hidden state)
parser.add_argument('--rnn_size', type=int, default=128,
help='size of RNN hidden state')
# TODO: (improve) Number of layers not used. Only a single layer implemented
# Number of layers parameter
parser.add_argument('--num_layers', type=int, default=1,
help='number of layers in the RNN')
# Model currently not used. Only LSTM implemented
# Type of recurrent unit parameter
parser.add_argument('--model', type=str, default='lstm',
help='rnn, gru, or lstm')
# Size of each batch parameter
parser.add_argument('--batch_size', type=int, default=10,
help='minibatch size')
# Length of sequence to be considered parameter
parser.add_argument('--seq_length', type=int, default=5,
help='RNN sequence length')
# Number of epochs parameter
parser.add_argument('--num_epochs', type=int, default=50,
help='number of epochs')
# Frequency at which the model should be saved parameter
parser.add_argument('--save_every', type=int, default=400,
help='save frequency')
# TODO: (resolve) Clipping gradients for now. No idea whether we should
# Gradient value at which it should be clipped
parser.add_argument('--grad_clip', type=float, default=10.,
help='clip gradients at this value')
# Learning rate parameter
parser.add_argument('--learning_rate', type=float, default=0.003,
help='learning rate')
# Decay rate for the learning rate parameter
parser.add_argument('--decay_rate', type=float, default=0.95,
help='decay rate for rmsprop')
# Dropout not implemented.
# Dropout probability parameter
parser.add_argument('--keep_prob', type=float, default=0.8,
help='dropout keep probability')
# Dimension of the embeddings parameter
parser.add_argument('--embedding_size', type=int, default=64,
help='Embedding dimension for the spatial coordinates')
# Size of neighborhood to be considered parameter
parser.add_argument('--neighborhood_size', type=int, default=32,
help='Neighborhood size to be considered for social grid')
# Size of the social grid parameter
parser.add_argument('--grid_size', type=int, default=2,
help='Grid size of the social grid')
# Maximum number of pedestrians to be considered
parser.add_argument('--maxNumPeds', type=int, default=27,
help='Maximum Number of Pedestrians')
# The leave out dataset
parser.add_argument('--leaveDataset', type=int, default=1,
help='The dataset index to be left out in training')
args = parser.parse_args()
train(args)
def train(args):
datasets = range(2)
# Remove the leaveDataset from datasets
datasets.remove(args.leaveDataset)
# Create the SocialDataLoader object
data_loader = SocialDataLoader(args.batch_size, args.seq_length, args.maxNumPeds, datasets, forcePreProcess=True)
with open(os.path.join('save', 'social_config.pkl'), 'wb') as f:
pickle.dump(args, f)
# Create a SocialModel object with the arguments
model = SocialModel(args)
# Initialize a TensorFlow session
with tf.Session() as sess:
# Initialize all variables in the graph
sess.run(tf.initialize_all_variables())
# Initialize a saver that saves all the variables in the graph
saver = tf.train.Saver(tf.all_variables())
# summary_writer = tf.train.SummaryWriter('/tmp/lstm/logs', graph_def=sess.graph_def)
# For each epoch
for e in range(args.num_epochs):
# Assign the learning rate value for this epoch
sess.run(tf.assign(model.lr, args.learning_rate * (args.decay_rate ** e)))
# Reset the data pointers in the data_loader
data_loader.reset_batch_pointer()
# For each batch
for b in range(data_loader.num_batches):
# Tic
start = time.time()
# Get the source, target and dataset data for the next batch
# x, y are input and target data which are lists containing numpy arrays of size seq_length x maxNumPeds x 3
# d is the list of dataset indices from which each batch is generated (used to differentiate between datasets)
x, y, d = data_loader.next_batch()
# variable to store the loss for this batch
loss_batch = 0
# For each sequence in the batch
for batch in range(data_loader.batch_size):
# x_batch, y_batch and d_batch contains the source, target and dataset index data for
# seq_length long consecutive frames in the dataset
# x_batch, y_batch would be numpy arrays of size seq_length x maxNumPeds x 3
# d_batch would be a scalar identifying the dataset from which this sequence is extracted
x_batch, y_batch, d_batch = x[batch], y[batch], d[batch]
if d_batch == 0 and datasets[0] == 0:
dataset_data = [640, 480]
else:
dataset_data = [720, 576]
grid_batch = getSequenceGridMask(x_batch, dataset_data, args.neighborhood_size, args.grid_size)
# Feed the source, target data
feed = {model.input_data: x_batch, model.target_data: y_batch, model.grid_data: grid_batch}
train_loss, _ = sess.run([model.cost, model.train_op], feed)
# if result[0][0] > 1:
# print result
loss_batch += train_loss
end = time.time()
loss_batch = loss_batch / data_loader.batch_size
print(
"{}/{} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}"
.format(
e * data_loader.num_batches + b,
args.num_epochs * data_loader.num_batches,
e,
loss_batch, end - start))
# Save the model if the current epoch and batch number match the frequency
if (e * data_loader.num_batches + b) % args.save_every == 0 and ((e * data_loader.num_batches + b) > 0):
checkpoint_path = os.path.join('save', 'social_model.ckpt')
saver.save(sess, checkpoint_path, global_step=e * data_loader.num_batches + b)
print("model saved to {}".format(checkpoint_path))
if __name__ == '__main__':
main()