Feesout
unknown
c_cpp
a year ago
2.3 kB
16
Indexable
#####Linear regression
# Import necessary libraries
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# Prepare the data
data = {'Size': [1000, 1500, 1200, 2000, 1800, 1300, 1600, 1400, 1700, 1100],
'Price': [150000, 200000, 180000, 250000, 220000, 190000, 210000, 200000, 225000, 170000]}
df = pd.DataFrame(data)
# Separate features (X) and target variable (y)
X = df[['Size']] # Independent variable (size)
y = df['Price'] # Dependent variable (price)
# Create a linear regression model
model = LinearRegression()
# Train the model on the data
model.fit(X, y)
# Make a prediction for a new house size
new_size = 1850
predicted_price = model.predict([[new_size]])
print("Predicted price for a house of 1850 sq ft:", predicted_price[0])
# Visualize the results
plt.scatter(X, y, color='blue', label='Actual Data')
plt.plot(X, model.predict(X), color='red', label='Regression Line')
plt.xlabel("Size (sq ft)")
plt.ylabel("Price (USD)")
plt.title("House Price Prediction")
plt.legend()
plt.show()
###### Ploolynomial Regression
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
# Read the data from a CSV file
df = pd.read_csv('house_prices.csv')
# Separate features (X) and target variable (y)
X = df[['Size']] # Independent variable (size)
y = df['Price'] # Dependent variable (price)
# Create polynomial features (e.g., degree 2)
poly_features = PolynomialFeatures(degree=2)
X_poly = poly_features.fit_transform(X)
# Create a linear regression model
model = LinearRegression()
# Train the model on the polynomial features
model.fit(X_poly, y)
# Make a prediction for a new house size
new_size = 1850
new_size_poly = poly_features.transform([[new_size]])
predicted_price = model.predict(new_size_poly)
print("Predicted price for a house of 1850 sq ft:", predicted_price[0])
# Visualize the results
plt.scatter(X, y, color='blue', label='Actual Data')
plt.plot(X, model.predict(poly_features.fit_transform(X)), color='red', label='Polynomial Regression')
plt.xlabel("Size (sq ft)")
plt.ylabel("Price (USD)")
plt.title("House Price Prediction")
plt.legend()
plt.show()Editor is loading...
Leave a Comment