model.fit с использованием tf.data.Dataset поднял «Ошибка типа: невозможно умножить последовательность на не-int типа NoneType» - PullRequest
0 голосов
/ 12 апреля 2020

Я запускаю это в Google Colab. Ошибка обнаружилась при подгонке модели к пользовательскому набору данных. Я создал функцию getDatasetAPI(splitType), которая возвращает tf.data.Dataset объект. Эта функция сопоставляет каждое имя файла с файлами в соответствующей папке, а затем с кортежем тензоров. Это задача сегментации. Не понимая, почему говорится, что ранг равен NoneType.

AUTOTUNE = tf.data.experimental.AUTOTUNE

def decode_img(filename, channels):
  img = tf.io.read_file(filename)
  img = tf.image.decode_jpeg(img, channels=channels)
  img = tf.image.convert_image_dtype(img, tf.float32)
  return img

getfilenames = lambda addr: sorted([f for f in os.listdir(addr)])

def getDatasetAPI(splitType):
  nirdir = tf.constant(DATASET_X+'/{}/images/nir/'.format(splitType))
  rgbdir = tf.constant(DATASET_X+'/{}/images/rgb/'.format(splitType))
  maskdir = tf.constant(DATASET_X+'/{}/masks/'.format(splitType))
  labeldir = tf.constant(DATASET+'/{}/labels/ground_truth/'.format(splitType))
  def process_path(f : tf.Tensor):
    rgbfile = tf.add(rgbdir,f)
    nirfile = tf.add(nirdir,f)
    f = f.numpy().decode()
    f = tf.constant(f[:-4]+'.png')
    labelfile = tf.add(labeldir,f)
    maskfile = tf.add(maskdir,f)
    rgb_img = decode_img(rgbfile,3)
    nir_img = decode_img(nirfile,1)
    label_img = tf.io.read_file(labelfile)
    label_img = tf.image.decode_image(label_img, channels=1)
    mask_img = decode_img(maskfile,1)
    concatenate = tf.concat([rgb_img, nir_img], -1)
    X = mask_img*concatenate
    T = tf.convert_to_tensor(label_img, num_classes=N_CLASSES)
    return (X, T)
  filenames = getfilenames(DATASET_X+'/{}/images/rgb/'.format(splitType))
  filenames = tf.data.Dataset.from_tensor_slices(filenames)
  return filenames.map(lambda x: tf.py_function(process_path, [x], Tout=(tf.float32, tf.float32)), num_parallel_calls=AUTOTUNE)

trainGenerator = getDatasetAPI('train').cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat()
trainGenerator = trainGenerator.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
valGenerator = getDatasetAPI('val').batch(BATCH_SIZE)

with strategy.scope():
  model = build_pspnet(N_CLASSES, 50, (IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS))
  model.compile(optimizer=OPTIMIZER,loss=sparse_categorical_crossentropy, metrics=["binary_accuracy"])
  # model.compile(optimizer=OPTIMIZER,loss=LOSS_FUNCTION, metrics=["binary_accuracy", DiceScore, tf.keras.metrics.MeanIoU(num_classes=N_CLASSES)])

  history = model.fit(trainGenerator, steps_per_epoch=trainSteps, epochs=EPOCH, validation_data=valGenerator,
                      validation_steps=valSteps, callbacks=[CheckpointCallback, LearningRateCallback])

След ошибки:

TypeError: in user code:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:505 train_function  *
        outputs = self.distribute_strategy.run(
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/tpu_strategy.py:170 run  **
        return self.extended.tpu_run(fn, args, kwargs, options)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/tpu_strategy.py:865 tpu_run
        return func(args, kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/tpu_strategy.py:914 tpu_function
        maximum_shape = tensor_shape.TensorShape([None] * rank)

    TypeError: can't multiply sequence by non-int of type 'NoneType
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...