繁体   English   中英

Keras和Conv1D问题的输入形状

[英]Keras and input shape to Conv1D issues

首先,我是神经网络和Keras的新手。

我正在尝试使用Keras创建一个简单的神经网络,其中输入是一个时间序列,而输出是另一个相同长度的时间序列(一维矢量)。

我制作了伪代码,以使用Conv1D层创建随机的输入和输出时间序列。 然后,Conv1D层输出6个不同的时间序列(因为我有6个滤波器),并且我定义的下一层将这些输出的全部6个相加到一个,即整个网络的输出。

import numpy as np
import tensorflow as tf
from tensorflow.python.keras.models import Model
from tensorflow.python.keras.layers import Conv1D, Input, Lambda


def summation(x):
    y = tf.reduce_sum(x, 0)
    return y


time_len = 100  # total length of time series
num_filters = 6 # number of filters/outputs to Conv1D layer
kernel_len = 10 # length of kernel (memory size of convolution)

# create random input and output time series
X = np.random.randn(time_len)
Y = np.random.randn(time_len)

# Create neural network architecture
input_layer = Input(shape = X.shape)
conv_layer = Conv1D(filters = num_filters, kernel_size = kernel_len, padding = 'same')(input_layer)
summation_layer = Lambda(summation)(conv_layer)

model = Model(inputs = input_layer, outputs = summation_layer)

model.compile(loss = 'mse', optimizer = 'adam', metrics = ['mae'])

model.fit(X,Y,epochs = 1, metrics = ['mae'])

我得到的错误是:

ValueError: Input 0 of layer conv1d_1 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 100]

查看Conv1D的Keras文档,输入形状应该是3D张量形状(批,阶梯,通道),如果我们使用一维数据,我不明白。

您能否解释每一项的含义:批次,步骤和渠道? 我应该如何调整我的一维矢量以使网络运行?

什么是(培训)样本?

(训练)数据可能包含数十个,数百个或数千个样本。 例如,像Cifar-10或ImageNet这样的图像数据集中的每个图像都是一个样本。 作为另一个示例,对于由在10年中的几天内记录的天气统计信息组成的时间序列数据集,每个训练样本可以是每天的时间序列。 如果我们一天记录了100个测量值,并且每个测量值都由温度和湿度组成(即每个测量值有两个特征),则我们的数据集的形状大致为(10x365, 100, 2)

批量大小是多少?

批量大小只是模型一次可以处理的样本数量。 我们可以在batch_size使用fit方法的batch_size参数设置批量大小。 公用值为16、32、64、128、256等(尽管您必须选择一个数字,以便您的计算机可以有足够的RAM来分配所需的资源)。

此外,“步长”(也称为“序列长度”)和“通道”(也称为“特征尺寸”)分别是测量的数量和每个测量的尺寸。 例如,在上面的天气示例中,我们的步骤为100,渠道为2。

要解决代码问题,您需要定义训练数据(即X ),使其具有以下形状: (num_samples, steps or time_len, channels or feat_size)

n_samples = 1000   # we have 1000 samples in our training data
n_channels = 1     # each measurement has one feature
X = np.random.randn(n_samples, time_len, n_channels)

# if you want to predict one value for each measurement
Y = np.random.randn(n_samples, time_len)

# or if you want to predict one value for each sample
Y = np.random.randn(n_samples)

编辑:

还有一件事是,您应该将一个样本的形状作为模型的输入形状。 因此,必须像shape=X.shape[1:]这样传递Input层的输入形状。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM