TensorFlow Exercises
Problem 1: Create a 1D TensorFlow constant (a Tensor) containing the numbers from 1 to 5. Then, multiply every number in that tensor by 10.
import tensorflow as tf
# 1. Create a constant Tensor
numbers = tf.constant([1, 2, 3, 4, 5])
# 2. Multiply by 10
multiplied_numbers = numbers * 10
# Alternatively, using TensorFlow's built-in math functions:
# multiplied_numbers = tf.math.multiply(numbers, 10)
print("Original Tensor:
", numbers)
print("
Multiplied Tensor:
", multiplied_numbers)
Problem 2: In machine learning, algorithms need to calculate derivatives to update their weights and “learn.” Create a TensorFlow Variable with the value of $3.0$. Use TensorFlow to calculate the derivative of the equation $y = x^2$ with respect to $x$.(Note: The mathematical derivative of $x^2$ is $2x$, so if $x=3$, the answer should be $6$).
from sklearn.linear_model import LinearRegression
import tensorflow as tf
# 1. Create a Variable (Variables can be modified/updated by TensorFlow)
x = tf.Variable(3.0)
# 2. Open a GradientTape to record operations
with tf.GradientTape() as tape:
y = x ** 2
# 3. Ask the tape to calculate the gradient (derivative) of y with respect to x
dy_dx = tape.gradient(y, x)
print(f"The value of x is: {x.numpy()}")
print(f"The derivative of y = x^2 at x=3 is: {dy_dx.numpy()}")
Problem 3: You have a tiny dataset representing the simple linear rule $y = (2x - 1)$.X: -1, 0, 1, 2, 3, 4Y: -3, -1, 1, 3, 5, 7Build a neural network with a single layer and a single neuron to learn this relationship. Train it for 500 epochs, then ask it to predict the Y value when X is 10.
import tensorflow as tf
import numpy as np
# 1. Provide the data
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)
# 2. Build a simple Sequential model (1 layer, 1 neuron)
model = tf.keras.Sequential([
tf.keras.layers.Dense(units=1, input_shape=[1])
])
# 3. Compile the model (Choose an optimizer and a loss function)
model.compile(optimizer='sgd', loss='mean_squared_error')
# 4. Train the model for 500 loops (epochs) over the data
# (Setting verbose=0 hides the training output so it doesn't spam your console)
model.fit(xs, ys, epochs=500, verbose=0)
# 5. Make a prediction
prediction = model.predict([10.0])
print(f"The model predicts that when X is 10, Y is roughly: {prediction[0][0]:.2f}")
# (The exact math answer is 19)