了解keras Conv1D输出

时间:2019-12-03 14:55:28

标签: keras deep-learning conv-neural-network

我试图了解一维卷积层的工作原理。

让我们准备数据

from sklearn.model_selection import train_test_split
import keras

import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv', 
                 names=['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'], header = 1)

df['labels'] = df['species'].astype('category').cat.codes

X = df[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']]
ylab = df['labels']
x_train, x_test, y_train, y_test = train_test_split(np.asarray(X), np.asarray(ylab), test_size=0.33, shuffle= True)

# The known number of output classes.
num_classes = 3

# Input image dimensions
input_shape = (4,)

# Convert class vectors to binary class matrices. This uses 1 hot encoding.
y_train_binary = keras.utils.to_categorical(y_train, num_classes)
y_test_binary = keras.utils.to_categorical(y_test, num_classes)

x_train = x_train[0:100,:].reshape(99, 4,1)
x_test = x_test[0:50,:].reshape(50, 4,1)

这是Keras模型,

from __future__ import print_function    
from keras.models import Sequential
import keras
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv1D
from keras.callbacks import ModelCheckpoint
from keras.models import model_from_json
from keras import backend as K

model = Sequential()
model.add(Conv1D(10, (4), input_shape=(4,1), activation='relu')) # filter size 4 is the max number of filters - becaus every feature is convoluted 
model.add(Flatten())
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
model.summary()

我的数据是4维的。因此,似乎CNN的过滤器大小不能大于4。因此,当我将其设置为4时,意味着所有4个功能都已包括在内。我很好奇Conv1D中的第一个参数 filter 是什么意思。

基于文档

filters: Integer, the dimensional of the output space (i.e. the number of output filters in the convolution). 

所以我很好奇如何从四个功能中生成十个? (可能是我遗漏了一些东西),但是我更喜欢可视化的解决方案,或者一个显示如何导出输出的公式。我注意到,但是增加过滤器的性能会更好(1比10)。因此,理想情况下,我们想了解它如何影响性能。

1 个答案:

答案 0 :(得分:0)

假设执行Valid填充并使用4单位宽的滤波器对4单位长的输入进行卷积,这就是它的工作原理。在这种情况下,有效的填充将导致单个输出。

因此您可以看到可以生成任意数量的输出。您需要的是更多内核(或过滤器)。这些过滤器本质上是tensorflow变量。这就是该层中的filter_size的意思。与示例中第二个参数中设置的过滤器宽度无关。

enter image description here

有关1D / 2D / 3D卷积如何工作的更多信息:Here

性能如何受到影响

至少可以说,过滤器学习输入的特征表示。表示越多,性能将越好(通常并非总是如此)。过滤器数量超过所需数量也会导致过拟合。因此,您需要使用超参数优化来达到这种平衡。