mjaramillo commited on
Commit
c6eaeda
·
1 Parent(s): 81e8a21

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -62
app.py CHANGED
@@ -1,67 +1,70 @@
1
- # This is a small and fast sklearn model, so the run-gradio script trains a model and deploys it
2
-
3
- import pandas as pd
4
  import numpy as np
5
- import sklearn
6
- import gradio as gr
7
- from sklearn import preprocessing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  from sklearn.model_selection import train_test_split
9
- from sklearn.ensemble import RandomForestClassifier
 
 
 
10
  from sklearn.metrics import accuracy_score
11
 
12
- data = pd.read_csv('https://raw.githubusercontent.com/gradio-app/titanic/master/train.csv')
13
- data.head()
14
-
15
- def encode_ages(df): # Binning ages
16
- df.Age = df.Age.fillna(-0.5)
17
- bins = (-1, 0, 5, 12, 18, 25, 35, 60, 120)
18
- categories = pd.cut(df.Age, bins, labels=False)
19
- df.Age = categories
20
- return df
21
-
22
- def encode_fares(df): # Binning fares
23
- df.Fare = df.Fare.fillna(-0.5)
24
- bins = (-1, 0, 8, 15, 31, 1000)
25
- categories = pd.cut(df.Fare, bins, labels=False)
26
- df.Fare = categories
27
- return df
28
-
29
- def encode_sex(df):
30
- mapping = {"male": 0, "female": 1}
31
- return df.replace({'Sex': mapping})
32
-
33
- def transform_features(df):
34
- df = encode_ages(df)
35
- df = encode_fares(df)
36
- df = encode_sex(df)
37
- return df
38
-
39
- train = data[['PassengerId', 'Fare', 'Age', 'Sex', 'Survived']]
40
- train = transform_features(train)
41
- train.head()
42
-
43
-
44
- X_all = train.drop(['Survived', 'PassengerId'], axis=1)
45
- y_all = train['Survived']
46
-
47
- num_test = 0.20
48
- X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, test_size=num_test, random_state=23)
49
-
50
- clf = RandomForestClassifier()
51
- clf.fit(X_train, y_train)
52
- predictions = clf.predict(X_test)
53
-
54
- def predict_survival(sex, age, fare):
55
- df = pd.DataFrame.from_dict({'Sex': [sex], 'Age': [age], 'Fare': [fare]})
56
- df = encode_sex(df)
57
- df = encode_fares(df)
58
- df = encode_ages(df)
59
- pred = clf.predict_proba(df)[0]
60
- return {'Muere': float(pred[0]), 'Sobrevive': float(pred[1])}
61
-
62
- sex = gr.inputs.Radio(['female', 'male'], label="Sex")
63
- age = gr.inputs.Slider(minimum=0, maximum=100, default=18, label="age")
64
- fare = gr.inputs.Slider(minimum=15, maximum=200, default=100, label="Tarifa en libras britanicas")
65
 
66
- gr.Interface(predict_survival, [sex, age, fare], "label", live=True, thumbnail="https://raw.githubusercontent.com/gradio-app/hub-titanic/master/thumbnail.png", analytics_enabled=False,
67
- title="Probabilidad de supervivencia", description="").launch();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import numpy as np
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ import seaborn as sns
5
+ url = 'https://raw.githubusercontent.com/MiguelJ125/creditcard_Jaramillo/main/Vehicle_policies_2020.csv'
6
+
7
+ df = pd.read_csv(url)
8
+
9
+ df = df.drop(["pol_number"], axis = 1)
10
+ df = df.drop(["claim_office"], axis = 1)
11
+ df = df.drop(["credit_score"], axis = 1)
12
+ df = df.drop(["annual_premium"], axis = 1)
13
+ df = df.drop(["agecat"], axis = 1)
14
+
15
+ df=df.dropna()
16
+
17
+ cleanup_nums = {"area": {"A": 1, "B": 2, "C": 3, "D": 4, "F": 5, "E": 6}}
18
+ df = df.replace(cleanup_nums)
19
+
20
+ from datetime import datetime
21
+
22
+ datetime = pd.to_datetime(df["date_of_birth"])
23
+ df["date_of_birth"] = datetime
24
+ df = df.copy()
25
+
26
+ df['date_of_birth'].dt.year
27
+ ahora = pd.Timestamp('now')
28
+ df['Edad'] = (ahora - df['date_of_birth']).astype('<m8[Y]')
29
+ df = df.drop(["date_of_birth"], axis = 1)
30
+
31
+ df = df.drop(["pol_eff_dt"], axis = 1)
32
+
33
+ df = pd.get_dummies(df, columns = ["gender"], drop_first = True)
34
+
35
+ cleanup_nums = {"veh_body": {"SEDAN": 1, "HBACK": 2, "STNWG": 3, "UTE": 4, "TRUCK": 5, "HDTOP": 6, "COUPE": 7, "PANVN": 8, "MIBUS": 9, "MCARA": 10, "CONVT": 11, "BUS": 12, "RDSTR": 13}}
36
+ df = df.replace(cleanup_nums)
37
+
38
+ df=df.drop(columns = ['claimcst0'])
39
+ X = df.drop(columns = ['numclaims'])
40
+ y = df['numclaims']
41
+
42
+ from sklearn.preprocessing import StandardScaler
43
+ scaler = StandardScaler()
44
+ X = scaler.fit_transform(X)
45
+
46
  from sklearn.model_selection import train_test_split
47
+
48
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=1)
49
+
50
+ from sklearn.tree import DecisionTreeClassifier
51
  from sklearn.metrics import accuracy_score
52
 
53
+ tree = DecisionTreeClassifier(max_depth = None)
54
+ tree.fit(X_train, y_train)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
+ def predict_siniestros(area, traf, vage, tipov, valorv, edad, Gen):
57
+ df = pd.DataFrame.from_dict({'area': [area], 'traffic_indexe': [traf], 'veh_age': [vage], 'veh_body': [tipov], 'veh_value': [valorv], 'Edad': [edad], 'gender_M': [Gen]})
58
+
59
+ pred=tree.predict(df)
60
+ return {'Es posible que tengas que reclamar al seguro': float(pred[0])}
61
+
62
+ area = gr.inputs.Radio(['1', '2', '3', '4', '5', '6'], label="Area: del 1 al 6")
63
+ traf = gr.inputs.Slider(minimum=0, maximum=200, default=100, label="Indice de trafico")
64
+ vage = gr.inputs.Slider(minimum=0, maximum=30, default=1, label="Cantidad de años del vehiculo")
65
+ tipov = gr.inputs.Radio(['1', '2', '3', '4', '5'], label="Tipo de auto (Sedan=1 Hback=2 Family=3 Utilitario=4 Camioneta=5")
66
+ valorv = gr.inputs.Slider(minimum=0, maximum=10, default=1, label="Valor del vehiculo (u$/10.000)")
67
+ edad = gr.inputs.Slider(minimum=16, maximum=100, default=18, label="Edad")
68
+ Gen = gr.inputs.Radio(['1', '0'], label="Genero (F=0 M=1)")
69
+ gr.Interface(predict_siniestros, [area, traf, vage, tipov, valorv, edad, Gen], "label", live=True, thumbnail="https://raw.githubusercontent.com/gradio-app/hub-titanic/master/thumbnail.png", analytics_enabled=False,
70
+ title="Cuantas veces es probable que tengas que reclamar al seguro en el transcurso de un año", description="Predice la cantidad de veces que por algun siniestro deberas acudir al seguro, con el fin de elegir un plan mas adecuado a cada persona").launch();