导入数据用模糊神经网络预测三分类并画出loss曲线,accuracy曲线和auc曲线python代码
时间: 2023-07-15 18:13:39 浏览: 93
下面是一个简单的模糊神经网络预测三分类的 Python 代码,并画出 loss 曲线、accuracy 曲线和 auc 曲线。
```
import numpy as np
import skfuzzy as fuzz
from sklearn.metrics import roc_auc_score, accuracy_score
import matplotlib.pyplot as plt
# 生成随机数据
X = np.random.rand(100, 4)
y = np.random.randint(0, 3, 100)
# 划分训练集和测试集
n_samples = X.shape[0]
n_train = int(n_samples * 0.8)
train_X, train_y = X[:n_train], y[:n_train]
test_X, test_y = X[n_train:], y[n_train:]
# 构建模糊神经网络
cntr, u, u0, d, jm, p, fpc = fuzz.cluster.cmeans(train_X.T, 3, 2, error=0.005, maxiter=1000, init=None)
# 预测测试集
test_u, _, _, _, _, _, _ = fuzz.cluster.cmeans_predict(test_X.T, cntr, 2, error=0.005, maxiter=1000)
test_predictions = np.argmax(test_u, axis=0)
# 计算 metrics
test_accuracy = accuracy_score(test_y, test_predictions)
test_auc = roc_auc_score(test_y, test_u.T)
# 打印结果
print('Accuracy:', test_accuracy)
print('AUC:', test_auc)
# 计算 loss 曲线、accuracy 曲线和 auc 曲线
n_iterations = 100
loss_curve = []
accuracy_curve = []
auc_curve = []
for i in range(n_iterations):
cntr, u, u0, d, jm, p, fpc = fuzz.cluster.cmeans(train_X.T, 3, 2, error=0.005, maxiter=1000, init=None)
train_u, _, _, _, _, _, _ = fuzz.cluster.cmeans_predict(train_X.T, cntr, 2, error=0.005, maxiter=1000)
train_predictions = np.argmax(train_u, axis=0)
train_accuracy = accuracy_score(train_y, train_predictions)
train_auc = roc_auc_score(train_y, train_u.T)
loss = np.sum((train_u - train_y) ** 2)
loss_curve.append(loss)
accuracy_curve.append(train_accuracy)
auc_curve.append(train_auc)
# 画出 loss 曲线、accuracy 曲线和 auc 曲线
plt.plot(loss_curve)
plt.title('Loss Curve')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.show()
plt.plot(accuracy_curve)
plt.title('Accuracy Curve')
plt.xlabel('Iteration')
plt.ylabel('Accuracy')
plt.show()
plt.plot(auc_curve)
plt.title('AUC Curve')
plt.xlabel('Iteration')
plt.ylabel('AUC')
plt.show()
```
上述代码中,我们使用了 `skfuzzy` 库来构建模糊神经网络,并使用 `roc_auc_score` 和 `accuracy_score` 函数来计算 metrics。我们还使用 `matplotlib` 库来画出 loss 曲线、accuracy 曲线和 auc 曲线。
阅读全文