基于癌症数据集,采用KNN实现癌症肿瘤鉴别,并通过准确率,精确率,召回率和f1-score评价模型
时间: 2024-05-07 14:22:38 浏览: 111
好的,这里提供一个基于sklearn库实现KNN算法的示例代码,用于对癌症数据集进行肿瘤鉴别,并计算模型的准确率、精确率、召回率和f1-score:
```python
# 导入库
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
# 加载数据集
data = load_breast_cancer()
X = data.data
y = data.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 定义KNN模型
knn = KNeighborsClassifier()
# 训练模型
knn.fit(X_train, y_train)
# 预测结果
y_pred = knn.predict(X_test)
# 计算模型评价指标
acc = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
# 输出结果
print("Accuracy:", acc)
print("Precision:", precision)
print("Recall:", recall)
print("F1-score:", f1)
```
你可以根据自己的数据集进行修改和调整,希望对你有帮助。
阅读全文