TensorFlow Basics
| Command / Concept | Description |
|---|
| import tensorflow as tf | Import TensorFlow library |
| tf.version | Check TensorFlow version |
| tf.constant([1, 2, 3]) | Create constant tensor |
| tf.Variable(10) | Create a variable |
| tf.convert_to_tensor([1,2,3]) | Convert list to tensor |
| tf.rank(tensor) | Get rank (dimensions) |
| tf.shape(tensor) | Get shape of tensor |
| tf.cast(tensor, dtype=tf.float32) | Change data type |
Tensor Operations
| Operation | Function | Description |
|---|
| Addition | tf.add(x, y) | Element-wise addition |
| Subtraction | tf.subtract(x, y) | Subtract tensors |
| Multiplication | tf.multiply(x, y) | Element-wise multiply |
| Division | tf.divide(x, y) | Element-wise divide |
| Matrix Multiply | tf.matmul(a, b) | Matrix multiplication |
| Transpose | tf.transpose(a) | Transpose tensor |
| Reshape | tf.reshape(a, [r, c]) | Reshape tensor |
| Sum | tf.reduce_sum(x) | Sum of elements |
| Mean | tf.reduce_mean(x) | Mean of elements |
| Max Index | tf.argmax(x, axis=1) | Index of max value |
| Equality | tf.equal(a, b) | Element-wise equality |
Random Tensors
| Command | Description |
|---|
| tf.random.normal([2,3], mean=0, stddev=1) | Tensor from normal distribution |
| tf.random.uniform([2,3], minval=0, maxval=10) | Tensor from uniform distribution |
| tf.random.shuffle(tensor) | Shuffle tensor elements |
Neural Network Layers
| Layer | Command | Description |
|---|
| Dense | tf.keras.layers.Dense(64, activation='relu') | Fully connected layer |
| Conv2D | tf.keras.layers.Conv2D(32, (3,3), activation='relu') | Convolutional layer |
| MaxPooling | tf.keras.layers.MaxPooling2D((2,2)) | Pooling layer |
| Dropout | tf.keras.layers.Dropout(0.5) | Dropout layer |
| Flatten | tf.keras.layers.Flatten() | Flatten input |
| Input | tf.keras.Input(shape=(784,)) | Define input layer |
Model Creation & Training
| Step | Command | Description |
|---|
| Create Sequential Model | model = tf.keras.models.Sequential([...]) | Create model structure |
| Compile | model.compile(optimizer='adam', loss='mse', metrics=['accuracy']) | Configure model |
| Train | model.fit(X_train, y_train, epochs=10, batch_size=32) | Train model |
| Evaluate | model.evaluate(X_test, y_test) | Evaluate performance |
| Predict | model.predict(X_new) | Make predictions |
Optimizers & Loss Functions
| Type | Command | Description |
|---|
| Optimizers | tf.keras.optimizers.Adam(learning_rate=0.001) | Adam optimizer |
| tf.keras.optimizers.SGD(learning_rate=0.01) | Gradient Descent |
| tf.keras.optimizers.RMSprop() | RMSprop optimizer |
| Loss Functions | tf.keras.losses.MeanSquaredError() | Regression loss |
| tf.keras.losses.BinaryCrossentropy() | Binary classification loss |
| tf.keras.losses.CategoricalCrossentropy() | Multi-class classification |
Activation Functions
| Activation | Command | Description |
|---|
| ReLU | tf.nn.relu(x) | Rectified Linear Unit |
| Sigmoid | tf.nn.sigmoid(x) | Output between 0–1 |
| Softmax | tf.nn.softmax(x) | Probability distribution |
| Tanh | tf.nn.tanh(x) | Hyperbolic tangent |
Gradient & Backpropagation
| Command | Description |
|---|
| with tf.GradientTape() as tape: | Record operations for auto differentiation |
| grad = tape.gradient(loss, var) | Compute gradient of loss w.r.t variable |
| optimizer.apply_gradients(zip(grads, vars)) | Apply computed gradients |
Saving & Loading Models
| Command | Description |
|---|
| model.save('model.h5') | Save entire model |
| tf.keras.models.load_model('model.h5') | Load saved model |
| model.save_weights('weights.h5') | Save weights only |
| model.load_weights('weights.h5') | Load saved weights |
TensorBoard & Visualization
| Command | Description |
|---|
| tensorboard --logdir=logs/ | Launch TensorBoard |
| tf.summary.scalar('loss', loss) | Log scalar values |
| tf.summary.histogram('weights', w) | Log histograms of weights |
Devices & Performance
| Command | Description |
|---|
| tf.config.list_physical_devices('GPU') | List available GPUs |
| tf.device('/GPU:0') | Assign GPU device |
| tf.config.experimental.set_memory_growth(gpu, True) | Prevent full GPU memory allocation |
Datasets and Pipelines
| Command | Description |
|---|
| from tensorflow.keras.datasets import mnist | Import dataset |
| (x_train, y_train), (x_test, y_test) = mnist.load_data() | Load dataset |
| x_train = x_train / 255.0 | Normalize data |
| dataset = tf.data.Dataset.from_tensor_slices((x, y)) | Create dataset pipeline |
| dataset = dataset.shuffle(1000).batch(32) | Shuffle and batch data |
Callbacks & Metrics
| Command | Description |
|---|
| tf.keras.callbacks.EarlyStopping(monitor='val_loss') | Stop when validation loss stops improving |
| tf.keras.callbacks.ModelCheckpoint(filepath='best_model.h5', save_best_only=True) | Save best model |
| tf.keras.metrics.Accuracy() | Accuracy metric |
| tf.keras.metrics.Precision() | Precision metric |
| tf.keras.metrics.Recall() | Recall metric |
Miscellaneous Useful Commands
| Command | Description |
|---|
| tf.summary.image('input_image', images) | Log images |
| tf.print(tensor) | Print tensor values |
| tf.debugging.check_numerics(tensor, 'error') | Check for NaN/Inf values |
| tf.experimental.numpy | Use NumPy-like ops in TF |