You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Keras的VGG19模型时报错All inputs to the layer should be tensors

问题修复方案

错误根因

报错由以下三个问题共同导致:

  • 直接调用model()时输入要求为Keras张量格式,你传入的是imageio读取的numpy数组,类型不匹配
  • 读取的图片包含alpha通道(第四维),和VGG19要求的3通道输入不匹配,你报错信息里的uint8数组最后一位255就是alpha通道数值
  • 缺少VGG19必备的输入预处理步骤,同时单张图片缺少批量维度

修复后可运行代码

from keras.applications.vgg19 import VGG19, preprocess_input
import keras.backend as K
from keras.models import Model
import imageio as iio
import numpy as np

image_shape = (384,384,3)
vgg19 = VGG19(include_top=False, weights='imagenet', input_shape=image_shape)
vgg19.trainable = False
for l in vgg19.layers:
    l.trainable = False
model = Model(inputs=vgg19.input, outputs=vgg19.get_layer('block5_conv4').output)
model.trainable = False

# 读取图片并去掉alpha通道
img1 = iio.imread('img1.jpg')[...,:3]
img2 = iio.imread('img2.jpg')[...,:3]

# 增加批量维度 + 执行VGG19官方预处理
img1_pre = preprocess_input(np.expand_dims(img1, axis=0))
img2_pre = preprocess_input(np.expand_dims(img2, axis=0))

# 用predict方法获取numpy格式的特征,再计算损失
feat1 = model.predict(img1_pre, verbose=0)
feat2 = model.predict(img2_pre, verbose=0)
mean = np.mean(np.square(feat1 - feat2))

# 如果需要保留Keras张量计算逻辑,可改用以下写法
# img1_tensor = K.constant(img1_pre)
# img2_tensor = K.constant(img2_pre)
# mean = K.mean(K.square(model(img1_tensor) - model(img2_tensor)))

补充说明

如果原始图片尺寸不是384*384,需要在读取后添加resize步骤,保证输入尺寸和模型定义的input_shape匹配。

内容的提问来源于stack exchange,提问作者Safi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 09:45:04