猿问

Keras、AIX360(LIME) - ValueError:输入数组的形状必须为

我正在尝试使用 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)

最后一行是错误所在。不要关注模型是如何训练的,那不是问题。


编辑:编辑代码,希望它可以在代码实验室中运行(添加第二行)


EDIT2:要完成:tensorflow 2.2.0 keras 2.4.3 aix360 0.2.0


慕娘9325324
浏览 115回答 1
1回答

呼唤远方

我添加了这个转换并对 RGB 图像进行了训练:def to_rgb(x):&nbsp; &nbsp; x_rgb = np.zeros((x.shape[0], 28, 28, 3))&nbsp; &nbsp; for i in range(3):&nbsp; &nbsp; &nbsp; &nbsp; x_rgb[..., i] = x[..., 0]&nbsp; &nbsp; return x_rgbtrain_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>
随时随地看视频慕课网APP

相关分类

Python
我要回答