Iam尝试实施一个简单的RNN LSTM模型,但遇到了麻烦。问题本身很简单。我将给模型连续5个数字(但一次给1个数字),然后我希望模型预测第6个数字。
示例: 输入数据: 1、2、3、4、5 (每个时间步长1位数字) 并且此序列的输出应为 6 。
我有一个csv文件,其中:
我想用Keras开发一个模型,并使其成功猜测第6个数字。
这就是我要做的:
1)首先实现一些我们需要的常量。
NR_FEATURES = 5
ITERATOR_BATCH_SIZE = 1
NR_EPOCHS = 15
2)定义训练时将使用的生成器。
def train_data_generator():
dataset = tf.contrib.data.make_csv_dataset(train_path1,
batch_size=ITERATOR_BATCH_SIZE,
num_epochs=NR_EPOCHS,
shuffle=True)
iter = dataset.make_one_shot_iterator()
next = iter.get_next()
ID = next['ID']
features = [next['nr1'], next['nr2'], next['nr3'], next['nr4'], next['nr5']]
features = tf.reshape(features, [NR_FEATURES, 1])
label = next['next_nr']
yield (features, label)
3)创建模型并开始训练。
input_data = Input(shape=(5, 1), name='input_data')
layer1_out = LSTM(1, return_sequences=False)(input_data) # only return the last output
lstm_model = Model(inputs=input_data, outputs=layer1_out)
lstm_model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])
lstm_model.fit_generator(train_data_generator(),
steps_per_epoch=(150/ITERATOR_BATCH_SIZE),
epochs=NR_EPOCHS,
verbose=1)
但是它立即崩溃了...
我收到的错误消息:
Epoch 1/15
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-af9dcbcbe289> in <module>()
8 steps_per_epoch=(150/ITERATOR_BATCH_SIZE),
9 epochs=NR_EPOCHS,
---> 10 verbose=1)
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
89 warnings.warn('Update your `' + object_name +
90 '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 91 return func(*args, **kwargs)
92 wrapper._original_function = func
93 return wrapper
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/engine/training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
2212 # build batch logs
2213 batch_logs = {}
-> 2214 if x is None or len(x) == 0:
2215 # Handle data tensors support when no input given
2216 # step-size = 1 for data tensors
TypeError: object of type 'Tensor' has no len()
我就是不明白。有人知道吗?
答案 0 :(得分:1)
您可以直接通过tensor
将numpy
转换为eval()
。
features = tf.reshape(features, [NR_FEATURES, 1])
# convert tensor to numpy
with tf.Session() as sess:
features = features.eval()
# Your data shape needs to be adjusted relative to your model input.
features = features.reshape(-1,NR_FEATURES,1)
label = next['next_nr']
label = np.array([label])
yield (features, label)