Spaces:
Runtime error
Runtime error
Commit
·
513afb6
1
Parent(s):
f4ca2fd
Create new file
Browse files
app.py
ADDED
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
import gradio as gr
|
5 |
+
import pandas as pd
|
6 |
+
import tarfile
|
7 |
+
import urllib.request
|
8 |
+
|
9 |
+
|
10 |
+
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/"
|
11 |
+
HOUSING_PATH = os.path.join("datasets", "housing")
|
12 |
+
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz"
|
13 |
+
|
14 |
+
def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
|
15 |
+
if not os.path.isdir(housing_path):
|
16 |
+
os.makedirs(housing_path)
|
17 |
+
tgz_path = os.path.join(housing_path, "housing.tgz")
|
18 |
+
urllib.request.urlretrieve(housing_url, tgz_path)
|
19 |
+
housing_tgz = tarfile.open(tgz_path)
|
20 |
+
housing_tgz.extractall(path=housing_path)
|
21 |
+
housing_tgz.close()
|
22 |
+
|
23 |
+
|
24 |
+
|
25 |
+
def load_housing_data(housing_path=HOUSING_PATH):
|
26 |
+
csv_path = os.path.join(housing_path, "housing.csv")
|
27 |
+
return pd.read_csv(csv_path)
|
28 |
+
|
29 |
+
|
30 |
+
#1. Download the data
|
31 |
+
|
32 |
+
fetch_housing_data()
|
33 |
+
|
34 |
+
housing_pd = load_housing_data()
|
35 |
+
housing_pd.head()
|
36 |
+
|
37 |
+
## tentatively drop categorical feature
|
38 |
+
housing = housing_pd.drop('ocean_proximity', axis=1)
|
39 |
+
housing
|
40 |
+
|
41 |
+
|
42 |
+
|
43 |
+
#2. Prepare the Data for Machine Learning Algorithms
|
44 |
+
## 1. split data to get train and test set
|
45 |
+
from sklearn.model_selection import train_test_split
|
46 |
+
train_set, test_set = train_test_split(housing, test_size=0.2, random_state=10)
|
47 |
+
|
48 |
+
## 2. clean the missing values
|
49 |
+
train_set_clean = train_set.dropna(subset=["total_bedrooms"])
|
50 |
+
train_set_clean
|
51 |
+
|
52 |
+
## 2. derive training features and training labels
|
53 |
+
train_labels = train_set_clean["median_house_value"].copy() # get labels for output label Y
|
54 |
+
train_features = train_set_clean.drop("median_house_value", axis=1) # drop labels to get features X for training set
|
55 |
+
|
56 |
+
|
57 |
+
## 4. scale the numeric features in training set
|
58 |
+
from sklearn.preprocessing import MinMaxScaler
|
59 |
+
scaler = MinMaxScaler() ## define the transformer
|
60 |
+
scaler.fit(train_features) ## call .fit() method to calculate the min and max value for each column in dataset
|
61 |
+
|
62 |
+
train_features_normalized = scaler.transform(train_features)
|
63 |
+
train_features_normalized
|
64 |
+
|
65 |
+
#3. Training ML model on the Training Set
|
66 |
+
|
67 |
+
from sklearn.linear_model import LinearRegression ## import the LinearRegression Function
|
68 |
+
lin_reg = LinearRegression() ## Initialize the class
|
69 |
+
lin_reg.fit(train_features_normalized, train_labels) # feed the training data X, and label Y for supervised learning
|
70 |
+
|
71 |
+
|
72 |
+
|
73 |
+
### visualize the data
|
74 |
+
def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
|
75 |
+
path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
|
76 |
+
print("Saving figure", fig_id, ' to ',path)
|
77 |
+
if tight_layout:
|
78 |
+
plt.tight_layout()
|
79 |
+
plt.savefig(path, format=fig_extension, dpi=resolution)
|
80 |
+
|
81 |
+
PROJECT_ROOT_DIR='./'
|
82 |
+
IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images")
|
83 |
+
os.makedirs(IMAGES_PATH, exist_ok=True)
|
84 |
+
|
85 |
+
images_path = os.path.join(PROJECT_ROOT_DIR, "images", "end_to_end_project")
|
86 |
+
os.makedirs(images_path, exist_ok=True)
|
87 |
+
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/"
|
88 |
+
filename = "california.png"
|
89 |
+
print("Downloading", filename)
|
90 |
+
url = DOWNLOAD_ROOT + "images/end_to_end_project/" + filename
|
91 |
+
urllib.request.urlretrieve(url, os.path.join(images_path, filename))
|
92 |
+
|
93 |
+
|
94 |
+
### written by Jie
|
95 |
+
def draw_map_customize(longitude,latitude, fig_id='test',fig_extension='png' ):
|
96 |
+
import matplotlib.image as mpimg
|
97 |
+
california_img=mpimg.imread(os.path.join(images_path, filename))
|
98 |
+
ax = housing.plot(kind="scatter", x="longitude", y="latitude", figsize=(10,7),
|
99 |
+
s=housing['population']/100, label="Population",
|
100 |
+
c="median_house_value", cmap=plt.get_cmap("jet"),
|
101 |
+
colorbar=False, alpha=0.4)
|
102 |
+
plt.imshow(california_img, extent=[-124.55, -113.80, 32.45, 42.05], alpha=0.5,
|
103 |
+
cmap=plt.get_cmap("jet"))
|
104 |
+
plt.ylabel("Latitude", fontsize=18)
|
105 |
+
plt.xlabel("Longitude", fontsize=18)
|
106 |
+
|
107 |
+
plt.xticks(fontsize=18, rotation=0)
|
108 |
+
plt.yticks(fontsize=18, rotation=0)
|
109 |
+
|
110 |
+
|
111 |
+
plt.plot(longitude,latitude, "ro", alpha=0.7, marker=r'$\clubsuit$', markersize=30)
|
112 |
+
|
113 |
+
plt.annotate("Your location is here", xy=(longitude,latitude), xytext=(longitude+1,latitude+1), fontsize=20,
|
114 |
+
arrowprops=dict(arrowstyle="->"))
|
115 |
+
|
116 |
+
|
117 |
+
prices = housing["median_house_value"]
|
118 |
+
tick_values = np.linspace(prices.min(), prices.max(), 11)
|
119 |
+
cbar = plt.colorbar(ticks=tick_values/prices.max())
|
120 |
+
cbar.ax.set_yticklabels(["$%dk"%(round(v/1000)) for v in tick_values], fontsize=14)
|
121 |
+
cbar.set_label('Median House Value', fontsize=16)
|
122 |
+
|
123 |
+
plt.legend(fontsize=16)
|
124 |
+
save_fig(fig_id)
|
125 |
+
#plt.show()
|
126 |
+
|
127 |
+
path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
|
128 |
+
return path
|
129 |
+
|
130 |
+
|
131 |
+
|
132 |
+
def get_sample_data(num_data):
|
133 |
+
sample_data = []
|
134 |
+
for i in range(num_data):
|
135 |
+
samp = housing.sample(1)
|
136 |
+
longitude = float(samp['longitude'].values[0])
|
137 |
+
latitude = float(samp['latitude'].values[0])
|
138 |
+
housing_median_age = float(samp['housing_median_age'].values[0])
|
139 |
+
total_rooms = float(samp['total_rooms'].values[0])
|
140 |
+
total_bedrooms = float(samp['total_bedrooms'].values[0])
|
141 |
+
population = float(samp['population'].values[0])
|
142 |
+
households = float(samp['households'].values[0])
|
143 |
+
median_income = float(samp['median_income'].values[0])
|
144 |
+
|
145 |
+
sample_data.append([longitude,latitude,housing_median_age,total_rooms,total_bedrooms,population,households,median_income])
|
146 |
+
return sample_data
|
147 |
+
|
148 |
+
|
149 |
+
def predict_price(longitude,latitude,housing_median_age,total_rooms,total_bedrooms,population,households,median_income):
|
150 |
+
# initialize data of lists.
|
151 |
+
data = {'longitude':float(longitude),
|
152 |
+
'latitude':float(latitude),
|
153 |
+
'housing_median_age':float(housing_median_age),
|
154 |
+
'total_rooms':float(total_rooms),
|
155 |
+
'total_bedrooms':float(total_bedrooms),
|
156 |
+
'population':float(population),
|
157 |
+
'households':float(households),
|
158 |
+
'median_income':float(median_income),
|
159 |
+
}
|
160 |
+
test_features = pd.DataFrame(columns=['longitude', 'latitude', 'housing_median_age', 'total_rooms',
|
161 |
+
'total_bedrooms', 'population', 'households', 'median_income'])
|
162 |
+
# Create DataFrame
|
163 |
+
test_features = test_features.append(data,ignore_index=True)
|
164 |
+
test_features = test_features.dropna(subset=["total_bedrooms"])
|
165 |
+
|
166 |
+
## 3. scale the numeric features in test set.
|
167 |
+
## important note: do not apply fit function on the test set, using same scalar from training set
|
168 |
+
test_features_normalized = scaler.transform(test_features)
|
169 |
+
test_features_normalized
|
170 |
+
|
171 |
+
pred = lin_reg.predict(test_features_normalized)[0]
|
172 |
+
|
173 |
+
map_file = draw_map_customize(longitude,latitude, fig_id='test',fig_extension='png' )
|
174 |
+
|
175 |
+
return pred,map_file
|
176 |
+
|
177 |
+
|
178 |
+
### configure inputs/outputs
|
179 |
+
|
180 |
+
|
181 |
+
set_longitude = gr.inputs.Slider(-124.350000, -114.310000, step=0.5, default=-120, label = 'Longitude')
|
182 |
+
set_latitude = gr.inputs.Slider(32, 41, step=0.5, default=33, label = 'Latitude')
|
183 |
+
set_housing_median_age = gr.inputs.Slider(1, 52, step=1, default=10, label = 'Housing_median_age (Year)')
|
184 |
+
set_total_rooms = gr.inputs.Slider(1, 40000, step=5, default=10000, label = 'Total_rooms')
|
185 |
+
set_total_bedrooms = gr.inputs.Slider(1, 6445, step=5, default=5000, label = 'Total_bedrooms')
|
186 |
+
set_population = gr.inputs.Slider(3, 35682, step=5, default=10, label = 'Population')
|
187 |
+
set_households = gr.inputs.Slider(1, 6082, step=5, default=10, label = 'Households')
|
188 |
+
set_median_income = gr.inputs.Slider(0, 15, step=0.5, default=10, label = 'Median_income')
|
189 |
+
|
190 |
+
|
191 |
+
|
192 |
+
set_label = gr.outputs.Textbox(label="Predicted Housing Prices")
|
193 |
+
|
194 |
+
# define output as the single class text
|
195 |
+
set_out_images = gr.outputs.Image(label="Closest Neighbors")
|
196 |
+
|
197 |
+
|
198 |
+
### configure gradio, detailed can be found at https://www.gradio.app/docs/#i_slider
|
199 |
+
interface = gr.Interface(fn=predict_price,
|
200 |
+
inputs=[set_longitude, set_latitude,set_housing_median_age,set_total_rooms,set_total_bedrooms,set_population,set_households,set_median_income],
|
201 |
+
outputs=[set_label,set_out_images],
|
202 |
+
examples_per_page = 2,
|
203 |
+
examples = get_sample_data(10),
|
204 |
+
title="CSCI4750/5750 Demo 3: Web Application for Housing Price Prediction",
|
205 |
+
description= "Click examples below for a quick demo",
|
206 |
+
theme = 'huggingface',
|
207 |
+
layout = 'vertical'
|
208 |
+
)
|
209 |
+
interface.launch(debug=True)
|