13/06/2024, 08:05 KnnClassifier - Jupyter Notebook
In [18]: from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier, kneighbors_graph
from sklearn.metrics import accuracy_score, r2_score, classification_report, confusion_m
import numpy
import pandas
import matplotlib.pyplot as plt
In [19]: dataset=load_breast_cancer()
In [20]: X = dataset.data
y = dataset.target
In [21]: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=4
In [22]: def knn_classifier():
model = KNeighborsClassifier(n_neighbors=2)
return model
In [ ]: KNNClassifier = knn_classifier()
In [24]: KNNClassifier.fit(X_train, y_train)
Out[24]: KNeighborsClassifier(n_neighbors=2)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the
notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with
nbviewer.org.
In [25]: y_pred = KNNClassifier.predict(X_test)
In [26]: df = pandas.DataFrame(data = numpy.transpose([y_test, y_pred]), columns=['Test', 'Predict
In [27]: df.Test = df.Test.replace(to_replace=[0,1], value=dataset.target_names)
df.Prediction = df.Prediction.replace(to_replace=[0,1], value=dataset.target_names)
In [28]: df.head(10)
Out[28]: Test Prediction
0 benign malignant
1 malignant malignant
2 malignant malignant
3 benign benign
4 benign benign
5 malignant malignant
6 malignant malignant
7 malignant malignant
8 benign benign
9 benign benign
In [29]: print(f"Accuracy score: {accuracy_score(y_test, y_pred) :0.2f}")
Accuracy score: 0.92
localhost:8888/notebooks/Desktop/ml lab/2/b/KnnClassifier.ipynb 1/2
13/06/2024, 08:05 KnnClassifier - Jupyter Notebook
In [30]: print(f"R2 score: {r2_score(y_test, y_pred) :0.2f}")
R2 score: 0.67
In [31]: print(classification_report(y_test, y_pred))
precision recall f1-score support
0 0.86 0.94 0.90 54
1 0.96 0.91 0.94 89
accuracy 0.92 143
macro avg 0.91 0.93 0.92 143
weighted avg 0.93 0.92 0.92 143
In [32]: print(confusion_matrix(y_test, y_pred))
[[51 3]
[ 8 81]]
In [33]: result = kneighbors_graph(X, n_neighbors=2)
print(result.toarray())
[[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
...
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]]
In [ ]:
localhost:8888/notebooks/Desktop/ml lab/2/b/KnnClassifier.ipynb 2/2