Professional Documents
Culture Documents
CODE:
# Importing necessary libraries
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
# Load the Iris dataset (replace this with your own dataset)
iris = load_iris()
X = iris.data
y = iris.target
# Making predictions
y_pred = classifier.predict(X_test)
# Checking accuracy
accuracy = metrics.accuracy_score(y_test, y_pred)
print('Accuracy: {:.2f}'.format(accuracy))
In this example:
1) We import necessary libraries including load_iris to load the Iris dataset, train_test_split
to split the dataset into training and testing sets, KNeighborsClassifier for KNN
2) We load the Iris dataset. Replace X with your feature matrix and y with your target
labels.
3) We split the dataset into training and testing sets using train_test_split.
and p=2).
5) We train the classifier on the training data using the fit method.
1. Initialization of the Classifier: We create a KNN classifier with 7 neighbors, using the
Euclidean distance metric. This prepares the classifier for learning.
python code
classifier = KNeighborsClassifier(n_neighbors=7, metric='minkowski', p=2)
2. Training the Classifier: We train the classifier using the training data (X_train,
y_train). This is where the classifier learns patterns in the data.
python code
classifier.fit(X_train, y_train)
3. Making Predictions: We use the trained classifier to predict labels for the test data
(X_test). This evaluates the classifier's ability to generalize to new, unseen data.
python code
y_pred = classifier.predict(X_test)
4. Evaluating Accuracy: We calculate the accuracy of the classifier by comparing
predicted labels (y_pred) with actual labels (y_test).
python code
accuracy = metrics.accuracy_score(y_test, y_pred)
print('Accuracy: {:.2f}'.format(accuracy))