问题描述
我使用keras(tensorflow后端)构建我的lstm网络,这是我的代码:
I use keras(tensorflow backend) to build my lstm network,this is my code:
from keras.models import Sequential,Model
from keras.layers import LSTM,Conv1D,Dense,MaxPooling1D,GlobalMaxPooling1D,Input,Concatenate
from keras.optimizers import Adam
x_input = Input(shape=(None,x_train.shape[-1]),name='input')
x_mid = Conv1D(32,4, activation='relu')(x_input)
x_mid = MaxPooling1D(3)(x_mid)
x_mid = Conv1D(32,4,activation = 'relu')(x_mid)
x_mid = LSTM(32,dropout=0.1, recurrent_dropout=0.2,activation='relu')(x_mid)
x_mid = Dense(1,activation='sigmoid')(x_mid)
other_input = Input(shape=(x_blend_train.shape[-1],),name='clfs_input')
merge_x = concatenate(inputs= [x_mid,other_input],axis = -1)
output = Dense(32,activation='relu')(merge_x)
output = Dense(1,activation='sigmoid')(output)
model = Model(inputs=[x_input,other_input],outputs=output)
model.compile(optimizer='adam',loss=['binary_crossentropy'],metrics=['acc'])
model.summary()
这就是我的网络
Layer (type) Output Shape Param # Connected to
==================================================================================================
input (InputLayer) (None, None, 49) 0
__________________________________________________________________________________________________
conv1d_56 (Conv1D) (None, None, 32) 6304 input[0][0]
__________________________________________________________________________________________________
max_pooling1d_26 (MaxPooling1D) (None, None, 32) 0 conv1d_56[0][0]
__________________________________________________________________________________________________
conv1d_57 (Conv1D) (None, None, 32) 4128 max_pooling1d_26[0][0]
__________________________________________________________________________________________________
lstm_26 (LSTM) (None, 32) 8320 conv1d_57[0][0]
__________________________________________________________________________________________________
dense_59 (Dense) (None, 1) 33 lstm_26[0][0]
__________________________________________________________________________________________________
clfs_input (InputLayer) (None, 1) 0
__________________________________________________________________________________________________
concatenate_20 (Concatenate) (None, 2) 0 dense_59[0][0]
clfs_input[0][0]
__________________________________________________________________________________________________
dense_60 (Dense) (None, 32) 96 concatenate_20[0][0]
__________________________________________________________________________________________________
dense_61 (Dense) (None, 1) 33 dense_60[0][0]
==================================================================================================
我的数据形状为:
x_train.shape: (1350, 14, 49) x_blend_train.shape: (1350, 1) y_train.shape: (1350, 1)
我的张量流和keras版本是:
my tensorflow and keras version are:
tensorflow version:'1.8.0-rc1' keras version:'2.1.6'
当我使用
model.fit( x={'input':x_train,'clfs_input':x_blend_train}, y=y_train, batch_size=64, epochs=10)
计算机向我返回错误:
InvalidArgumentError: slice index 0 of dimension 0 out of bounds.
[[Node: lstm_25/strided_slice_13 = 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/device:CPU:0"](lstm_25/transpose, loss_11/dense_58_loss/Const_2, lstm_25/strided_slice_9/stack_2, lstm_25/strided_slice_9/stack_2)]]
以及有关错误的更多详细信息:
and more detail about error:
Epoch 1/10
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
1321 try:
-> 1322 return fn(*args)
1323 except errors.OpError as e:
/opt/conda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
1306 return self._call_tf_sessionrun(
-> 1307 options, feed_dict, fetch_list, target_list, run_metadata)
1308
/opt/conda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
1408 self._session, options, feed_dict, fetch_list, target_list,
-> 1409 run_metadata)
1410 else:
InvalidArgumentError: slice index 0 of dimension 0 out of bounds.
[[Node: lstm_25/strided_slice_13 = 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/device:CPU:0"](lstm_25/transpose, loss_11/dense_58_loss/Const_2, lstm_25/strided_slice_9/stack_2, lstm_25/strided_slice_9/stack_2)]]
During handling of the above exception, another exception occurred:
InvalidArgumentError Traceback (most recent call last)
<ipython-input-66-c2316b8cd20c> in <module>()
----> 1 model.fit( x={'input':x_train,'clfs_input':x_blend_train}, y=y_train, batch_size=64, epochs=10)
2 y_pred = model.predict({'input':x_train,'clfs_input':x_blend_test})
/opt/conda/lib/python3.6/site-packages/Keras-2.1.6-py3.6.egg/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
1031 initial_epoch=initial_epoch,
1032 steps_per_epoch=steps_per_epoch,
-> 1033 validation_steps=validation_steps)
1034
1035 def evaluate(self, x=None, y=None,
/opt/conda/lib/python3.6/site-packages/Keras-2.1.6-py3.6.egg/keras/engine/training_arrays.py in fit_loop(model, f, ins, out_labels, batch_size, epochs, verbose, callbacks, val_f, val_ins, shuffle, callback_metrics, initial_epoch, steps_per_epoch, validation_steps)
193 ins_batch[i] = ins_batch[i].toarray()
194
--> 195 outs = f(ins_batch)
196 if not isinstance(outs, list):
197 outs = [outs]
/opt/conda/lib/python3.6/site-packages/Keras-2.1.6-py3.6.egg/keras/backend/tensorflow_backend.py in __call__(self, inputs)
2489 session = get_session()
2490 updated = session.run(fetches=fetches, feed_dict=feed_dict,
-> 2491 **self.session_kwargs)
2492 return updated[:len(self.outputs)]
2493
/opt/conda/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
898 try:
899 result = self._run(None, fetches, feed_dict, options_ptr,
--> 900 run_metadata_ptr)
901 if run_metadata:
902 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
/opt/conda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1133 if final_fetches or final_targets or (handle and feed_dict_tensor):
1134 results = self._do_run(handle, final_targets, final_fetches,
-> 1135 feed_dict_tensor, options, run_metadata)
1136 else:
1137 results = []
/opt/conda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
1314 if handle is None:
1315 return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1316 run_metadata)
1317 else:
1318 return self._do_call(_prun_fn, handle, feeds, fetches)
/opt/conda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
1333 except KeyError:
1334 pass
-> 1335 raise type(e)(node_def, op, message)
1336
1337 def _extend_graph(self):
我不知道该如何处理这个错误,我尝试使用Google在github中找到答案并查看问题,但我没有找到可以帮助我的东西。我们期待您的帮助。
I don't know how to deal with this erro and I try to use google to find answer and look issue in github, but I did't find something can help me. I look forward to your help.
推荐答案
让我们进行一次观察,看看会发生什么。单个观察结果具有以下形状:(14,49)。
在第一个Conv1D层之后,它将更改为(11,32)(内核大小为4,步幅为1)。在第一个Maxpooling1D图层之后,它将转到(3,32)(由于您未设置跨步,因此默认为您的池大小为3)。如果我们看一下您的第二个conv1D层,它的内核大小等于4,大于您数据帧的第一个维数。
Let's take a single observation and see what happens. A single observation has the following shape : (14 , 49).After the first Conv1D layer, it will change to (11,32) (kernel size of 4 and strides of 1). After the first Maxpooling1D layer, it will go to (3 , 32) (since you din't set strides, it will default to your pool size which is 3). If we look at your second conv1D layer, it has a kernel size equal to 4, which is greater to the number of the first dimension of your dataframe.
我建议设置第一行:
x_input = Input(shape=(x_train.shape[-2],x_train.shape[-1]),name='input')
这将使您更容易地看到形状您在每一层中的输入更改。
this will allow you to see more easily how the shape of your input change in each layer.
这篇关于如何处理keras:erro:切片索引0的维度0超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!