尝试将模型从 keras 导出到 CoreML

Trying to export a model from keras to CoreML

这是我第一个使用keras的项目。

想法是创建一个可以识别木材颜色的模型。如果一种颜色是我要识别的颜色,我会得到 1 如果不是,我会得到 0.

我有一个这样的 csv 文件:

red,green,blue,isWood
63,110,255,0
58,104,255,0
63,112,255,0
96,141,198,1
95,140,197,1
95,138,195,1

我结合网上找到的几个教程创建了这个模型。

import pandas as pd

train_df = pd.read_csv('woodData.csv')

train_df.head()

#create a dataframe with all training data except the target column
train_X = train_df.drop(columns=['isWood'])

#check that the target variable has been removed
train_X.head()

#create a dataframe with only the target column
train_y = train_df[['isWood']]

#view dataframe
train_y.head()

from keras.models import Sequential
from keras.layers import Dense
#create model
model = Sequential()

#get number of columns in training data
n_cols = train_X.shape[1]

#add model layers
model.add(Dense(10, activation='relu', input_shape=(n_cols,)))
model.add(Dense(10, activation='relu'))
model.add(Dense(1))

#compile model using mse as a measure of model performance
model.compile(optimizer='adam', loss='mean_squared_error')

# LINE 1
coreml_model = coremltools.converters.keras.convert(model, ['red','green','blue'], 'isWood')
coreml_model.input_description['red'] = 'red value'
coreml_model.input_description['green'] = 'green value'
coreml_model.input_description['blue'] = 'blue value'
coreml_model.output_description['isWood'] = '1 = is wood, 0 is not wood'
coreml_model.save('wood.mlmodel')

此应用在线崩溃

coreml_model.input_description['green'] = 'green value'

出现以下错误消息:

Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/coremltools/models/model.py in __setitem__(self, key, value)
     77                 f.shortDescription = value
     78                 return
---> 79         raise AttributeError("No feature with name %s." % key)
     80 
     81     def __iter__(self):

AttributeError: No feature with name green.

我试过将LINE 1修改为

coreml_model = coremltools.converters.keras.convert(model, input_names=['red','green','blue'], output_names='isWood')

coreml_model = coremltools.converters.keras.convert(model, input_names=['red','green','blue'], output_names=['isWood'])

没有区别。

有什么想法吗?

我认为问题是您的 Keras 模型只有一个输入(具有 3 个特征)所以您只能在 coremltools.converters.keras.convert 中给出一个输入名称。

尝试用以下内容替换 LINE 1

coreml_model = coremltools.converters.keras.convert(model, 'rgb-color', 'isWood')