在嘗試匯入 VGG19 模型時,下面的代碼會生成非張量輸入的錯誤。雖然我在這里關注另一個這個代碼片段。
代碼:
from keras.applications.vgg19 import VGG19
import keras.backend as K
from keras.models import Model
import imageio as iio
image_shape = (384,384,3)
vgg19 = VGG19(include_top=False, weights='imagenet', input_shape=image_shape)
vgg19.trainable = False
# Make trainable as False
for l in vgg19.layers:
l.trainable = False
model = Model(inputs=vgg19.input, outputs=vgg19.get_layer('block5_conv4').output)
model.trainable = False
img1 = iio.imread('img1.jpg')
img2 = iio.imread('img2.jpg')
mean = K.mean(K.square(model(img1) - model(img2)))
錯誤:
...,
[164, 90, 0, 255],
[164, 90, 0, 255],
[164, 90, 0, 255]]]], dtype=uint8)]. All inputs to the layer should be tensors.
無法弄清楚為什么。
uj5u.com熱心網友回復:
也許嘗試將您的影像轉換為張量:
import numpy
from PIL import Image
from keras.applications.vgg19 import VGG19
import keras.backend as K
from keras.models import Model
import imageio as iio
# Create random images
for n in range(2):
a = numpy.random.rand(384,384,3) * 255
im = Image.fromarray(a.astype('uint8')).convert('RGB')
im.save('test
.jpg' % n)
image_shape = (384,384,3)
vgg19 = VGG19(include_top=False, weights='imagenet', input_shape=image_shape)
vgg19.trainable = False
# Make trainable as False
for l in vgg19.layers:
l.trainable = False
model = Model(inputs=vgg19.input, outputs=vgg19.get_layer('block5_conv4').output)
model.trainable = False
img1 = iio.imread('test0.jpg')
img2 = iio.imread('test1.jpg')
img1 = tf.expand_dims(tf.constant(img1), axis=0)
img2 = tf.expand_dims(tf.constant(img2), axis=0)
mean = K.mean(K.square(model(img1) - model(img2)))
print(mean)
tf.Tensor(5.283036, shape=(), dtype=float32)
代替tf.expand_dims,您也可以這樣做:
img1 = tf.constant([img1])
img2 = tf.constant([img2])
還有一個選項可以加載您的影像tf.keras.preprocessing.image.load_img:
img1 = tf.keras.preprocessing.image.load_img('test0.jpg')
img2 = tf.keras.preprocessing.image.load_img('test1.jpg')
img1 = tf.constant([tf.keras.preprocessing.image.img_to_array(img1)])
img2 = tf.constant([tf.keras.preprocessing.image.img_to_array(img2)])
mean = K.mean(K.square(model(img1) - model(img2)))
print(mean)
uj5u.com熱心網友回復:
此頁面中的代碼作業正常。我稍微改變了代碼。
image_shape = (384,384,3)
base_model = VGG19(include_top=False, weights='imagenet', input_shape=image_shape)
model = Model(inputs=base_model.input, outputs=base_model.get_layer('block5_conv4').output)
img01 = iio.imread('test0.jpg').astype('float32')
img11 = iio.imread('test1.jpg').astype('float32')
imgx1 = normalize(img01)
imgx2 = normalize(img11)
img1 = np.expand_dims(imgx1, axis=0)
img2 = np.expand_dims(imgx2, axis=0)
mean = np.mean((model.predict(img1) - model.predict(img2))**2)
print(mean)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/372468.html
上一篇:ValueError:無法為形狀為“(20,200)”的張量“Placeholder:0”提供形狀(20,3000)的值
