预测Keras中的类 - IndexError:索引196超出了轴0的大小为196的范围

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了预测Keras中的类 - IndexError:索引196超出了轴0的大小为196的范围相关的知识,希望对你有一定的参考价值。

我使用Keras训练了卷积神经网络(CNN),并保存了模型以用于预测某些测试图像的类别。

输入将是图像和一些数字特征的组合(特别是12个特征)。

我有以下代码进行此类测试:

from keras.models import load_model
from keras import optimizers
import cv2
import numpy as np
import pandas as pd
import os

test_directory_edges = '/test'
test_df = pd.read_csv('/test.csv')
test_images_edge = []

df_test = pd.DataFrame(test_df)

# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
test_df = sc.fit_transform(test_df)
test_df = sc.transform(test_df)

test_border_irregularity_features = df_test.iloc[:,0:12].values

model = load_model('saved_model.h5')

for root, dirs, files in os.walk(test_directory_edges):
    sortedFiles = sorted(files, key=lambda x:int(x.split('.')[0]))
    for file in sortedFiles[0:]:
        img = cv2.imread(root + '/' + file)
        img = cv2.resize(img,(512,512),interpolation=cv2.INTER_AREA)
        img = img.reshape((-1,512,512,1))
        test_images_edge.append(img)

test_images_edge = np.array(test_images_edge)
test_images_edge = test_images_edge.reshape((-1,512,512,1))

#test_predictions = model.predict([test_images_edge,test_border_irregularity_features.reshape((196,12))])
test_predictions = model.predict([test_images_edge,test_border_irregularity_features])
# round predictions
test_rounded = [round(x[0]) for x in test_predictions]

test_prediction = pd.DataFrame(test_rounded,columns=['predictions']).to_csv('test_prediction.csv')

然而,当我运行代码时,我得到以下内容:

IndexError: index 196 is out of bounds for axis 0 with size 196

在这一行上恰好发生了这种情况:

test_predictions = model.predict([test_images_edge,test_border_irregularity_features])

关于如何解决这个问题的任何想法?

谢谢。

编辑-1

这是完整的堆栈跟踪:

File "test_model.py", line 38, in <module>
    test_predictions = model.predict([test_images_edge,test_border_irregularity_features])
  File "/home/me/keras/lib/python2.7/site-packages/keras/engine/training.py", line 1517, in predict
    batch_size=batch_size, verbose=verbose)
  File "/home/me/keras/lib/python2.7/site-packages/keras/engine/training.py", line 1139, in _predict_loop
    ins_batch = _slice_arrays(ins, batch_ids)
  File "/home/me/keras/lib/python2.7/site-packages/keras/engine/training.py", line 402, in _slice_arrays
    return [None if x is None else x[start] for x in arrays]
IndexError: index 196 is out of bounds for axis 0 with size 196

这是型号代码:

input_layer_edge = Conv2D(32,(5,5), activation='relu')(image_input_edge)
cov1_edge = Conv2D(24,(5,5),activation='relu',subsample=(2,2))(input_layer_edge)
cov2_edge = Conv2D(36,(5,5),activation='relu',subsample=(2,2))(cov1_edge)
cov3_edge = Conv2D(48,(5,5),activation='relu',subsample=(2,2))(cov2_edge)
cov4_edge = Conv2D(64,(5,5),activation='relu')(cov3_edge)
cov5_edge = Conv2D(64,(3,3),activation='relu')(cov4_edge)
flatten_edge = Flatten()(cov5_edge)

merge = concatenate([flatten_edge,features_input])

d1 = Dense(100, activation='relu')(merge)
out = Dense(1,activation='sigmoid')(d1)

model = Model(inputs=[image_input_edge,features_input], outputs=[out])
答案

这可能是由于输入数组之间的形状不匹配。特别是因为您的模型有两个输入图层,所以输入到模型的两个输入数组必须具有相同数量的样本。请通过打印两个输入数组的形状来验证是否是这种情况,并检查两个打印元组中的第一个数字是否相同:

print(test_images_edge.shape, test_border_irregularity_features.shape)

# alternatively:
assert test_images_edge.shape[0] == test_border_irregularity_features.shape[0], "Different number of samples!"

以上是关于预测Keras中的类 - IndexError:索引196超出了轴0的大小为196的范围的主要内容,如果未能解决你的问题,请参考以下文章

Keras model.fit() IndexError:列表索引超出范围

在 keras 中使用 LSTM 进行预测

IndexError: List Index out of range Keras Tokenizer

无法使用 keras.load_model 保存/加载模型 - IndexError: list index out of range

神经网络的显着性图(使用 Keras)

Keras 中的 LSTM 序列预测只输出输入的最后一步