gpt4 book ai didi

python - Keras, AIX360(LIME) - ValueError : the input array must be have a shape == (. ., ..,[ ..,] 3)), got (28, 28, 1)

转载 作者:行者123 更新时间:2023-12-04 09:15:40 25 4
gpt4 key购买 nike

我正在尝试使用来自 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 中运行(添加第二行)
EDIT2:要完成:
tensorflow 2.2.0
keras 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)), got (28, 28, 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63231969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com