尝试将模型从keras导出到CoreML

时间:2019-02-05 11:21:18

标签: python keras coreml coremltools

这是我第一个使用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'])

没有区别。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我认为问题在于您的Keras模型只有一个输入(具有3个功能),因此您只能在coremltools.converters.keras.convert中输入一个输入名称。

尝试将LINE 1替换为以下内容:

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