- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个小的决策树代码,我相信我将所有内容都转换为 int,并且我已经使用 isnan、max 等检查了我的训练/测试数据。
我真的不知道为什么会出现这个错误。
因此,我尝试从决策树传递 Mnist 数据集,然后使用类进行攻击。
这是代码:
from AttackUtils import Attack
from AttackUtils import calc_output_weighted_weights, targeted_gradient, non_targeted_gradient, non_targeted_sign_gradient
(X_train_woae, y_train_woae), (X_test_woae, y_test_woae) = mnist.load_data()
X_train_woae = X_train_woae.reshape((len(X_train_woae), np.prod(X_train_woae.shape[1:])))
X_test_woae = X_test_woae.reshape((len(X_test_woae), np.prod(X_test_woae.shape[1:])))
from sklearn import tree
#model_woae = LogisticRegression(multi_class='multinomial', solver='lbfgs', fit_intercept=False)
model_woae = tree.DecisionTreeClassifier(class_weight='balanced')
model_woae.fit(X_train_woae, y_train_woae)
#model_woae.coef_ = model_woae.feature_importances_
coef_int = np.round(model_woae.tree_.compute_feature_importances(normalize=False) * X_train_woae.size).astype(int)
attack_woae = Attack(model_woae)
attack_woae.prepare(X_train_woae, y_train_woae, X_test_woae, y_test_woae)
weights_woae = attack_woae.weights
num_classes_woae = len(np.unique(y_train_woae))
attack_woae.create_one_hot_targets(y_test_woae)
attack_woae.attack_to_max_epsilon(non_targeted_gradient, 50)
non_targeted_scores_woae = attack_woae.scores
所以攻击类进行扰动和非目标梯度攻击。 这是攻击类别:
import numpy as np
from sklearn.metrics import accuracy_score
def calc_output_weighted_weights(output, w):
for c in range(len(output)):
if c == 0:
weighted_weights = output[c] * w[c]
else:
weighted_weights += output[c] * w[c]
return weighted_weights
def targeted_gradient(foolingtarget, output, w):
ww = calc_output_weighted_weights(output, w)
for k in range(len(output)):
if k == 0:
gradient = foolingtarget[k] * (w[k]-ww)
else:
gradient += foolingtarget[k] * (w[k]-ww)
return gradient
def non_targeted_gradient(target, output, w):
ww = calc_output_weighted_weights(output, w)
for k in range(len(target)):
if k == 0:
gradient = (1-target[k]) * (w[k]-ww)
else:
gradient += (1-target[k]) * (w[k]-ww)
return gradient
def non_targeted_sign_gradient(target, output, w):
gradient = non_targeted_gradient(target, output, w)
return np.sign(gradient)
class Attack:
def __init__(self, model):
self.fooling_targets = None
self.model = model
def prepare(self, X_train, y_train, X_test, y_test):
self.images = X_test
self.true_targets = y_test
self.num_samples = X_test.shape[0]
self.train(X_train, y_train)
print("Model training finished.")
self.test(X_test, y_test)
print("Model testing finished. Initial accuracy score: " + str(self.initial_score))
def set_fooling_targets(self, fooling_targets):
self.fooling_targets = fooling_targets
def train(self, X_train, y_train):
self.model.fit(X_train, y_train)
self.weights = self.model.coef_
self.num_classes = self.weights.shape[0]
def test(self, X_test, y_test):
self.preds = self.model.predict(X_test)
self.preds_proba = self.model.predict_proba(X_test)
self.initial_score = accuracy_score(y_test, self.preds)
def create_one_hot_targets(self, targets):
self.one_hot_targets = np.zeros(self.preds_proba.shape)
for n in range(targets.shape[0]):
self.one_hot_targets[n, targets[n]] = 1
def attack(self, attackmethod, epsilon):
perturbed_images, highest_epsilon = self.perturb_images(epsilon, attackmethod)
perturbed_preds = self.model.predict(perturbed_images)
score = accuracy_score(self.true_targets, perturbed_preds)
return perturbed_images, perturbed_preds, score, highest_epsilon
def perturb_images(self, epsilon, gradient_method):
perturbed = np.zeros(self.images.shape)
max_perturbations = []
for n in range(self.images.shape[0]):
perturbation = self.get_perturbation(epsilon, gradient_method, self.one_hot_targets[n], self.preds_proba[n])
perturbed[n] = self.images[n] + perturbation
max_perturbations.append(np.max(perturbation))
highest_epsilon = np.max(np.array(max_perturbations))
return perturbed, highest_epsilon
def get_perturbation(self, epsilon, gradient_method, target, pred_proba):
gradient = gradient_method(target, pred_proba, self.weights)
inf_norm = np.max(gradient)
perturbation = epsilon / inf_norm * gradient
return perturbation
def attack_to_max_epsilon(self, attackmethod, max_epsilon):
self.max_epsilon = max_epsilon
self.scores = []
self.epsilons = []
self.perturbed_images_per_epsilon = []
self.perturbed_outputs_per_epsilon = []
for epsilon in range(0, self.max_epsilon):
perturbed_images, perturbed_preds, score, highest_epsilon = self.attack(attackmethod, epsilon)
self.epsilons.append(highest_epsilon)
self.scores.append(score)
self.perturbed_images_per_epsilon.append(perturbed_images)
self.perturbed_outputs_per_epsilon.append(perturbed_preds)
这是它给出的回溯:
值错误
Traceback (most recent call last) in 4 num_classes_woae = len(np.unique(y_train_woae)) 5 attack_woae.create_one_hot_targets(y_test_woae) ----> 6 attack_woae.attack_to_max_epsilon(non_targeted_gradient, 50) 7 non_targeted_scores_woae = attack_woae.scores
~\MULTIATTACK\AttackUtils.py in attack_to_max_epsilon(self, attackmethod, max_epsilon) 106 self.perturbed_outputs_per_epsilon = [] 107 for epsilon in range(0, self.max_epsilon): --> 108 perturbed_images, perturbed_preds, score, highest_epsilon = self.attack(attackmethod, epsilon) 109 self.epsilons.append(highest_epsilon) 110 self.scores.append(score)
~\MULTIATTACK\AttackUtils.py in attack(self, attackmethod, epsilon) 79 def attack(self, attackmethod, epsilon): 80 perturbed_images, highest_epsilon = self.perturb_images(epsilon, attackmethod) ---> 81 perturbed_preds = self.model.predict(perturbed_images) 82 score = accuracy_score(self.true_targets, perturbed_preds) 83 return perturbed_images, perturbed_preds, score, highest_epsilon
...\appdata\local\programs\python\python35\lib\site-packages\sklearn\tree\tree.py in predict(self, X, check_input) 413 """ 414 check_is_fitted(self, 'tree_') --> 415 X = self._validate_X_predict(X, check_input) 416 proba = self.tree_.predict(X) 417 n_samples = X.shape[0]
...\appdata\local\programs\python\python35\lib\site-packages\sklearn\tree\tree.py in _validate_X_predict(self, X, check_input) 374 """Validate X whenever one tries to predict, apply, predict_proba""" 375 if check_input: --> 376 X = check_array(X, dtype=DTYPE, accept_sparse="csr") 377 if issparse(X) and (X.indices.dtype != np.intc or 378 X.indptr.dtype != np.intc):
...\appdata\local\programs\python\python35\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator) 566 if force_all_finite: 567 _assert_all_finite(array, --> 568 allow_nan=force_all_finite == 'allow-nan') 569 570 shape_repr = _shape_repr(array.shape)
...\appdata\local\programs\python\python35\lib\site-packages\sklearn\utils\validation.py in _assert_all_finite(X, allow_nan) 54 not allow_nan and not np.isfinite(X).all()): 55 type_err = 'infinity' if allow_nan else 'NaN, infinity' ---> 56 raise ValueError(msg_err.format(type_err, X.dtype)) 57 58
ValueError: Input contains NaN, infinity or a value too large for dtype('float32').
编辑:
我已将系数数字添加为 0,现在它在线下的 attack.attack_to_max_epsilon(non_targeted_gradient, epsilon_number)
处给出了相同的错误
最佳答案
在训练之前尝试将 one-hot enconde 应用于您的标签..
from sklearn.preprocessing import LabelEncoder
mylabels= ["label1", "label2", "label2"..."n.label"]
le = LabelEncoder()
labels = le.fit_transform(mylabels)
然后尝试分割您的数据:
from sklearn.model_selection import train_test_split
(x_train, x_test, y_train, y_test) = train_test_split(data,
labels,
test_size=0.25)
现在您的标签可能会用数字进行编码,这有利于训练机器学习算法。
关于python - 决策树分类器我不断收到 NaN 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56318601/
关于 B 树与 B+ 树,网上有一个比较经典的问题:为什么 MongoDb 使用 B 树,而 MySQL 索引使用 B+ 树? 但实际上 MongoDb 真的用的是 B 树吗?
如何将 R* Tree 实现为持久(基于磁盘)树?保存 R* 树索引或保存叶值的文件的体系结构是什么? 注意:此外,如何在这种持久性 R* 树中执行插入、更新和删除操作? 注意事项二:我已经实现了一个
目前,我正在努力用 Java 表示我用 SML 编写的 AST 树,这样我就可以随时用 Java 遍历它。 我想知道是否应该在 Java 中创建一个 Node 类,其中包含我想要表示的数据,以及一个数
我之前用过这个库http://www.cs.umd.edu/~mount/ANN/ .但是,它们不提供范围查询实现。我猜是否有一个 C++ 范围查询实现(圆形或矩形),用于查询二维数据。 谢谢。 最佳
在进一步分析为什么MySQL数据库索引选择使用B+树之前,我相信很多小伙伴对数据结构中的树还是有些许模糊的,因此我们由浅入深一步步探讨树的演进过程,在一步步引出B树以及为什么MySQL数据库索引选择
操作系统的那棵“树” 今天从一颗 开始,我们看看如何从小树苗长成一颗苍天大树。 运转CPU CPU运转起来很简单,就是不断的从内存取值执行。 CPU没有好好运转 IO是个耗费时间的活,如果CPU在取值
我想为海洋生物学类(class)制作一个简单的系统发育树作为教育示例。我有一个具有分类等级的物种列表: Group <- c("Benthos","Benthos","Benthos","Be
我从这段代码中删除节点时遇到问题,如果我插入数字 12 并尝试删除它,它不会删除它,我尝试调试,似乎当它尝试删除时,它出错了树的。但是,如果我尝试删除它已经插入主节点的节点,它将删除它,或者我插入数字
B+ 树的叶节点链接在一起。将 B+ 树的指针结构视为有向图,它不是循环的。但是忽略指针的方向并将其视为链接在一起的无向叶节点会在图中创建循环。 在 Haskell 中,如何将叶子构造为父内部节点的子
我在 GWT 中使用树控件。我有一个自定义小部件,我将其添加为 TreeItem: Tree testTree = new Tree(); testTree.addItem(myWidget); 我想
它有点像混合树/链表结构。这是我定义结构的方式 struct node { nodeP sibling; nodeP child; nodeP parent; char
我编写了使用队列遍历树的代码,但是下面的出队函数生成错误,head = p->next 是否有问题?我不明白为什么这部分是错误的。 void Levelorder(void) { node *tmp,
例如,我想解析以下数组: var array1 = ["a.b.c.d", "a.e.f.g", "a.h", "a.i.j", "a.b.k"] 进入: var json1 = { "nod
问题 -> 给定一棵二叉树和一个和,确定该树是否具有从根到叶的路径,使得沿路径的所有值相加等于给定的和。 我的解决方案 -> public class Solution { public bo
我有一个创建 java 树的任务,它包含三列:运动名称、运动类别中的运动计数和上次更新。类似的东西显示在下面的图像上: 如您所见,有 4 种运动:水上运动、球类运动、跳伞运动和舞蹈运动。当我展开 sk
我想在 H2 数据库中实现 B+ Tree,但我想知道,B+ Tree 功能在 H2 数据库中可用吗? 最佳答案 H2 已经使用了 B+ 树(PageBtree 类)。 关于mysql - H2数据库
假设我们有 5 个字符串数组: String[] array1 = {"hello", "i", "cat"}; String[] array2 = {"hello", "i", "am"}; Str
我正在处理树。每个节点都有带有 Tree * 值的对象。我读取的数据如下所示: 1 2 2 ... 这意味着,将 1 作为 0 的子节点,将 2 作为 1 的子节点,将 3 作为 o 2 的子节点。在
我正在寻找一个好的 JavaScript 树/树网格包。现在——在你回答之前: 它需要能够在大量节点上正常运行。可能有 1,000 个兄弟节点。它需要能够在 2 或 3 秒内绘制到 1,000 个节点
下面的代码块究竟是如何工作的?更具体地说,程序如何知道返回哪个选项? return ancestor (node1->left(), node2) || ancestor
我是一名优秀的程序员,十分优秀!