Saadiee commited on
Commit
afd5026
ยท
verified ยท
1 Parent(s): 252804f

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +66 -0
  2. hf_knn_project.py +50 -0
  3. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ from datasets import load_dataset
5
+ from sklearn.preprocessing import StandardScaler
6
+ from sklearn.neighbors import KNeighborsClassifier
7
+ from sklearn.preprocessing import LabelEncoder
8
+
9
+ st.title("๐ŸŒธ AI Flower Species Classification System")
10
+ st.write("Built with **K-Nearest Neighbors (KNN)** and trained using a dataset fetched live from **Hugging Face**.")
11
+
12
+ @st.cache_data
13
+ def load_hf_data():
14
+ dataset = load_dataset("scikit-learn/iris", split="train")
15
+ return pd.DataFrame(dataset)
16
+
17
+ with st.spinner("Fetching dataset from Hugging Face..."):
18
+ df = load_hf_data()
19
+
20
+ st.success("Dataset successfully loaded from Hugging Face!")
21
+
22
+ # Dynamically select features and target
23
+ feature_columns = df.columns[:4]
24
+ target_column = df.columns[-1]
25
+
26
+ X = df[feature_columns]
27
+ y_text = df[target_column]
28
+
29
+ # Convert text labels (Iris-setosa, etc.) into numbers (0, 1, 2) for model and graph coloring
30
+ encoder = LabelEncoder()
31
+ y = encoder.fit_transform(y_text)
32
+
33
+ # Scale and Train KNN Model
34
+ scaler = StandardScaler()
35
+ X_scaled = scaler.fit_transform(X)
36
+
37
+ knn = KNeighborsClassifier(n_neighbors=3)
38
+ knn.fit(X_scaled, y)
39
+
40
+ # Sidebar UI Controls for User Input
41
+ st.sidebar.header("๐ŸŽ›๏ธ Input Flower Measurements")
42
+ inputs = []
43
+ for col in feature_columns:
44
+ val = st.sidebar.slider(f"{col}", float(X[col].min()), float(X[col].max()), float(X[col].mean()))
45
+ inputs.append(val)
46
+
47
+ # Prediction Button
48
+ if st.button("Predict Species"):
49
+ user_input = scaler.transform([inputs])
50
+ pred = knn.predict(user_input)
51
+
52
+ predicted_name = encoder.inverse_transform(pred)[0]
53
+
54
+ st.subheader("โœจ Result:")
55
+ st.success(f"The predicted flower species is: **{predicted_name}**")
56
+
57
+ # Graph Visualization
58
+ st.subheader("๐Ÿ“Š Dataset Visualization & Your Input")
59
+ fig, ax = plt.subplots(figsize=(8, 5))
60
+ scatter = ax.scatter(X.iloc[:, 0], X.iloc[:, 1], c=y, cmap='viridis', s=60, edgecolors='k', label='Dataset Clusters')
61
+ ax.scatter(inputs[0], inputs[1], color='red', marker='X', s=250, label='Your Custom Input')
62
+ ax.set_xlabel(feature_columns[0])
63
+ ax.set_ylabel(feature_columns[1])
64
+ plt.colorbar(scatter, label='Species Code')
65
+ ax.legend()
66
+ st.pyplot(fig)
hf_knn_project.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ from sklearn.model_selection import train_test_split
5
+ from sklearn.preprocessing import StandardScaler
6
+ from sklearn.neighbors import KNeighborsClassifier
7
+ from sklearn.metrics import accuracy_score
8
+
9
+ print("1. Downloading dataset from Hugging Face...")
10
+ # Fetching a clean tabular dataset directly from Hugging Face Hub
11
+ dataset = load_dataset("scikit-learn/iris", split="train")
12
+ df = pd.DataFrame(dataset)
13
+
14
+ # Features (Measurements) and Target (Species)
15
+ X = df[['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']]
16
+ y = df['target']
17
+
18
+ print("2. Splitting and scaling data...")
19
+ # Split into training and testing sets
20
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
21
+
22
+ # Scale features for accurate KNN distance calculations
23
+ scaler = StandardScaler()
24
+ X_train_scaled = scaler.fit_transform(X_train)
25
+ X_test_scaled = scaler.transform(X_test)
26
+
27
+ print("3. Training the KNN Model...")
28
+ # Train KNN with 3 neighbors
29
+ knn = KNeighborsClassifier(n_neighbors=3)
30
+ knn.fit(X_train_scaled, y_train)
31
+
32
+ # Check model accuracy
33
+ y_pred = knn.predict(X_test_scaled)
34
+ print(f"Model Accuracy: {accuracy_score(y_test, y_pred) * 100:.2f}%")
35
+
36
+ # Test a brand new sample prediction
37
+ new_sample = [[5.1, 3.5, 1.4, 0.2]]
38
+ new_sample_scaled = scaler.transform(new_sample)
39
+ prediction = knn.predict(new_sample_scaled)
40
+ print(f"Prediction for new sample [Class]: {prediction[0]}")
41
+
42
+ print("4. Generating Graph...")
43
+ # Simple 2D plot using first two features (Sepal Length vs Sepal Width)
44
+ plt.figure(figsize=(8, 6))
45
+ plt.scatter(df['sepal length (cm)'], df['sepal width (cm)'], c=df['target'], cmap='viridis', s=80, edgecolors='k')
46
+ plt.title("Hugging Face Dataset - KNN Classification (Iris Sepal Dimensions)")
47
+ plt.xlabel("Sepal Length (cm)")
48
+ plt.ylabel("Sepal Width (cm)")
49
+ plt.grid(True)
50
+ plt.show()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ matplotlib
4
+ scikit-learn
5
+ datasets