TensorFlow First Program

Writing your first TensorFlow program is a milestone moment. In this topic, you build a neural network that learns to convert temperatures from Celsius to Fahrenheit. This example teaches you the full workflow of a TensorFlow project without overwhelming you with complex data or advanced concepts.

The Problem: Temperature Conversion

The formula to convert Celsius to Fahrenheit is: F = C × 1.8 + 32

You will not tell TensorFlow this formula. Instead, you give it a list of Celsius and Fahrenheit pairs and ask it to figure out the formula by itself. This mirrors how TensorFlow works in the real world — you provide data, not rules.

Training Data:
Celsius     Fahrenheit
-40     →   -40
-10     →   14
  0     →   32
  8     →   46.4
 15     →   59
 22     →   71.6
 38     →   100.4

Step 1 — Import TensorFlow and NumPy

import tensorflow as tf
import numpy as np

TensorFlow handles the model building and training. NumPy handles the numerical arrays (lists of numbers). You almost always use both together.

Step 2 — Prepare the Training Data

celsius    = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)
fahrenheit = np.array([-40,  14, 32, 46.4, 59, 71.6, 100.4], dtype=float)

The dtype=float tells NumPy to treat these as decimal numbers, not integers. TensorFlow needs floating-point numbers for its internal math.

Step 3 — Build the Model

model = tf.keras.Sequential([
    tf.keras.layers.Dense(units=1, input_shape=[1])
])

Here is what each part does:

  • Sequential — a model where data flows in a straight line from one layer to the next
  • Dense layer — a layer where every input connects to every output
  • units=1 — this layer produces exactly one output number (the Fahrenheit value)
  • input_shape=[1] — this layer accepts one input number (the Celsius value)
Diagram of this model:

[Celsius Input]
      |
      v
[Dense Layer (1 neuron)]
  - Multiplies input by weight W
  - Adds bias B
  - Output = W × Input + B
      |
      v
[Fahrenheit Output]

This single neuron secretly represents the formula F = W × C + B. TensorFlow's job is to learn that W ≈ 1.8 and B ≈ 32.

Step 4 — Compile the Model

model.compile(
    optimizer=tf.keras.optimizers.Adam(0.1),
    loss='mean_squared_error'
)

Optimizer: Adam — Adam is a smart adjustment algorithm. The number 0.1 is the learning rate, which controls how large each weight adjustment is. A smaller learning rate means slower but more careful learning. A larger one is faster but risks overshooting the correct values.

Loss: Mean Squared Error — This measures how wrong the model's predictions are. It calculates the average of the squared differences between predicted and actual values. The model aims to make this number as small as possible.

Step 5 — Train the Model

history = model.fit(celsius, fahrenheit, epochs=500, verbose=False)
print("Training finished!")

epochs=500 means the model sees all 7 training examples 500 times. Each pass through the full dataset is one epoch. After 500 epochs, the model has had 3,500 training steps total.

The history variable stores the loss value at each epoch. You can use it later to plot how the loss decreased over time.

Step 6 — Make a Prediction

result = model.predict([100.0])
print(f"100°C is approximately {result[0][0]:.1f}°F")

The correct answer is 212°F. After 500 epochs of training on just 7 data points, the model predicts very close to 212°F. This demonstrates the power of gradient descent — TensorFlow found the right formula through repetition and adjustment, not through being told the answer.

Step 7 — Check What the Model Learned

weights, bias = model.layers[0].get_weights()
print(f"Weight: {weights[0][0]:.2f}")
print(f"Bias:   {bias[0]:.2f}")

Expected output (approximately):

Weight: 1.80
Bias:   31.99

The model discovered that multiplying by approximately 1.8 and adding approximately 32 converts Celsius to Fahrenheit. It learned the actual formula without being told!

The Complete Program

import tensorflow as tf
import numpy as np

# Training data
celsius    = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)
fahrenheit = np.array([-40,  14, 32, 46.4, 59, 71.6, 100.4], dtype=float)

# Build the model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(units=1, input_shape=[1])
])

# Compile the model
model.compile(
    optimizer=tf.keras.optimizers.Adam(0.1),
    loss='mean_squared_error'
)

# Train the model
model.fit(celsius, fahrenheit, epochs=500, verbose=False)

# Make a prediction
result = model.predict([100.0])
print(f"100°C = {result[0][0]:.1f}°F")

# Check learned weights
weights, bias = model.layers[0].get_weights()
print(f"Weight: {weights[0][0]:.2f}, Bias: {bias[0]:.2f}")

Understanding the Training Process Visually

Epoch 1:   Weight=0.1, Bias=0.0  → Prediction: 10°F  → Loss: HIGH
Epoch 50:  Weight=0.8, Bias=12   → Prediction: 92°F  → Loss: MEDIUM
Epoch 200: Weight=1.6, Bias=28   → Prediction: 188°F → Loss: LOW
Epoch 500: Weight=1.8, Bias=32   → Prediction: 212°F → Loss: VERY LOW

The model starts with random weights and terrible predictions. Each epoch nudges the weights slightly closer to the correct values. By epoch 500, the weights are almost exactly 1.8 and 32.

What This Program Taught You

  • How to prepare data as NumPy arrays
  • How to build a model using tf.keras.Sequential
  • How to compile a model with a loss function and optimizer
  • How to train a model using model.fit()
  • How to make predictions using model.predict()
  • How to inspect what the model learned using get_weights()

This workflow — prepare data, build model, compile, train, predict — repeats in every TensorFlow project, from simple tasks like this one to complex image recognition systems trained on millions of photos. The next topic dives deeper into the fundamental building block of all TensorFlow computations: the tensor.

Leave a Comment

Your email address will not be published. Required fields are marked *