【问题标题】:python+ keras Error: Error when checking target: expected dense_2 to have 3 dimensionspython keras错误:检查目标时出错:预期密集_2具有3个维度
【发布时间】:2018-04-04 23:11:23
【问题描述】:

我有 DNA 数据作为 Keras 的输入,DNA 数据是一个单热编码阵列,因此每个 DNA 序列都是 4 个通道(每种核苷酸一个通道)。 one-hot矩阵在matlab中,维度为:(4,400,100) 100个样本。

第一个 matlab 的尺寸为 row* cloumn * slice (4, 400, 100) 但我改变尺寸以获得 (100, 4, 400) 像 python 格式

    import scipy.io 
    x = scipy.io.loadmat('x.mat')
    x2 = x['x']
    x2 = np.ascontiguousarray(x2.T)
    x2 = np.ascontiguousarray(x2.swapaxes(1, 2))
    X_train =x2
    y = scipy.io.loadmat('y.mat')
    y2 = y['y']
    Y_train = np_utils.to_categorical(y2, 2)

现在 X_train 的形状是:(100, 4, 400) Y_train 形状为 (100, 2)

2)

而我的模型是 Conv1D 看起来是这样的:

model = Sequential()
model.add(Conv1D(32, 3, activation='relu', input_shape=(4, 400)))
model.add(MaxPooling1D(2))
model.add(Dropout(0.5))

model.add(Dense(128, activation='relu'))

model.add(Dense(1, activation='sigmoid'))


model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X_train, Y_train, batch_size=16, epochs=10)

错误消息

Traceback (most recent call last): in <module>
    model.fit(X_train, Y_train, batch_size=16, epochs=5)

in _standardize_user_data
    exception_prefix='target')
  in _standardize_input_data
    str(array.shape))
ValueError: Error when checking target: expected dense_2 to have 3 dimensions, but got array with shape (100, 2)

【问题讨论】:

  • 您能在帖子中添加 Y_train、X_train 的形状吗?

标签: python keras


【解决方案1】:

试试这个版本:

import numpy as np
from keras.models import Sequential
from keras.layers import Conv1D, MaxPooling1D, Dropout, Dense, Flatten

# This generates some test sample for me to check your code
X_train = np.random.rand(100, 4, 400)
Y_train = np.random.rand(100, 2)

model = Sequential()

model.add(Conv1D(32, 3, activation='relu', input_shape=(4, 400)))
model.add(MaxPooling1D(2))
model.add(Dropout(0.5))
model.add(Flatten()) # <- You need a flatten here
model.add(Dense(128, activation='relu'))
model.add(Dense(2, activation='sigmoid')) # <- the last dense must have output 2

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X_train, Y_train, batch_size=16, epochs=10)
  1. 我在Dropout之后添加了Flatten层(记得导入)
  2. 由于输出为(2,),所以需要第二层DenseDense(2)

如果您将输出更改为具有维度 (1,),则再次放入 Dense(1),同时将损失从 categorical_crossentropy 更改为 binary_crossentropy

【讨论】:

  • 不客气!如果有效,您可以接受答案吗?
猜你喜欢
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
  • 2019-11-18
相关资源
最近更新 更多