We use datasets from files to easily load and work with data stored on your computer. This helps us train machine learning models with real data.
Dataset from files in TensorFlow
tf.data.Dataset.from_tensor_slices(filenames) # or for images image_dataset = tf.keras.utils.image_dataset_from_directory(directory_path, batch_size=32, image_size=(256, 256))
from_tensor_slices creates a dataset from a list of file paths.
image_dataset_from_directory loads images from folders and labels them automatically.
import tensorflow as tf filenames = ["file1.txt", "file2.txt"] dataset = tf.data.Dataset.from_tensor_slices(filenames) for file in dataset: print(file.numpy())
import tensorflow as tf image_dataset = tf.keras.utils.image_dataset_from_directory( "./images", batch_size=16, image_size=(128, 128) ) for images, labels in image_dataset.take(1): print(images.shape, labels.numpy())
This program creates two text files, loads their paths into a TensorFlow dataset, reads the file contents, and prints them.
import tensorflow as tf import os # Create example text files os.makedirs('data', exist_ok=True) with open('data/file1.txt', 'w') as f: f.write('Hello TensorFlow') with open('data/file2.txt', 'w') as f: f.write('Dataset from files') # List of file paths filenames = ["data/file1.txt", "data/file2.txt"] # Create dataset from file names file_dataset = tf.data.Dataset.from_tensor_slices(filenames) # Function to read file content @tf.function def read_file(filename): text = tf.io.read_file(filename) return text # Map function to dataset text_dataset = file_dataset.map(read_file) # Print contents for text in text_dataset: print(text.numpy().decode('utf-8'))
Use tf.io.read_file to read file contents inside the dataset pipeline.
Mapping functions lets you preprocess data as it loads.
Datasets help handle large data efficiently without loading all at once.
Datasets from files let you load data stored on disk easily.
You can create datasets from file paths or directly from image folders.
Use mapping to read and preprocess file contents during loading.
Practice
tf.data.Dataset.from_tensor_slices() with file paths in TensorFlow?Solution
Step 1: Understand the function purpose
tf.data.Dataset.from_tensor_slices()creates a dataset from a tensor, often a list of file paths, not the file contents themselves.Step 2: Clarify dataset content
The dataset holds file paths as strings, which can be mapped later to read actual file data.Final Answer:
To create a dataset that holds file paths which can be read later -> Option DQuick Check:
from_tensor_slices(file_paths) = dataset of paths [OK]
- Thinking it reads file contents immediately
- Confusing dataset creation with saving files
- Assuming it converts tensors to images
Solution
Step 1: Recall correct TensorFlow method
The method to create a dataset from a list of tensors (like file paths) isfrom_tensor_slices().Step 2: Verify options
Methods liketf.data.Dataset.load(),tf.data.Dataset.read_files(), andtf.data.Dataset.create()are not valid TensorFlow dataset creation methods.Final Answer:
dataset = tf.data.Dataset.from_tensor_slices(image_paths) -> Option AQuick Check:
Correct method is from_tensor_slices [OK]
- Using non-existent methods like read_files or load
- Confusing dataset creation with file reading
- Misspelling method names
import tensorflow as tf
image_paths = ["img1.jpg", "img2.jpg"]
dataset = tf.data.Dataset.from_tensor_slices(image_paths)
for item in dataset:
print(item.numpy().decode())Solution
Step 1: Understand dataset content
The dataset contains string tensors of file paths: b'img1.jpg', b'img2.jpg'.Step 2: Decode bytes to string
Callingitem.numpy()returns bytes, anddecode()converts bytes to normal strings.Final Answer:
img1.jpg\nimg2.jpg -> Option CQuick Check:
Decoded bytes = file names [OK]
- Printing tensor directly without decoding
- Expecting list output instead of individual prints
- Confusing bytes and strings
import tensorflow as tf
image_paths = ["img1.jpg", "img2.jpg"]
dataset = tf.data.Dataset.from_tensor_slices(image_paths)
dataset = dataset.map(tf.io.read_file)
for img in dataset:
print(img.numpy().shape)Solution
Step 1: Analyze dataset after map
After mappingtf.io.read_file, each element is a scalar string tensor containing raw file bytes.Step 2: Understand tensor shape
img.numpy()returns Python bytes (raw file content), which has no.shapeattribute. Printingimg.numpy().shaperaises AttributeError.Final Answer:
Cannot print shape of a scalar string tensor -> Option AQuick Check:
img.numpy() is bytes; no .shape [OK]
- Assuming read_file returns image tensor
- Thinking from_tensor_slices rejects lists
- Believing map() is invalid on datasets
Solution
Step 1: Understand dataset creation from folder
dataset = tf.data.Dataset.list_files('images/*').map(lambda x: tf.image.resize(tf.io.decode_image(tf.io.read_file(x)), (128,128))).batch(16) useslist_filesto get file paths, then maps reading, decoding, and resizing images correctly.Step 2: Check batch and resize parameters
Images are resized to (128,128) and batched in groups of 16 as required.Final Answer:
dataset = tf.data.Dataset.list_files('images/*').map(lambda x: tf.image.resize(tf.io.decode_image(tf.io.read_file(x)), (128,128))).batch(16) -> Option BQuick Check:
list_files + map + resize + batch = correct pipeline [OK]
- Using wrong batch size or image size parameters
- Confusing keras and tf.data APIs
- Not decoding images before resizing
Ready to prove it?
Pass the test and this pattern moves unknown
