修改代码使得该代码可以求GaussianNB 高斯朴素贝叶斯模型的准确率,精确率,召回率,F1分数的各个各列除以最大值以及各列减Min除以(Max-Min)
时间: 2024-10-12 09:06:17 浏览: 33
为了修改代码来计算每个指标相对于最大值和最小值的规范化版本,你可以这样做:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
def normalize_scores(scores, max_val=None, min_val=None):
if max_val is None:
max_val = scores.max(axis=0)
if min_val is None:
min_val = scores.min(axis=0)
normalized_scores = (scores - min_val) / (max_val - min_val)
return normalized_scores
# 加载数据并进行处理
[X, Y] = LoadData('Iris')
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)
model = GaussianNB()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# 计算原始指标
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average='weighted')
recall = recall_score(y_test, y_pred, average='weighted')
f1 = f1_score(y_test, y_pred, average='weighted')
# 定义最大值和最小值变量,假设我们已经计算过一次
original_scores = np.array([accuracy, precision, recall, f1])
max_values = original_scores.max(axis=0)
min_values = original_scores.min(axis=0)
# 对指标进行规范化
normalized_scores = normalize_scores(np.array([accuracy, precision, recall, f1]), max_values, min_values)
print(f"原始指标:\n{'Accuracy':<15} {accuracy:<10}\n"
f"Precision: {precision:<15} {original_scores[1]:<10}\n"
f"Recall: {recall:<15} {original_scores[2]:<10}\n"
f"F1 Score: {f1:<15} {original_scores[3]:<10}")
print(f"规范化指标(除以最大值):\n"
f"Accuracy: {normalized_scores[0]:<15} {normalized_scores[0]:<10}\n"
f"Precision: {normalized_scores[1]:<15} {normalized_scores[1]:<10}\n"
f"Recall: {normalized_scores[2]:<15} {normalized_scores[2]:<10}\n"
f"F1 Score: {normalized_scores[3]:<15} {normalized_scores[3]:<10}")
print(f"规范化指标(减去最小值,除以Max-Min):\n"
f"Accuracy: {normalized_scores[0]:<15} {normalized_scores[0]:<10}\n"
f"Precision: {normalized_scores[1]:<15} {normalized_scores[1]:<10}\n"
f"Recall: {normalized_scores[2]:<15} {normalized_scores[2]:<10}\n"
f"F1 Score: {normalized_scores[3]:<15} {normalized_scores[3]:<10}")
阅读全文