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.
%pip install --upgrade pip
%pip install tensorflow-macos
%pip install tensorflow-metalRestart kernel again.
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")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))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())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))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)Install scikit-learn once:
%pip install scikit-learnRestart 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)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])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.