You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TensorFlow中使用.experimental模块避免属性错误

解决TensorFlow中layers.experimental属性错误问题

错误原因

你遇到的AttributeError是因为TensorFlow版本迭代后,原处于实验阶段的预处理层(如Resizing、RandomFlip)已经从layers.experimental.preprocessing迁移至正式的layers.preprocessing模块,旧的experimental子模块已被移除。

修复步骤

  • 替换预处理层路径:将所有layers.experimental.preprocessing.XXX替换为layers.preprocessing.XXX
  • 修正测试集变量名错误:代码中de_test = ds_test.batch(BATCH_SIZE)是笔误,应改为ds_test = ds_test.batch(BATCH_SIZE),否则测试集未正确按批次处理
  • 可选优化:原代码定义了data_augmentation序列但未使用,建议将其加入模型,让数据增强在模型训练时自动执行

修改后的完整代码

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%概率左右翻转
    # 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)
ds_test = ds_test.batch(BATCH_SIZE)  # 修正变量名错误
ds_test = ds_test.prefetch(AUTOTUNE)


data_augmentation = keras.Sequential([
    layers.preprocessing.Resizing(height=32, width=32),
    layers.preprocessing.RandomFlip(mode="horizontal"),
    layers.preprocessing.RandomContrast(factor=0.1),
])
model = keras.Sequential ([
    keras.Input((32, 32, 3)),
    data_augmentation,  # 加入数据增强层
    layers.Conv2D(4, 3, padding="same", activation='relu'),
    layers.Conv2D(8, 3, padding="same", activation='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)

内容的提问来源于stack exchange,提问作者Isesele Victor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 07:24:51