iamironman4279 commited on
Commit
45d5669
·
verified ·
1 Parent(s): 7bf6b63

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -101
app.py CHANGED
@@ -1,104 +1,50 @@
1
- # Gradio Implementation: Lenix Carter
2
- # License: BSD 3-Clause or CC-0
3
-
4
- import gradio as gr
5
  import numpy as np
6
- import matplotlib
7
- import matplotlib.pyplot as plt
8
-
9
- from sklearn import datasets
10
  from sklearn.model_selection import train_test_split
11
- from sklearn.decomposition import PCA
12
- from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
13
- from sklearn.neighbors import KNeighborsClassifier, NeighborhoodComponentsAnalysis
14
- from sklearn.pipeline import make_pipeline
15
- from sklearn.preprocessing import StandardScaler
16
-
17
- matplotlib.use('agg')
18
-
19
- def reduce_dimensions(n_neighbors, random_state):
20
- # Load Digits dataset
21
- X, y = datasets.load_digits(return_X_y=True)
22
-
23
- # Split into train/test
24
- X_train, X_test, y_train, y_test = train_test_split(
25
- X, y, test_size=0.5, stratify=y, random_state=random_state
26
- )
27
-
28
- dim = len(X[0])
29
- n_classes = len(np.unique(y))
30
-
31
- # Reduce dimension to 2 with PCA
32
- pca = make_pipeline(StandardScaler(), PCA(n_components=2, random_state=random_state))
33
-
34
- # Reduce dimension to 2 with LinearDiscriminantAnalysis
35
- lda = make_pipeline(StandardScaler(), LinearDiscriminantAnalysis(n_components=2))
36
-
37
- # Reduce dimension to 2 with NeighborhoodComponentAnalysis
38
- nca = make_pipeline(
39
- StandardScaler(),
40
- NeighborhoodComponentsAnalysis(n_components=2, random_state=random_state),
41
- )
42
-
43
- # Use a nearest neighbor classifier to evaluate the methods
44
- knn = KNeighborsClassifier(n_neighbors=n_neighbors)
45
-
46
- # Make a list of the methods to be compared
47
- dim_reduction_methods = [("PCA", pca), ("LDA", lda), ("NCA", nca)]
48
-
49
- dim_red_graphs = []
50
-
51
- for i, (name, model) in enumerate(dim_reduction_methods):
52
- new = plt.figure()
53
-
54
- # Fit the method's model
55
- model.fit(X_train, y_train)
56
-
57
- # Fit a nearest neighbor classifier on the embedded training set
58
- knn.fit(model.transform(X_train), y_train)
59
-
60
- # Compute the nearest neighbor accuracy on the embedded test set
61
- acc_knn = knn.score(model.transform(X_test), y_test)
62
-
63
- # Embed the data set in 2 dimensions using the fitted model
64
- X_embedded = model.transform(X)
65
-
66
- # Plot the projected points and show the evaluation score
67
- plt.scatter(X_embedded[:, 0], X_embedded[:, 1], c=y, s=30, cmap="Set1")
68
- plt.title(
69
- "{}, KNN (k={})\nTest accuracy = {:.2f}".format(name, n_neighbors, acc_knn)
70
- )
71
- dim_red_graphs.append(new)
72
- return dim_red_graphs
73
-
74
- title = "Dimensionality Reduction with Neighborhood Components Analysis"
75
- with gr.Blocks() as demo:
76
- gr.Markdown(f" # {title}")
77
- gr.Markdown("""
78
- This example performs and displays the results of Principal Component Analysis, Linear Descriminant Analysis, and Neighborhood Component Analysis on the Digits dataset.
79
-
80
- The result shows that NCA produces visually meaningful clustering.
81
-
82
- This based on the example [here](https://scikit-learn.org/stable/auto_examples/neighbors/plot_nca_dim_reduction.html#sphx-glr-auto-examples-neighbors-plot-nca-dim-reduction-py)
83
- """)
84
- with gr.Row():
85
- n_neighbors = gr.Slider(2, 10, 3, step=1, label="Number of Neighbors for KNN")
86
- random_state = gr.Slider(0, 100, 0, step=1, label="Random State")
87
- with gr.Row():
88
- pca_graph = gr.Plot(label="PCA")
89
- lda_graph = gr.Plot(label="LDA")
90
- nca_graph = gr.Plot(label="NCA")
91
- n_neighbors.change(
92
- fn=reduce_dimensions,
93
- inputs=[n_neighbors, random_state],
94
- outputs=[pca_graph, lda_graph, nca_graph]
95
- )
96
- random_state.change(
97
- fn=reduce_dimensions,
98
- inputs=[n_neighbors, random_state],
99
- outputs=[pca_graph, lda_graph, nca_graph]
100
- )
101
-
102
  if __name__ == '__main__':
103
- demo.launch()
104
-
 
 
 
 
 
 
 
 
 
 
 
 
1
  import numpy as np
2
+ import pandas as pd
 
 
 
3
  from sklearn.model_selection import train_test_split
4
+ from sklearn.linear_model import LinearRegression
5
+ import streamlit as st
6
+ def preprocess_data(df):
7
+ df.replace({'sex': {'male': 0, 'female': 1}}, inplace=True)
8
+ df.replace({'smoker': {'yes': 0, 'no': 1}}, inplace=True)
9
+ df.replace({'region': {'southeast': 0, 'southwest': 1, 'northwest': 2, 'northeast': 3}}, inplace=True)
10
+ def calculate_bmi(weight, height):
11
+ if height == 0:
12
+ return 0
13
+ height_in_meters = height / 100
14
+ bmi = weight / (height_in_meters ** 2)
15
+ return bmi
16
+ def main():
17
+ st.title("Medical Insurance Prediction Model")
18
+ st.sidebar.header('USER INPUT PARAMETERS')
19
+ p1 = st.sidebar.slider("Enter Your Age", 18, 100)
20
+ s1 = st.sidebar.selectbox("Sex", ["Male", "Female"])
21
+ p2 = 1 if s1 == "Male" else 0
22
+ weight = st.sidebar.number_input("Enter Your Weight (kg)", min_value=0.0, max_value=200.0)
23
+ height_feet = st.sidebar.number_input("Enter Your Height (feet)", min_value=0.0, max_value=8.0)
24
+ height_cm = height_feet * 30.48
25
+ calculated_bmi = calculate_bmi(weight, height_cm)
26
+ p3_placeholder = st.sidebar.empty()
27
+ p3_placeholder.text(f"Calculated BMI: {round(calculated_bmi, 2)}")
28
+ p3 = st.sidebar.number_input("this is Your BMI Value", float(calculated_bmi), float(medical_df['bmi'].max()))
29
+ p4 = st.sidebar.slider("Enter Number of Children", 0, 5)
30
+ s2 = st.sidebar.selectbox("Smoker", ["Yes", "No"])
31
+ p5 = 1 if s2 == "Yes" else 0
32
+ region_mapping = {0: 'Southeast', 1: 'Southwest', 2: 'Northwest', 3: 'Northeast'}
33
+ region_options = list(region_mapping.values())
34
+ p6 = st.sidebar.selectbox("Enter Your Region", region_options)
35
+ if st.sidebar.button('Predict'):
36
+ p6_numeric = list(region_mapping.keys())[list(region_mapping.values()).index(p6)]
37
+ input_data = np.array([p1, p2, calculated_bmi, p4, p5, p6_numeric]).reshape(1, -1)
38
+ prediction = lg.predict(input_data)
39
+ st.balloons()
40
+ st.success(f'Medical Insurance prediction : {round(prediction[0], 2)}')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  if __name__ == '__main__':
42
+ csv_file_path = 'insurance.csv'
43
+ medical_df = pd.read_csv(csv_file_path)
44
+ preprocess_data(medical_df)
45
+ X = medical_df.drop('charges', axis=1)
46
+ y = medical_df['charges']
47
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=2)
48
+ lg = LinearRegression()
49
+ lg.fit(X_train, y_train)
50
+ main()