我是 tf.data API 的新手,并嘗試在
然后,我嘗試使用以下代碼加載影像:
import tensorflow as tf
BATCH_SIZE = 128
IMG_HEIGHT = 224
IMG_WIDTH = 224
def read_images(X, y):
X = tf.io.read_file(X)
X = tf.io.decode_image(X, expand_animations=False, dtype=tf.float32, channels=3)
X = tf.image.resize(X, [IMG_HEIGHT, IMG_WIDTH])
X = tf.keras.applications.efficientnet.preprocess_input(X, data_format="channels_last")
return (X, y)
def build_data_pipeline(X, y):
data = tf.data.Dataset.from_tensor_slices((X, y))
data = data.map(read_images)
data = data.batch(BATCH_SIZE)
data = data.prefetch(tf.data.AUTOTUNE)
return data
tf_data = build_data_pipeline(train_df["file_path"], train_df["target"])
在此之后,我嘗試使用以下代碼訓練我的模型
model.fit(tf_data, epochs=10)
但是訓練準確率只有 50%,而使用 ImageDataGenerator,我得到了 99% 的準確率。因此,問題出在我無法找出的資料加載部分的某個地方。
我將 EfficientNetB0 與從 imagenet 訓練的權重一起用作特征提取器,最后將單個神經元層用作分類器。
預訓練的 EfficientNetB0 模型:
pretrained_model = tf.keras.applications.EfficientNetB0(
input_shape=(IMG_HEIGHT, IMG_WIDTH, 3),
include_top=False,
weights="imagenet"
)
for layer in pretrained_model.layers:
layer.trainable = False
在 EfficientNetB0 末端具有一個神經元的密集層:
pretrained_output = pretrained_model.get_layer('top_activation').output
x = tf.keras.layers.GlobalAveragePooling2D()(pretrained_output)
x = tf.keras.layers.BatchNormalization()(x)
x = tf.keras.layers.Dense(1, activation="sigmoid")(x)
model = tf.keras.models.Model(pretrained_model.input, x)
編譯模型:
model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["accuracy"]
)
uj5u.com熱心網友回復:
在上面的notebook 中,將輸入閱讀功能更改read_images如下:
def read_images(X, y):
X = tf.io.read_file(X)
X = tf.image.decode_jpeg(X, channels = 3)
X = tf.image.resize(X, [IMG_HEIGHT, IMG_WIDTH]) #/255.0
return (X, y)
另請注意,tf.keras.applications.EfficientNet-Bx具有內置的歸一化層。因此,最好不要對上述函式(即/255.0)中的資料進行歸一化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/393779.html
標籤:Python 张量流 凯拉斯 tf.data.dataset
上一篇:TensorFlow中的矩陣冪
下一篇:如何標準化張量
