使用KFold进行训练集和验证集的拆分,使用准确率和召回率来挑选合适的阈值(threshold) 1.KFold(进行交叉验证) 2.np.logical_and(两bool数组都是正即为正) ...

---恢复内容开始---

1. k_fold = KFold(n_split, shuffle) 构造KFold的索引切割器

k_fold.split(indices) 对索引进行切割。

参数说明:n_split表示切割的份数,假设切割的份数为10,那么有9份是训练集有1份是测试集,shuffle是否进行清洗,indices表示需要进行切割的索引值

import numpy as np
from sklearn.model_selection import KFold

indices = np.arange(20)
k_fold = KFold(n_splits=10, shuffle=False)
train_test_set = k_fold.split(indices)
for (train_set, test_set) in train_test_set:
    print(train_set)
    print(test_set)

2.np.logical_and(pred_issame, test_issame) # 如果pred_issame中的元素和test_issame都是True, 返回的也是True,否者返回的是False

参数说明:pred_issame输入的bool数组,test_issame输入的bool数组

import numpy as np
pred_issame = np.array([True, True, False, False])
actual_issame = np.array([False, True, False, False])
print(np.logical_and(pred_issame, actual_issame))
# [False  True False False]

3. np.logical_not(pred_issame)  # 将输入的True转换为False,False转换为Train 

参数说明: pred_issame 表示输入的bool数组

import numpy as np
pred_issame = np.array([True, True, False, False])
print(np.logical_not(pred_issame))
# [False False  True  True]

第一步:构造indices的索引值,使用KFold对incides进行train_set和test_set的生成

第二步: 使用np.arange(0, 4, 0.4)  构造threshold的列表,循环threshold列表

第三步:

        第一步: 使用np.less(dist, threshold) 来获得预测结果

        第二步:

                tp = np.logical_and(pred_issame, actual_issame)  # 正样本被判定为正样本

                fp = np.logical_and(pre_issame, np.logical_not(actual_issame)) # 负样本被判断为正样本

                tn = np.logical_and(np.logical_not(pre_issame), np.logical_not(actual_issame)) # 负样本判断为负样本

                fn = np.logical_and(np.logical_not(pre_issame), actual_issame) # 正样本被判断为负样本

                tpr = 0 if tp + fn == 0 else float(tp) / float(tp + fn)  # 召回率

                fpr = 0 if fp + tn == 0 else float(tn) / float(fp + tn)

                accur = (tp + tn) / (tp+fp+fn+tn)

第四步:使用threshold_max = np.argmax(accur) # 获得准确率最大的索引值,即为thresholds最好的索引值 

def calculate_roc(thresh, dist, actual_issame):
    pre_issame = np.less(dist, thresh)
    tp = np.sum(np.logical_and(pre_issame, actual_issame)) # 正样本被预测为正样本
    fp = np.sum(np.logical_and(pre_issame, np.logical_not(actual_issame))) # 负样本被预测为正样本
    tn = np.sum(np.logical_and(np.logical_not(pre_issame), np.logical_not(actual_issame))) # 负样本被预测为负样本
    fn = np.sum(np.logical_and(np.logical_not(pre_issame),  actual_issame)) # 正样本被预测为负样本

    tpr = 0 if tp + tn == 0 else float(tp) / float(tp + fn)
    fpr = 0 if tp + fn == 0 else float(tn) / float(fp + tn)
    accur = ((tp + tn) / dist.size)
    return tpr, fpr, accur
#
import numpy as np
from sklearn.model_selection import KFold
distance = np.array([0.1, 0.2, 0.3, 0.25, 0.33, 0.20, 0.18, 0.24])
actual_issame = np.array([True, True, False, False, False, True, True, False])
k_fold = KFold(n_splits=4, shuffle=False)
indices = np.arange(len(distance))
for k_num, (train_set, test_set) in enumerate(k_fold.split(indices)):
    thresholds = np.arange(0, 1, 0.04)
    accuracy = np.zeros(len(thresholds))
    for threshold_index, threshold in enumerate(thresholds):
        _, _, accuracy[threshold_index] = calculate_roc(threshold, distance[train_set], actual_issame[train_set])

    max_threshold = np.argmax(accuracy)
    print(thresholds[max_threshold])

 

 

  

 

 

---恢复内容结束---

转载于:https://www.cnblogs.com/my-love-is-python/p/11352581.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于图坍缩的图多分类代码实现,使用Python编写,使用scikit-learn库进行建模和训练: ``` import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC from sklearn.metrics import accuracy_score from sklearn.base import BaseEstimator, TransformerMixin class GraphTransformer(BaseEstimator, TransformerMixin): """ 图坍缩转换器 """ def __init__(self, threshold=0.5): self.threshold = threshold def fit(self, X, y=None): return self def transform(self, X): # 计算相似度矩阵 N = X.shape[0] similarity = np.zeros((N, N)) for i in range(N): for j in range(i+1, N): similarity[i,j] = similarity[j,i] = np.exp(-np.sum(np.square(X[i]-X[j]))) # 计算权重矩阵 weights = np.zeros((N, N)) for i in range(N): for j in range(i+1, N): if similarity[i,j] >= self.threshold: weights[i,j] = weights[j,i] = 1 # 构建连通图 graph = {} for i in range(N): graph[i] = set([j for j in range(N) if weights[i,j]==1]) # 图坍缩 labels = [i for i in range(N)] while len(graph) > 1: u, v = min([(u, v) for u in graph for v in graph[u] if u != v], key=lambda x: weights[x]) graph[u].update(graph[v]) del graph[v] labels[v] = u return np.array([labels]).T # 随机生成数据集 X, y = make_classification(n_samples=100, n_features=10, n_classes=5, random_state=42) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 构建Pipeline并进行训练和预测 pipe = Pipeline([ ('scaler', StandardScaler()), ('graph', GraphTransformer(threshold=0.5)), ('svm', SVC(kernel='rbf', C=1, gamma='scale', random_state=42)) ]) pipe.fit(X_train, y_train) y_pred = pipe.predict(X_test) # 计算准确率 acc = accuracy_score(y_test, y_pred) print('Accuracy:', acc) ``` 说明: 1. 代码中使用scikit-learn库中的`make_classification`函数随机生成一个包含100个样本、10个特征、5个类别的数据集。 2. `GraphTransformer`是一个自定义的转换器类,用于将原始数据集转换为连通图上的标签。其中`fit`方法不需要做任何事情,`transform`方法根据相似度矩阵和阈值计算权重矩阵,构建连通图,并进行图坍缩。 3. Pipeline中包含了三个步骤:数据标准化、图坍缩转换和SVM分类器。其中SVM分类器使用径向基函数(RBF)作为核函数。 4. 计算准确率并输出。 使用自己随机生成的数据集进行训练和预测,只需要将代码中的数据集替换为自己的数据即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值