Specifying class or sample weights in Keras for one-hot encoded labels in a TF Dataset
...Because the Keras documentation does not specify the keys for the class_weights..

You may get an idea with these two parameters,

labels: Either &quot;inferred&quot; (labels are generated from the directory structure), or a list/tuple of integer labels of the same size as the number of image files found in the directory. Labels should be sorted according to the alphanumeric order of the image file paths (obtained via os.walk(directory) in Python).


class_names: Only valid if &quot;labels&quot; is &quot;inferred&quot;. This is the explicit list of class names (must match names of subdirectories). Used to control the order of the classes (otherwise alphanumerical order is used).

So, it will be mapped to alphabetical order if not specified explicitly.
traindata = image_dataset_from_directory(&quot;/content/Data&quot;) # Default
traindata = image_dataset_from_directory(&quot;/content/Data&quot;,class_names=['train_data','test_data']) #as per the values passed in class_names


Does anyone have a solution that may work in combination with a dataset loaded by image_dataset_from_directory?

You may try a wrapper of a custom Generator over the initial Keras generator. Below is a very basic code sample
def cust_gen():
    for image, label in traindata:
        yield image, label, np.ones((2,1)) # 3rd parm is the sample_weight

history = model.fit(cust_gen(), epochs=epochs) 

You will have to write a custom code to create the sample_weight for each batch.