Hi guys, I have a issue about implementing fit_generator with multi-input-output, here's my problem:
my model is 3 inputs and 3 outputs, I have to build a generator myself like:
def multi_input_generator(data_path):
gen = image.ImageDataGenerator()
trn_a = gen.flow_from_directory(data_path + 'a/', target_size=(224, 224), batch_size=1, class_mode=None, shuffle=False)
trn_p = gen.flow_from_directory(data_path + 'p/', target_size=(224, 224), batch_size=1, class_mode=None, shuffle=False)
trn_n = gen.flow_from_directory(data_path + 'n/', target_size=(224, 224), batch_size=1, class_mode=None, shuffle=False)
while True:
x1 = trn_a.next()
x2 = trn_p.next()
x3 = trn_n.next()
y = np.zeros((1, 4096))
yield ([x1, x2, x3], [y, y, y])
#yield [x1[0], x2[0], x3[0]], [x1[1], x2[1], x3[1]]
my input shape and output shape is :
mas_vgg.input_shape : [(None, 224, 224, 3), (None, 224, 224, 3), (None, 224, 224, 3)]
mas_vgg.output_shape : [(None, 4096), (None, 4096), (None, 4096)]
my triplet loss function is :
def triplet_loss(y_true, y_pred):
mse1 = losses.mean_squared_error(y_pred[0], y_pred[1])
mse2 = losses.mean_squared_error(y_pred[0], y_pred[2])
basic_loss = (mse1 - mse2) + 1
loss = K.maximum(basic_loss, 0) + y_true[0]*0
return loss
as you can see, my triplet loss doesn't need the "y_ture", so I set y = np.zeros((1, 4096))
in the multi_input_generator().
when I use fit_generator:
mas_vgg.fit_generator(multi_input_generator(data_path), steps_per_epoch=10000,
epochs=1, verbose=1)
it raised error:
Epoch 1/1
Found 10000 images belonging to 1 classes.
Found 10000 images belonging to 1 classes.
Found 10000 images belonging to 1 classes.
-------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
1326 try:
-> 1327 return fn(*args)
1328 except errors.OpError as e:
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
1305 feed_dict, fetch_list, target_list,
-> 1306 status, run_metadata)
1307
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/contextlib.py in __exit__(self, type, value, traceback)
65 try:
---> 66 next(self.gen)
67 except StopIteration:
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status()
465 compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466 pywrap_tensorflow.TF_GetCode(status))
467 finally:
InvalidArgumentError: slice index 1 of dimension 0 out of bounds.
[[Node: strided_slice_73 = StridedSlice[Index=DT_INT32, T=DT_FLOAT, begin_mask=0, ellipsis_mask=0, end_mask=0, new_axis_mask=0, shrink_axis_mask=1, _device="/job:localhost/replica:0/task:0/gpu:0"](vgg16/fc2/Relu, strided_slice_73/stack, strided_slice_73/stack_1, strided_slice_73/stack_2)]]
[[Node: Mean_89/_1413 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_3023_Mean_89", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
During handling of the above exception, another exception occurred:
InvalidArgumentError Traceback (most recent call last)
<ipython-input-169-f6028f67dbe7> in <module>()
1 mas_vgg.fit_generator(multi_input_generator(data_path), steps_per_epoch=10000,
----> 2 epochs=1, verbose=1)
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
86 warnings.warn('Update your `' + object_name +
87 '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 88 return func(*args, **kwargs)
89 wrapper._legacy_support_signature = inspect.getargspec(func)
90 return wrapper
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/keras/engine/training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_q_size, workers, pickle_safe, initial_epoch)
1900 outs = self.train_on_batch(x, y,
1901 sample_weight=sample_weight,
-> 1902 class_weight=class_weight)
1903
1904 if not isinstance(outs, list):
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/keras/engine/training.py in train_on_batch(self, x, y, sample_weight, class_weight)
1640 ins = x + y + sample_weights
1641 self._make_train_function()
-> 1642 outputs = self.train_function(ins)
1643 if len(outputs) == 1:
1644 return outputs[0]
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py in __call__(self, inputs)
2267 updated = session.run(self.outputs + [self.updates_op],
2268 feed_dict=feed_dict,
-> 2269 **self.session_kwargs)
2270 return updated[:len(self.outputs)]
2271
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
893 try:
894 result = self._run(None, fetches, feed_dict, options_ptr,
--> 895 run_metadata_ptr)
896 if run_metadata:
897 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1122 if final_fetches or final_targets or (handle and feed_dict_tensor):
1123 results = self._do_run(handle, final_targets, final_fetches,
-> 1124 feed_dict_tensor, options, run_metadata)
1125 else:
1126 results = []
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
1319 if handle is None:
1320 return self._do_call(_run_fn, self._session, feeds, fetches, targets,
-> 1321 options, run_metadata)
1322 else:
1323 return self._do_call(_prun_fn, self._session, handle, feeds, fetches)
/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
1338 except KeyError:
1339 pass
-> 1340 raise type(e)(node_def, op, message)
1341
1342 def _extend_graph(self):
InvalidArgumentError: slice index 1 of dimension 0 out of bounds.
[[Node: strided_slice_73 = StridedSlice[Index=DT_INT32, T=DT_FLOAT, begin_mask=0, ellipsis_mask=0, end_mask=0, new_axis_mask=0, shrink_axis_mask=1, _device="/job:localhost/replica:0/task:0/gpu:0"](vgg16/fc2/Relu, strided_slice_73/stack, strided_slice_73/stack_1, strided_slice_73/stack_2)]]
[[Node: Mean_89/_1413 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_3023_Mean_89", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Caused by op 'strided_slice_73', defined at:
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/ipykernel/__main__.py", line 3, in <module>
app.launch_new_instance()
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/traitlets/config/application.py", line 658, in launch_instance
app.start()
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/ipykernel/kernelapp.py", line 477, in start
ioloop.IOLoop.instance().start()
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/zmq/eventloop/ioloop.py", line 177, in start
super(ZMQIOLoop, self).start()
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tornado/ioloop.py", line 888, in start
handler_func(fd_obj, events)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
self._handle_recv()
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
self._run_callback(callback, msg)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
callback(*args, **kwargs)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher
return self.dispatch_shell(stream, msg)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
handler(stream, idents, msg)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 399, in execute_request
user_expressions, allow_stdin)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/ipykernel/zmqshell.py", line 533, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2827, in run_ast_nodes
if self.run_code(code, result):
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-159-df13bd1185e7>", line 1, in <module>
mas_vgg.compile(Adam(lr=1e-4), loss=[triplet_loss, triplet_loss, triplet_loss])
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/keras/engine/training.py", line 911, in compile
sample_weight, mask)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/keras/engine/training.py", line 436, in weighted
score_array = fn(y_true, y_pred)
File "<ipython-input-146-fb691543e267>", line 2, in triplet_loss
mse1 = losses.mean_squared_error(y_pred[0], y_pred[1])
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 509, in _SliceHelper
name=name)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 677, in strided_slice
shrink_axis_mask=shrink_axis_mask)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/ops/gen_array_ops.py", line 3744, in strided_slice
shrink_axis_mask=shrink_axis_mask, name=name)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
op_def=op_def)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2630, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/home/ubuntu/anaconda3/envs/gputest/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1204, in __init__
self._traceback = self._graph._extract_stack() # pylint: disable=protected-access
InvalidArgumentError (see above for traceback): slice index 1 of dimension 0 out of bounds.
[[Node: strided_slice_73 = StridedSlice[Index=DT_INT32, T=DT_FLOAT, begin_mask=0, ellipsis_mask=0, end_mask=0, new_axis_mask=0, shrink_axis_mask=1, _device="/job:localhost/replica:0/task:0/gpu:0"](vgg16/fc2/Relu, strided_slice_73/stack, strided_slice_73/stack_1, strided_slice_73/stack_2)]]
[[Node: Mean_89/_1413 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_3023_Mean_89", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
why I receive this error? I think the shape of y_predict is the same as y_true (1, 4096), no matter I try to set y = (1, 4096) or (4096, 1) or something else, the error still rise. Any ideas would be greatful !
I was having similar error with the triplet loss you defined though I wasn't using fit_generator. I think the error is in the way you have defined model and triplet loss. In triplet loss you are expecting a list of 3 outputs(anchor, positive, negative). I was providing a array which was output of Concatenate. For me, the issue resolved when I changed for example, y_pred[0] to y_pred[:,0,:]. You might need to change your implementation suitably. Hope that answered it.
Do,
mse1 = losses.mean_squared_error(y_pred[:,0,:], y_pred[:,1,:])
mse2 = losses.mean_squared_error(y_pred[:,0,:], y_pred[:,2,:])