In the world of real estate, determining property prices involves numerous factors, from location and size to amenities and market trends. Simple linear regression, a foundational technique in machine learning, provides a practical way to predict housing prices based on key features like the number of rooms or square footage.
In this article, I delve into the process of applying simple linear regression to a housing dataset, from data preprocessing and feature selection to building a model that can offer valuable price insights. Whether you’re new to data science or seeking to deepen your understanding, this project serves as a hands-on exploration of how data-driven predictions can shape smarter real estate decisions.
First things first, you start by importing your libraries:
import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt
#Read from the directory where you stored the data data = pd.read_csv('/kaggle/input/california-housing-prices/housing.csv')
data
#Test to see if there arent any null values data.info()
#Trying to draw the same number of null values data.dropna(inplace = True)
data.info()
#From our data, we are going to train and test our data from sklearn.model_selection import train_test_split X = data.drop(['median_house_value'], axis = 1) y = data['median_house_value']
y
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
#Examining correlation between x and y training data train_data = X_train.join(y_train)
train_data
#Visualizing the above train_data.hist(figsize=(15, 8))
#Encoding non-numeric columns to see if they are useful and categorical for analysis train_data_encoded = pd.get_dummies(train_data, drop_first=True) correlation_matrix = train_data_encoded.corr() print(correlation_matrix)
train_data_encoded.corr()
plt.figure(figsize=(15,8)) sns.heatmap(train_data_encoded.corr(), annot=True, cmap = "inferno")
import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt
#Read from the directory where you stored the data data = pd.read_csv('/kaggle/input/california-housing-prices/housing.csv')
data
ocean_proximity
INLAND 5183
NEAR OCEAN 2108
NEAR BAY 1783
ISLAND 5
Name: count, dtype: int64
#Test to see if there arent any null values data.info()
#Trying to draw the same number of null values data.dropna(inplace = True)
data.info()
#From our data, we are going to train and test our data from sklearn.model_selection import train_test_split X = data.drop(['median_house_value'], axis = 1) y = data['median_house_value']
y
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
#Examining correlation between x and y training data train_data = X_train.join(y_train)
train_data
#Visualizing the above train_data.hist(figsize=(15, 8))
#Encoding non-numeric columns to see if they are useful and categorical for analysis train_data_encoded = pd.get_dummies(train_data, drop_first=True) correlation_matrix = train_data_encoded.corr() print(correlation_matrix)
train_data_encoded.corr()
plt.figure(figsize=(15,8)) sns.heatmap(train_data_encoded.corr(), annot=True, cmap = "inferno")
train_data['total_rooms'] = np.log(train_data['total_rooms'] + 1) train_data['total_bedrooms'] = np.log(train_data['total_bedrooms'] +1) train_data['population'] = np.log(train_data['population'] + 1) train_data['households'] = np.log(train_data['households'] + 1)
train_data.hist(figsize=(15, 8))
0.5092972905670141
#convert ocean_proximity factors into binary's using one_hot_encoding train_data.ocean_proximity.value_counts()
#For each feature of the above we will then create its binary(0 or 1) pd.get_dummies(train_data.ocean_proximity)
0.4447616558596853
#Dropping afterwards the proximity train_data = train_data.join(pd.get_dummies(train_data.ocean_proximity)).drop(['ocean_proximity'], axis=1)
train_data
#recheck for correlation plt.figure(figsize=(18, 8)) sns.heatmap(train_data.corr(), annot=True, cmap ='twilight')
0.5384474921332503
I would really say that training a machine is not the easiest of processes but to keep improving the results above you can add more features under the param_grid such as the min_feature and in that way your best estimator score can keep on improvimng.
If you got till this far please like and share your comment below, your opinion really matters. Thank you!??❤️
The above is the detailed content of House_Price_Prediction. For more information, please follow other related articles on the PHP Chinese website!

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
