“IndexError:列表索引超出范围”当尝试使用keras的vgg16加载权重时

时间:2017-05-02 01:21:56

标签: python tensorflow keras index-error

我想加载从这个地址下载的一组预先训练的重量:

  

https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3

我使用下面的代码加载权重:

import os
from PIL import Image
import tensorflow
from keras.models import Sequential

im = Image.open("test.png")
model_vgg = Sequential()
model = model_vgg.load_weights("vgg16_weights.h5")
print(model.predict_classes(im))

收到此错误:

Using TensorFlow backend.
Traceback (most recent call last):
  File "predict.py", line 8, in <module>
    model = model_vgg.load_weights("vgg16_weights.h5")
  File "C:\Users\Cliente\AppData\Local\Programs\Python\Python35\lib\site-packag
s\keras\models.py", line 707, in load_weights
    if legacy_models.needs_legacy_support(self):
  File "C:\Users\Cliente\AppData\Local\Programs\Python\Python35\lib\site-packag
s\keras\legacy\models.py", line 5, in needs_legacy_support
    return isinstance(model.layers[0], Merge)
IndexError: list index out of range

图像未被引用,因为您可以看到,问题发生在8º线。 Tensorflow和Keras是最新的。 我认为我在某个地方犯了一个错误,因为其他人似乎没有在下载网站的评论中对此错误做任何评论。

有什么问题?为什么不能加载它?

1 个答案:

答案 0 :(得分:3)

这里的问题是您尝试将权重加载到VGG模型而不仅仅是Sequential容器的模型。错误在于说你的模型没有任何图层,当然它是剂量的(毕竟它只是顺序容器)。

您必须定义VGG模型,然后加载权重。

因此,在与获得weights的链接相同的链接上使用模型进行编译并按原样加载权重:

以下是对链接处代码的引用:

from keras.models import Sequential

from keras.layers.core import Flatten, Dense, Dropout
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.optimizers import SGD
import cv2, numpy as np

def VGG_16(weights_path=None):
    model = Sequential()
    model.add(ZeroPadding2D((1,1),input_shape=(3,224,224)))
    model.add(Convolution2D(64, 3, 3, activation='relu'))
    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(64, 3, 3, activation='relu'))
    model.add(MaxPooling2D((2,2), strides=(2,2)))

    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(128, 3, 3, activation='relu'))
    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(128, 3, 3, activation='relu'))
    model.add(MaxPooling2D((2,2), strides=(2,2)))

    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(256, 3, 3, activation='relu'))
    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(256, 3, 3, activation='relu'))
    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(256, 3, 3, activation='relu'))
    model.add(MaxPooling2D((2,2), strides=(2,2)))

    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(512, 3, 3, activation='relu'))
    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(512, 3, 3, activation='relu'))
    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(512, 3, 3, activation='relu'))
    model.add(MaxPooling2D((2,2), strides=(2,2)))

    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(512, 3, 3, activation='relu'))
    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(512, 3, 3, activation='relu'))
    model.add(ZeroPadding2D((1,1)))
    model.add(Convolution2D(512, 3, 3, activation='relu'))
    model.add(MaxPooling2D((2,2), strides=(2,2)))

    model.add(Flatten())
    model.add(Dense(4096, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(4096, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(1000, activation='softmax'))

    if weights_path:
        model.load_weights(weights_path)

    return model

if __name__ == "__main__":
    im = cv2.resize(cv2.imread('cat.jpg'), (224, 224)).astype(np.float32)
    im[:,:,0] -= 103.939
    im[:,:,1] -= 116.779
    im[:,:,2] -= 123.68
    im = im.transpose((2,0,1))
    im = np.expand_dims(im, axis=0)

    # Test pretrained model
    model = VGG_16('vgg16_weights.h5')
    sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
    model.compile(optimizer=sgd, loss='categorical_crossentropy')
    out = model.predict(im)
    print np.argmax(out)