import streamlit as st import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, confusion_matrix from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense # Load Iris dataset iris = load_iris() X = iris.data y = iris.target # Only use the first two classes for binary classification X = X[y != 2] y = y[y != 2] # Split the dataset into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Standardize the data scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # Build the logistic regression model using Keras model = Sequential() model.add(Dense(1, input_dim=4, activation='sigmoid')) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Train the model model.fit(X_train, y_train, epochs=100, verbose=0) # Predict and evaluate the model y_pred_train = (model.predict(X_train) > 0.5).astype("int32") y_pred_test = (model.predict(X_test) > 0.5).astype("int32") train_accuracy = accuracy_score(y_train, y_pred_train) test_accuracy = accuracy_score(y_test, y_pred_test) conf_matrix = confusion_matrix(y_test, y_pred_test) # Streamlit interface st.title('Logistic Regression with Keras on Iris Dataset') st.write('## Model Performance') st.write(f'Training Accuracy: {train_accuracy:.2f}') st.write(f'Testing Accuracy: {test_accuracy:.2f}') st.write('## Confusion Matrix') fig, ax = plt.subplots() ax.matshow(conf_matrix, cmap=plt.cm.Blues, alpha=0.3) for i in range(conf_matrix.shape[0]): for j in range(conf_matrix.shape[1]): ax.text(x=j, y=i, s=conf_matrix[i, j], va='center', ha='center') plt.xlabel('Predicted Label') plt.ylabel('True Label') st.pyplot(fig) st.write('## Make a Prediction') sepal_length = st.number_input('Sepal Length (cm)', min_value=0.0, max_value=10.0, value=5.0) sepal_width = st.number_input('Sepal Width (cm)', min_value=0.0, max_value=10.0, value=3.5) petal_length = st.number_input('Petal Length (cm)', min_value=0.0, max_value=10.0, value=1.4) petal_width = st.number_input('Petal Width (cm)', min_value=0.0, max_value=10.0, value=0.2) if st.button('Predict'): input_data = np.array([[sepal_length, sepal_width, petal_length, petal_width]]) input_data_scaled = scaler.transform(input_data) prediction = (model.predict(input_data_scaled) > 0.5).astype("int32") st.write(f'Prediction: {"Setosa" if prediction[0][0] == 0 else "Versicolor"}')