使用Tensorflow数据集向Keras馈入时出现尺寸错误

时间:2019-01-24 03:23:46

标签: keras tensorflow-datasets

我有一个TFRecords文件,该文件由60个示例组成,这些示例包含一些像素的六个Landsat带值以及每个像素的标签,并且我想用它来训练Keras分类器。但是,当我尝试使用数据加载网络时,我遇到了尺寸不匹配的问题。

TFRecords文件的生成具有以下结构:

# TFRecords file contains below features per each example
bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7','landcover']
columns = [tf.FixedLenFeature(shape=[1], dtype=tf.float32) for k in bands]
featuresDict = dict(zip(bands, columns))

我定义生成器函数和Keras模型的代码如下:

def tfdata_generator_training(fileName, batchSize=None):

  dataset = tf.data.TFRecordDataset(fileName, compression_type='GZIP')

  def parse_tfrecord(example):
      features = tf.parse_single_example(example, featuresDict)
      # Extract landcover and remove it from dictionary
      labels = features.pop('landcover')    
      labels = tf.one_hot(tf.cast(labels, tf.uint8), 3)
      # Return list of dictionary values (to be convertable to numpy array for Keras) and pixel label in one-hot format
      return list(features.values()), labels    

  # Map the parsing function over the dataset
  dataset = dataset.map(parse_tfrecord)
  dataset = dataset.batch(batchSize)
  return dataset

training_data = tfdata_generator_training(fileName=<my_file_path>, batchSize=1)

def keras_model():
    from tensorflow.keras.layers import Dense, Input

    inputs = Input(shape=(6,1))
    x = Dense(5, activation='relu')(inputs)
    x = Dense(7, activation='relu')(x)
    outputs = Dense(3, activation='softmax')(x)

    return tf.keras.Model(inputs, outputs)

model = keras_model()
model.compile('adam', 'categorical_crossentropy', metrics=['acc'])
model.fit(training_data.make_one_shot_iterator(), steps_per_epoch=60, epochs=8)

但是运行代码时出现以下错误:

ValueError: Error when checking target: expected dense_2 to have shape (6, 3) but got array with shape (1, 3)

我的代码有什么问题?我还尝试获取输入层的尺寸,Tensorflow打印输出如下:

(<tf.Tensor 'IteratorGetNext:0' shape=(?, 6, 1) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(?, 1, 3) dtype=float32>)

0 个答案:

没有答案