【问题标题】:How to extract 'image' and 'label' out of Tensorflow?如何从 Tensorflow 中提取“图像”和“标签”?
【发布时间】:2021-02-13 17:22:02
【问题描述】:

我已经从 CIFAR10 加载了我的训练集和验证集,如下所示:

train = tfds.load('cifar10', split='train[:90%]', shuffle_files=True)
validation = tfds.load('cifar10', split='train[-10%:]', shuffle_files=True)

我已经为我的 CNN 创建了架构

model = ...

现在我正在尝试使用 model.fit() 来训练我的模型,但我不知道如何从我的对象中分离出“图像”和“标签”。训练和验证如下所示:

print(train) # same layout as the validation set
<_OptionsDataset shapes: {id: (), image: (32, 32, 3), label: ()}, types: {id: tf.string, image: tf.uint8, label: tf.int64}>

我的幼稚方法是这样,但那些 OptionsDatasets 不能下标。

history = model.fit(train['image'], train['label'], epochs=100, batch_size=64, validation_data=(validation['image'], test['label'], verbose=0)

【问题讨论】:

    标签: python tensorflow machine-learning conv-neural-network


    【解决方案1】:

    我们可以这样做

    import tensorflow as tf
    import tensorflow_datasets as tfds
    
    def normalize(img, label):
      img = tf.cast(img, tf.float32) / 255.
      return (img, label)
    
    ds = tfds.load('mnist', split='train', as_supervised=True)
    ds = ds.shuffle(1024).batch(32).prefetch(tf.data.experimental.AUTOTUNE)
    ds = ds.map(normalize)
    
    for i in ds.take(1):
        print(i[0].shape, i[1].shape)
    # (32, 28, 28, 1) (32,)
    
    • 使用as_supervised=Trueimagelabel 作为元组返回
    • 使用.map() 应用预处理功能甚至增强。

    型号

    # declare input shape 
    input = tf.keras.Input(shape=(28,28,1))
    
    # Block 1
    x = tf.keras.layers.Conv2D(32, 3, strides=2, activation="relu")(input)
    
    # Now that we apply global max pooling.
    gap = tf.keras.layers.GlobalMaxPooling2D()(x)
    
    # Finally, we add a classification layer.
    output = tf.keras.layers.Dense(10, activation='softmax')(gap)
    
    # bind all
    func_model = tf.keras.Model(input, output)
    

    编译并运行

    print('\nFunctional API')
    func_model.compile(
              metrics=['accuracy'],
              loss= 'sparse_categorical_crossentropy', # labels are integer (not one-hot)
              optimizer = tf.keras.optimizers.Adam()
              )
    
    func_model.fit(ds)
    # 1875/1875 [==============================] - 15s 7ms/step - loss: 2.1782 - accuracy: 0.2280
    

    【讨论】:

      猜你喜欢
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 2019-10-07
      • 2018-10-06
      • 2021-07-19
      • 1970-01-01
      • 2016-03-24
      • 2018-06-27
      相关资源
      最近更新 更多