# -*- coding: utf-8 -*-
"""K-Means clustering with Prediction, Test Score and Confusion Matrix2.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1PhxwPtvymskRZcO18J6px8vkMhN1KNUR
"""

# Importing required libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import confusion_matrix, accuracy_score

# Load the Iris dataset
data = pd.read_csv("/content/Irisdata.csv")

# Selecting features (independent variables)
X = data.iloc[:, [1, 2, 3, 4]].values

# Extracting actual target labels (species)
y = data.iloc[:, 5].values

# Encoding string labels into numbers
le = LabelEncoder()
y_encoded = le.fit_transform(y)

# Finding the optimal number of clusters using the Elbow method
wcss = []
for i in range(1, 11):
    kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=0)
    kmeans.fit(X)
    wcss.append(kmeans.inertia_)

# Plotting the Elbow graph
plt.plot(range(1, 11), wcss, marker='o')
plt.title('The Elbow Method')
plt.xlabel('Number of Clusters')
plt.ylabel('WCSS (Within Cluster Sum of Squares)')
plt.show()

# Applying K-Means with 3 clusters (based on Elbow method)
kmeans = KMeans(n_clusters=3, init='k-means++', max_iter=300, n_init=10, random_state=0)
y_kmeans = kmeans.fit_predict(X)

# Aligning K-Means cluster labels with actual species labels
from scipy.stats import mode

labels = np.zeros_like(y_kmeans)
for i in range(3):
    mask = (y_kmeans == i)
    labels[mask] = mode(y_encoded[mask])[0]

# Calculating confusion matrix and accuracy
cm = confusion_matrix(y_encoded, labels)
acc = accuracy_score(y_encoded, labels)

print("\nConfusion Matrix:\n", cm)
print("\nAccuracy Score:", round(acc * 100, 2), "%")

# Visualizing the clusters
plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s=100, c='red', label='Cluster 1')
plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s=100, c='blue', label='Cluster 2')
plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s=100, c='green', label='Cluster 3')

# Plotting centroids
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1],
            s=200, c='yellow', label='Centroids', marker='X')

plt.title('K-Means Clustering (Iris Dataset)')
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.legend()
plt.show()

# Example Prediction
sample = [[5.1, 3.5, 1.4, 0.2]]
pred_cluster = kmeans.predict(sample)
print("\nPredicted Cluster for sample", sample, ":", pred_cluster[0])



#second code+++++++++++++++++++++++++++++++++++++++++++=


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans

# Load dataset
dataset = pd.read_csv('/content/Irisdata.csv')
print(dataset.head())

# Select features (make sure to exclude ID or non-numeric columns)
X = dataset.iloc[:, [1, 2, 3, 4]].values

# Elbow method to find optimal number of clusters
wcss = []
for i in range(1, 11):
    kmeans = KMeans(
        n_clusters=i, 
        init='k-means++', 
        max_iter=300, 
        n_init=10, 
        random_state=0
    )
    kmeans.fit(X)
    wcss.append(kmeans.inertia_)

# Plot Elbow Curve
plt.figure(figsize=(8, 5))
plt.plot(range(1, 11), wcss, marker='o')
plt.title('Elbow Method for Optimal k')
plt.xlabel('Number of Clusters')
plt.ylabel('WCSS (Within Cluster Sum of Squares)')
plt.grid(True)
plt.show()

# Applying KMeans with optimal clusters (3 for Iris)
kmeans = KMeans(
    n_clusters=3, 
    init='k-means++', 
    max_iter=300, 
    n_init=10, 
    random_state=0
)
y_kmeans = kmeans.fit_predict(X)

# Plot the clusters (using the first two features for 2D visualization)
plt.figure(figsize=(8, 6))
plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s=100, c='red', label='Iris-setosa')
plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s=100, c='blue', label='Iris-versicolour')
plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s=100, c='green', label='Iris-virginica')

# Plot centroids
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], 
            s=200, c='yellow', edgecolor='black', marker='X', label='Centroids')

plt.title('Clusters of Iris Species')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.legend()
plt.grid(True)
plt.show()


