How to implement linear regression using keras.Explain with a case study

1.1K    Asked by ranjan_6399 in Data Science , Asked on Jan 15, 2020
Answered by Ranjana Admin

Let us load housing data to perform linear regression using keras.

import matplotlib.pyplot as plt

import pandas as pd

import numpy as np

Now we will load the data

df = pd.read_csv('../data/housing-data.csv')

Now we create feature and target variables

X = df[['sqft', 'bdrms', 'age']].values

y = df['price'].values

Now we will import keras and other libraries

from keras.models import Sequential

from keras.layers import Dense

from keras.optimizers import Adam

Now we create a regression model

model = Sequential()

model.add(Dense(1, input_shape=(3,)))

model.compile(Adam(lr=0.8), 'mean_squared_error')

Now we split the data

from sklearn.model_selection import train_test_split

# split the data into train and test with a 20% test size

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

Now we fit and predict the model

model.fit(X_train, y_train)

from sklearn.metrics import r2_score

# check the R2score on training and test set

y_train_pred = model.predict(X_train)

y_test_pred = model.predict(X_test)

print("The R2 score on the Train set is: {:0.3f}".format(r2_score(y_train, y_train_pred)))

print("The R2 score on the Test set is: {:0.3f}".format(r2_score(y_test, y_test_pred)))



Your Answer

Answer (1)

This code demonstrates how to perform linear regression using Keras. It follows a structured approach: PaybyPlateMa 


Loading Data: The housing dataset is read into a Pandas DataFrame.


Feature & Target Selection: sqft, bdrms, and age are chosen as features, while price is the target variable.


Building the Model: A simple Keras Sequential model is created with a single dense layer for regression.


Compiling the Model: The optimizer used is Adam with a learning rate of 0.8, and mean_squared_error is the loss function.


Splitting Data: The dataset is split into training and testing sets using an 80-20 ratio.


Training & Evaluation: The model is trained on X_train, and predictions are made for both training and test sets. The R² score is then calculated to assess model performance.


One improvement could be normalizing the features (X) before training to enhance convergence and accuracy. Overall, this is a solid approach to applying deep learning for regression tasks!

6 Hours

Interviews

Parent Categories