Regression in TensorFlow is almost the same as the classification. A slight difference is that in Regression, the number of neurons in the output layer is one because regression models provide one output for each sample.
Please feel free to download the dataset from here:
First import the necessary packages and the dataset:
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
df = pd.read_csv('/content/Housing_1.csv')Checking for the null values:
df.isna().sum()We didn’t find any null values here.
Split for training and testing:
train, test = train_test_split(df, test_size=0.2, random_state=2)Let’s normalize the data. For that first I will get the basic stats of the data using the .describe().
train_stats = train.describe()
train_stats = train_stats.drop(columns=['price'])
train_stats = train_stats.transpose()
Here is the “normalize” function:
def normalize(x):
return (x - train_stats['mean']) / train_stats['std']Exclude the ‘price’ column from the data because the ‘price’ column is our target variable for this exercise.
train_x = train.drop(columns=['price'])
test_x = test.drop(columns=['price'])
train_y = train['price']
test_y = test['price']Use the normalize function to normalize the training features:
train_x = normalize(train_x)
test_x = normalize(test_x)Here is the model definition:
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape = (13, )),
tf.keras.layers.Dense(200, activation = 'relu'),
tf.keras.layers.Dense(128, activation = 'relu'),
tf.keras.layers.Dense(1, activation='relu')
])Compile the model using a suitable optimizer, loss function, and accuracy metrics, and then fit the training data to the model:
import keras
model.compile(optimizer=keras.optimizers.Adam(learning_rate=1e-2),
loss = 'mean_squared_error',
metrics = tf.keras.metrics.RootMeanSquaredError()
)
h = model.fit(train_x, train_y, epochs = 100)Plotting the loss in every epoch to see the trend:
plt.plot(range(100), h.history['loss'])
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.show()
That’s all about the regression model.