Giter VIP home page Giter VIP logo

Comments (15)

dimabendera avatar dimabendera commented on July 25, 2024 1

Здраствуйте!
Путаница возникает из за многократного перезапуска train в jupyter.

В замороженную модель .pb нужно явно укразывать точку входа, у нас по историчиским причинам она называлась input_2:0. Скорее всего в вашем случае это название отличается, но это легко исправить:
1 способ.
загрузите модель .h5. которую хотите конвертировать,
затем напишите model.summary(), вы увидете архитекуру сети
первый слой - это тот который мы должны указать как точку входа,
скорее всего он будет начинаться с "input".
Затем просто добовляем

class MyNumberClassificator(OptionsDetector):
    def __init__(self):
        OptionsDetector.__init__(self)
        self.INPUT_NODE = "НАЗВАНИЕ_СЛОЯ:0"
        ...

2 способ. Поменять название в .h5 с помощью вот этого скрипта

import keras
# Указываем путь к модели
PATH = "../models/ocr/eu/anpr_ocr_eu_2-gpu.h5"

# Загружаем модель
model = keras.models.load_model(PATH, compile=False)
# Смотрим на слои входа и  выхода
model.summary()

# Вместо "the_input" указываем слой входа
inp = model.get_layer("the_input")
# Вместо "softmax" указываем слой входа
out = model.get_layer("softmax")

# Указываем новые названия
inp.name = "the_input_eu"
out.name = "softmax_eu"

# Строим модель от новых слоев входа и выхода
net_inp = inp.input
net_out = out.output
model = keras.Model(input=net_inp, output=net_out)

# Смотрим всё ли ок
model.summary()

# Сохраняем новую .h5 модели
model.save(PATH)

Вместо сохранения можно сразу конвертировать в .pb

Вы сами тренировали модель или использовали какую то из наших? Если нашу, то это наша ошибка, укажите пожалуйсто версию модели и мы её перезальём с правильным названием входа.

from nomeroff-net.

dimabendera avatar dimabendera commented on July 25, 2024

Здраствуйте, я бы вам рекомендовал самому попытаться конвертировать модель из .h5 в .pb.
Как это сделать можете посмотреть тут https://github.com/ria-com/nomeroff-net/blob/master/train/ocr-ru.ipynb в секции "Convert keras OCR .h5 model to .pb graph".

from nomeroff-net.

flash1nho avatar flash1nho commented on July 25, 2024

Спасибо, я как раз читаю по этим темам ! 👍

from nomeroff-net.

flash1nho avatar flash1nho commented on July 25, 2024

И снова здравствуйте! :)
Сконвертировал из datasets все модели.
Использовал dataset: https://nomeroff.net.ua/datasets/autoriaNumberplateOptionsDataset-2019-03-06.zip
Python: 3.6
Tenserflow + GPU 1.13.1

Код, train/py/options.py

import os
import sys
import warnings
warnings.filterwarnings('ignore')

# change this property
NOMEROFF_NET_DIR = os.path.abspath('../../')

DATASET_NAME = "options"
VERSION = "2019_05_21"

LOG_DIR = os.path.join(NOMEROFF_NET_DIR, "logs/")
PATH_TO_DATASET = os.path.join(NOMEROFF_NET_DIR, "datasets/", DATASET_NAME)
RESULT_PATH = os.path.join(NOMEROFF_NET_DIR, "models/", 'numberplate_{}_{}.h5'.format(DATASET_NAME, VERSION))

FROZEN_MODEL_PATH = os.path.join(NOMEROFF_NET_DIR, "models/", 'numberplate_{}_{}.pb'.format(DATASET_NAME, VERSION))

sys.path.append(NOMEROFF_NET_DIR)

from NomeroffNet import OptionsDetector
from NomeroffNet.Base import convert_keras_to_freeze_pb

# definde your parameters
# definde your parameters
class MyNumberClassificator(OptionsDetector):
    def __init__(self):
        OptionsDetector.__init__(self)
        # outputs 1
        self.CLASS_STATE = ["BACKGROUND", "FILLED", "NOT_FILLED"]

        # outputs 2
        self.CLASS_REGION = ["xx-unknown", "eu-ua-2015", "eu-ua-2004", "eu-ua-1995", "eu", "xx-transit", "ru"]

        self.EPOCHS           = 10
        self.BATCH_SIZE       = 64

        self.HEIGHT         = 64
        self.WEIGHT         = 295

# initialize region detector.
numberClassificator = MyNumberClassificator()
numberClassificator.prepare(PATH_TO_DATASET)

# train
model = numberClassificator.train(LOG_DIR, cnn="simple")

numberClassificator.test()

numberClassificator.save(RESULT_PATH)
#model = numberClassificator.load(RESULT_PATH)

import keras
keras.backend.clear_session()
model = numberClassificator.load(RESULT_PATH)
convert_keras_to_freeze_pb(numberClassificator.MODEL, FROZEN_MODEL_PATH)

Модель создалась успешно, но при запуске скрипта происходит ошибка:

  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/importer.py", line 426, in import_graph_def
    graph._c_graph, serialized, options)  # pylint: disable=protected-access
tensorflow.python.framework.errors_impl.InvalidArgumentError: Requested return tensor 'input_2:0' not found in graph def

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "paint.py", line 76, in <module>
    paint()
  File "paint.py", line 53, in paint
    optionsDetector.load(OPTIONS_MODEL_PATH)
  File "nomeroff-net/NomeroffNet/OptionsDetector.py", line 261, in load
    self.load_frozen(path_to_model)
  File "nomeroff-net/NomeroffNet/OptionsDetector.py", line 317, in load_frozen
    graph_def, return_elements = [self.INPUT_NODE, self.OUTPUT_NODES[0], self.OUTPUT_NODES[1]]
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 507, in new_func
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/importer.py", line 430, in import_graph_def
    raise ValueError(str(e))
ValueError: Requested return tensor 'input_2:0' not found in graph def

Не подскажете?)

from nomeroff-net.

flash1nho avatar flash1nho commented on July 25, 2024

Тренировал сам, используя этот dataset - https://nomeroff.net.ua/datasets/autoriaNumberplateOptionsDataset-2019-03-06.zip
Код, который использовал, описал выше.

from nomeroff-net.

flash1nho avatar flash1nho commented on July 25, 2024

Если использовать Ваши модели без конвертации в *.pb, то происходит следующее:

ValueError: NodeDef mentions attr 'explicit_paddings' not in Op<name=Conv2D; signature=input:T, filter:T -> output:T; attr=T:type,allowed=[DT_HALF, DT_BFLOAT16, DT_FLOAT, DT_DOUBLE]; attr=strides:list(int); attr=use_cudnn_on_gpu:bool,default=true; attr=padding:string,allowed=["SAME", "VALID"]; attr=data_format:string,default="NHWC",allowed=["NHWC", "NCHW"]; attr=dilations:list(int),default=[1, 1, 1, 1]>; NodeDef: {{node import/conv1/convolution}} = Conv2D[T=DT_FLOAT, data_format="NHWC", dilations=[1, 1, 1, 1], explicit_paddings=[], padding="VALID", strides=[1, 2, 2, 1], use_cudnn_on_gpu=true](import/zero_padding2d_1/Pad, import/conv1/kernel/read). (Check whether your GraphDef-interpreting binary is up to date with your GraphDef-generating binary.).

from nomeroff-net.

flash1nho avatar flash1nho commented on July 25, 2024

Спасибо! Все собралось и сконвертировалось, скрипт работает...
Остался последний вопрос, почему скрипт так медленно работает?
Выполняется 20 секунд...
Стоит Tenserflow + GPU
Trace выполнения скрипта:

Using TensorFlow backend.
2019-05-22 13:32:52.085232: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2599990000 Hz
2019-05-22 13:32:52.086878: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55eae8bf18b0 executing computations on platform Host. Devices:
2019-05-22 13:32:52.086920: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): <undefined>, <undefined>
2019-05-22 13:32:52.221899: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55eaeb671930 executing computations on platform CUDA. Devices:
2019-05-22 13:32:52.221946: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): GeForce GTX 1080 Ti, Compute Capability 6.1
2019-05-22 13:32:52.222150: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1433] Found device 0 with properties: 
name: GeForce GTX 1080 Ti major: 6 minor: 1 memoryClockRate(GHz): 1.582
pciBusID: 0000:03:00.0
totalMemory: 10.92GiB freeMemory: 10.77GiB
2019-05-22 13:32:52.222184: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-05-22 13:32:52.223896: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-22 13:32:52.223923: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0 
2019-05-22 13:32:52.223936: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N 
2019-05-22 13:32:52.224094: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10479 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:03:00.0, compute capability: 6.1)
2019-05-22 13:32:52.650468: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-05-22 13:32:52.650517: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-22 13:32:52.650527: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0 
2019-05-22 13:32:52.650538: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N 
2019-05-22 13:32:52.650660: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10479 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:03:00.0, compute capability: 6.1)
2019-05-22 13:32:52.656849: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-05-22 13:32:52.656886: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-22 13:32:52.656898: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0 
2019-05-22 13:32:52.656906: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N 
2019-05-22 13:32:52.656991: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10479 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:03:00.0, compute capability: 6.1)
WARNING:tensorflow:From /usr/local/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
WARNING:tensorflow:From nomeroff-net/Mask_RCNN/mrcnn/model.py:772: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
2019-05-22 13:32:58.746578: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-05-22 13:32:58.746645: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-22 13:32:58.746660: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0 
2019-05-22 13:32:58.746671: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N 
2019-05-22 13:32:58.746770: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10479 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:03:00.0, compute capability: 6.1)
2019-05-22 13:32:58.883343: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-05-22 13:32:58.883409: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-22 13:32:58.883423: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0 
2019-05-22 13:32:58.883434: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N 
2019-05-22 13:32:58.883548: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10479 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:03:00.0, compute capability: 6.1)
2019-05-22 13:32:58.963243: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-05-22 13:32:58.963311: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-22 13:32:58.963327: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0 
2019-05-22 13:32:58.963338: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N 
2019-05-22 13:32:58.963436: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10479 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:03:00.0, compute capability: 6.1)
2019-05-22 13:33:07.380990: I tensorflow/stream_executor/dso_loader.cc:152] successfully opened CUDA library libcublas.so.10.0 locally
['']
20

from nomeroff-net.

dimabendera avatar dimabendera commented on July 25, 2024

Проверьте точно ли ваш tensorflow использует GPU :

from tensorflow.python.client import device_lib

# Получить все устройства
local_device_protos = device_lib.list_local_devices()
print(local_device_protos)

# Только GPU
local_gpu_device_protos = [x.name for x in local_device_protos if x.device_type == 'GPU']
print(local_gpu_device_protos)

from nomeroff-net.

flash1nho avatar flash1nho commented on July 25, 2024

local_device_protos:

[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 14518210691399499541
, name: "/device:XLA_CPU:0"
device_type: "XLA_CPU"
memory_limit: 17179869184
locality {
}
incarnation: 6496402294402102289
physical_device_desc: "device: XLA_CPU device"
, name: "/device:XLA_GPU:0"
device_type: "XLA_GPU"
memory_limit: 17179869184
locality {
}
incarnation: 5239292805269579555
physical_device_desc: "device: XLA_GPU device"
, name: "/device:GPU:0"
device_type: "GPU"
memory_limit: 10989060096
locality {
  bus_id: 1
  links {
  }
}
incarnation: 7951977328508398585
physical_device_desc: "device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:03:00.0, compute capability: 6.1"
]

local_gpu_device_protos

['/device:GPU:0']

from nomeroff-net.

dimabendera avatar dimabendera commented on July 25, 2024

Скорее всего вы учитываете время вместе с временем загрузки модели. Фактически она должна загрузится один раз, а потом многократно использоваться.

Пожалуйста, попробуйте запустить этот скрипт используя вашу модель. Так вы сможете более точно узнать скорость оброботки одной фотографии.
Первый раз gpu работает медленнее, из за того что она фактически "разгоняется".

Так же хочу отметить что у вас происходит весьма долгая загрузка модели.
Тут дело в том, что драйвер тратит некоторое время на сканирование всей шины и определение GPU. Для того, чтобы упростить эту задачу существует сервис nvidia-persistenced.
Попробуйте запустить в командной строке:

systemctl enable nvidia-persistenced.service;
systemctl start nvidia-persistenced.service;
systemctl status nvidia-persistenced.service;

from nomeroff-net.

ApelSYN avatar ApelSYN commented on July 25, 2024

Спасибо! Все собралось и сконвертировалось, скрипт работает...
Остался последний вопрос, почему скрипт так медленно работает?
Выполняется 20 секунд...

Игорь, скрипт кроме того что непосредственно распознает номера, на этапе загрузки загружает модели и проводит множество стартовых инициализаций. Для того чтоб эти операции не повторялись вместе с очередным запуском на распознавание есть смысл написать на питоне небольшой REST-сервис, который на вход будет получать файл для распознавания а на выходе возвращать зоны с распознанными номерами.

Также можно все оформить не через REST-сервис а через брокер очередей, например RabbitMQ или Apache Kafka. Тогда python-воркер будет брать очередную задачу, обрабатывать и отправлять в очередь обработанных заданий информацию о результатах распознавания.

В качестве фреймворка для создания REST-сервиса можете посмотреть Tornado.

Со временем мы планируем написать такой сервис и добавить его в проект, но это планы не на ближайшее время.

from nomeroff-net.

flash1nho avatar flash1nho commented on July 25, 2024

Ваша демка получается работает через REST ?
https://nomeroff.net.ua/
Если нет, то мне непонятно почему у вас так быстро :)

from nomeroff-net.

ApelSYN avatar ApelSYN commented on July 25, 2024

from nomeroff-net.

flash1nho avatar flash1nho commented on July 25, 2024

Спасибо за советы и помощь! Буду пробовать поднимать сервис

from nomeroff-net.

flash1nho avatar flash1nho commented on July 25, 2024

It Works!
примерно ~1sec
Взял из примера Flask Server
https://github.com/himanshurawlani/keras-and-tensorflow-serving

from nomeroff-net.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.