How train a tf.data.Dataset
Hello, I woould like to train the flowers dataset in this tutorial https://www.tensorflow.org/tutorials/load_data/images here is my code
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
AUTOTUNE = tf.data.experimental.AUTOTUNE
import IPython.display as display
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import os
import pathlib
data_dir = tf.keras.utils.get_file(origin='https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',
fname='flower_photos', untar=True)
data_dir = pathlib.Path(data_dir)
CLASS_NAMES = np.array([item.name for item in data_dir.glob('*') if item.name != "LICENSE.txt"])
list_ds = tf.data.Dataset.list_files(str(data_dir/'*/*'))
BATCH_SIZE = 32
IMG_HEIGHT = 224
IMG_WIDTH = 224
def get_label(file_path):
# convert the path to a list of path components
parts = tf.strings.split(file_path, os.path.sep)
# The second to last is the class-directory
return parts[-2] == CLASS_NAMES
def decode_img(img):
# convert the compressed string to a 3D uint8 tensor
img = tf.image.decode_jpeg(img, channels=3)
# Use `convert_image_dtype` to convert to floats in the [0,1] range.
img = tf.image.convert_image_dtype(img, tf.float32)
# resize the image to the desired size.
return tf.image.resize(img, [IMG_WIDTH, IMG_HEIGHT])
def process_path(file_path):
label = get_label(file_path)
# load the raw data from the file as a string
img = tf.io.read_file(file_path)
img = decode_img(img)
return img, label
labeled_ds = list_ds.map(process_path, num_parallel_calls=tf.data.experimental.AUTOTUNE)
def prepare_for_training(ds, cache=True, shuffle_buffer_size=1000):
# This is a small dataset, only load it once, and keep it in memory.
# use `.cache(filename)` to cache preprocessing work for datasets that don't
# fit in memory.
if cache:
if isinstance(cache, str):
ds = ds.cache(cache)
else:
ds = ds.cache()
ds = ds.shuffle(buffer_size=shuffle_buffer_size)
# Repeat forever
ds = ds.repeat()
ds = ds.batch(BATCH_SIZE)
# `prefetch` lets the dataset fetch batches in the background while the model
# is training.
ds = ds.prefetch(buffer_size=AUTOTUNE)
return ds
train_ds = prepare_for_training(labeled_ds)
VGG16_MODEL = tf.keras.applications.VGG16(input_shape=(224, 224, 3),
include_top=False,
weights='imagenet')
#VGG16_MODEL.trainable=False
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
prediction_layer = tf.keras.layers.Dense(5,activation='softmax', kernel_initializer='zeros')
model = tf.keras.Sequential([ VGG16_MODEL, global_average_layer, prediction_layer ])
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.001, momentum=0.9),
loss=tf.keras.losses.CategoricalCrossentropy(),
metrics=["accuracy"])
model.fit(train_ds,
epochs=100,
steps_per_epoch=(2800 / 32))
>
the error was
485 # In this case we have created variables on the first call, so we run the
486 # defunned version which is guaranteed to never create variables.
--> 487 return self._stateless_fn(*args, **kwds) # pylint: disable=not-callable
488 elif self._stateful_fn is not None:
489 # Release the lock early so that multiple threads can perform the call
TypeError: 'NoneType' object is not callable
To debug your program, remove all the unnecessary lines until you can isolate the element which make the program bug.
for example ? what i can remove?
All the pre-processing, try with a simpler model. Basically try to reproduce the same bug with a code snippet of 10 lines of code or less
Closing this. Please reopen a new issue with a ~10 lines reproductible code snippet if the problem hasn't been solved.
def get_label(file_path): # convert the path to a list of path components parts = tf.strings.split(file_path, os.path.sep) # The second to last is the class-directory return tf.cast(parts[-2] == CLASS_NAMES, dtype=tf.int32)