A linear Regression model uses to predict the output of a continuous value, like a stock price or a time series. In contrast with a classification problem, where we use it to predict a discrete label like where a picture contains a dog or a cat.

In this tutorial, We build a Linear Regression model to predict the Celsius degree from a given Fahrenheit degree.TensorFlow Keras is our API for building Linear Regression models and for running Machine Learning models.

Create the Model

Here, We’ve designed the simplest Linear Regression model which is a series of connected layers of things called neurons. We’ll use a Sequential model with two densely connected hidden layers, and an output layer that returns a single, continuous value. 

model = keras.Sequential([
    keras.layers.Dense(64, activation=tf.nn.relu, input_shape=[1]),
    keras.layers.Dense(64, activation=tf.nn.relu),
    keras.layers.Dense(1)
  ])

optimizer = tf.keras.optimizers.RMSprop(0.001)

Compile Model

A typical loss function for the Linear regression model is the Mean Square Error (MSE). It gives an idea of how much error the system typically makes in its predictions, with a higher weight for large errors.

optimizer = tf.keras.optimizers.RMSprop(0.001)

model.compile(loss='mean_squared_error',
                optimizer=optimizer,
                metrics=['mean_absolute_error', 'mean_squared_error'])

Create Dataset

To train the model, we’ll input the Fahrenheit degree as an input and Celsius degree as an output label.

Fahrenheit=np.array([-140,-136,-124,-112,-105,-96,-88,-75,-63,-60,-58,-40,-20,-10,0,30,35,48,55,69,81,89,95,99,105,110,120,135,145,158,160],dtype=float)

Celsius=np.array([-95.55,-93.33,-86.66,-80,-76.11,-71.11,-66.66,-59.44,-52.77,-51.11,-50,-40,-28.88,-23.33,-17.77,-1.11,1.66,8.88,12,20,27.22,31.66,35,37.22,40.55,43.33,48.88,57.22,62.77,70,71.11],dtype=float)

Train Model

Now we are going to feed Fahrenheit and Celsius to train our model.

model.fit(Fahrenheit,Celsius,epochs=500)

What we’re going to do is just going to give it a bunch of data and then what a neural network will do is it will iterate across that data and figure out the patterns between them. So it’s gone through 500 iterations of trying to figure out the pattern.

Predict Data

We know 200 degrees Fahrenheit is 93.33 of Celsius. We’re getting 92.10 because we use only a small amount of data it’s giving me a very high probability of the relationship between those two numbers being Fahrenheit to centigrade. So now I’ve built a model. It’s a very very simple model.