首页 > 解决方案 > python:keras包:(ValueError:没有这样的层:fc1)

问题描述

当我尝试执行我的 python 代码时,我得到了这个错误:(ValueError:没有这样的层:fc1):错误捕获

我在我的代码中使用 TensorFlow 和 Keras 包来检测图像中的对象并从自定义数据集中返回相似的图像。

它在本地工作得很好,但是当我在服务器 OVH 中托盘时总是出现错误(我托盘将图层更改为“block5_pool”,但它不适用于我的代码。)

我的代码:

from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.keras.models import Model
import numpy as np
from PIL import Image
from datetime import datetime
from flask import Flask, request, render_template
from pathlib import Path


class FeatureExtractor:
    def __init__(self):
        base_model = VGG16(weights='imagenet', include_top=False)
        self.model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc1').output)

    def extract(self, img):
        """
        Extract a deep feature from an input image
        Args:
            img: from PIL.Image.open(path) or tensorflow.keras.preprocessing.image.load_img(path)

        Returns:
            feature (np.ndarray): deep feature with the shape=(4096, )
        """
        img = img.resize((224, 224))  
        img = img.convert('RGB')  
        x = image.img_to_array(img)  
        x = np.expand_dims(x, axis=0)  
        x = preprocess_input(x) 
        feature = self.model.predict(x)[0]
        return feature / np.linalg.norm(feature)


path = "/home/virtuag/www/storage/searchSCB.jpg"


img =  Image.open(path) 
app = Flask(__name__)
fe = FeatureExtractor()
features = []
img_paths = []
for feature_path in Path("/home/virtuag/www/storage/images_article").glob("*.npy"):
    features.append(np.load(feature_path))
    img_paths.append(Path("/home/virtuag/www/storage/images_article") / (feature_path.stem + ".jpg"))
features = np.array(features)
query = fe.extract(img)
dists = np.linalg.norm(features-query, axis=1)  # L2 distances to features
ids = np.argsort(dists)[:30]  # Top 30 results
scores = [img_paths[id] for id in ids]  
print (scores)```
thank you

标签: pythonnumpytensorflowubuntukeras

解决方案


from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.keras.models import Model
import numpy as np
from PIL import Image
#from feature_extractor import FeatureExtractor
from datetime import datetime
from flask import Flask, request, render_template
from pathlib import Path
from keras.optimizers import Adam
from tensorflow.keras.layers import Dropout, Dense, Activation, Flatten


class FeatureExtractor:
    def __init__(self):
        input_shape = (224, 224, 3)
        base_model = VGG16(weights='imagenet', include_top=False, input_shape=input_shape)
        
        for layer in base_model.layers:
            layer.trainable = False
        last = base_model.layers[-1].output
        x = Flatten()(last)
        x = Dense(1000, activation='relu', name='fc1')(x)
        x = Dropout(0.3)(x)
        x = Dense(10, activation='softmax', name='predictions')(x)
        model = Model(base_model.input, x)
        model.compile(optimizer=Adam(lr=0.001),
        loss = 'categorical_crossentropy',metrics=['accuracy'])
        self.model = Model(inputs=base_model.input, outputs=base_model.layers[-1].output)

    def extract(self, img):
        """
        Extract a deep feature from an input image
        Args:
      img: from PIL.Image.open(path) or tensorflow.keras.preprocessing.image.load_img(path)

        Returns:
            feature (np.ndarray): deep feature with the shape=(4096, )
        """
        img = img.resize((224, 224))  
        img = img.convert('RGB')  
        x = image.img_to_array(img) 
        x = np.expand_dims(x, axis=0) 
        x = preprocess_input(x)  
        feature = self.model.predict(x)[0]  
        return feature / np.linalg.norm(feature)  


path = "/home/virtuag/www/storage/searchSCB.jpg"
#path = "c:/xamppp/htdocs/projet/V-stock/PWA/public/storage/searchSCB.jpg"

img =  Image.open(path) 
app = Flask(__name__)

fe = FeatureExtractor()
features = []
img_paths = []
for feature_path in Path("/home/virtuag/www/storage/images_article").glob("*.npy"):
#for feature_path in Path("c:/xamppp/htdocs/projet/V-stock/PWA/public/storage/images_article").glob("*.npy"):
    features.append(np.load(feature_path))
    #img_paths.append(Path("c:/xamppp/htdocs/projet/V-stock/PWA/public/storage/images_article") / (feature_path.stem + ".jpg"))
    img_paths.append(Path("/home/virtuag/www/storage/images_article") / (feature_path.stem + ".jpg"))
features = np.array(features)
query = fe.extract(img)
dists = np.linalg.norm(features-query, axis=1)  
ids = np.argsort(dists)[:30]  
scores = [img_paths[id] for id in ids]  
#print (img_paths)
#print(query)

and the error : 
raceback (most recent call last):   File "server.py", line 71, in <module>     scores = [img_paths[id] for id in ids]     File "server.py", line 71, in <listcomp>     scores = [img_paths[id] for id in ids]   TypeError: only integer scalar arrays can be converted to a scalar index  

推荐阅读