Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
Training a linear regression model end to end with TensorFlow
Load the dataset
Build the model
multiple linear regression
Evaluate performance
b = 1.5, w_1 = 2, w_2 = 5X_1 and X_2 are drawn uniformly from [0, 10]x1 = tf.random.uniform([150], minval=0, maxval=10)
x2 = tf.random.uniform([150], minval=0, maxval=10)
y = 1.5 + 2.0 * x1 + 5.0 * x2
dataset = tf.stack([y, x1, x2], axis=1)b, w_1, w_2 purely from the generated (x1, x2, y) datadataset_shuffled = tf.random.shuffle(dataset, seed=22)
train_data, test_data = dataset_shuffled[:125], dataset_shuffled[125:]
x_train, y_train = train_data[:, 1:], train_data[:, 0]125 training rows, 25 test rows, about 17% held outtf.Module plus @tf.function traces the model into a reusable graphclass LinearRegression(tf.Module):
@tf.function
def __call__(self, x):
if not self.built:
self.w = tf.Variable(tf.random.uniform([x.shape[-1], 1]))
self.b = tf.Variable(tf.random.uniform([]))
self.built = True
return tf.squeeze(tf.matmul(x, self.w) + self.b, axis=1)def mse_loss(y_pred, y):
return tf.reduce_mean(tf.square(y_pred - y))w and b to minimize this lossGPU utilization, but more memory and can generalize worse| Batch Size | When to Use |
|---|---|
1 | Extreme cases, reinforcement learning, online learning |
8 - 16 | Small datasets, memory-constrained GPUs |
32 (default) | Good balance of speed and generalization |
64 - 128 | Large datasets, powerful GPUs |
256+ | Extremely large datasets with TPU/GPU clusters |
| Model Type | Suggested learning_rate |
|---|---|
| Simple linear regression | 0.01 - 0.1 |
| Deep neural networks | 0.001 - 0.01 |
| Convolutional neural networks | 0.0001 - 0.01 |
| Transformers | 0.00001 - 0.0001 |
| Reinforcement learning | 0.0001 - 0.1 |
tf.data.Dataset handles shuffling and batching efficientlytrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_dataset = train_dataset.shuffle(buffer_size=125).batch(32)32, with a smaller final batch of 29w and bfor epoch in range(epochs):
for x_batch, y_batch in train_dataset:
with tf.GradientTape() as tape:
y_pred = lin_reg(x_batch)
loss = mse_loss(y_pred, y_batch)
grads = tape.gradient(loss, lin_reg.variables)
for g, v in zip(grads, lin_reg.variables):
v.assign_sub(learning_rate * g)| Epoch | MSE Loss |
|---|---|
0 | 299.503 |
10 | 0.078 |
20 | 0.062 |
30 | 0.051 |
40 | 0.041 |
50 | 0.034 |
60 | 0.028 |
70 | 0.024 |
80 | 0.019 |
90 | 0.016 |
100 epochs: final train loss 0.014, final test loss 0.012b, w_1, w_2 from the generated data alone| Parameter | True Value | Recovered Value |
|---|---|---|
b | 1.5 | ≈ 1.18 |
w_1 | 2.0 | ≈ 2.03 |
w_2 | 5.0 | ≈ 5.02 |
tf.GradientTape plus assign_sub(learning_rate * gradient) is the core training stepMahmoud Abas|ML Review and Gradient Descent Example