如何将数组用作密集层的输入

时间:2018-07-17 14:02:54

标签: python tensorflow keras

我正在用python和Keras编码神经网络。我想在网络中添加一个密集层。

在此密集层之后,我将使用一些transposed convolutions,因此我需要像这样重塑初始输入:

labels = np.array([1,2,3,4,5])

train_data_initial = np.array([[1,2,4],[2,4,8],[3,6,9],[4,8,16],[5,10,20]])

input_ = labels.reshape(5,1,1,1)

train_data = train_data_initial.reshape(5,3,1,1)

当我想在密集层中使用此输入时,按照documentation中给出的示例,会出现以下错误:

ValueError: setting an array element with a sequence.

这是我的代码:

import numpy as np

import tensorflow as tf

from keras.models import Sequential

from keras.layers import Dense

from keras.initializers import RandomNormal, Constant

from keras import losses

from keras import optimizers

sess = tf.Session()

# Datas

labels = np.array([1,2,3,4,5])

train_data_initial = np.array([[1,2,4],[2,4,8],[3,6,9],[4,8,16],[5,10,20]])

input_ = labels.reshape(5,1,1,1)

train_data = train_data_initial.reshape(5,3,1,1)

# Definition of the model

model = Sequential()

tf.reset_default_graph()

model.add(Dense((5,3,1,1), activation= None, kernel_initializer = RandomNormal(mean=0.0, stddev=0.001, seed=None), bias_initializer = Constant(value = 0.1), input_shape=(1,1,1,)))

# Here there will have some Conv2DTranspose

model.compile(loss=losses.mean_squared_error, optimizer= optimizers.Adam(lr=0.01))

model.fit(input_,train_data, 5, 10)

以及返回的完整错误消息:

ValueError                                Traceback (most recent call last)
<ipython-input-1-7d1f10e177f1> in <module>()
     31 tf.reset_default_graph()
     32 
---> 33 model.add(Dense((5,3,1,1), activation= None, kernel_initializer = RandomNormal(mean=0.0, stddev=0.001, seed=None), bias_initializer = Constant(value = 0.1), input_shape=(1,1,1,)))
     34 
     35 # Here there will have some Conv2DTranspose

/usr/local/lib/python3.5/dist-packages/keras/engine/sequential.py in add(self, layer)
    164                     # and create the node connecting the current layer
    165                     # to the input layer we just created.
--> 166                     layer(x)
    167                     set_inputs = True
    168                 else:

/usr/local/lib/python3.5/dist-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    430                                          '`layer.build(batch_input_shape)`')
    431                 if len(input_shapes) == 1:
--> 432                     self.build(input_shapes[0])
    433                 else:
    434                     self.build(input_shapes)

/usr/local/lib/python3.5/dist-packages/keras/layers/core.py in build(self, input_shape)
    870                                       name='kernel',
    871                                       regularizer=self.kernel_regularizer,
--> 872                                       constraint=self.kernel_constraint)
    873         if self.use_bias:
    874             self.bias = self.add_weight(shape=(self.units,),

/usr/local/lib/python3.5/dist-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
     89                 warnings.warn('Update your `' + object_name +
     90                               '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 91             return func(*args, **kwargs)
     92         wrapper._original_function = func
     93         return wrapper

/usr/local/lib/python3.5/dist-packages/keras/engine/base_layer.py in add_weight(self, name, shape, dtype, initializer, regularizer, trainable, constraint)
    247         if dtype is None:
    248             dtype = K.floatx()
--> 249         weight = K.variable(initializer(shape),
    250                             dtype=dtype,
    251                             name=name,

/usr/local/lib/python3.5/dist-packages/keras/initializers.py in __call__(self, shape, dtype)
     82     def __call__(self, shape, dtype=None):
     83         return K.random_normal(shape, self.mean, self.stddev,
---> 84                                dtype=dtype, seed=self.seed)
     85 
     86     def get_config(self):

/usr/local/lib/python3.5/dist-packages/keras/backend/tensorflow_backend.py in random_normal(shape, mean, stddev, dtype, seed)
   4052         seed = np.random.randint(10e6)
   4053     return tf.random_normal(shape, mean=mean, stddev=stddev,
-> 4054                             dtype=dtype, seed=seed)
   4055 
   4056 

/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/random_ops.py in random_normal(shape, mean, stddev, dtype, seed, name)
     70   """
     71   with ops.name_scope(name, "random_normal", [shape, mean, stddev]) as name:
---> 72     shape_tensor = _ShapeTensor(shape)
     73     mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean")
     74     stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev")

/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/random_ops.py in _ShapeTensor(shape)
     41   else:
     42     dtype = None
---> 43   return ops.convert_to_tensor(shape, dtype=dtype, name="shape")
     44 
     45 

/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py in convert_to_tensor(value, dtype, name, preferred_dtype)
   1012       name=name,
   1013       preferred_dtype=preferred_dtype,
-> 1014       as_ref=False)
   1015 
   1016 

/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, ctx)
   1102 
   1103     if ret is None:
-> 1104       ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
   1105 
   1106     if ret is NotImplemented:

/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref)
    233                                          as_ref=False):
    234   _ = as_ref
--> 235   return constant(v, dtype=dtype, name=name)
    236 
    237 

/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/constant_op.py in constant(value, dtype, shape, name, verify_shape)
    212   tensor_value.tensor.CopyFrom(
    213       tensor_util.make_tensor_proto(
--> 214           value, dtype=dtype, shape=shape, verify_shape=verify_shape))
    215   dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)
    216   const_tensor = g.create_op(

/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape)
    431     else:
    432       _AssertCompatible(values, dtype)
--> 433       nparray = np.array(values, dtype=np_dt)
    434       # check to them.
    435       # We need to pass in quantized values as tuples, so don't apply the shape

ValueError: setting an array element with a sequence.

谢谢您的帮助

1 个答案:

答案 0 :(得分:0)

抛出错误是因为Dense()期望第一个参数是整数,并且该参数是输出空间的维数。但是,如果要重塑形状,则应添加另一层。

num_dense_units = 32
model.add(Dense(num_dense_units, activation= None, kernel_initializer = RandomNormal(mean=0.0, stddev=0.001, seed=None), bias_initializer = Constant(value = 0.1), input_shape=(1,1,1,)))
model.add(Reshape((5,3,1,1)))