Predicting House Prices with Neural Networks in Python

Welcome back to TopNotch Programmer! In today’s blog post, we’re diving into the world of neural networks with a fun and practical example: predicting house prices. Whether you’re a data science enthusiast or just curious about how machine learning works, this tutorial will guide you through building and training a neural network using Python. Let’s get started!

Introduction to Neural Networks

Before we jump into the code, let’s quickly cover the basics. A neural network is a computational model inspired by the way the human brain works. It’s composed of layers of neurons that process and transform input data to make predictions. Here’s a simple breakdown:

  • Input Layer: Receives the input data (features of the house in our case).
  • Hidden Layers: Perform computations and identify patterns in the data.
  • Output Layer: Produces the final prediction (house price).

Step-by-Step Guide to Predicting House Prices

Step 1: Install Necessary Libraries

First, we need to install the required libraries. Open your terminal or command prompt and run:

pip install tensorflow keras pandas numpy

Step 2: Import Libraries

Create a new Python file (e.g., house_price_prediction.py) and add the following code to import the necessary libraries:

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import pandas as pd
import numpy as np

Step 3: Prepare Data

We’ll use a sample dataset with features like the number of bedrooms, bathrooms, square footage, and location. The target variable is the price of the house.

# Sample Data
data = {
'bedrooms': [3, 4, 2, 5],
'bathrooms': [2, 3, 1, 4],
'sqft': [1500, 2000, 800, 2500],
'location': [1, 2, 1, 2], # 1 for urban, 2 for suburban
'price': [300000, 450000, 200000, 500000]
}

# Convert to DataFrame
df = pd.DataFrame(data)

# Split features and target
X = df[['bedrooms', 'bathrooms', 'sqft', 'location']]
y = df['price']

Step 4: Build the Model

Next, we’ll build the neural network model. We’ll create a sequential model and add layers to it.

# Create a sequential model
model = Sequential()

# Add input layer and hidden layer
model.add(Dense(units=64, activation='relu', input_shape=(4,)))

# Add another hidden layer
model.add(Dense(units=32, activation='relu'))

# Add output layer
model.add(Dense(units=1))

Step 5: Compile the Model

We need to compile the model before training it. We’ll use the Adam optimizer and mean squared error as the loss function.

model.compile(optimizer='adam', loss='mean_squared_error')

Step 6: Train the Model

Now, let’s train the model using our dataset. We’ll set the number of epochs to 100 and the batch size to 1.

model.fit(X, y, epochs=100, batch_size=1)

Step 7: Make Predictions

Finally, we’ll use the trained model to make predictions. Let’s predict the price of a house with 3 bedrooms, 2 bathrooms, 1500 square feet, located in an urban area.

# Sample input for prediction
sample_input = np.array([[3, 2, 1500, 1]]) # 3 bedrooms, 2 bathrooms, 1500 sqft, urban location

# Predict price
predicted_price = model.predict(sample_input)
print(f"Predicted Price: ${predicted_price[0][0]:,.2f}")

Full Code Together

Here’s the complete code for easy copying:

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import pandas as pd
import numpy as np

# Sample Data
data = {
'bedrooms': [3, 4, 2, 5],
'bathrooms': [2, 3, 1, 4],
'sqft': [1500, 2000, 800, 2500],
'location': [1, 2, 1, 2], # 1 for urban, 2 for suburban
'price': [300000, 450000, 200000, 500000]
}

# Convert to DataFrame
df = pd.DataFrame(data)

# Split features and target
X = df[['bedrooms', 'bathrooms', 'sqft', 'location']]
y = df['price']

# Create a sequential model
model = Sequential()

# Add input layer and hidden layer
model.add(Dense(units=64, activation='relu', input_shape=(4,)))

# Add another hidden layer
model.add(Dense(units=32, activation='relu'))

# Add output layer
model.add(Dense(units=1))

# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')

# Train the model
model.fit(X, y, epochs=100, batch_size=1)

# Sample input for prediction
sample_input = np.array([[3, 2, 1500, 1]]) # 3 bedrooms, 2 bathrooms, 1500 sqft, urban location

# Predict price
predicted_price = model.predict(sample_input)
print(f"Predicted Price: ${predicted_price[0][0]:,.2f}")

Conclusion

And there you have it! We’ve built and trained a neural network to predict house prices using Python. Neural networks can be incredibly powerful tools for making predictions and identifying patterns in data. If you enjoyed this tutorial, be sure to check out my YouTube channel, TopNotch Programmer, for more tech tutorials and fun programming projects. Stay tuned for more exciting content!

Watch my video for better understand:

Happy coding!