Linear Regression Model for House Price Prediction in Python
Simple example of how to use scikit-learn library in Python to implement machine learning:
Suppose we want to train a model to predict the price of a house based on its size (in square feet). We can use a linear regression model for this task. Here's the code:
import numpy as np from sklearn.linear_model import LinearRegression # Generate some random data for training size = np.array([[100], [150], [200], [250], [300], [350], [400], [450], [500], [550]]) price = np.array([150000, 200000, 250000, 300000, 350000, 400000, 450000, 500000, 550000, 600000]) # Train the model model = LinearRegression() model.fit(size, price) # Predict the price of a new house with 400 square feet new_size = np.array([[400]]) predicted_price = model.predict(new_size) print(predicted_price)
Explanation:
First, we import the necessary libraries:
numpyfor numerical operations andLinearRegressionfromsklearn.linear_modelfor the linear regression model.We generate some random training data:
sizeis a 2D array of size (10, 1) with 10 samples (houses) and 1 feature (size), andpriceis a 1D array of size (10,) with the corresponding prices.We create an instance of the
LinearRegressionclass and fit the model to the training data using thefitmethod.We create a new sample with a size of 400 square feet and predict its price using the
predictmethod.Finally, we print the predicted price, which is approximately $358,181.
Note that this is a simple example for illustration purposes only. In practice, you would need to preprocess the data, split it into training and testing sets, tune the hyperparameters, and evaluate the model's performance, among other things.
Comments
Post a Comment