genrate Iris data set app
- User
genrate Iris data set app
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
genrate Iris data set app
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The Iris dataset is one of the most popular datasets in machine learning, consisting of measurements from three different species of iris flowers: Setosa, Versicolor, and Virginica. In this guide, I'll walk you through creating an interactive application to visualize and analyze this dataset, as well as build a classification model.
The Iris dataset contains 150 samples (50 for each species) with four features measured for each flower:
This dataset is perfect for beginners in machine learning as it's small, well-structured, and shows clear patterns among the different species[1][2].
Streamlit is an excellent framework for quickly building interactive data apps. Let's create an Exploratory Data Analysis (EDA) app for the Iris dataset.
First, install the required packages:
pip install streamlit pandas numpy matplotlib seaborn scikit-learn
Create a new Python file (e.g., iris_app.py) with the following code:
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.decomposition import PCA
# Set page title
st.title('Iris EDA App')
st.header('Exploratory Data Analysis')
st.subheader('Iris Dataset')
# Load iris dataset
@st.cache_data
def load_data():
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = [iris.target_names[i] for i in iris.target]
return df, iris
df, iris = load_data()
Add functionality to preview the dataset:
# Data preview section
if st.checkbox('Show Dataset'):
st.write("### Iris Dataset")
preview_option = st.radio("Choose Preview Option",
["Head", "Tail", "Sample", "All Data"])
if preview_option == "Head":
st.write(df.head())
elif preview_option == "Tail":
st.write(df.tail())
elif preview_option == "Sample":
st.write(df.sample(10))
else:
st.write(df)
# Dataset information
if st.checkbox('Show Column Names'):
st.write(df.columns.tolist())
if st.checkbox('Show Dimensions'):
st.write(f"Rows: {df.shape}, Columns: {df.shape[1]}")
if st.checkbox('Show Summary Statistics'):
st.write(df.describe())
# Visualizations
st.header("Data Visualization")
# Create a sidebar for visualization options
viz_option = st.selectbox("Select Visualization Type",
["Scatter Plot", "Pair Plot", "Distribution Plot",
"PCA Visualization", "Correlation Heatmap"])
if viz_option == "Scatter Plot":
st.subheader("Scatter Plot")
x_feature = st.selectbox("Select X-axis feature", df.columns[:-1])
y_feature = st.selectbox("Select Y-axis feature",
[col for col in df.columns[:-1] if col != x_feature])
fig, ax = plt.subplots(figsize=(10, 6))
for species in iris.target_names:
subset = df[df['species'] == species]
ax.scatter(subset[x_feature], subset[y_feature], label=species, alpha=0.7)
ax.set_xlabel(x_feature)
ax.set_ylabel(y_feature)
ax.legend()
st.pyplot(fig)
elif viz_option == "Pair Plot":
st.subheader("Pair Plot")
fig = sns.pairplot(df, hue="species", height=2.5)
st.pyplot(fig)
elif viz_option == "Distribution Plot":
st.subheader("Distribution Plot")
feature = st.selectbox("Select feature", df.columns[:-1])
fig, ax = plt.subplots(figsize=(10, 6))
for species in iris.target_names:
subset = df[df['species'] == species]
sns.kdeplot(subset[feature], label=species, ax=ax)
ax.set_xlabel(feature)
ax.set_ylabel("Density")
ax.legend()
st.pyplot(fig)
elif viz_option == "PCA Visualization":
st.subheader("PCA Visualization")
# Apply PCA
pca = PCA(n_components=3)
X_reduced = pca.fit_transform(iris.data)
# Create 3D plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
# Plot each species
for i, species in enumerate(iris.target_names):
indices = iris.target == i
ax.scatter(X_reduced[indices, 0], X_reduced[indices, 1],
X_reduced[indices, 2], label=species)
ax.set_title("First three PCA dimensions")
ax.set_xlabel("1st Eigenvector")
ax.set_ylabel("2nd Eigenvector")
ax.set_zlabel("3rd Eigenvector")
ax.legend()
st.pyplot(fig)
elif viz_option == "Correlation Heatmap":
st.subheader("Correlation Heatmap")
fig, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(df.iloc[:, :-1].corr(), annot=True, cmap='coolwarm', ax=ax)
st.pyplot(fig)
Save your file and run it using this command:
streamlit run iris_app.py
This will launch a local web server and open your app in a web browser[4].
For those who prefer working with Delphi, you can create an Iris Flower Classification app using DelphiFMX and Support Vector Machines:
For a more focused approach on visualizing the Iris dataset with Principal Component Analysis:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris
# Load data
iris = load_iris()
X = iris.data
y = iris.target
# Apply PCA
pca = PCA(n_components=3)
X_reduced = pca.fit_transform(X)
# Create 3D plot
fig = plt.figure(1, figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
# Plot each species
for i, target_name in enumerate(iris.target_names):
indices = y == i
ax.scatter(X_reduced[indices, 0],
X_reduced[indices, 1],
X_reduced[indices, 2],
label=target_name)
ax.set_title("PCA of Iris Dataset")
ax.set_xlabel("1st Principal Component")
ax.set_ylabel("2nd Principal Component")
ax.set_zlabel("3rd Principal Component")
ax.legend()
plt.show()
This visualization helps to see how PCA can transform the 4-dimensional Iris data into 3 dimensions, making the different species more distinguishable[5].
Creating an Iris dataset application is an excellent way to learn data analysis, visualization, and machine learning concepts. The approach outlined in this guide using Streamlit provides a quick and interactive way to explore the dataset, visualize patterns, and build classification models.
For more advanced applications, consider adding features like:
By working with this classic dataset, you'll gain valuable skills that can be applied to more complex machine learning projects in the future.
# Machine Learning Model Section
st.header("Iris Flower Classification")
# Create tabs for model selection
model_tab = st.radio("Select Model", ["K-Nearest Neighbors", "Support Vector Machine"])
# Feature selection
st.subheader("Feature Selection")
sepal_length = st.slider("Sepal Length (cm)", float(df["sepal length (cm)"].min()),
float(df["sepal length (cm)"].max()),
float(df["sepal length (cm)"].mean()))
sepal_width = st.slider("Sepal Width (cm)", float(df["sepal width (cm)"].min()),
float(df["sepal width (cm)"].max()),
float(df["sepal width (cm)"].mean()))
petal_length = st.slider("Petal Length (cm)", float(df["petal length (cm)"].min()),
float(df["petal length (cm)"].max()),
float(df["petal length (cm)"].mean()))
petal_width = st.slider("Petal Width (cm)", float(df["petal width (cm)"].min()),
float(df["petal width (cm)"].max()),
float(df["petal width (cm)"].mean()))
# User input as a dataframe
user_input = pd.DataFrame({
'sepal length (cm)': [sepal_length],
'sepal width (cm)': [sepal_width],
'petal length (cm)': [petal_length],
'petal width (cm)': [petal_width]
})
# Display the user input
st.write("### User Input Features")
st.write(user_input)
# Model Training and Prediction
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
if model_tab == "K-Nearest Neighbors":
n_neighbors = st.slider("n_neighbors", 1, 20, 5)
model = KNeighborsClassifier(n_neighbors=n_neighbors)
else:
model = SVC()
model.fit(X_train, y_train)
# Make prediction
prediction = model.predict(user_input)
prediction_species = iris.target_names[prediction]
# Display prediction
st.subheader("Prediction")
st.write(f"The model predicts this flower is: **{prediction_species}**")
# Display decision boundaries (for 2D visualization)
st.subheader("Model Decision Boundaries")
st.write("Visualizing decision boundaries using two features:")
feature1 = st.selectbox("Select first feature", df.columns[:-1], index=0)
feature2 = st.selectbox("Select second feature", df.columns[:-1], index=1)
# Get indices of the selected features
feature_indices = [
list(df.columns).index(feature1),
list(df.columns).index(feature2)
]
# Create mesh grid
x_min, x_max = X[:, feature_indices].min() - 1, X[:, feature_indices].max() + 1
y_min, y_max = X[:, feature_indices[1]].min() - 1, X[:, feature_indices[1]].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
# Train model on selected features only
model_2d = SVC() if model_tab == "Support Vector Machine" else KNeighborsClassifier(n_neighbors=n_neighbors)
model_2d.fit(X[:, feature_indices], y)
# Make predictions on mesh grid
Z = model_2d.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# Plot decision boundaries
fig, ax = plt.subplots(figsize=(10, 8))
ax.contourf(xx, yy, Z, alpha=0.3)
# Plot training points
for i, species in enumerate(iris.target_names):
indices = y == i
ax.scatter(X[indices, feature_indices], X[indices, feature_indices[1]],
label=species, edgecolors='k')
ax.set_xlabel(feature1)
ax.set_ylabel(feature2)
ax.set_title(f'Decision Boundaries ({model_tab})')
ax.legend()
st.pyplot(fig)