简体   繁体   English

具有多个输入的馈送keras模型

[英]Feeding keras model with multiple inputs

I am trying to do a simple hello world with Keras and stuck. 我正在尝试与Keras打个招呼,陷入困境。 At the beginning I had 1 layer with 1 input and 1 output and it worked pretty well for a straight line approximation ;) 刚开始时,我有1层1输入1输出,对于直线逼近效果很好;)

import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import RMSprop
from keras.losses import mean_squared_error
mo = Sequential()
d = Dense(1, input_shape=(1,))
mo.add(d)
mo.summary()

mo.compile(loss=mean_squared_error, optimizer=RMSprop(lr=0.4), metrics=['accuracy'])

mo.trainable = True

for i in range(-100, 100):
    mo.train_on_batch(x = [i], y = [i])

After that I've got bravery for 2 input parameters: 之后,我对2个输入参数非常勇敢:

d = Dense(1, input_shape=(2,))
for i in range(-100, 100):
    mo.train_on_batch(x = [np.array([i,i])], y = [i])

np.array([1,1]).shape # gives (2,)

Though I am getting an exception: 虽然我遇到一个例外:

ValueError: Error when checking input: expected dense_53_input to have shape (2,) but got array with shape (1,) ValueError:检查输入时出错:预期density_53_input具有形状(2,),但数组的形状为(1,)

I tried various combinations like [[i],[i]] . 我尝试了[[i],[i]]类的各种组合。

The first dimension is always the batch dimension in Keras. 第一维始终是Keras中的批次维。 Batch size refers to the number of samples processed in a pass (forward and backward). 批次大小是指一次通过(向前和向后)处理的样品数量。 When you specify the input_shape argument it does not include the batch dimension. 当您指定input_shape参数时,它不包括批次尺寸。 Therefore, a network with input shape of (2,) takes input data of shape (?,2) where ? 因此,输入形状为(2,)的网络采用形状为(?,2)输入数据,其中? refers to the batch size. 指批次大小。 So you must pass arrays of shape (?,2) : 因此,您必须传递形状为(?,2)数组:

mo.train_on_batch(x=[np.array([[i,i]])], y=[i])

since: 以来:

np.array([[i,i]]).shape   # it is (1,2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM