我正在尝试使用 Keras 的模型制作一些程序,然后使用 AIX360 的 Lime 解释器(它只是原始 LIME 的包装器)来解释它。所有数据均为 MNIST 灰度数字。但就我而言,我无法解释该实例,因为我不知道该向解释者提供什么内容。
我的代码:
!pip install aix360
!pip install tensorflow==2.2.0
from __future__ import print_function
import warnings
# Supress jupyter warnings if required for cleaner output
warnings.simplefilter('ignore')
import numpy as np
import pandas as pd
import keras
import keras.layers
from keras.utils.np_utils import to_categorical # convert to one-hot-encoding
from keras.models import Sequential # Sequeantial layer addition
from aix360.algorithms.lime import LimeImageExplainer
print('Using keras:', keras.__version__)
# Load dataset
from keras.datasets import mnist
# Tuple of Numpy arrays: (x_train, y_train), (x_test, y_test).
(train, train_labels), (test, test_labels) = mnist.load_data()
# save input image dimensions
img_rows = train.shape[1]
img_cols = train.shape[2]
# Get classes and number of values
value_counts = pd.value_counts(train_labels).sort_index()
num_classes = value_counts.count()
train = train/255
test = test/255
train = train.reshape(train.shape[0], img_rows, img_cols, 1)
test = test.reshape(test.shape[0], img_rows, img_cols, 1)
model = keras.Sequential([
keras.layers.Flatten(input_shape=(img_rows, img_cols,1)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(num_classes)
])
model.compile(loss='sparse_categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
batch_size = 128
epochs = 1
model.fit(train, train_labels,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(test, test_labels))
score = model.evaluate(test, test_labels, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
limeExplainer = LimeImageExplainer()
limeExplainer.explain_instance(test[0], model.predict_proba)
最后一行是错误所在。不要关注模型是如何训练的,这不是问题。
编辑:编辑代码,使其有望在 Codelab 中运行(添加第二行)
编辑2:要完成: tensorflow 2.2.0 喀拉斯2.4.3 aix360 0.2.0
最佳答案
我添加了此转换并在 RGB 图像上进行了训练:
def to_rgb(x):
x_rgb = np.zeros((x.shape[0], 28, 28, 3))
for i in range(3):
x_rgb[..., i] = x[..., 0]
return x_rgb
train_rgb = to_rgb(train)
test_rgb = to_rgb(test)
它起作用了:
limeExplainer.explain_instance(test_rgb[0], model.predict_proba)
100%
1000/1000 [00:00<00:00, 2598.51it/s]
<lime.lime_image.ImageExplanation at 0x7f8d20381f50>
关于python - Keras,AIX360(LIME) - ValueError : the input array must be have a shape == (. ., ..,[ ..,] 3)),得到 (28, 28, 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63231969/