具有模型输入和输出的神经网络都是矩阵

时间:2020-07-01 11:07:53

标签: keras neural-network

我是Keras的初学者。我想创建一个多感知器模型(密集层),输入为10x4矩阵,输出为5x4矩阵。我可以将input_shape =(10,4)用于输入,但是输出如何?请帮帮我

model = Sequential()
model.add(Dense(16, activation='relu', name='layer1', input_shape = (10,4)))
model.add(Dense(8, activation='relu', name='layer2'))
model.add(Dense(8, activation='relu', name='layer3'))
...?

1 个答案:

答案 0 :(得分:0)

什么是输入矩阵?第一维是否对应于批次大小?如果是这样,则应声明密集层的输入形状,如下所示:

model.add(Dense(16, activation='relu', name='layer1', input_shape = (4,)))

Keras为您照顾批次尺寸。

否则,如果输入的尺寸有3个(BATCH,TIMESTEPS,FEATURES),则应使用RNN或Conv1d。

此外,由于以Dense(8)结尾的顺序模型,您的输出将具有以下形状:(BATCH,8)。

如果您认为使用RNN太复杂或不需要这样做,则可以按如下所示整理输入内容:

import numpy as np

inp_tensor = np.random.uniform(size=(5, 10, 4)) # Batch size 5 and your input matrix
inp_tensor = inp_tensor.reshape(5, -1) # Now tensor has shape (5, 10 * 4)

model = Sequential()
model.add(Dense(16, activation='relu', name='layer1', input_shape = (10 * 4,)))
model.add(Dense(8, activation='relu', name='layer2'))
# Note that the output is 5 * 4, which corresponds to the desired output shape (5, 4) but flattened 
model.add(Dense(5 * 4, activation='relu', name='layer3'))

model.compile(...)
model.fit(...)

# At inference time, we do the same
test_inp = np.random.uniform(size=(1, 10, 4)) # A single instance
pred = model.predict(test_inp.reshape(1, -1)

# Recover your desired output shape
pred = pred.reshape(1, 5, 4)