'"unsupported operand type(s) for /: 'str' and 'str'" When setting file paths
I'm programming a convnet for images I've split test/train/validation in the directory labelled ds_dir below.
from tensorflow.keras.utils import
image_dataset_from_directory
train_dataset = image_dataset_from_directory(
ds_dir / 'train',
image_size=(50,50))
validation_dataset = image_dataset_from_directory(
ds_dir / 'validation',
image_size=(50, 50))
test_dataset = image_dataset_from_directory(
ds_dir / 'test',
image_size=(50,50))
It returns the error in the title even though it works perfectly with the book exercise from Chollet's book on Deep Learning. I tried setting three separate directories but then this resulted in it detecting no images in any of them.
Solution 1:[1]
You can't use / operator between 2 str, that isn't defined, what would it mean ?
To join them as a path, use pathlib.Path
ds_dir = Path('/content/gdrive/MyDrive/Colab Notebooks/dataset2/')
other_dir = ds_dir / 'train'
# equivalent of
other_dir = ds_dir.joinpath('train')
# or with os.path
other_dir = os.path.join(ds_dir, 'train')
That is better that string concatenation like ds_dir + '/' + 'train'
becayse it handles the correct / regarding platform, and handler if the first ends with / or not, or the last start with / or not
Solution 2:[2]
That's because you are considering / as an operation instead of a character. The solution is including that in the string. In your example:
train_dataset = image_dataset_from_directory(
ds_dir '/train',
image_size=(50,50))
or
train_dataset = image_dataset_from_directory(
ds_dir '/' + 'train',
image_size=(50,50))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | azro |
Solution 2 | Palinuro |