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

633    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, 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


Parent Categories