Repository navigation
Expand file tree
/
Copy pathPython Code
More file actions
213 lines (177 loc) · 7.82 KB
/
Copy pathPython Code
File metadata and controls
213 lines (177 loc) · 7.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# Property Price Prediction based on Inflation Forecast
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression, Ridge, ElasticNet
from sklearn.model_selection import train_test_split
from sklearn.ensemble import StackingRegressor
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
from sklearn.preprocessing import StandardScaler
from xgboost import XGBRegressor
import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D
file_path = "C:\\Users\\adity\\pythonlang\\pythonproj.xlsx"
try:
df = pd.read_excel(file_path)
print("File Loaded Successfully!\n")
print(df.iloc[:20,:])
except Exception as e:
print(f"Error loading file: {e}")
exit()
def total_price(df):
required_area = int(input("Enter the required area in sqft: "))
if 'AveragePrice' in df.columns:
df['price_per_sqft'] = df['AveragePrice']
df['total_price'] = df['price_per_sqft'] * required_area
return df[['Areas', 'total_price']].groupby('Areas').mean().sort_values(by='total_price', ascending=False)
else:
print("missing_data")
return df
def calc_price_stats(df):
if 'AveragePrice' in df.columns:
area_stats = df.groupby('Areas')['AveragePrice'].agg(['mean', 'median', 'std', 'min', 'max'])
area_stats['coef_var'] = (area_stats['std'] / area_stats['mean']) * 100
return area_stats.sort_values('mean', ascending=False)
return None
#gdp = [7.5, 7.1, 6.8, 6.1, 4.2, 7.3, 8.7, 6.8, 6.0]
#ur = [5.0, 4.9, 4.7, 4.5, 6.1, 7.0, 6.6, 6.3, 5.9]
#money = [10.5, 11.2, 12, 12.8, 13.8, 14.5, 16.3, 17.5, 18.0]
#inflation_rate = [5.5, 5.1, 4.8, 4.6, 4.8, 6.6, 5.3, 6.8, 6.0]
gdp = [7.5, 7.1, 6.8, 6.1, 4.2, 7.3, 8.7, 6.8, 6.0, 7.2, 6.9, 7.0, 6.5, 5.8, 7.8, 8.2, 6.7, 7.4, 6.3, 7.1,
7.6, 6.4, 8.1, 7.9, 6.2, 7.7, 8.3, 6.6, 7.0, 6.8, 7.3, 8.0, 6.1, 7.5, 6.9, 7.2, 8.4, 6.7, 7.1, 6.5]
ur = [5.0, 4.9, 4.7, 4.5, 6.1, 7.0, 6.6, 6.3, 5.9, 5.2, 4.8, 5.1, 5.5, 6.2, 4.6, 4.4, 5.3, 4.9, 5.7, 5.0,
4.7, 5.6, 4.3, 4.5, 5.8, 4.8, 4.2, 5.4, 5.1, 4.9, 5.0, 4.4, 6.0, 4.6, 5.2, 4.8, 4.3, 5.5, 4.9, 5.3]
money = [10.5, 11.2, 12.0, 12.8, 13.8, 14.5, 16.3, 17.5, 18.0, 11.8, 12.5, 13.2, 14.0, 15.2, 11.0, 10.8,
13.5, 12.2, 14.8, 11.5, 10.9, 15.0, 10.7, 11.3, 15.5, 12.0, 10.6, 14.3, 12.8, 11.7, 12.3, 10.5,
16.0, 11.2, 13.0, 12.6, 10.4, 14.6, 12.1, 13.8]
inflation_rate = [5.5, 5.1, 4.8, 4.6, 4.8, 6.6, 5.3, 6.8, 6.0, 5.4, 5.0, 5.2, 5.6, 6.0, 4.9, 4.7, 5.5, 5.1,
5.8, 5.3, 4.9, 5.9, 4.6, 4.8, 6.1, 5.2, 4.5, 5.7, 5.4, 5.1, 5.3, 4.7, 6.3, 4.9, 5.4, 5.2,
4.6, 5.8, 5.2, 5.6]
indf = pd.DataFrame({"gdp growth": gdp, "unemployment": ur, "money_supp": money})
print(indf)
X = StandardScaler().fit_transform(indf)
y = inflation_rate
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42)
base_xgb = XGBRegressor(n_estimators=500, learning_rate=0.3, max_depth=2, random_state=42)
base_ridge = Ridge(alpha=0.4, random_state=42)
stacked_model = StackingRegressor(
estimators=[
('xgb', base_xgb),
('ridge', base_ridge)
],
final_estimator=ElasticNet(alpha=0.1, l1_ratio=0.4, random_state=42, max_iter=3000),
cv=4
)
stacked_model.fit(X_train, y_train)
y_pred = stacked_model.predict(X_test)
y_train_pred = stacked_model.predict(X_train)
r2_test = r2_score(y_test, y_pred)
mse_test = mean_squared_error(y_test, y_pred)
mae_test = mean_absolute_error(y_test, y_pred)
rmse_test = np.sqrt(mse_test)
r2_train = r2_score(y_train, y_train_pred)
mse_train = mean_squared_error(y_train, y_train_pred)
print("\n=== Model Performance Metrics ===")
print(f"Train R2 Score: {r2_train:.4f}")
print(f"Test R2 Score: {r2_test:.4f}")
print(f"Test MSE: {mse_test:.4f}")
print(f"Test RMSE: {rmse_test:.4f}")
print(f"Test MAE: {mae_test:.4f}")
def plot_inflation():
plt.figure(figsize=(6, 4))
sns.lineplot(x=range(len(y_test)), y=y_test, label='Actual', marker='o')
sns.lineplot(x=range(len(y_pred)), y=y_pred, label='Predicted', marker='D')
plt.title("Inflation Rate Prediction")
plt.xlabel("Index")
plt.ylabel("Inflation Rate")
plt.legend()
plt.tight_layout()
plt.show()
plot_inflation()
def Price_vs_inflation():
Prices = np.linspace(50, 100, len(y_pred))
Time = np.linspace(5, 10, len(y_pred))
Time_mesh, Prices_mesh = np.meshgrid(Time, Prices)
Inflation_mesh = np.tile(y_pred, (len(Prices), 1)).T
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(Prices_mesh, Time_mesh, Inflation_mesh, cmap='viridis')
ax.set_xlabel('Average Price (Lakhs)')
ax.set_ylabel('Years')
ax.set_zlabel('Predicted Inflation Rate')
plt.title('Inflated Price')
plt.tight_layout()
plt.show()
print()
print("Future Price Prediction")
user_loc =input("Enter the location ")
user_area=int(input("Enter desired area"))
price=df.loc[df['Areas'] == user_loc, 'AveragePrice'].iloc[0]
area_price = price*user_area
print(user_loc,user_area,area_price)
avg_inflation = np.mean(y_pred) / 100
GrowthRate = 0.08
real_growth = GrowthRate - avg_inflation
for years in [5, 7, 10]:
future_price = area_price * ((1 + real_growth) ** years)
print(f"Price after {years} years: ₹{round(future_price):,}")
def plot_price_difference():
years = [5, 7, 10]
curr_price = area_price
avg_inflation = np.mean(y_pred) / 100
GrowthRate = 0.08
real_growth = GrowthRate- avg_inflation
future_prices = [curr_price * ((1 + real_growth) ** yr) for yr in years]
plt.figure(figsize=(7, 4))
plt.bar([f"{yr} yrs (Now)" for yr in years], [curr_price]*len(years), label='Current Price', alpha=0.6)
plt.bar([f"{yr} yrs (Future)" for yr in years], future_prices, label='Predicted Price', alpha=0.8)
plt.ylabel("Price (INR)")
plt.title("Before vs After Property Price")
plt.xticks(rotation=45)
plt.legend()
plt.tight_layout()
plt.show()
plot_price_difference()
def plot_area_price_heatmap(df):
area_price_df = df[['Areas', 'AveragePrice']].groupby('Areas').mean()
area_price_df = area_price_df.sort_values('AveragePrice', ascending=False)
plt.figure(figsize=(80, 6))
sns.heatmap(area_price_df.T, annot=True, fmt=".0f", cmap="YlOrRd",cbar=True, linewidths=0.8)
plt.title("Average Total Price by Area")
plt.xticks(rotation=45, ha='right', fontsize=10)
plt.tight_layout()
plt.show()
plot_area_price_heatmap(df)
Price_vs_inflation()
def plot_top_areas(df, top_n=15):
area_stats = df.groupby('Areas')['AveragePrice'].agg(['mean', 'count']).reset_index()
area_stats = area_stats.nlargest(top_n, 'mean')
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
sns.barplot(data=area_stats, y='Areas', x='mean', ax=axes[0], palette='rocket')
axes[0].set_xlabel('Average Price per Sqft (INR)', fontsize=11)
axes[0].set_ylabel('Areas', fontsize=11)
axes[0].set_title(f'Top {top_n} Most Expensive Areas', fontsize=12, fontweight='bold')
axes[0].grid(axis='x', alpha=0.3)
sns.scatterplot(data=area_stats, x='mean', y='count', size='mean',
sizes=(50, 500), alpha=0.6, ax=axes[1], legend=False)
axes[1].set_xlabel('Average Price per Sqft (INR)', fontsize=11)
axes[1].set_ylabel('Number of Properties', fontsize=11)
axes[1].set_title('Price vs Property Count', fontsize=12, fontweight='bold')
axes[1].grid(alpha=0.3)
plt.tight_layout()
plt.show()
#plot_top_areas(df)
import pickle
with open('stacked_model.pkl', 'wb') as f:
pickle.dump(stacked_model, f)
with open('y_pred.pkl', 'wb') as f:
pickle.dump(y_pred, f)
with open('y_test.pkl', 'wb') as f:
pickle.dump(y_test, f)
with open('metrics.pkl', 'wb') as f:
pickle.dump({
'r2_train': r2_train,
'r2_test': r2_test,
'mse_test': mse_test,
'rmse_test': rmse_test,
'mae_test': mae_test}, f)