如何在tensorflow中使用.experimental模块而不产生属性错误

问题描述 投票:0回答:1

我正在学习阿拉丁·佩尔森 (aladdin persson) 撰写的关于数据增强的教程。在教程中,tensorflow中的一些预处理模块在当时(3年前)仍在实验中,例如RandomFlip、Resizing。因此本教程使用了像layers.experimental.preprocessing.Resizing("data property")这样的代码。 然而,尽管 3 年前教程中代码的输出没有引发任何错误,但我现在没有得到无错误的输出,这些是我收到的回溯错误:

Traceback (most recent call last):
  File "c:\Users\USER\CODE\PycharmProjects\pythonProject2Conda\main4.py", line 54, in <module>
    layers.experimental.preprocessing.Resizing(height=32, width=32),
    ^^^^^^^^^^^^^^^^^^^
AttributeError: module 'keras._tf_keras.keras.layers' has no attribute 'experimental'

这是实际的代码主体,根据我的理解,它应该训练我的神经网络进行数据增强。

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, regularizers
import tensorflow_datasets as tfds
import pandas as pd
from tensorflow.keras.optimizers.legacy import Adam

#HYPER PARAMETERS

(ds_train, ds_test), ds_info = tfds.load(
    "cifar10",
    split=["train", "test"],
    shuffle_files=True,
    as_supervised=True,
    with_info=True
)

def normalize_img(image, label):
    return tf.cast(image, tf.float32)/255.0, label

AUTOTUNE = tf.data.experimental.AUTOTUNE
BATCH_SIZE = 32

def augment(image, label):
    new_height = new_width = 32
    image = tf.image.resize(image, (new_height, new_width))

    if tf.random.uniform((), minval=0, maxval=1) <0.1:
        image = tf.tile(tf.image.rgb_to_grayscale(image), [1,1,3])
    
    image = tf.image.random_brightness(image, max_delta = 0.1)
    image = tf.image.random_contrast(image, lower=0.1, upper=0.2)

    image = tf.image.random_flip_left_right(image) #50% of cases will be flipped left and right
    # image = tf.image.random_flip_up_down(image) 50%

    return image, label

ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE)
ds_train = ds_train.cache()
ds_train = ds_train.shuffle(ds_info.splits["train"].num_examples)
#ds_train = ds_train.map(augment, num_parallel_calls=AUTOTUNE)
ds_train = ds_train.batch(BATCH_SIZE)
ds_train = ds_train.prefetch(AUTOTUNE)

ds_test = ds_test.map(normalize_img, num_parallel_calls=AUTOTUNE)
de_test = ds_test.batch(BATCH_SIZE)
ds_test = ds_test.prefetch(AUTOTUNE)


data_augmentation = keras.Sequential([
    layers.experimental.preprocessing.Resizing(height=32, width=32),
    layers.experimental.preprocessing.RandomFlip(mode="horizontal"),
    layers.experimental.preprocessing.RandomContrast(factor=0.1),
])
model = keras.Sequential ([
    keras.Input((32, 32, 3)),
    
    layers.Conv2D(4, 3, padding="same", activation='relu'),
    layers.Conv2D(8, 3, padding="same", ctivation='relu'),
    layers.MaxPooling2D(),
    layers.Conv2D(16, 3, activation='relu'),
    layers.Flatten(),
    layers.Dense(64, activation="relu"),
    layers.Dense(10),

])

model.compile(
    optimizer=keras.optimizers.Adam(3e-4),
    loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=["accuracy"],

)

model.fit(ds_train, epochs=5, verbose=2)
model.evaluate(ds_test)


python tensorflow keras layer image-augmentation
1个回答
0
投票

三年前的“实验性”功能不再是实验性的,这并不奇怪!毕竟,将新功能带出该阶段才是我们的目标。

RandomFlip
Resizing
RandomContrast
现在是成熟的功能,并且“.experimental.preprocessing”已从其语法中删除以反映这一点。

将您的

data_augmentation
作业替换为:

data_augmentation = keras.Sequential([
    layers.Resizing(height=32, width=32),
    layers.RandomFlip(mode="horizontal"),
    layers.RandomContrast(factor=0.1),
])
© www.soinside.com 2019 - 2024. All rights reserved.