TensorFlow Cheat Sheet
This is a copy of a conversation between ChatGPT & Anonymous.
Tensorflow sheetsheet
Here’s a TensorFlow Cheat Sheet to help you quickly reference key concepts and functions.
1. Installation & Import
bash
`pip install tensorflow
`
python
`import tensorflow as tf
print(tf.__version__) # Check version
`
2. Tensors
Creating Tensors
python
`x = tf.constant([[1, 2], [3, 4]]) # Immutable tensor
y = tf.Variable([[5, 6], [7, 8]]) # Mutable tensor
`
Random Tensors
python
`rand = tf.random.normal([2, 2]) # Normal distribution
rand_uniform = tf.random.uniform([2, 2], minval=0, maxval=1) # Uniform
`
Operations on Tensors
python
`a = tf.constant([1, 2, 3])
b = tf.constant([4, 5, 6])
c = a + b # Addition
d = a * b # Multiplication
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/7
e = tf.matmul(x, y) # Matrix multiplication
f = tf.reshape(x, [1, 4]) # Reshape
g = tf.reduce_sum(x) # Sum of elements
`
3. Building a Neural Network
Defining a Model
python
`model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(10,)),
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
`
Compiling the Model
python
`model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
`
Training the Model
python
`model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_val, y_val))
`
Evaluating the Model
python
`loss, acc = model.evaluate(X_test, y_test)
print(f"Loss: {loss}, Accuracy: {acc}")
`
Making Predictions
python
`predictions = model.predict(X_new)
`
4. Working with Data
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/7
Loading Datasets
python
`from tensorflow.keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train, X_test = X_train / 255.0, X_test / 255.0 # Normalize
`
Using TensorFlow Datasets
python
`import tensorflow_datasets as tfds
dataset = tfds.load('mnist', split='train', as_supervised=True)
`
Creating a TensorFlow Data Pipeline
python
`train_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))
train_dataset = train_dataset.shuffle(10000).batch(32).prefetch(tf.data.AUTOTUNE)
`
5. Custom Training Loop
python
`loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam()
for epoch in range(10):
for x_batch, y_batch in train_dataset:
with tf.GradientTape() as tape:
predictions = model(x_batch, training=True)
loss = loss_object(y_batch, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
`
6. Saving & Loading Models
Saving a Model
python
`model.save('my_model') # Save entire model
model.save_weights('my_weights.h5') # Save only weights
`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/7
Loading a Model
python
`loaded_model = tf.keras.models.load_model('my_model')
`
7. GPU Utilization
Check GPU Availability
python
`print("Num GPUs Available:", len(tf.config.list_physical_devices('GPU')))
`
Force TensorFlow to Use CPU/GPU
python
`with tf.device('/CPU:0'):
a = tf.constant([1.0, 2.0])
`
8. TensorFlow Lite (TFLite)
Convert Model to TFLite
python
`converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
`
This cheat sheet gives you a solid overview of TensorFlow essentials. Let me know if you need more
details on any topic!
Train on image datasets
Training a Model on an Image Dataset with TensorFlow & Keras
Here’s a complete workflow to train a deep learning model on image datasets using TensorFlow.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/7
1. Import Dependencies
python
`import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import numpy as np
import os
`
2. Load & Preprocess the Image Dataset
Using TensorFlow Datasets
python
`import tensorflow_datasets as tfds
dataset_name = 'cats_vs_dogs' # Change to your dataset
(ds_train, ds_test), ds_info = tfds.load(
dataset_name, split=['train[:80%]', 'train[80%:]'], as_supervised=True, with_info=True
)
`
Using a Local Dataset
python
`data_dir = 'path_to_your_images' # Replace with your dataset path
img_size = (224, 224)
batch_size = 32
train_dataset = keras.preprocessing.image_dataset_from_directory(
data_dir, validation_split=0.2, subset="training", seed=123,
image_size=img_size, batch_size=batch_size
)
val_dataset = keras.preprocessing.image_dataset_from_directory(
data_dir, validation_split=0.2, subset="validation", seed=123,
image_size=img_size, batch_size=batch_size
)
`
3. Data Augmentation (Optional)
python
`data_augmentation = keras.Sequential([
layers.RandomFlip("horizontal"),
layers.RandomRotation(0.1),
layers.RandomZoom(0.1),
])
`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/7
4. Build a CNN Model
python
`model = keras.Sequential([
layers.Rescaling(1./255, input_shape=(224, 224, 3)), # Normalize pixels
data_augmentation,
layers.Conv2D(32, (3,3), activation='relu'),
layers.MaxPooling2D(2,2),
layers.Conv2D(64, (3,3), activation='relu'),
layers.MaxPooling2D(2,2),
layers.Conv2D(128, (3,3), activation='relu'),
layers.MaxPooling2D(2,2),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dropout(0.5), # Reduce overfitting
layers.Dense(1, activation='sigmoid') # Binary classification
])
`
5. Compile the Model
python
`model.compile(
optimizer='adam',
loss='binary_crossentropy', # Use 'sparse_categorical_crossentropy' for multi-class
metrics=['accuracy']
)
`
6. Train the Model
python
`epochs = 10
history = model.fit(train_dataset, validation_data=val_dataset, epochs=epochs)
`
7. Evaluate the Model
python
`test_loss, test_acc = model.evaluate(ds_test)
print(f"Test Accuracy: {test_acc:.2f}")
`
8. Visualize Training Results
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/7
python
`plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
`
9. Make Predictions on New Images
python
`from tensorflow.keras.preprocessing import image
import numpy as np
img_path = 'path_to_test_image.jpg' # Provide an image path
img = image.load_img(img_path, target_size=(224, 224))
img_array = image.img_to_array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
prediction = model.predict(img_array)
print("Prediction:", "Dog" if prediction[0][0] > 0.5 else "Cat")
`
10. Save & Load the Model
python
`model.save("image_classifier_model.h5") # Save model
new_model = keras.models.load_model("image_classifier_model.h5") # Load model
`
This is a basic CNN model for image classification. For better accuracy, you can fine-tune pretrained
models like ResNet, MobileNet, or EfficientNet. Let me know if you need that!
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/7