import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

# 1. Prepare the Training Data
# Features: [Weight in grams, Texture scale 1-10]
X_train = np.array([
    [140, 8],  # Apple 1
    [150, 7],  # Apple 2
    [130, 9],  # Apple 3
    [200, 2],  # Orange 1
    [220, 3],  # Orange 2
    [210, 1],  # Orange 3
])
X_test = np.array([
    [170, 8],  # Apple 4
    [190, 4]   # Orange 4
])

# Labels: 0 for Apple, 1 for Orange
Y_train = np.array([0, 0, 0, 1, 1, 1])
Y_test = np.array([0, 1])

# Initialize the K-NN Classifier
# We'll look at the 3 nearest neighbors (k=3)
knn = KNeighborsClassifier(n_neighbors=3)

# Train the model
knn.fit(X_train, Y_train)

# Predict for th test fruit
prediction = knn.predict(X_test)

# Output the result
fruit_type = "Apple" if prediction[0] == 0 else "Orange"
print(f"The apple is classified as: {fruit_type}")
fruit_type = "Apple" if prediction[1] == 0 else "Orange"
print(f"The orange is classified as: {fruit_type}")

# Check the probability (How sure is the model?)
probability = knn.predict_proba(X_test)
print(f"Confidence for the apple: {probability[0][prediction[0]] * 100:.0f}%")
print(f"Confidence for the orange: {probability[1][prediction[1]] * 100:.0f}%")

# Compute the accuracy
accuracy = accuracy_score(Y_test,prediction)
print(f"The accuracy is {accuracy}")
