- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试用 LIME 解释我在 Keras 中的卷积神经网络 bult 的输出.
我的神经网络是一个多类文本分类器,其中每个类都是独立的。因此,文本可以包含 1 类和 2 类或仅包含 1 类等。第五个“类”(无)用于文本中没有类的情况。
然而,虽然我设法用 Keras 和 Lime 解释了一个二元分类案例,但我无法得到具有独立类的多类案例。找到第一个帮助here :
但是,我的代码不起作用,我从 Lime 收到内部错误,例如:“ValueError:发现样本数量不一致的输入变量:[5000, 100000]”
from lime.lime_text import LimeTextExplainer, TextDomainMapper
explainer = LimeTextExplainer(class_names=encoder.classes_)
chosen_text = 2
def flatten_predict(i):
global model
# catch single string inputs and convert them to list
if i.__class__ != list:
i = [i]
print("## Caught and transformed single string.")
# list for predictions
predStorage = []
# loop through input list and predict
for textInput in i:
textInput = preprocess(textInput)
textInput = make_predictable(textInput)
pred = model.predict(textInput)
pred = np.append(pred, 1-pred, axis=1)
# control output of function
predStorage.extend(pred)
return np.asarray(predStorage)
def get_predict_proba_fn_of_class(label):
"""assuming wrapped_predict outputs an (n, d) array of prediction probabilities, where d is the number of labels"""
def rewrapped_predict(strings):
preds = flatten_predict(strings)[:, np.where(flatten_predict(strings)==label)].reshape(-1, 1)
ret = np.asarray(np.hstack([(1 - preds), preds]))
return ret
return rewrapped_predict
str = 'Ein sehr freundlicher Arzt.'
preds = flatten_predict(str)
labels_to_explain = preds#
print(labels_to_explain)
explanation_for_label = {}
for label in labels_to_explain:
wrapped = get_predict_proba_fn_of_class(label)
explanation_for_label[label] = explainer.explain_instance(str, wrapped)
explanation_for_label[label].show_in_notebook()
错误信息:
ValueError Traceback (most recent call last)
<ipython-input-26-8df61aaa23f4> in <module>()
53 for label in labels_to_explain:
54 wrapped = get_predict_proba_fn_of_class(label)
---> 55 explanation_for_label[label] = explainer.explain_instance(str, wrapped)
56 explanation_for_label[label].show_in_notebook()
57
/usr/local/lib/python3.6/dist-packages/lime/lime_text.py in explain_instance(self, text_instance, classifier_fn, labels, top_labels, num_features, num_samples, distance_metric, model_regressor)
405 data, yss, distances, label, num_features,
406 model_regressor=model_regressor,
--> 407 feature_selection=self.feature_selection)
408 return ret_exp
409
/usr/local/lib/python3.6/dist-packages/lime/lime_base.py in explain_instance_with_data(self, neighborhood_data, neighborhood_labels, distances, label, num_features, feature_selection, model_regressor)
155 weights,
156 num_features,
--> 157 feature_selection)
158
159 if model_regressor is None:
/usr/local/lib/python3.6/dist-packages/lime/lime_base.py in feature_selection(self, data, labels, weights, num_features, method)
104 n_method = 'highest_weights'
105 return self.feature_selection(data, labels, weights,
--> 106 num_features, n_method)
107
108 def explain_instance_with_data(self,
/usr/local/lib/python3.6/dist-packages/lime/lime_base.py in feature_selection(self, data, labels, weights, num_features, method)
78 clf = Ridge(alpha=0, fit_intercept=True,
79 random_state=self.random_state)
---> 80 clf.fit(data, labels, sample_weight=weights)
81 feature_weights = sorted(zip(range(data.shape[0]),
82 clf.coef_ * data[0]),
/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/ridge.py in fit(self, X, y, sample_weight)
678 self : returns an instance of self.
679 """
--> 680 return super(Ridge, self).fit(X, y, sample_weight=sample_weight)
681
682
/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/ridge.py in fit(self, X, y, sample_weight)
489
490 X, y = check_X_y(X, y, ['csr', 'csc', 'coo'], dtype=_dtype,
--> 491 multi_output=True, y_numeric=True)
492
493 if ((sample_weight is not None) and
/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, warn_on_dtype, estimator)
764 y = y.astype(np.float64)
765
--> 766 check_consistent_length(X, y)
767
768 return X, y
/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
233 if len(uniques) > 1:
234 raise ValueError("Found input variables with inconsistent numbers of"
--> 235 " samples: %r" % [int(l) for l in lengths])
236
237
ValueError: Found input variables with inconsistent numbers of samples: [5000, 100000]
有谁知道我做错了什么?我很确定这与输入格式有关。
最佳答案
我现在设法解决了这个问题。这是为那些可能对此感兴趣的人提供的解决方案。
简而言之,诀窍是从 get_predict_proba_fn_of_class
中的 numpy 数组中选择正确的列。虽然我有五个独立的分类分数加起来不等于一个,但我必须在新列中为每个标签的分类分数添加负分数(例如,对于 0.67,我添加了 1-0.67),然后选择原始列和新列。
from lime.lime_text import LimeTextExplainer, TextDomainMapper
print(encoder.classes_)
##https://lime-ml.readthedocs.io/en/latest/lime.html#module-lime.lime_text
def flatten_predict(i):
global model
# catch single string input and convert to list
if i.__class__ != list:
i = [i]
# list for predictions
predStorage = []
# loop through input list and predict
for textInput in i:
textInput = preprocess(textInput)
textInput = make_predictable(textInput)
pred = model.predict(textInput)
pred = np.append(pred, 1-pred, axis=1)
predStorage.extend(pred)
return np.asarray(predStorage)
def get_predict_proba_fn_of_class(strings):
def rewrapped_predict(strings):
pred = flatten_predict(strings)
index = np.where(pred==label)[1][0]
preds = pred[:, index::5]
return preds
return rewrapped_predict
string="Der Arzt weiß, was er tut und hat mir alles genau erklärt."
print("Simple model prediction:", model.predict(make_predictable(preprocess(string))))
labels_to_explain = flatten_predict(string)
print("labels_to_explain:", labels_to_explain)
explanation_for_label = {}
for index, label in enumerate(labels_to_explain[0]):
if index < (len(labels_to_explain[0])/2):
actual_classes = [encoder.classes_[index], 'None']
explainer = LimeTextExplainer(class_names=actual_classes)
wrapped = get_predict_proba_fn_of_class(string) # function returns function!
explanation_for_label[label] = explainer.explain_instance(string, wrapped)
explanation_for_label[label].show_in_notebook()
关于python - 用 LIME 解释 CNN (Keras) 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54072496/
R-CNN、fast R-CNN、faster R-CNN 和 YOLO 在以下方面有什么区别: (1) 同一图像集上的精度 (2) 给定 SAME IMAGE SIZE,运行时间 (3) 支持安卓移
我试图比较 CNN 模型和组合 CNN-SVM 模型进行分类的准确性结果。然而我发现 CNN 模型比 CNN-SVM 组合模型具有更好的准确性。这是正确的还是可能发生? 最佳答案 这取决于很多因素,但
我知道这可能是一个愚蠢的问题,但我对机器学习和人工神经网络有点陌生。 深度卷积神经网络和密集卷积神经网络有什么区别吗? 提前致谢! 最佳答案 密集 CNN 是深度 CNN 的一种,其中每一层都与比自身
我正在使用预训练的 CNN 从图片中提取特征。使用这些特征作为新 CNN/NN 的输入有意义吗?以前做过吗?我很高兴得到答复。 最佳答案 这称为微调。这是非常常用的。通常,我们会删除 VGG 或类似网
与 caffe 合作几个月后,我已经能够成功地训练我自己的模型。例如,比我自己的模型更进一步,我已经能够用 1000 个类来训练 ImageNet。 现在在我的项目中,我试图提取我感兴趣的区域。之后我
我正在使用下面的 LeNet 架构来训练我的图像分类模型,我注意到每次迭代都不会提高训练和验证的准确性。这方面的任何专家都可以解释可能出了什么问题吗? 训练样本 - 属于 2 个类别的 110 张图像
我使用剩余连接实现了以下 CNN,用于在 CIFAR10 上对 10 个类进行分类: class ConvolutionalNetwork(nn.Module): def __init__(se
我有一组二维输入数组 m x n即 A,B,C我必须预测两个二维输出数组,即 d,e我确实有预期值。如果您愿意,您可以将输入/输出视为灰色图像。 由于空间信息是相关的(这些实际上是 2D 物理域)我想
我正在开发一个交通跟踪系统,该系统可以分析已经收集的视频。我正在使用opencv,线程,pytorch和dectron2。为了加快从opencv抓帧的速度,我决定使用Thread,该线程运行一个循环,
我正在解决一个问题,需要我构建一个深度学习模型,该模型必须基于某些输入图像输出另一个图像。值得注意的是,这两个图像在概念上是相关的,但它们没有相同的尺寸。 起初我认为具有最终密集层(其参数是输出图像的
我正在制作一个卷积网络来预测 3 类图像:猫、狗和人。我训练了又训练它,但是当我传递猫图像来预测时,它总是给出错误的输出。我尝试了其他猫的照片,但结果没有改变。对于人和狗来说没有问题,只是对于猫来说。
我接到一项任务,要实现一个卷积神经网络,该网络可以评估 MNIST dataset 中找到的手写数字。网络架构如下所示: 我已经实现了一个与架构相匹配的 CNN,不幸的是它的准确率只有 10% 左右。
我正在尝试在 Keras 中重新创建 CNN 来对点云数据进行分类。 CNN 在 this 中描述。纸。 网络设计 这是我当前的实现: inputs = Input(shape=(None, 3))
我想为有 300 个类的数据集设计 CNN。我已经用以下模型对两个类(class)进行了测试。它具有良好的准确性。 model = Sequential([ Conv2D(16, 3, padding
我成功训练了 CNN 模型,但是当我向模型提供图像以使其预测标签时,出现错误。 这是我的模型(我正在使用 saver.restore 恢复它)... # load dataset mnist = in
我恢复了用于人脸检测的预训练模型,该模型一次获取单个图像并返回边界框。如果这些图像具有不同的尺寸,如何才能获取一批图像? 最佳答案 您可以使用tf.image.resize_images方法来实现这一
我有大约 8200 张图像用于人脸检测任务。其中 4800 个包含人脸。其他 3400 张图像包含 3D 人脸面具(由橡胶/ latex 制成)、卡通人脸、猴子脸的图像。我想检测给定的图像是否包含真实
我有一组合成噪声图像。示例如下: 我还有它们相应的干净文本图像作为我的地面实况数据。下面的例子: 两个图像的尺寸为4918 x 5856。它的大小是否适合训练我的执行图像去噪的卷积神经网络?如果没有,
大家好! 由于我正在尝试制作一个将灰度图像转换为 RGB 图像的全卷积神经网络,所以我想知道是否可以在不同大小的图像(不同的像素和比率)上训练和测试模型。通常你只会下采样或上采样,这是我不想做的。我听
我正在研究 CNN 特征的早期和晚期融合。我从 CNN 的多层中获取了特征。对于早期融合,我捕获了三个不同层的特征,然后水平连接它们 F= [F1' F2' F3']; 对于后期融合,我正在阅读此 p
我是一名优秀的程序员,十分优秀!