【问题标题】:Errors with simple Neural Network in Keras/TensorflowKeras/Tensorflow 中简单神经网络的错误
【发布时间】:2019-04-13 22:18:52
【问题描述】:

我正在构建一个简单的神经网络。数据是一个热编码的 231 长向量。每个 231 个长向量被分配一个 8 长的一个热编码标签。

到目前为止我的代码是:

ssdf = pd.read_csv("/some/path/to/1AMX_one_hot.csv", sep=',')

ss = ssdf.iloc[:,3:11] # slice the df for the ss
labels = ss.values # vector of all ss's
labels = labels.astype('int32')
# data
onehot = ssdf.iloc[:,11:260]
data = onehot.values
data = data.astype('int32')

model = tf.keras.Sequential()
# Adds a densely-connected layer with 64 units to the model:
model.add(layers.Dense(64, activation='relu'))

# Add another:
model.add(layers.Dense(64, activation='relu'))

# Add a softmax layer with 8 output units:
model.add(layers.Dense(8, activation='softmax'))


model.compile(Adam(lr=.0001), 
          loss='sparse_categorical_crossentropy', 
          metrics=['accuracy']
)

## fit the model
model.fit(data, labels, epochs=10, batch_size=32)

问题是输出层是 8 个单元,但是我的标签不是单个单元,它们是 8 长的向量,是一个热编码的。如何将其表示为输出?

错误信息是:

TypeError: Unable to build 'Dense' layer with non-floating point dtype <dtype: 'int32'>

完整追溯:

Traceback (most recent call last):
  File "/some/path/to/file/main.py", line 36, in <module>
    model.fit(data, labels, epochs=10, batch_size=32)
  File "/anaconda3/lib/python3.7/site-    packages/tensorflow/python/keras/engine/training.py", line 806, in fit
    shuffle=shuffle)
  File "/anaconda3/lib/python3.7/site-    packages/tensorflow/python/keras/engine/training.py", line 2503, in     _standardize_user_data
    self._set_inputs(cast_inputs)
  File "/anaconda3/lib/python3.7/site-    packages/tensorflow/python/training/tracking/base.py", line 456, in     _method_wrapper
    result = method(self, *args, **kwargs)
  File "/anaconda3/lib/python3.7/site-    packages/tensorflow/python/keras/engine/training.py", line 2773, in     _set_inputs
    outputs = self.call(inputs, training=training)
  File "/anaconda3/lib/python3.7/site-    packages/tensorflow/python/keras/engine/sequential.py", line 256, in call
outputs = layer(inputs, **kwargs)
  File "/anaconda3/lib/python3.7/site-    packages/tensorflow/python/keras/engine/base_layer.py", line 594, in     __call__
    self._maybe_build(inputs)
  File "/anaconda3/lib/python3.7/site-    packages/tensorflow/python/keras/engine/base_layer.py", line 1713, in     _maybe_build
    self.build(input_shapes)
  File "/anaconda3/lib/python3.7/site-    packages/tensorflow/python/keras/layers/core.py", line 963, in build
    'dtype %s' % (dtype,))

【问题讨论】:

  • 请包含完整的回溯。同样在您的情况下,您应该使用分类交叉熵损失,而不是稀疏版本。
  • 刚刚添加了回溯!啊,好的,谢谢!

标签: python tensorflow keras


【解决方案1】:

您的示例代码中有几个问题:

  1. 您的网络需要一个输入层或输入形状。
  2. 提供您的数据标签为:astype(np.float32)

如果您的标签的形状为 (150, 8),则用 8 个神经元拟合最后一层。

model.add(layers.Dense(8, activation='softmax'))
model.compile(Adam(lr=0.0001),
              loss='categorical_crossentropy',
              metrics=['accuracy'])

更新:

ssdf = pd.read_csv("/some/path/to/1AMX_one_hot.csv", sep=',')

ss = ssdf.iloc[:,3:11] # slice the df for the ss
labels = ss.values # vector of all ss's
labels = labels.astype('float32')                     # changed this
# data
onehot = ssdf.iloc[:,11:260]
data = onehot.values
data = data.astype('float32')                         # changed this

model = tf.keras.Sequential()
# Adds a densely-connected layer with 64 units to the model:
model.add(layers.Dense(64, activation='relu'))

# Add another:
model.add(layers.Dense(64, activation='relu'))

# Add a softmax layer with 8 output units:
model.add(layers.Dense(8, activation='softmax'))


model.compile(Adam(lr=.0001), 
          loss='categorical_crossentropy',            # changed this
          metrics=['accuracy']
)

## fit the model
model.fit(data, labels, epochs=10, batch_size=32)

【讨论】:

  • ss[:, 3:11] 已经是一个热编码,输出为:[[0 0 0 ... 0 0 1] [0 0 0 ... 0 0 1]... [0 1 0 ... 0 0 0] [0 0 0 ... 0 0 1]]
  • 然后将其 (labels.reshape((labels.shape[0], 64))) 展平为一维数组并输入为Dense(64, activation='softmax')
  • 我收到错误ValueError: cannot reshape array of size 1200 into shape (150,64)
  • 您的标签数组的形状是什么? print(labels.shape)
  • 形状为 (150, 8)
猜你喜欢
  • 1970-01-01
  • 2016-08-18
  • 2017-07-08
  • 2019-08-06
  • 2019-02-05
  • 2022-01-08
  • 2020-12-09
  • 2020-03-21
  • 2021-01-25
相关资源
最近更新 更多