Coremltools: ошибки, позволяющие получить простейшую сверточную модель - PullRequest
0 голосов
/ 05 апреля 2020

Предположим, я создаю простейшую модель в Керасе:

from keras.layers import *
from keras import Input, Model

import coremltools


def MyModel(inputs_shape=(None,None,3), channels=64):

        inpt = Input(shape=inputs_shape)

        # channels
        skip = Conv2D(channels, (3, 3), strides=1, activation=None, padding='same', name='conv_in')(inpt)
        out = Conv2D(3, (3, 3), strides=1, padding='same', activation='tanh',name='out')(skip)

        return Model(inputs=inpt, outputs=out)


model = MyModel()


coreml_model = coremltools.converters.keras.convert(model,
    input_names=["inp1"],
    output_names=["out1"],
    image_scale=1.0,
    model_precision='float32',
    use_float_arraytype=True,
    input_name_shape_dict={'inp1': [None, 384, 384, 3]}
    )


spec = coreml_model._spec


print(spec.description.input[0])

print(spec.description.input[0].type.multiArrayType.shape)

print(spec.description.output[0])


coremltools.utils.save_spec(spec, "test.mlmodel")

Вывод:

2 : out, <keras.layers.convolutional.Conv2D object at 0x7f08ca491470>
3 : out__activation__, <keras.layers.core.Activation object at 0x7f08ca4b0b70>
name: "inp1"
type {
  multiArrayType {
    shape: 3
    shape: 384
    shape: 384
    dataType: FLOAT32
  }
}

[3, 384, 384]
name: "out1"
type {
  multiArrayType {
    shape: 3
    dataType: FLOAT32
  }
}

Таким образом, форма вывода равна 3, что неверно. И когда я пытаюсь избавиться от input_name_shape_dict, я получаю:

Please provide a finite height (H), width (W) & channel value (C) using input_name_shape_dict arg with key = 'inp1' and value = [None, H, W, C]
Converted .mlmodel can be modified to have flexible input shape using coremltools.models.neural_network.flexible_shape_utils

Итак, он хочет NHW C.

Попытка вывода дает:

Layer 'conv_in' of type 'Convolution' has input rank 3 but expects rank at least 4

Когда я пытаюсь добавить дополнительное измерение для ввода:

spec.description.input[0].type.multiArrayType.shape.extend([1, 3, 384, 384])
del spec.description.input[0].type.multiArrayType.shape[0]
del spec.description.input[0].type.multiArrayType.shape[0]
del spec.description.input[0].type.multiArrayType.shape[0]
[name: "inp1"
type {
  multiArrayType {
    shape: 1
    shape: 3
    shape: 384
    shape: 384
    dataType: FLOAT32
  }
}
]

Я получаю для вывода:

Shape (1 x 384 x 384 x 3) was not in enumerated set of allowed shapes

Следуя этому совету и делая форму ввода (1,1,384,384,3) не поможет.

Как я могу заставить его работать и выдает правильный вывод?

Вывод:

From PIL import Image

model_cml = coremltools.models.MLModel('my.mlmodel')

# load image
img = np.array(Image.open('patch4.png').convert('RGB'))[np.newaxis,...]/127.5 - 1

# Make predictions
predictions = model_cml.predict({'inp1':img})

# save result
res = predictions['out1']
res = np.clip((res[0]+1)*127.5,0,255).astype(np.uint8)

Image.fromarray(res).save('out32.png')

ОБНОВЛЕНИЕ:

Я могу запустить эту модель с входными данными (3,1,384,384), в результате получается (1,3,3,384,384) что не имеет никакого смысла для меня.

ОБНОВЛЕНИЕ 2:

установка фиксированной формы в Keras

def MyModel(inputs_shape=(384,384,3), channels=64):

        inpt = Input(shape=inputs_shape)

фиксированная проблема с выходной формой, но я все еще не могу запустить модель (Layer 'conv_in' of type 'Convolution' has input rank 3 but expects rank at least 4)

ОБНОВЛЕНИЕ:

Следующее работает, чтобы избавиться от несоответствия форм ввода и conv_in.

1). Понижение до coremltools==3.0. Версия 3.3 (модель версии 4) кажется сломанной.

2.) Использовать фиксированную форму в модели keras, нет input_shape_dist и переменную форму для модели coreml

from keras.layers import *
from keras import Input, Model

import coremltools


def MyModel(inputs_shape=(384,384,3), channels=64):

        inpt = Input(shape=inputs_shape)

        # channels
        skip = Conv2D(channels, (3, 3), strides=1, activation=None, padding='same', name='conv_in')(inpt)
        out = Conv2D(3, (3, 3), strides=1, padding='same', activation='tanh',name='out')(skip)

        return Model(inputs=inpt, outputs=out)


model = MyModel()

model.save('test.model')

print(model.summary())

'''
# v.3.3
coreml_model = coremltools.converters.keras.convert(model,
    input_names=["image"],
    output_names="out1",
    image_scale=1.0,
    model_precision='float32',
    use_float_arraytype=True,
    input_name_shape_dict={'inp1': [None, 384, 384, 3]}
    )
'''

coreml_model = coremltools.converters.keras.convert(model,
    input_names=["image"],
    output_names="out1",
    image_scale=1.0,
    model_precision='float32',

    )


spec = coreml_model._spec


from coremltools.models.neural_network import flexible_shape_utils
shape_range = flexible_shape_utils.NeuralNetworkMultiArrayShapeRange()
shape_range.add_channel_range((3,3))
shape_range.add_height_range((64, 384))
shape_range.add_width_range((64, 384))
flexible_shape_utils.update_multiarray_shape_range(spec, feature_name='image', shape_range=shape_range)


print(spec.description.input)

print(spec.description.input[0].type.multiArrayType.shape)

print(spec.description.output)


coremltools.utils.save_spec(spec, "my.mlmodel")

В сценарии вывода, массив данных формы (1,1,3,384,384):

img = np.zeros((1,1,3,384,384))

# Make predictions
predictions = model_cml.predict({'inp1':img})
res = predictions['out1'] # (3, 384,384)

1 Ответ

1 голос
/ 05 апреля 2020

Вы можете игнорировать, что файл mlmodel имеет в выходной форме, если он неверен. Это скорее проблема метаданных, то есть модель все равно будет работать нормально и делать правильные вещи. Преобразователь не всегда может определить правильную форму вывода (не знаю почему).

...