Creating a Simple Linear Regression Model with TensorFlow
Linear regression is a machine learning algorithm that models the linear relationship (a relationship that can be represented by a straight line) between an input and an output.
For example, consider the following relationship:
-
When x is 1, y is 2
-
When x is 2, y is 4
-
When x is 3, y is 6
This relationship can be expressed as a linear relationship like y = 2x
.
The code below is an example of creating a simple machine learning model that helps a computer learn the pattern of numbers.
To break it down simply, the computer learns to output twice the number it is given.
import tensorflow as tf
import numpy as np
# Define input data
x_train = np.array([1, 2, 3, 4, 5], dtype=np.float32)
# Define output data
y_train = np.array([2, 4, 6, 8, 10], dtype=np.float32)
# Create model
model = tf.keras.Sequential([
# Create a Dense layer with 1 input value and 1 output value
tf.keras.layers.Dense(units=1, input_shape=[1])
])
# Compile model
model.compile(optimizer='sgd', loss='mean_squared_error')
# Train the model by repeating the data 100 times to learn the rule
model.fit(x_train, y_train, epochs=100, verbose=1)
# Make a prediction
print(model.predict([6])) # Expected output: A value close to 12
Let's go over each part of the code.
1. Defining Input and Output Data
x_train
is the input data (1, 2, 3, 4, 5), and y_train
is the output data (2, 4, 6, 8, 10).
In other words, the output is twice the input value.
2. Creating the Model
Use tf.keras.Sequential()
to create a neural network model.
Dense(units=1, input_shape=[1])
means a layer with one input and one output.
3. Compiling the Model
optimizer='sgd'
indicates using Stochastic Gradient Descent (SGD) for training. SGD helps minimize the loss function.
loss='mean_squared_error'
is a method for reducing error.
Training the Model
model.fit(x_train, y_train, epochs=100, verbose=1)
trains the model by repeating the data 100 times to learn the rule.
Making Predictions
When you execute model.predict([6])
, it predicts a value close to twice 6, which is 12.
We've now created a simple linear regression model.
In the next class, we'll go through a simple quiz to review what we've learned about TensorFlow.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.