GantMan / nsfw_model

Keras model of NSFW detector
Other
1.8k stars 279 forks source link

Can not squeeze dim[1], expected a dimension of 1, got 2\n\t [[{{node predict/MobilenetV2/Logits/Squeeze}}]] #92

Closed luozhouyang closed 1 year ago

luozhouyang commented 3 years ago

I download the latest model from release, and serving the model using tf serving. But when I make a POST request to the server, errors occur:

{'error': 'Can not squeeze dim[1], expected a dimension of 1, got 2\n\t [[{{node predict/MobilenetV2/Logits/Squeeze}}]]'}

Here is my client:

import json
import logging
import os

import numpy as np
import requests
import tensorflow as tf

class ImageNSFWClassifier:

    def __init__(self, url='http://localhost:8501/v1/models/nsfw:predict', target_size=(244, 244)):
        self.url = url
        self.target_size = target_size

    def __call__(self, images, **kwargs):
        images = self._preprocess_images(images)
        preds = self._post(images)
        print(preds)

    def _post(self, images):
        images = np.array(images)
        # image shape is: [2, 244, 244, 3]
        logging.info('images shape: %s', images.shape)
        req = {
            # 'inputs': {
            #     'input': images.tolist()
            # }
            'instances': images.tolist()
        }
        # logging.info('req:\n %s', json.dumps(req, indent=4))
        resp = requests.post(self.url, data=json.dumps(req)).json()
        return resp

    def _preprocess_images(self, images):
        loaded_images = []
        for img_path in images:
            try:
                img = tf.keras.preprocessing.image.load_img(img_path, target_size=self.target_size)
                img = tf.keras.preprocessing.image.img_to_array(img)
                img = img / 255
                loaded_images.append(img)
            except Exception as e:
                logging.exception('Exception occurs when processing image: %s', img_path)
                logging.exception('Exception is:\n %s', e)
                continue
        return loaded_images

classifier = ImageNSFWClassifier()
classifier(images=[
    'data/images/img0.jpg',
    'data/images/img01.jpg'
])
colindean commented 1 year ago

If this is still a problem, please provide the version of nsfw_detector that you're using, your Python version, your Python platform, and a complete code example of how you're invoking nsfw_detector, and reopen the issue.