# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import torch
from sklearn.model_selection import train_test_split
from torch import nn,optim
import warnings
warnings.filterwarnings("ignore")

df = pd.read_csv('Real estate.csv')
df.head()

df.drop(['X1 transaction date','No','X5 latitude','X6 longitude'],axis=1,inplace=True)
df.head(1)

X = df.iloc[: , :3]
X = X.values
X = X.astype('float32')
X[:5]

y = df.iloc[: , 3]
y = y.values
y = y.astype('float32')
y.shape

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

from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)

X_train = torch.from_numpy(X_train)
y_train = torch.from_numpy(y_train)
X_test = torch.from_numpy(X_test)
y_test = torch.from_numpy(y_test)

from torch.utils.data import DataLoader , TensorDataset
train_ds = TensorDataset(X_train, y_train)
train_ds[0:3]

# Define data loader
batch_size = 30
train_dl = DataLoader(train_ds, batch_size, shuffle=True)


# Defining a training function

def train(n_epoch, model, criterion, opt):
    loss_list = []
    
    for epoch in range(n_epoch):
        total = 0
        for xb,yb in train_dl:
            # Generate predictions
            pred = model(xb)
            loss = criterion(pred, yb)
            total+=loss.item()
            # Perform gradient descent
            loss.backward()
            opt.step()
            opt.zero_grad()
        
        loss_list.append(total)              
    
    return loss_list            


# ## Linear Regression 

model1 = nn.Linear(3, 1)
print(model1.weight)
print(model1.bias)

criterion = nn.MSELoss()

opt = torch.optim.SGD(model1.parameters(), 0.001)

l=train(100, model1 , criterion , opt)

preds = model1(X_test)
preds[:5]

test = y_test.detach().numpy()
test = test.reshape(-1,1)
test[:5]

comp = preds.detach().numpy()
print("Mean absolute error: %.2f" % np.mean(np.absolute(comp - test)))

print(comp[:5])
print('')
print(test[:5])

plt.figure(figsize=(16,8))
plt.plot(l)
plt.xlabel('Epochs')
plt.ylabel('Loss')


# ## Feedfoward Neural Network

class Net(nn.Module):
    #Initilize The Layers
    def __init__(self):
        super().__init__()
        self.l1 = nn.Linear(3,4)
        self.o1 = nn.ReLU()
        self.l2 = nn.Linear(4,1)
        
    def forward(self,x):
        x = self.l1(x)
        x = self.o1(x)
        x = self.l2(x)
        return(x)


nmodel = Net()

opt1 = torch.optim.SGD(nmodel.parameters(), 0.001)
cr = nn.MSELoss()

co=train(100, nmodel , cr , opt1)

plt.figure(figsize=(16,8))
plt.plot(co)
plt.xlabel('Epochs')
plt.ylabel('Loss')

predn = nmodel(X_test)
predn[:5]

test1 = y_test.detach().numpy()
test1 = test.reshape(-1,1)
test1[:5]

comp1 = predn.detach().numpy()
print("Mean absolute error: %.2f" % np.mean(np.absolute(comp1 - test1)))

a = np.array([5.0,390.56840,5]).reshape(-1,1)
a = sc_X.fit_transform(a)
a =a.reshape(1,-1)
a = a.astype('float32')
a = torch.from_numpy(a)

fut1 = model1(a)
fut2 = nmodel(a)
print("THE PREDICTED HOUSE PRICE by Linear Regression Model is:",fut1)
print("")
print("THE PREDICTED HOUSE PRICE by Neural Network Model is: ",fut2)







StarcoderdataJupyterScriptsDedupFiltered