TensorFlow Cheat Sheet
TensorFlow Cheat Sheet
Tensorflow sheetsheet
Here’s a TensorFlow Cheat Sheet to help you quickly reference key concepts and functions.
python
`import tensorflow as tf
print(tf.__version__) # Check version
`
2. Tensors
Creating Tensors
python
Random Tensors
python
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
`
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')
])
`
python
`model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
`
python
python
Making Predictions
python
`predictions = model.predict(X_new)
`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/7
Loading Datasets
python
python
python
`loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam()
python
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
python
`with tf.device('/CPU:0'):
a = tf.constant([1.0, 2.0])
`
python
`converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
This cheat sheet gives you a solid overview of TensorFlow essentials. Let me know if you need more
details on any topic!
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
`
python
python
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
)
`
`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.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dropout(0.5), # Reduce overfitting
layers.Dense(1, activation='sigmoid') # Binary classification
])
`
`model.compile(
optimizer='adam',
loss='binary_crossentropy', # Use 'sparse_categorical_crossentropy' for multi-class
metrics=['accuracy']
)
`
`epochs = 10
history = model.fit(train_dataset, validation_data=val_dataset, epochs=epochs)
`
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()
`
prediction = model.predict(img_array)
print("Prediction:", "Dog" if prediction[0][0] > 0.5 else "Cat")
`
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