conv1D 中的形状维度
Dimension of shape in conv1D
我尝试构建一个只有一层的 CNN,但我遇到了一些问题。
事实上,编译器告诉我
ValueError: Error when checking model input: expected conv1d_1_input
to have 3 dimensions, but got array with shape (569, 30)
这是代码
import numpy
from keras.models import Sequential
from keras.layers.convolutional import Conv1D
numpy.random.seed(7)
datasetTraining = numpy.loadtxt("CancerAdapter.csv",delimiter=",")
X = datasetTraining[:,1:31]
Y = datasetTraining[:,0]
datasetTesting = numpy.loadtxt("CancereEvaluation.csv",delimiter=",")
X_test = datasetTraining[:,1:31]
Y_test = datasetTraining[:,0]
model = Sequential()
model.add(Conv1D(2,2,activation='relu',input_shape=X.shape))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X, Y, epochs=150, batch_size=5)
scores = model.evaluate(X_test, Y_test)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
如果无法查看更多详细信息,您的数据在预处理后的形状不正确。
将 X 重塑为 3 个维度:
np.reshape(X, (1, X.shape[0], X.shape[1]))
td; lr 您需要重塑您的数据,使 空间 维度使 Conv1d
有意义:
X = np.expand_dims(X, axis=2) # reshape (569, 30) to (569, 30, 1)
# now input can be set as
model.add(Conv1D(2,2,activation='relu',input_shape=(30, 1))
从本质上重塑数据集,如下所示:
features
.8, .1, .3
.2, .4, .6
.7, .2, .1
收件人:
[[.8
.1
.3],
[.2,
.4,
.6
],
[.7,
.2,
.1]]
说明和示例
通常卷积在空间维度上起作用。内核在产生张量的维度上“卷积”。在 Conv1D 的情况下,内核在每个示例的 'steps' 维度上传递。
你会看到 Conv1D 在 NLP 中使用,其中 steps
是句子中的单词数量(填充到某个固定的最大长度)。这些词将被编码为长度为 4 的向量。
这是一个例句:
jack .1 .3 -.52 |
is .05 .8, -.7 |<--- kernel is `convolving` along this dimension.
a .5 .31 -.2 |
boy .5 .8 -.4 \|/
在这种情况下,我们将输入设置为 conv 的方式:
maxlen = 4
input_dim = 3
model.add(Conv1D(2,2,activation='relu',input_shape=(maxlen, input_dim))
在您的情况下,您会将特征视为空间维度,每个特征的长度为 1。(见下文)
这是您数据集中的示例
att1 .04 |
att2 .05 | < -- kernel convolving along this dimension
att3 .1 | notice the features have length 1. each
att4 .5 \|/ example have these 4 featues.
我们将 Conv1D 示例设置为:
maxlen = num_features = 4 # this would be 30 in your case
input_dim = 1 # since this is the length of _each_ feature (as shown above)
model.add(Conv1D(2,2,activation='relu',input_shape=(maxlen, input_dim))
如您所见,您的数据集必须重塑为 (569, 30, 1)
使用:
X = np.expand_dims(X, axis=2) # reshape (569, 30, 1)
# now input can be set as
model.add(Conv1D(2,2,activation='relu',input_shape=(30, 1))
这是一个完整的示例,您可以 运行(我将使用 Functional API)
from keras.models import Model
from keras.layers import Conv1D, Dense, MaxPool1D, Flatten, Input
import numpy as np
inp = Input(shape=(5, 1))
conv = Conv1D(filters=2, kernel_size=2)(inp)
pool = MaxPool1D(pool_size=2)(conv)
flat = Flatten()(pool)
dense = Dense(1)(flat)
model = Model(inp, dense)
model.compile(loss='mse', optimizer='adam')
print(model.summary())
# get some data
X = np.expand_dims(np.random.randn(10, 5), axis=2)
y = np.random.randn(10, 1)
# fit model
model.fit(X, y)
我在其他帖子中也提到过:
要将形状为 (nrows, ncols)
的常用特征 table 数据输入到 Keras 的 Conv1d,需要以下两个步骤:
xtrain.reshape(nrows, ncols, 1)
# For conv1d statement:
input_shape = (ncols, 1)
例如,取 iris 数据集的前 4 个特征:
查看常用格式及其形状:
iris_array = np.array(irisdf.iloc[:,:4].values)
print(iris_array[:5])
print(iris_array.shape)
输出显示通常的格式及其形状:
[[5.1 3.5 1.4 0.2]
[4.9 3. 1.4 0.2]
[4.7 3.2 1.3 0.2]
[4.6 3.1 1.5 0.2]
[5. 3.6 1.4 0.2]]
(150, 4)
以下代码改变了格式:
nrows, ncols = iris_array.shape
iris_array = iris_array.reshape(nrows, ncols, 1)
print(iris_array[:5])
print(iris_array.shape)
以上代码数据格式及其形状的输出:
[[[5.1]
[3.5]
[1.4]
[0.2]]
[[4.9]
[3. ]
[1.4]
[0.2]]
[[4.7]
[3.2]
[1.3]
[0.2]]
[[4.6]
[3.1]
[1.5]
[0.2]]
[[5. ]
[3.6]
[1.4]
[0.2]]]
(150, 4, 1)
这适用于 Keras 的 Conv1d。因为需要input_shape (4,1)
。
我有一个稀疏矩阵作为输入,所以我无法在不转换为普通数组的情况下重塑它
解决方案是使用 keras Reshape 层:
from keras.layers.core import Reshape
...
model = Sequential()
model.add(Reshape((X.shape[1], 1), input_shape=(X.shape[1], )))
model.add(Conv1D(2,2,activation='relu'))
...
对于稀疏矩阵,在我的例子中,行:73196,列:101 在通过 array_ = sparse_matrix.A
将我的稀疏矩阵转换为数组之后,我使用了 numpy 的 reshape 函数,然后我使用了下面的代码
x_train_all = np.reshape(array_ , (73196, 101,1))
在输入层我使用了下面的代码:
input2 = Input(shape=(101,1), dtype='float32', name='input2')
我尝试构建一个只有一层的 CNN,但我遇到了一些问题。 事实上,编译器告诉我
ValueError: Error when checking model input: expected conv1d_1_input to have 3 dimensions, but got array with shape (569, 30)
这是代码
import numpy
from keras.models import Sequential
from keras.layers.convolutional import Conv1D
numpy.random.seed(7)
datasetTraining = numpy.loadtxt("CancerAdapter.csv",delimiter=",")
X = datasetTraining[:,1:31]
Y = datasetTraining[:,0]
datasetTesting = numpy.loadtxt("CancereEvaluation.csv",delimiter=",")
X_test = datasetTraining[:,1:31]
Y_test = datasetTraining[:,0]
model = Sequential()
model.add(Conv1D(2,2,activation='relu',input_shape=X.shape))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X, Y, epochs=150, batch_size=5)
scores = model.evaluate(X_test, Y_test)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
如果无法查看更多详细信息,您的数据在预处理后的形状不正确。
将 X 重塑为 3 个维度:
np.reshape(X, (1, X.shape[0], X.shape[1]))
td; lr 您需要重塑您的数据,使 空间 维度使 Conv1d
有意义:
X = np.expand_dims(X, axis=2) # reshape (569, 30) to (569, 30, 1)
# now input can be set as
model.add(Conv1D(2,2,activation='relu',input_shape=(30, 1))
从本质上重塑数据集,如下所示:
features
.8, .1, .3
.2, .4, .6
.7, .2, .1
收件人:
[[.8
.1
.3],
[.2,
.4,
.6
],
[.7,
.2,
.1]]
说明和示例
通常卷积在空间维度上起作用。内核在产生张量的维度上“卷积”。在 Conv1D 的情况下,内核在每个示例的 'steps' 维度上传递。
你会看到 Conv1D 在 NLP 中使用,其中 steps
是句子中的单词数量(填充到某个固定的最大长度)。这些词将被编码为长度为 4 的向量。
这是一个例句:
jack .1 .3 -.52 |
is .05 .8, -.7 |<--- kernel is `convolving` along this dimension.
a .5 .31 -.2 |
boy .5 .8 -.4 \|/
在这种情况下,我们将输入设置为 conv 的方式:
maxlen = 4
input_dim = 3
model.add(Conv1D(2,2,activation='relu',input_shape=(maxlen, input_dim))
在您的情况下,您会将特征视为空间维度,每个特征的长度为 1。(见下文)
这是您数据集中的示例
att1 .04 |
att2 .05 | < -- kernel convolving along this dimension
att3 .1 | notice the features have length 1. each
att4 .5 \|/ example have these 4 featues.
我们将 Conv1D 示例设置为:
maxlen = num_features = 4 # this would be 30 in your case
input_dim = 1 # since this is the length of _each_ feature (as shown above)
model.add(Conv1D(2,2,activation='relu',input_shape=(maxlen, input_dim))
如您所见,您的数据集必须重塑为 (569, 30, 1) 使用:
X = np.expand_dims(X, axis=2) # reshape (569, 30, 1)
# now input can be set as
model.add(Conv1D(2,2,activation='relu',input_shape=(30, 1))
这是一个完整的示例,您可以 运行(我将使用 Functional API)
from keras.models import Model
from keras.layers import Conv1D, Dense, MaxPool1D, Flatten, Input
import numpy as np
inp = Input(shape=(5, 1))
conv = Conv1D(filters=2, kernel_size=2)(inp)
pool = MaxPool1D(pool_size=2)(conv)
flat = Flatten()(pool)
dense = Dense(1)(flat)
model = Model(inp, dense)
model.compile(loss='mse', optimizer='adam')
print(model.summary())
# get some data
X = np.expand_dims(np.random.randn(10, 5), axis=2)
y = np.random.randn(10, 1)
# fit model
model.fit(X, y)
我在其他帖子中也提到过:
要将形状为 (nrows, ncols)
的常用特征 table 数据输入到 Keras 的 Conv1d,需要以下两个步骤:
xtrain.reshape(nrows, ncols, 1)
# For conv1d statement:
input_shape = (ncols, 1)
例如,取 iris 数据集的前 4 个特征:
查看常用格式及其形状:
iris_array = np.array(irisdf.iloc[:,:4].values)
print(iris_array[:5])
print(iris_array.shape)
输出显示通常的格式及其形状:
[[5.1 3.5 1.4 0.2]
[4.9 3. 1.4 0.2]
[4.7 3.2 1.3 0.2]
[4.6 3.1 1.5 0.2]
[5. 3.6 1.4 0.2]]
(150, 4)
以下代码改变了格式:
nrows, ncols = iris_array.shape
iris_array = iris_array.reshape(nrows, ncols, 1)
print(iris_array[:5])
print(iris_array.shape)
以上代码数据格式及其形状的输出:
[[[5.1]
[3.5]
[1.4]
[0.2]]
[[4.9]
[3. ]
[1.4]
[0.2]]
[[4.7]
[3.2]
[1.3]
[0.2]]
[[4.6]
[3.1]
[1.5]
[0.2]]
[[5. ]
[3.6]
[1.4]
[0.2]]]
(150, 4, 1)
这适用于 Keras 的 Conv1d。因为需要input_shape (4,1)
。
我有一个稀疏矩阵作为输入,所以我无法在不转换为普通数组的情况下重塑它
解决方案是使用 keras Reshape 层:
from keras.layers.core import Reshape
...
model = Sequential()
model.add(Reshape((X.shape[1], 1), input_shape=(X.shape[1], )))
model.add(Conv1D(2,2,activation='relu'))
...
对于稀疏矩阵,在我的例子中,行:73196,列:101 在通过 array_ = sparse_matrix.A
将我的稀疏矩阵转换为数组之后,我使用了 numpy 的 reshape 函数,然后我使用了下面的代码
x_train_all = np.reshape(array_ , (73196, 101,1))
在输入层我使用了下面的代码:
input2 = Input(shape=(101,1), dtype='float32', name='input2')