eaglelandsonce commited on
Commit
c15b0e0
·
verified ·
1 Parent(s): 028c091

Update pages/5_RealDataSetRegression.py

Browse files
Files changed (1) hide show
  1. pages/5_RealDataSetRegression.py +109 -101
pages/5_RealDataSetRegression.py CHANGED
@@ -1,107 +1,115 @@
1
  import streamlit as st
2
  import numpy as np
3
  import pandas as pd
4
- import tensorflow as tf
5
- from matplotlib import pyplot as plt
6
-
7
- # Function to build the model
8
- def build_model(my_learning_rate):
9
- model = tf.keras.models.Sequential()
10
- model.add(tf.keras.layers.Dense(units=1, input_shape=(1,)))
11
- model.compile(optimizer=tf.keras.optimizers.RMSprop(learning_rate=my_learning_rate),
12
- loss='mean_squared_error',
13
- metrics=[tf.keras.metrics.RootMeanSquaredError()])
14
- return model
15
-
16
- # Function to train the model
17
- def train_model(model, df, feature, label, epochs, batch_size):
18
- history = model.fit(x=df[feature], y=df[label], batch_size=batch_size, epochs=epochs)
19
- trained_weight = model.get_weights()[0][0]
20
- trained_bias = model.get_weights()[1]
21
- epochs = history.epoch
22
- hist = pd.DataFrame(history.history)
23
- rmse = hist["root_mean_squared_error"]
24
- return trained_weight, trained_bias, epochs, rmse
25
-
26
- # Function to plot the model
27
- def plot_the_model(trained_weight, trained_bias, feature, label, df):
28
- plt.figure(figsize=(10, 6))
29
- plt.xlabel(feature)
30
- plt.ylabel(label)
31
-
32
- random_examples = df.sample(n=200)
33
- plt.scatter(random_examples[feature], random_examples[label])
34
-
35
- x0 = 0
36
- y0 = trained_bias
37
- x1 = random_examples[feature].max()
38
- y1 = trained_bias + (trained_weight * x1)
39
- plt.plot([x0, x1], [y0, y1], c='r')
40
-
41
- st.pyplot(plt)
42
-
43
- # Function to plot the loss curve
44
- def plot_the_loss_curve(epochs, rmse):
45
- plt.figure(figsize=(10, 6))
46
- plt.xlabel("Epoch")
47
- plt.ylabel("Root Mean Squared Error")
48
-
49
- plt.plot(epochs, rmse, label="Loss")
50
- plt.legend()
51
- plt.ylim([rmse.min()*0.97, rmse.max()])
52
- st.pyplot(plt)
53
-
54
- # Load the dataset
55
- @st.cache_data
56
- def load_data():
57
- url = "https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv"
58
- df = pd.read_csv(url)
59
- df["median_house_value"] /= 1000.0
60
- return df
61
-
62
- training_df = load_data()
63
 
64
  # Streamlit interface
65
- st.title("Simple Linear Regression with Real Data")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
- st.write("https://colab.research.google.com/github/google/eng-edu/blob/main/ml/cc/exercises/linear_regression_with_a_real_dataset.ipynb?utm_source=mlcc&utm_campaign=colab-external&utm_medium=referral&utm_content=linear_regression_real_tf2-colab&hl=en")
68
-
69
- if st.checkbox('Show raw data'):
70
- st.write(training_df.head())
71
-
72
- learning_rate = st.sidebar.slider('Learning Rate', min_value=0.001, max_value=1.0, value=0.01, step=0.01)
73
- epochs = st.sidebar.slider('Epochs', min_value=1, max_value=1000, value=30, step=1)
74
- batch_size = st.sidebar.slider('Batch Size', min_value=1, max_value=len(training_df), value=30, step=1)
75
- feature = st.sidebar.selectbox('Select Feature', training_df.columns)
76
- label = 'median_house_value'
77
-
78
- my_model = None # Initialize the model variable
79
-
80
- if st.sidebar.button('Run'):
81
- my_model = build_model(learning_rate)
82
- weight, bias, epochs, rmse = train_model(my_model, training_df, feature, label, epochs, batch_size)
83
-
84
- st.subheader('Model Plot')
85
- plot_the_model(weight, bias, feature, label, training_df)
86
-
87
- st.subheader('Loss Curve')
88
- plot_the_loss_curve(epochs, rmse)
89
-
90
- # Function to make predictions
91
- def predict_house_values(n, feature, label):
92
- batch = training_df[feature][10000:10000 + n]
93
- predicted_values = my_model.predict_on_batch(x=batch)
94
-
95
- st.write("feature label predicted")
96
- st.write(" value value value")
97
- st.write(" in thousand$ in thousand$")
98
- st.write("--------------------------------------")
99
- for i in range(n):
100
- st.write("%5.0f %6.0f %15.0f" % (training_df[feature][10000 + i],
101
- training_df[label][10000 + i],
102
- predicted_values[i][0] ))
103
-
104
- n_predictions = st.sidebar.slider('Number of Predictions', min_value=1, max_value=100, value=10)
105
- if my_model is not None and st.sidebar.button('Predict'):
106
- st.subheader('Predictions')
107
- predict_house_values(n_predictions, feature, label)
 
1
  import streamlit as st
2
  import numpy as np
3
  import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ from sklearn.datasets import load_iris
6
+ from sklearn.model_selection import train_test_split
7
+ from sklearn.preprocessing import StandardScaler
8
+ from sklearn.metrics import accuracy_score, confusion_matrix
9
+ from tensorflow.keras.models import Sequential
10
+ from tensorflow.keras.layers import Dense
11
+ from tensorflow.keras.utils import plot_model
12
+ import io
13
+
14
+ # Load Iris dataset
15
+ iris = load_iris()
16
+ X = iris.data
17
+ y = iris.target
18
+
19
+ # Only use the first two classes for binary classification
20
+ X = X[y != 2]
21
+ y = y[y != 2]
22
+
23
+ # Split the dataset into training and testing sets
24
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
25
+
26
+ # Standardize the data
27
+ scaler = StandardScaler()
28
+ X_train = scaler.fit_transform(X_train)
29
+ X_test = scaler.transform(X_test)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  # Streamlit interface
32
+ st.title('Logistic Regression with Keras on Iris Dataset')
33
+ st.write("""
34
+ ## Introduction
35
+ Logistic Regression is a statistical model used for binary classification tasks.
36
+ In this tutorial, we will use the Iris dataset to classify whether a flower is
37
+ **Setosa** or **Versicolor** based on its features.
38
+ """)
39
+
40
+ # Display Iris dataset information
41
+ st.write("### Iris Dataset")
42
+ st.write("""
43
+ The Iris dataset contains 150 samples of iris flowers, each described by four features:
44
+ sepal length, sepal width, petal length, and petal width. There are three classes: Setosa, Versicolor, and Virginica.
45
+ For this example, we'll only use the Setosa and Versicolor classes.
46
+ """)
47
+ st.write(pd.DataFrame(X, columns=iris.feature_names).head())
48
+
49
+ # Plotting sample data
50
+ st.write("### Sample Data Distribution")
51
+ fig, ax = plt.subplots()
52
+ for i, color in zip([0, 1], ['blue', 'orange']):
53
+ idx = np.where(y == i)
54
+ ax.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i], edgecolor='k')
55
+ ax.set_xlabel(iris.feature_names[0])
56
+ ax.set_ylabel(iris.feature_names[1])
57
+ ax.legend()
58
+ st.pyplot(fig)
59
+
60
+ # User input for number of epochs
61
+ epochs = st.slider('Select number of epochs for training:', min_value=10, max_value=200, value=100, step=10)
62
+
63
+ # Build the logistic regression model using Keras
64
+ model = Sequential()
65
+ model.add(Dense(1, input_dim=4, activation='sigmoid'))
66
+ model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
67
+
68
+ # Display the model architecture
69
+ st.write("### Model Architecture")
70
+ st.write(model.summary())
71
+ fig, ax = plt.subplots()
72
+ buf = io.BytesIO()
73
+ plot_model(model, to_file=buf, show_shapes=True, show_layer_names=True)
74
+ buf.seek(0)
75
+ st.image(buf, caption='Logistic Regression Model Architecture', use_column_width=True)
76
+
77
+ # Train the model
78
+ model.fit(X_train, y_train, epochs=epochs, verbose=0)
79
+
80
+ # Predict and evaluate the model
81
+ y_pred_train = (model.predict(X_train) > 0.5).astype("int32")
82
+ y_pred_test = (model.predict(X_test) > 0.5).astype("int32")
83
+
84
+ train_accuracy = accuracy_score(y_train, y_pred_train)
85
+ test_accuracy = accuracy_score(y_test, y_pred_test)
86
+
87
+ conf_matrix = confusion_matrix(y_test, y_pred_test)
88
+
89
+ st.write('## Model Performance')
90
+ st.write(f'Training Accuracy: {train_accuracy:.2f}')
91
+ st.write(f'Testing Accuracy: {test_accuracy:.2f}')
92
+
93
+ st.write('## Confusion Matrix')
94
+ fig, ax = plt.subplots()
95
+ ax.matshow(conf_matrix, cmap=plt.cm.Blues, alpha=0.3)
96
+ for i in range(conf_matrix.shape[0]):
97
+ for j in range(conf_matrix.shape[1]):
98
+ ax.text(x=j, y=i, s=conf_matrix[i, j], va='center', ha='center')
99
+
100
+ plt.xlabel('Predicted Label')
101
+ plt.ylabel('True Label')
102
+ st.pyplot(fig)
103
+
104
+ st.write('## Make a Prediction')
105
+ sepal_length = st.number_input('Sepal Length (cm)', min_value=0.0, max_value=10.0, value=5.0)
106
+ sepal_width = st.number_input('Sepal Width (cm)', min_value=0.0, max_value=10.0, value=3.5)
107
+ petal_length = st.number_input('Petal Length (cm)', min_value=0.0, max_value=10.0, value=1.4)
108
+ petal_width = st.number_input('Petal Width (cm)', min_value=0.0, max_value=10.0, value=0.2)
109
+
110
+ if st.button('Predict'):
111
+ input_data = np.array([[sepal_length, sepal_width, petal_length, petal_width]])
112
+ input_data_scaled = scaler.transform(input_data)
113
+ prediction = (model.predict(input_data_scaled) > 0.5).astype("int32")
114
+ st.write(f'Prediction: {"Setosa" if prediction[0][0] == 0 else "Versicolor"}')
115