python - 将 InputLayer 添加到现有 Keras 模型以与 Android Tensor Flow Library 一起使用

标签 python machine-learning tensorflow keras image-recognition

我对 keras 和 TensorFlow 非常陌生,

当尝试将 Keras 模型(在新的 iOS IA 框架上编译并正常工作)转换为要在 Android 中使用的 tensorflow 模型时,我缺少输入节点。

因此,我尝试将 InputLayer 添加到我的模型中,但没有成功。

我得到的错误如下(每次运行时占位符编号都不同......):

InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_159' with dtype float
     [[Node: Placeholder_159 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

这是我的代码,与工作 KERAS 模型相比,修改的部分是此标签之间的几行######################## ################

# dimensions of our images.
img_width, img_height = 150, 150

train_data_dir = '/train'
validation_data_dir = '/validation'
nb_train_samples = 120 #target 2700
nb_validation_samples = 24 #target 600
epochs = 20 #target 50
batch_size = 15 #target 30

if K.image_data_format() == 'channels_first':

    input_shape = (None, 3, img_width, img_height)

else:

    input_shape = (None, img_width, img_height, 3)



##########################
#
#  THIS IS THE CODE FOR INTRODUCING THE INPUT LAYER

# To create the input layer Instanciate an input placeholder
inputp = tensorflow.placeholder(tensorflow.float32, shape=input_shape) 

model = Sequential()

# ADD the input layer as the first layer of the model
model.add(InputLayer(input_tensor=inputp, input_shape=input_shape)) 

#the working code without the input layer was (input_shape without the None dimension):
# model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Conv2D(32, (3, 3)))

#
#  THE REST OF THE CODE IS IDENTICAL TO THE WORKING KERAS MODEL
##########################

model.add(Activation('relu'))    
model.add(MaxPooling2D(pool_size=(2, 2))) 
model.add(Conv2D(32, (3, 3)))    
model.add(Activation('relu'))    
model.add(MaxPooling2D(pool_size=(2, 2)))    
model.add(Conv2D(64, (3, 3)))   
model.add(Activation('relu'))    
model.add(MaxPooling2D(pool_size=(2, 2)))    
model.add(Flatten())    
model.add(Dense(64))    
model.add(Activation('relu'))    
model.add(Dropout(0.5))    
model.add(Dense(3))    
model.add(Activation('softmax')) #use sigmoid when binary and softmax when categorical

model.compile(loss='categorical_crossentropy',    
              optimizer='rmsprop',    
              metrics=['accuracy'])

# this is the augmentation configuration we will use for training

train_datagen = ImageDataGenerator(    
    rescale=1. / 255,    
    shear_range=0.2,    
    zoom_range=0.2,   
    horizontal_flip=True)

# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(    
    train_data_dir,    
    target_size=(img_width, img_height),    
    batch_size=batch_size,    
    class_mode='categorical')

validation_generator = test_datagen.flow_from_directory(    
    validation_data_dir,    
    target_size=(img_width, img_height),    
    batch_size=batch_size,    
    class_mode='categorical')

model.fit_generator(  
    train_generator,    
    steps_per_epoch=nb_train_samples // batch_size,    
    epochs=epochs,    
    validation_data=validation_generator,    
    validation_steps=nb_validation_samples // batch_size)


model.save('androidtest_model.h5')
model.save_weights('androidtest_weights.h5')

最佳答案

使用 Keras API,您不必使用 Tensor 来输入数据。

首先设置展平的输入形状:

# Start construction of the Keras Sequential model.
model = Sequential()

# Add an input layer which is similar to a feed_dict in TensorFlow.
# Note that the input-shape must be a tuple containing the image-size.
model.add(InputLayer(input_shape=(3*img_width*img_height)))

# Add the real shape that conv layer spect
model.add(Reshape((img_width,img_height , 3)))

然后将图像作为 numpy 数组传递来训练网络,这与 scikitlearn 类似

# Note that train_datagen and train_labels must be numpy array object
model.fit(x=train_datagen,
          y=train_labels,
          epochs=1, batch_size=128)

关于python - 将 InputLayer 添加到现有 Keras 模型以与 Android Tensor Flow Library 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45286957/

相关文章:

tensorflow - keras Conv2d值错误: Negative dimension size

python - 为什么使用 tf.py_function 的模型无法序列化?

python - 使用 np.where 值的长度不匹配或如何根据条件将值写入新列

python - 处理 RNN/LSTM 中的缺失数据(时间序列)

javascript - 使用 Django 模板(列表和字典)将 Python 数据结构转换为 js 数据结构

machine-learning - Caffe : train network accuracy = 1 constant ! 准确性问题

python - 尽管存在相关性,为什么 R2 为负?

tensorflow - 导入错误 : No module named tensorflow_transform. 光束

python 如何重新引发已经捕获的异常?

python - 迭代字典键值并用已知计数求平均值