Skip to content

Instantly share code, notes, and snippets.

@devops-school
Created February 14, 2026 07:45
Show Gist options
  • Select an option

  • Save devops-school/74be61e5e81c14961e60c315e0c4e569 to your computer and use it in GitHub Desktop.

Select an option

Save devops-school/74be61e5e81c14961e60c315e0c4e569 to your computer and use it in GitHub Desktop.
Basic of Tensorflow

1) Install TensorFlow inside Jupyter (macOS)

Run this in a notebook code cell:

%pip install --upgrade pip
%pip install "tensorflow>=2.15,<3"

Then restart the kernel:

  • Notebook menu: Kernel → Restart Kernel

If you’re on Apple Silicon (M1/M2/M3), this usually works. If it fails, use the Apple build below.

If install fails on Apple Silicon (M1/M2/M3) use this instead:

%pip install --upgrade pip
%pip install tensorflow-macos
%pip install tensorflow-metal

Restart kernel again.


2) Verify TensorFlow is working

import tensorflow as tf
print("TF version:", tf.__version__)
print("Devices:", tf.config.list_physical_devices())

(Optional GPU check on Apple Silicon)

tf.config.list_physical_devices("GPU")

Beginner TensorFlow Workflow Examples

Example 1: Tensors basics (create, shape, math)

import tensorflow as tf

a = tf.constant([1, 2, 3])
b = tf.constant([10, 20, 30])

print("a:", a)
print("shape:", a.shape)
print("a+b:", a + b)
print("a*b:", a * b)

m = tf.constant([[1.0, 2.0], [3.0, 4.0]])
print("m:\n", m)
print("transpose:\n", tf.transpose(m))

Example 2: Convert NumPy → TensorFlow and back

import numpy as np
import tensorflow as tf

x_np = np.array([[1, 2], [3, 4]], dtype=np.float32)
x_tf = tf.convert_to_tensor(x_np)

print("numpy:\n", x_np)
print("tensor:\n", x_tf)
print("back to numpy:\n", x_tf.numpy())

Example 3: Build a tiny neural network (Keras) + train (Regression)

We’ll learn a line: y = 3x + 2

import numpy as np
import tensorflow as tf

# Data
x = np.arange(-50, 51, 1).astype(np.float32)
y = 3 * x + 2

# Model
model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(1,)),
    tf.keras.layers.Dense(1)
])

model.compile(optimizer="sgd", loss="mse")

history = model.fit(x, y, epochs=50, verbose=0)

print("Done training.")
print("Predict x=10:", model.predict(np.array([10], dtype=np.float32), verbose=0))

Example 4: Evaluate + Plot training loss (very useful)

import matplotlib.pyplot as plt

plt.plot(history.history["loss"])
plt.title("Training Loss")
plt.xlabel("Epoch")
plt.ylabel("MSE Loss")
plt.show()

loss = model.evaluate(x, y, verbose=0)
print("Final loss:", loss)

Example 5: Classification (beginner) using the Iris dataset

Install scikit-learn once:

%pip install scikit-learn

Restart kernel once if asked.

Now run:

import numpy as np
import tensorflow as tf
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# Load data
iris = load_iris()
X = iris.data.astype(np.float32)
y = iris.target.astype(np.int32)

# Train/test split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# Scale features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train).astype(np.float32)
X_test = scaler.transform(X_test).astype(np.float32)

# Model (3-class classification)
model_cls = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(4,)),
    tf.keras.layers.Dense(16, activation="relu"),
    tf.keras.layers.Dense(3, activation="softmax")
])

model_cls.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"]
)

model_cls.fit(X_train, y_train, epochs=30, verbose=0)

test_loss, test_acc = model_cls.evaluate(X_test, y_test, verbose=0)
print("Test accuracy:", test_acc)

Example 6: Save and Load a TensorFlow model

import os
import tensorflow as tf
import numpy as np

save_dir = "saved_tf_model"
model_cls.save(save_dir)  # saves folder

loaded = tf.keras.models.load_model(save_dir)

# Predict the first 5 test samples
pred = loaded.predict(X_test[:5], verbose=0)
print("Predicted classes:", np.argmax(pred, axis=1))
print("True classes     :", y_test[:5])

Common Issues (macOS)

If you still get “command not found” or weird import issues

Always verify you’re using the same Python as notebook:

import sys
print(sys.executable)

And ensure you installed TensorFlow using %pip inside the notebook.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment