how to test just one video in Conv3D example?
I am trying to just read the output of the network for just one video after loading the model from a file. Here's part of the code I'm using (the whole test file is at the end):
`z = cntk.load_model("test_model")
test_reader = VideoReader(os.path.join(data_path, 'test_map.csv'), num_output_classes, False)
videos, labels, current_minibatch = test_reader.next_minibatch(minibatch_size)
test_reader.reset() test_reader.has_more() videos, labels, current_minibatch = test_reader.next_minibatch(minibatch_size)
print(str(labels[0].shape)) print(str(videos[0].shape))
z.eval({input_var : videos[0], label_var : labels[0]})`
with this I get the following error which I don't know how to fix:
` (11,) (3, 16, 112, 112)
Traceback (most recent call last):
File "Conv#Dtest.py", line 153, in
[CALL STACK] [0x7f4085fe0d0c] + 0x5f9d0c [0x7f408601ccd1] CNTK::CompositeFunction:: Forward (std::unordered_map<CNTK::Variable,std::shared_ptrCNTK::Value,std::hashCNTK::Variable,std::equal_toCNTK::Variable,std::allocator<std::pair<CNTK::Variable const,std::shared_ptrCNTK::Value>>> const&, std::unordered_map<CNTK::Variable,std::shared_ptrCNTK::Value,std::hashCNTK::Variable,std::equal_toCNTK::Variable,std::allocator<std::pair<CNTK::Variable const,std::shared_ptrCNTK::Value>>>&, CNTK::DeviceDescriptor const&, std::unordered_set<CNTK::Variable,std::hashCNTK::Variable,std::equal_toCNTK::Variable,std::allocatorCNTK::Variable> const&, std::unordered_set<CNTK::Variable,std::hashCNTK::Variable,std::equal_toCNTK::Variable,std::allocatorCNTK::Variable> const&) + 0xc91 [0x7f4085fe8a81] CNTK::Function:: Forward (std::unordered_map<CNTK::Variable,std::shared_ptrCNTK::Value,std::hashCNTK::Variable,std::equal_toCNTK::Variable,std::allocator<std::pair<CNTK::Variable const,std::shared_ptrCNTK::Value>>> const&, std::unordered_map<CNTK::Variable,std::shared_ptrCNTK::Value,std::hashCNTK::Variable,std::equal_toCNTK::Variable,std::allocator<std::pair<CNTK::Variable const,std::shared_ptrCNTK::Value>>>&, CNTK::DeviceDescriptor const&, std::unordered_set<CNTK::Variable,std::hashCNTK::Variable,std::equal_toCNTK::Variable,std::allocatorCNTK::Variable> const&, std::unordered_set<CNTK::Variable,std::hashCNTK::Variable,std::equal_toCNTK::Variable,std::allocatorCNTK::Variable> const&) + 0x81 [0x7f408681c6f4] + 0x466f4 [0x7f40869d6663] + 0x200663 [0x7f4092935d99] PyCFunction_Call + 0xf9 [0x7f40929bcce3] PyEval_EvalFrameEx + 0x7cd3 [0x7f40929befc9] + 0x145fc9 [0x7f40929bd13d] PyEval_EvalFrameEx + 0x812d [0x7f40929befc9] + 0x145fc9 [0x7f40929bf158] PyEval_EvalCodeEx + 0x48 [0x7f4092913c91] + 0x9ac91 [0x7f40928e04c6] PyObject_Call + 0x56 [0x7f40929bb286] PyEval_EvalFrameEx + 0x6276 [0x7f40929befc9] + 0x145fc9 [0x7f40929bd13d] PyEval_EvalFrameEx + 0x812d [0x7f40929befc9] + 0x145fc9 [0x7f40929bd13d] PyEval_EvalFrameEx + 0x812d [0x7f40929befc9] + 0x145fc9 [0x7f40929bf158] PyEval_EvalCodeEx + 0x48 [0x7f40929bf19b] PyEval_EvalCode + 0x3b [0x7f40929e4410] PyRun_FileExFlags + 0x130 [0x7f40929e5a03] PyRun_SimpleFileExFlags + 0x183 [0x7f4092a00ce7] Py_Main + 0xca7 [0x400bbd] main + 0x15d [0x7f40919a2ec5] __libc_start_main + 0xf5 [0x400999] `
Here's all the code. It should be run in the same directory as Conv3D Video example after saving the model in a file named "test_model":
` from future import print_function import sys import os import csv import numpy as np from random import randint
from PIL import Image import imageio
import cntk from cntk import Trainer from cntk.utils import * from cntk.layers import * from cntk.learner import sgd, momentum_sgd, learning_rate_schedule, momentum_schedule, momentum_as_time_constant_schedule, UnitType from cntk.ops import input_variable, cross_entropy_with_softmax, classification_error, relu, minus, element_times, constant from _cntk_py import set_computation_network_trace_level
''' Paths relative to current python file.''' abs_path = os.path.dirname(os.path.abspath(file)) data_path = os.path.join(abs_path, "..", "..", "DataSets", "UCF11") model_path = os.path.join(abs_path, "Models")
class VideoReader(object):
'''
A simple VideoReader:
It iterates through each video and select 16 frames as
stacked numpy arrays.
Similar to http://vlg.cs.dartmouth.edu/c3d/c3d_video.pdf
'''
def init(self, map_file, label_count, is_training):
'''
Load video file paths and their corresponding labels.
'''
self.map_file = map_file
self.label_count = label_count
self.width = 112
self.height = 112
self.sequence_length = 16
self.channel_count = 3
self.is_training = is_training
self.video_files = []
self.targets = []
self.batch_start = 0
with open(map_file) as csv_file:
data = csv.reader(csv_file)
for row in data:
self.video_files.append(row[0])
target = [0.0] * self.label_count
target[int(row[1])] = 1.0
self.targets.append(target)
self.indices = np.arange(len(self.video_files))
if self.is_training:
np.random.shuffle(self.indices)
def size(self):
return len(self.video_files)
def has_more(self):
if self.batch_start < self.size():
return True
return False
def reset(self):
if self.is_training:
np.random.shuffle(self.indices)
self.batch_start = 0
def next_minibatch(self, batch_size):
'''
Return a mini batch of sequence frames and their corresponding ground truth.
'''
batch_end = min(self.batch_start + batch_size, self.size())
current_batch_size = batch_end - self.batch_start
if current_batch_size < 0:
raise Exception('Reach the end of the training data.')
inputs = np.empty(shape=(current_batch_size, self.channel_count, self.sequence_length, self.height, self.width), dtype=np.float32)
targets = np.empty(shape=(current_batch_size, self.label_count), dtype=np.float32)
for idx in range(self.batch_start, batch_end):
index = self.indices[idx]
inputs[idx - self.batch_start, :, :, :, :] = self._select_features(self.video_files[index])
targets[idx - self.batch_start, :] = self.targets[index]
self.batch_start += current_batch_size
return inputs, targets, current_batch_size
def _select_features(self, video_file):
'''
Select a sequence of frames from video_file and return them as
a Tensor.
'''
video_reader = imageio.get_reader(video_file, 'ffmpeg')
num_frames = len(video_reader)
if self.sequence_length > num_frames:
raise ValueError('Sequence length {} is larger then the total number of frames {} in {}.'.format(self.sequence_length, num_frames, video_file))
# select which sequence frames to use.
step = 1
expanded_sequence = self.sequence_length
if num_frames > 2self.sequence_length:
step = 2
expanded_sequence = 2self.sequence_length
seq_start = int(num_frames/2) - int(expanded_sequence/2)
if self.is_training:
seq_start = randint(0, num_frames - expanded_sequence)
frame_range = [seq_start + step*i for i in range(self.sequence_length)]
video_frames = []
for frame_index in frame_range:
video_frames.append(self._read_frame(video_reader.get_data(frame_index)))
return np.stack(video_frames, axis=1)
def _read_frame(self, data):
'''
Based on http://vlg.cs.dartmouth.edu/c3d/c3d_video.pdf
We resize the image to 128x171 first, then selecting a 112x112
crop.
'''
if (self.width >= 171) or (self.height >= 128):
raise ValueError("Target width need to be less than 171 and target height need to be less than 128.")
image = Image.fromarray(data)
image.thumbnail((171, 128), Image.ANTIALIAS)
center_w = image.size[0] / 2
center_h = image.size[1] / 2
image = image.crop((center_w - self.width / 2,
center_h - self.height / 2,
center_w + self.width / 2,
center_h + self.height / 2))
norm_image = np.array(image, dtype=np.float32)
norm_image -= 128.0
norm_image /= 128.0
return np.ascontiguousarray(np.transpose(norm_image, (2, 0, 1)))
num_output_classes = 11 epoch_size = 1 minibatch_size = 1
z = cntk.load_model("test_model") test_reader = VideoReader(os.path.join(data_path, 'test_map.csv'), num_output_classes, False)
image_height = test_reader.height image_width = test_reader.width num_channels = test_reader.channel_count sequence_length = test_reader.sequence_length num_output_classes = test_reader.label_count
videos, labels, current_minibatch = test_reader.next_minibatch(minibatch_size)
epoch_size = 1 minibatch_size = 1 test_reader.reset()
input_var = input_variable((num_channels, sequence_length, image_height, image_width), np.float32) label_var = input_variable(num_output_classes, np.float32)
test_reader.has_more() videos, labels, current_minibatch = test_reader.next_minibatch(minibatch_size) print(str(labels.shape)) print(str(videos.shape)) z.eval({input_var : videos[0], label_var : labels[0]})`
Here's the solution. Just need to change the last line to
output=z.eval({z.arguments[0]:[videos[0]]})
One example of output I got is
[[[-0.00604576 0.00987199 0.02238975 -0.00510733 -0.00958173 0.01408552
-0.02715118 0.01530281 0.02082001 -0.03386964 0.03201934]]]