-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpenguins_streamlit.py
164 lines (145 loc) · 4.73 KB
/
penguins_streamlit.py
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
import pickle
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import streamlit as st
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
st.title("Penguin Classifier")
st.write(
"""This app uses 6 inputs to predict
the species of penguin using a model
built on the Palmer's Penguins dataset.
Use the form below to get started!"""
)
password_guess = st.text_input("What is the Password?")
if password_guess != st.secrets["password"]:
st.stop()
penguin_file = st.file_uploader("Upload your own penguin data")
if penguin_file is None:
rf_pickle = open("random_forest_penguin.pickle", "rb")
map_pickle = open("output_penguin.pickle", "rb")
rfc = pickle.load(rf_pickle)
unique_penguin_mapping = pickle.load(map_pickle)
rf_pickle.close()
map_pickle.close()
penguin_df = pd.read_csv("penguins.csv")
else:
penguin_df = pd.read_csv(penguin_file)
penguin_df = penguin_df.dropna()
output = penguin_df["species"]
features = penguin_df[
[
"island",
"bill_length_mm",
"bill_depth_mm",
"flipper_length_mm",
"body_mass_g",
"sex",
]
]
features_dummies = pd.get_dummies(features)
output, unique_penguin_mapping = pd.factorize(output)
x_train, x_test, y_train, y_test = train_test_split(features_dummies, output, test_size=0.8)
rfc = RandomForestClassifier(random_state=15)
rfc.fit(x_train, y_train)
y_pred = rfc.predict(x_test)
score = round(accuracy_score(y_pred, y_test), 2)
st.write(
f"""We trained a Random Forest model on these data,
it has a score of {score}! Use the
inputs below to try out the model"""
)
with st.form("user_inputs"):
island = st.selectbox("Penguin Island", options=["Biscoe", "Dream", "Torgerson"])
sex = st.selectbox("Sex", options=["Female", "Male"])
bill_length = st.number_input("Bill Length (mm)", min_value=0)
bill_depth = st.number_input("Bill Depth (mm)", min_value=0)
flipper_length = st.number_input("Flipper Length (mm)", min_value=0)
body_mass = st.number_input("Body Mass (g)", min_value=0)
st.form_submit_button()
island_biscoe, island_dream, island_torgerson = 0, 0, 0
if island == "Biscoe":
island_biscoe = 1
elif island == "Dream":
island_dream = 1
elif island == "Torgerson":
island_torgerson = 1
sex_female, sex_male = 0, 0
if sex == "Female":
sex_female = 1
elif sex == "Male":
sex_male = 1
new_prediction = rfc.predict(
[
[
bill_length,
bill_depth,
flipper_length,
body_mass,
island_biscoe,
island_dream,
island_torgerson,
sex_female,
sex_male,
]
]
)
st.subheader("Predicting Your Penguin's Species:")
prediction_species = unique_penguin_mapping[new_prediction][0]
st.write(f"We predict your penguin is of the {prediction_species} species.")
st.subheader(f"{prediction_species}")
st.write(
"""We used a machine learning
(Random Forest) model to predict the
species, the features used in this
prediction are ranked by relative
importance below."""
)
if penguin_file is None:
st.image("feature_importance.png")
else:
features = penguin_df[
[
"island",
"bill_length_mm",
"bill_depth_mm",
"flipper_length_mm",
"body_mass_g",
"sex",
]
]
fig, ax = plt.subplots()
ax = sns.barplot(x=rfc.feature_importances_, y=features.columns)
plt.title("Which features are the most important for species prediction?")
plt.xlabel("Importance")
plt.ylabel("Feature")
plt.tight_layout()
st.write(
"""Below are the histograms for each
continuous variable separated by penguin species.
The vertical line represents the inputted value."""
)
fig, ax = plt.subplots()
ax = sns.displot(x=penguin_df["bill_length_mm"], hue=penguin_df["species"])
plt.axvline(bill_length, color="red")
plt.title("Bill Length by Species")
st.pyplot(ax)
fig, ax = plt.subplots()
ax = sns.displot(x=penguin_df["bill_depth_mm"], hue=penguin_df["species"])
plt.axvline(bill_depth, color="red")
plt.title("Bill Depth by Species")
st.pyplot(ax)
fig, ax = plt.subplots()
ax = sns.displot(x=penguin_df["flipper_length_mm"], hue=penguin_df["species"])
plt.axvline(flipper_length, color="red")
plt.title("Flipper Length by Species")
st.pyplot(ax)
fig, ax = plt.subplots()
ax = sns.displot(x=penguin_df["body_mass_g"], hue=penguin_df["species"])
plt.axvline(body_mass, color="red")
plt.title("Body Mass by Species")
st.pyplot(ax)
st.write(penguin_df.head())
st.write(unique_penguin_mapping)