jackesfonseca commited on
Commit
2f15ada
·
1 Parent(s): 955485e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -0
app.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ from PIL import Image
4
+ import requests
5
+ from pathlib import Path
6
+ import torch, numpy as np, pandas as pd
7
+ from fastai.data.transforms import RandomSplitter
8
+ from torch import tensor
9
+
10
+ def car_purchase():
11
+ np.set_printoptions(linewidth=140)
12
+ torch.set_printoptions(linewidth=140, sci_mode=False, edgeitems=7)
13
+ pd.set_option('display.width', 140)
14
+
15
+ path = Path('/dataset')
16
+
17
+ df = pd.read_csv(path/'Car_Purchasing_Data.csv')
18
+
19
+ df = df.drop(columns=['Customer Name', 'Customer e-mail', 'Country'])
20
+
21
+ gender = sorted(df.Gender.unique())
22
+
23
+ df.rename(columns={'Gender': 'gender',
24
+ 'Age': 'age',
25
+ 'Annual Salary': 'annual_salary',
26
+ 'Credit Card Debt': 'credit_card_debt',
27
+ 'Net Worth': 'net_worth',
28
+ 'Car Purchase Amount': 'car_purchase_amount'},
29
+ inplace=True)
30
+
31
+ t_dep = tensor(df.car_purchase_amount)
32
+
33
+ indep_cols = ['gender', 'age', 'annual_salary', 'credit_card_debt', 'car_purchase_amount']
34
+ t_indep = tensor(df[indep_cols].values, dtype=torch.float)
35
+
36
+
37
+ torch.manual_seed(390)
38
+
39
+ n_coeff = t_indep.shape[1]
40
+ coeffs = torch.rand(n_coeff)-0.5
41
+
42
+ vals, indices = t_indep.max(dim=0)
43
+ vals_d, indices_d = t_dep.max(dim=0)
44
+ t_indep = t_indep / vals
45
+ t_dep = t_dep / vals_d
46
+
47
+ def calc_preds(coeffs, indeps):
48
+ return (indeps*coeffs).sum(axis=1)
49
+
50
+ def calc_loss(coeffs, indeps, deps):
51
+ return torch.abs(calc_preds(coeffs, indeps)-deps).mean()
52
+
53
+ coeffs.requires_grad_()
54
+
55
+ loss = calc_loss(coeffs, t_indep, t_dep).to(dtype=torch.float32)
56
+
57
+ loss.backward()
58
+
59
+ coeffs.grad
60
+
61
+ with torch.no_grad():
62
+ coeffs.sub_(coeffs.grad * 0.1)
63
+ coeffs.grad.zero_()
64
+ print(calc_loss(coeffs, t_indep, t_dep).to(dtype=torch.float32))
65
+
66
+ trn_split,val_split=RandomSplitter(seed=42)(df)
67
+
68
+ trn_indep,val_indep = t_indep[trn_split],t_indep[val_split]
69
+ trn_dep,val_dep = t_dep[trn_split],t_dep[val_split]
70
+ len(trn_indep),len(val_indep)
71
+
72
+ def update_coeffs(coeffs, lr):
73
+ coeffs.sub_(coeffs.grad * lr)
74
+ coeffs.grad.zero_()
75
+
76
+ def one_epoch(coeffs, lr):
77
+ loss = calc_loss(coeffs, trn_indep, trn_dep)
78
+ loss.backward()
79
+ with torch.no_grad(): update_coeffs(coeffs, lr)
80
+ print(f"{loss:.3f}", end="; ")
81
+
82
+ def init_coeffs():
83
+ return (torch.rand(n_coeff)-0.5).requires_grad_()
84
+
85
+ def train_model(epochs, lr):
86
+ torch.manual_seed(442)
87
+ coeffs = init_coeffs()
88
+ for i in range(epochs): one_epoch(coeffs, lr=lr)
89
+ return coeffs
90
+
91
+ coeffs = train_model(6, lr=0.2)
92
+
93
+ def show_coeffs():
94
+ return dict(zip(indep_cols, coeffs.requires_grad_(False)))
95
+
96
+ show_coeffs()
97
+
98
+ demo = gr.Interface(
99
+ fn=car_purchase,
100
+ title="Car Purchase Analytics",
101
+ description="Experiment with the features to predict car purchase amount.",
102
+ allow_flagging="never",
103
+ inputs=[
104
+ gr.inputs.Number(default=30.0, label="Age"),
105
+ gr.inputs.Radio(['female', 'male'], label="Sex"),
106
+
107
+ gr.inputs.Number(default=1.0, label="Annual Salary"),
108
+ gr.inputs.Number(default=1.0, label="Credit Card Debt"),
109
+ gr.inputs.Number(default=1.0, label="Credit Card Debt"),
110
+ ],
111
+ outputs=gr.Image(type="pil"))
112
+
113
+ demo.launch()