Skip to content

Commit d67ea24

Browse files
committed
video prediction model code
1 parent 2cbd337 commit d67ea24

7 files changed

+1252
-0
lines changed

video_prediction/README.md

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# Video Prediction with Neural Advection
2+
3+
*A TensorFlow implementation of the models described in [Finn et al. (2016)]
4+
(http://arxiv.org/abs/1605.07157).*
5+
6+
This video prediction model, which is optionally conditioned on actions,
7+
predictions future video by internally predicting how to transform the last
8+
image (which may have been predicted) into the next image. As a result, it can
9+
reuse apperance information from previous frames and can better generalize to
10+
objects not seen in the training set. Some example predictions on novel objects
11+
are shown below:
12+
13+
![Animation](https://storage.googleapis.com/push_gens/novelgengifs9/16_70.gif)
14+
![Animation](https://storage.googleapis.com/push_gens/novelgengifs9/2_96.gif)
15+
![Animation](https://storage.googleapis.com/push_gens/novelgengifs9/1_38.gif)
16+
![Animation](https://storage.googleapis.com/push_gens/novelgengifs9/11_10.gif)
17+
![Animation](https://storage.googleapis.com/push_gens/novelgengifs9/3_34.gif)
18+
19+
When the model is conditioned on actions, it changes it's predictions based on
20+
the passed in action. Here we show the models predictions in response to varying
21+
the magnitude of the passed in actions, from small to large:
22+
23+
![Animation](https://storage.googleapis.com/push_gens/webgifs/0xact_0.gif)
24+
![Animation](https://storage.googleapis.com/push_gens/05xact_0.gif)
25+
![Animation](https://storage.googleapis.com/push_gens/webgifs/1xact_0.gif)
26+
![Animation](https://storage.googleapis.com/push_gens/webgifs/15xact_0.gif)
27+
28+
![Animation](https://storage.googleapis.com/push_gens/webgifs/0xact_17.gif)
29+
![Animation](https://storage.googleapis.com/push_gens/webgifs/05xact_17.gif)
30+
![Animation](https://storage.googleapis.com/push_gens/webgifs/1xact_17.gif)
31+
![Animation](https://storage.googleapis.com/push_gens/webgifs/15xact_17.gif)
32+
33+
34+
Because the model is trained with an l2 objective, it represents uncertainty as
35+
blur.
36+
37+
## Requirements
38+
* Tensorflow (see tensorflow.org for installation instructions)
39+
* spatial_tranformer model in tensorflow/models, for the spatial tranformer
40+
predictor (STP).
41+
42+
## Data
43+
The data used to train this model is located
44+
[here](https://sites.google.com/site/brainrobotdata/home/push-dataset).
45+
46+
To download the robot data, run the following.
47+
```shell
48+
./download_data.sh
49+
```
50+
51+
## Training the model
52+
53+
To train the model, run the prediction_train.py file.
54+
```shell
55+
python prediction_train.py
56+
```
57+
58+
There are several flags which can control the model that is trained, which are
59+
exeplified below:
60+
```shell
61+
python prediction_train.py \
62+
--data_dir=push/push_train \ # path to the training set.
63+
--model=CDNA \ # the model type to use - DNA, CDNA, or STP
64+
--output_dir=./checkpoints \ # where to save model checkpoints
65+
--event_log_dir=./summaries \ # where to save training statistics
66+
--num_iterations=100000 \ # number of training iterations
67+
--pretrained_model=model \ # path to model to initialize from, random if emtpy
68+
--sequence_length=10 \ # the number of total frames in a sequence
69+
--context_frames=2 \ # the number of ground truth frames to pass in at start
70+
--use_state=1 \ # whether or not to condition on actions and the initial state
71+
--num_masks=10 \ # the number of transformations and corresponding masks
72+
--schedsamp_k=900.0 \ # the constant used for scheduled sampling or -1
73+
--train_val_split=0.95 \ # the percentage of training data for validation
74+
--batch_size=32 \ # the training batch size
75+
--learning_rate=0.001 \ # the initial learning rate for the Adam optimizer
76+
```
77+
78+
If the dynamic neural advection (DNA) model is being used, the `--num_masks`
79+
option should be set to one.
80+
81+
The `--context_frames` option defines both the number of initial ground truth
82+
frames to pass in, as well as when to start penalizing the model's predictions.
83+
84+
The data directory `--data_dir` should contain tfrecord files with the format
85+
used in the released push dataset. See
86+
[here](https://sites.google.com/site/brainrobotdata/home/push-dataset) for
87+
details. If the `--use_state` option is not set, then the data only needs to
88+
contain image sequences, not states and actions.
89+
90+
91+
## Contact
92+
93+
To ask questions or report issues please open an issue on the tensorflow/models
94+
[issues tracker](https://github.com/tensorflow/models/issues).
95+
Please assign issues to @cbfinn.
96+
97+
## Credits
98+
99+
This code was written by Chelsea Finn.

video_prediction/download_data.sh

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#!/bin/bash
2+
# Copyright 2016 The TensorFlow Authors All Rights Reserved.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
# ==============================================================================
16+
17+
18+
# Example:
19+
#
20+
# download_dataset.sh datafiles.txt ./tmp
21+
#
22+
# will download all of the files listed in the file, datafiles.txt, into
23+
# a directory, "./tmp".
24+
#
25+
# Each line of the datafiles.txt file should contain the path from the
26+
# bucket root to a file.
27+
28+
ARGC="$#"
29+
LISTING_FILE=push_datafiles.txt
30+
if [ "${ARGC}" -ge 1 ]; then
31+
LISTING_FILE=$1
32+
fi
33+
OUTPUT_DIR="./"
34+
if [ "${ARGC}" -ge 2 ]; then
35+
OUTPUT_DIR=$2
36+
fi
37+
38+
echo "OUTPUT_DIR=$OUTPUT_DIR"
39+
40+
mkdir "${OUTPUT_DIR}"
41+
42+
function download_file {
43+
FILE=$1
44+
BUCKET="https://storage.googleapis.com/brain-robotics-data"
45+
URL="${BUCKET}/${FILE}"
46+
OUTPUT_FILE="${OUTPUT_DIR}/${FILE}"
47+
DIRECTORY=`dirname ${OUTPUT_FILE}`
48+
echo DIRECTORY=$DIRECTORY
49+
mkdir -p "${DIRECTORY}"
50+
curl --output ${OUTPUT_FILE} ${URL}
51+
}
52+
53+
while read filename; do
54+
download_file $filename
55+
done <${LISTING_FILE}

video_prediction/lstm_ops.py

+110
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
# Copyright 2016 The TensorFlow Authors All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
# ==============================================================================
15+
16+
"""Convolutional LSTM implementation."""
17+
18+
import tensorflow as tf
19+
20+
from tensorflow.contrib.slim import add_arg_scope
21+
from tensorflow.contrib.slim import layers
22+
23+
24+
def init_state(inputs,
25+
state_shape,
26+
state_initializer=tf.zeros_initializer,
27+
dtype=tf.float32):
28+
"""Helper function to create an initial state given inputs.
29+
30+
Args:
31+
inputs: input Tensor, at least 2D, the first dimension being batch_size
32+
state_shape: the shape of the state.
33+
state_initializer: Initializer(shape, dtype) for state Tensor.
34+
dtype: Optional dtype, needed when inputs is None.
35+
Returns:
36+
A tensors representing the initial state.
37+
"""
38+
if inputs is not None:
39+
# Handle both the dynamic shape as well as the inferred shape.
40+
inferred_batch_size = inputs.get_shape().with_rank_at_least(1)[0]
41+
batch_size = tf.shape(inputs)[0]
42+
dtype = inputs.dtype
43+
else:
44+
inferred_batch_size = 0
45+
batch_size = 0
46+
47+
initial_state = state_initializer(
48+
tf.pack([batch_size] + state_shape),
49+
dtype=dtype)
50+
initial_state.set_shape([inferred_batch_size] + state_shape)
51+
52+
return initial_state
53+
54+
55+
@add_arg_scope
56+
def basic_conv_lstm_cell(inputs,
57+
state,
58+
num_channels,
59+
filter_size=5,
60+
forget_bias=1.0,
61+
scope=None,
62+
reuse=None):
63+
"""Basic LSTM recurrent network cell, with 2D convolution connctions.
64+
65+
We add forget_bias (default: 1) to the biases of the forget gate in order to
66+
reduce the scale of forgetting in the beginning of the training.
67+
68+
It does not allow cell clipping, a projection layer, and does not
69+
use peep-hole connections: it is the basic baseline.
70+
71+
Args:
72+
inputs: input Tensor, 4D, batch x height x width x channels.
73+
state: state Tensor, 4D, batch x height x width x channels.
74+
num_channels: the number of output channels in the layer.
75+
filter_size: the shape of the each convolution filter.
76+
forget_bias: the initial value of the forget biases.
77+
scope: Optional scope for variable_scope.
78+
reuse: whether or not the layer and the variables should be reused.
79+
80+
Returns:
81+
a tuple of tensors representing output and the new state.
82+
"""
83+
spatial_size = inputs.get_shape()[1:3]
84+
if state is None:
85+
state = init_state(inputs, list(spatial_size) + [2 * num_channels])
86+
with tf.variable_scope(scope,
87+
'BasicConvLstmCell',
88+
[inputs, state],
89+
reuse=reuse):
90+
inputs.get_shape().assert_has_rank(4)
91+
state.get_shape().assert_has_rank(4)
92+
c, h = tf.split(3, 2, state)
93+
inputs_h = tf.concat(3, [inputs, h])
94+
# Parameters of gates are concatenated into one conv for efficiency.
95+
i_j_f_o = layers.conv2d(inputs_h,
96+
4 * num_channels, [filter_size, filter_size],
97+
stride=1,
98+
activation_fn=None,
99+
scope='Gates')
100+
101+
# i = input_gate, j = new_input, f = forget_gate, o = output_gate
102+
i, j, f, o = tf.split(3, 4, i_j_f_o)
103+
104+
new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j)
105+
new_h = tf.tanh(new_c) * tf.sigmoid(o)
106+
107+
return new_h, tf.concat(3, [new_c, new_h])
108+
109+
110+

video_prediction/prediction_input.py

+119
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# Copyright 2016 The TensorFlow Authors All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
# ==============================================================================
15+
16+
"""Code for building the input for the prediction model."""
17+
18+
import os
19+
20+
import numpy as np
21+
import tensorflow as tf
22+
23+
from tensorflow.python.platform import flags
24+
from tensorflow.python.platform import gfile
25+
26+
27+
FLAGS = flags.FLAGS
28+
29+
# Original image dimensions
30+
ORIGINAL_WIDTH = 640
31+
ORIGINAL_HEIGHT = 512
32+
COLOR_CHAN = 3
33+
34+
# Default image dimensions.
35+
IMG_WIDTH = 64
36+
IMG_HEIGHT = 64
37+
38+
# Dimension of the state and action.
39+
STATE_DIM = 5
40+
41+
42+
def build_tfrecord_input(training=True):
43+
"""Create input tfrecord tensors.
44+
45+
Args:
46+
training: training or validation data.
47+
Returns:
48+
list of tensors corresponding to images, actions, and states. The images
49+
tensor is 5D, batch x time x height x width x channels. The state and
50+
action tensors are 3D, batch x time x dimension.
51+
Raises:
52+
RuntimeError: if no files found.
53+
"""
54+
filenames = gfile.Glob(os.path.join(FLAGS.data_dir, '*'))
55+
if not filenames:
56+
raise RuntimeError('No data files found.')
57+
index = int(np.floor(FLAGS.train_val_split * len(filenames)))
58+
if training:
59+
filenames = filenames[:index]
60+
else:
61+
filenames = filenames[index:]
62+
filename_queue = tf.train.string_input_producer(filenames, shuffle=True)
63+
reader = tf.TFRecordReader()
64+
_, serialized_example = reader.read(filename_queue)
65+
66+
image_seq, state_seq, action_seq = [], [], []
67+
68+
for i in range(FLAGS.sequence_length):
69+
image_name = 'move/' + str(i) + '/image/encoded'
70+
action_name = 'move/' + str(i) + '/commanded_pose/vec_pitch_yaw'
71+
state_name = 'move/' + str(i) + '/endeffector/vec_pitch_yaw'
72+
if FLAGS.use_state:
73+
features = {image_name: tf.FixedLenFeature([1], tf.string),
74+
action_name: tf.FixedLenFeature([STATE_DIM], tf.float32),
75+
state_name: tf.FixedLenFeature([STATE_DIM], tf.float32)}
76+
else:
77+
features = {image_name: tf.FixedLenFeature([1], tf.string)}
78+
features = tf.parse_single_example(serialized_example, features=features)
79+
80+
image_buffer = tf.reshape(features[image_name], shape=[])
81+
image = tf.image.decode_jpeg(image_buffer, channels=COLOR_CHAN)
82+
image.set_shape([ORIGINAL_HEIGHT, ORIGINAL_WIDTH, COLOR_CHAN])
83+
84+
if IMG_HEIGHT != IMG_WIDTH:
85+
raise ValueError('Unequal height and width unsupported')
86+
87+
crop_size = min(ORIGINAL_HEIGHT, ORIGINAL_WIDTH)
88+
image = tf.image.resize_image_with_crop_or_pad(image, crop_size, crop_size)
89+
image = tf.reshape(image, [1, crop_size, crop_size, COLOR_CHAN])
90+
image = tf.image.resize_bicubic(image, [IMG_HEIGHT, IMG_WIDTH])
91+
image = tf.cast(image, tf.float32) / 255.0
92+
image_seq.append(image)
93+
94+
if FLAGS.use_state:
95+
state = tf.reshape(features[state_name], shape=[1, STATE_DIM])
96+
state_seq.append(state)
97+
action = tf.reshape(features[action_name], shape=[1, STATE_DIM])
98+
action_seq.append(action)
99+
100+
image_seq = tf.concat(0, image_seq)
101+
102+
if FLAGS.use_state:
103+
state_seq = tf.concat(0, state_seq)
104+
action_seq = tf.concat(0, action_seq)
105+
[image_batch, action_batch, state_batch] = tf.train.batch(
106+
[image_seq, action_seq, state_seq],
107+
FLAGS.batch_size,
108+
num_threads=FLAGS.batch_size,
109+
capacity=100 * FLAGS.batch_size)
110+
return image_batch, action_batch, state_batch
111+
else:
112+
image_batch = tf.train.batch(
113+
[image_seq],
114+
FLAGS.batch_size,
115+
num_threads=FLAGS.batch_size,
116+
capacity=100 * FLAGS.batch_size)
117+
zeros_batch = tf.zeros([FLAGS.batch_size, FLAGS.sequence_length, STATE_DIM])
118+
return image_batch, zeros_batch, zeros_batch
119+

0 commit comments

Comments
 (0)