构建knn分类器的代码
时间: 2023-08-08 15:12:55 浏览: 140
knn.zip_knn
Sure! Here is an example code to build a k-nearest neighbors (kNN) classifier using Python and scikit-learn library:
```python
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Load your dataset and split it into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create a kNN classifier with k=5
knn = KNeighborsClassifier(n_neighbors=5)
# Train the classifier using the training data
knn.fit(X_train, y_train)
# Make predictions on the testing data
y_pred = knn.predict(X_test)
# Evaluate the accuracy of the classifier
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
In this code, `X` represents the feature matrix and `y` represents the corresponding labels. The dataset is split into training and testing sets using the `train_test_split` function. The `n_neighbors` parameter of `KNeighborsClassifier` is set to 5, meaning it considers 5 nearest neighbors for classification.
After training, the classifier makes predictions on the testing data using the `predict` method. The accuracy of the classifier is then evaluated by comparing the predicted labels (`y_pred`) with the true labels (`y_test`).
Remember to replace `X` and `y` with your actual feature matrix and labels respectively.
阅读全文