输入错误尺寸的coremltools导出模型?

时间:2018-07-03 19:52:34

标签: python tensorflow keras coreml coremltools

我通过coremltools导出了模型:

coreml_model = coremltools.converters.keras.convert(model)
coreml_model.save('my_model.mlmodel')

然后,当我将其导入iOS时,我得到了:

input1 MultiArray (Double 1)

在我看来,输入尺寸不正确。我认为应该是30个双精度值和1个二进制输出,所以可能是MultiArray (Double 30)作为输入?

好吧,我还是尝试过:

let model = PredictionModel()
guard let random_test_input = try? MLMultiArray(shape: [30], dataType: .double) else {
    return
}
let d = [28.946907457340416, 23.651251205295942, 20.848493236981295, 2.9486505022627476, 19.76246988067936, 13.44847786346712, 19.84888646187787, 9.577035016581378, 20.277092056011174, 4.428205956020074, 26.57346212148054, 13.3277424887711, 10.922006581604867, 23.47004848915737, 4.120362794693939, 24.86682912094741, 4.565591023296161, 16.85564118150741, 8.300754854155517, 10.43274595744203, 6.135850806878693, 7.737464090946267, 0.6374431422342641, 2.7510065670854624, 25.327854311852775, 18.685750099316806, 8.455681186509617, 25.651466411041778, 7.055552151358634, 0.33626649072226567]
for (index, element) in d.enumerated() {
    random_test_input[index] = NSNumber(value: element)
}
do{
    let output = try model.prediction(input1: random_test_input)
    print(output)
}catch{
    print(error)
    return
}

我得到一个错误:

  

输入要素input1表示为长度为30的向量,但是模型期望输入的长度为1。

这是我的导出代码:

batch_size = 50
epochs = 10
test_size = 500
input_dim = 30

data = np.load(data_filename)
x, y = data['x'], data['y']  # x.shape = (3114, 30) 3114 training samples with 30 data points per sample

# y is a category matrix [0, 1, 0, 0] means that there's a one. [0, 0, 0, 1] means there is a 4. 
# y.shape = (3114, 2); In our case we only have 0's and 1's, so [1, 0] or [0, 1]

# Shuffle them
p = np.random.permutation(x.shape[0])
x, y = x[p], y[p]

x_train, x_test = x[:2000], x[2000:]
y_train, y_test = y[:2000], y[2000:]

x_train, x_test = np.expand_dims(x_train, axis=2), np.expand_dims(x_test, axis=2)
#Add another dimension. I don't really know why we do this. x_train.shape = (2000, 30, 1)

# Model Architecture
model = Sequential()

# Convolutional Layer
model.add(Conv1D(filters=10, kernel_size=5, input_shape=(input_dim, 1))) #
model.add(Flatten())

# Dense Layer
model.add(Dense(input_dim, activation='relu'))

# Logits Layer
# model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))

rmsprop = optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)
sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(optimizer=rmsprop,
    loss='binary_crossentropy',
    metrics=['accuracy'],
)

model.fit(x=x_train, y=y_train, batch_size=batch_size, epochs=epochs)

accuracy = model.evaluate(x=x_test, y=y_test, batch_size=batch_size)

print("Overall accuracy: {}".format(accuracy[1]))
print(model.output.op.name)

coreml_model = coremltools.converters.keras.convert(model)
coreml_model.save('my_model.mlmodel')

0 个答案:

没有答案