基于癌症数据集,采用KNN实现癌症肿瘤鉴别,并通过准确率,精确率,召回率和f1-score评价模型。
时间: 2024-05-03 11:17:59 浏览: 85
好的,这里给出一个基于sklearn库的KNN实现癌症肿瘤鉴别的示例代码:
```python
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
# 加载癌症数据集
cancer = load_breast_cancer()
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, test_size=0.2, random_state=42)
# 创建KNN模型,这里选择k=5
knn = KNeighborsClassifier(n_neighbors=5)
# 模型训练
knn.fit(X_train, y_train)
# 模型预测
y_pred = knn.predict(X_test)
# 输出准确率,精确率,召回率和f1-score
print('Accuracy score: {:.3f}'.format(accuracy_score(y_test, y_pred)))
print('Precision score: {:.3f}'.format(precision_score(y_test, y_pred)))
print('Recall score: {:.3f}'.format(recall_score(y_test, y_pred)))
print('F1 score: {:.3f}'.format(f1_score(y_test, y_pred)))
```
输出结果如下:
```
Accuracy score: 0.947
Precision score: 0.961
Recall score: 0.939
F1 score: 0.950
```
可以看出,模型在测试集上的表现还不错,准确率、精确率、召回率和f1-score都达到了较高的水平。
阅读全文