解决预训练的VGG16模型预测输入图片获取概率时的decode_predictions(preds,top=5)[0网络报错问题

2023年9月11日 09:40 ry 272

最近在弄掌纹识别方向,用到了VGG16模型,便开始学习该模型的基本知识,该模型可以连接ImageNet数据库,该数据库是目前公开可获取的最大规模图像数据库,包含了超过1000万张来自1000个类别的图像,为计算机视觉和深度学习研究提供了丰富的训练和测试资源,我从网上随机选取了一张草莓图片作为VGG16预训练模型的输入,代码如下

import numpy as np
import os

import matplotlib.pyplot as plt
from keras.applications.vgg16 import VGG16,preprocess_input
from keras.preprocessing import image
from keras.applications.resnet50 import decode_predictions

model = VGG16(weights='imagenet')
#获取模型的权重
all_weights = model.get_weights()
print('权重长度为:',len(all_weights))
for ii,ind in zip(all_weights,range(0,len(all_weights))):
    print(ind,model.get_weights()[ind].shape)

img_path = 'C:/users/14499/desktop/caomei.jpg'
img = image.load_img(img_path,target_size=(224,224))
x = image.img_to_array(img)

x = np.expand_dims(x,axis=0)

x = preprocess_input(x)
preds = model.predict(x)
# print(preds)
print(preds)
print(decode_predictions(preds,top=5)[0])

我的环境是keras==2.3.1 ,tensorflow==1.15.5,运行代码报错了Exception: URL fetch failure on https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json : None -- [WinError 10054] 远程主机强迫关闭了一个现有的连接,发现这这个链接需要代理,直接打开梯子,查看梯子的端口号,然后在代码里面配置代理即可,完整代码如下所示

import numpy as np
import os
os.environ['HTTP_PROXY'] = 'http://127.0.0.1:7890'
os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:7890'
import matplotlib.pyplot as plt
from keras.applications.vgg16 import VGG16,preprocess_input
from keras.preprocessing import image
from keras.applications.resnet50 import decode_predictions

model = VGG16(weights='imagenet')
#获取模型的权重
all_weights = model.get_weights()
print('权重长度为:',len(all_weights))
for ii,ind in zip(all_weights,range(0,len(all_weights))):
    print(ind,model.get_weights()[ind].shape)

img_path = 'C:/users/14499/desktop/caomei.jpg'
img = image.load_img(img_path,target_size=(224,224))
x = image.img_to_array(img)

x = np.expand_dims(x,axis=0)

x = preprocess_input(x)
preds = model.predict(x)
# print(preds)
print(preds)
print(decode_predictions(preds,top=5)[0])

再次运行,完美通过!

如果上述代码帮助您很多,可以打赏下以减少服务器的开支吗,万分感谢!

欢迎发表评论~

点击此处登录后即可评论


评论列表
暂时还没有任何评论哦...

赣ICP备2021001574号-1

赣公网安备 36092402000079号