首页 > 解决方案 > 如何将非矩形数组输入到顺序 Keras

问题描述

我想向 NRR 输入一个非矩形数组列表:

features_set = [
    [[1, 2, 3], [5, 4, 6]], 
    [[2, 8, 9]]
]

labels = [5, 8]

但是使用 Keras - Sequential 我得到了错误:

model.fit(features_set, labels, epochs = 100, batch_size = 32)

ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型列表)。

我如何输入这些数据?因为时间步长没有定义的大小。

标签: pythontensorflowrecurrent-neural-network

解决方案


我能够Tensorflow Version 2.x使用以下虚拟代码重现您的错误 -

重现错误的代码 -

%tensorflow_version 2.x
import tensorflow as tf
print(tf.__version__)
import numpy as np
from numpy import loadtxt
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Input, Concatenate

input1 = Input(shape=(3,))

# define model
x = Dense(12, input_shape = (2,), activation='relu')(input1)
x = Dense(8, activation='relu')(x)
x = Dense(1, activation='sigmoid')(x)

model = Model(inputs=input1, outputs=x)

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Model Summary
model.summary()

features_set = [
    [[1, 2, 3], [5, 4, 6]], 
    [[2, 8, 9]]
]

labels = [5, 8]

# Fit the model
model.fit(x=features_set, y=labels, epochs=150, batch_size=10, verbose=0)

输出 -

2.3.0
Model: "functional_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         [(None, 3)]               0         
_________________________________________________________________
dense (Dense)                (None, 12)                48        
_________________________________________________________________
dense_1 (Dense)              (None, 8)                 104       
_________________________________________________________________
dense_2 (Dense)              (None, 1)                 9         
=================================================================
Total params: 161
Trainable params: 161
Non-trainable params: 0
_________________________________________________________________
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-ecade355bf68> in <module>()
     35 
     36 # Fit the model
---> 37 model.fit(x=features_set, y=labels, epochs=150, batch_size=10, verbose=0)

14 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/constant_op.py in convert_to_eager_tensor(value, ctx, dtype)
     96       dtype = dtypes.as_dtype(dtype).as_datatype_enum
     97   ctx.ensure_initialized()
---> 98   return ops.EagerTensor(value, ctx.device_name, dtype)
     99 
    100 

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).

要修复此错误,请使用 将 转换list为不规则张量tf.ragged.constant。在此之后将参差不齐的张量转换为张量并在模型中使用。

固定代码 -

%tensorflow_version 2.x
import tensorflow as tf
print(tf.__version__)
import numpy as np
from numpy import loadtxt
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Input, Concatenate

input1 = Input(shape=(3,))

# define model
x = Dense(12, input_shape = (2,), activation='relu')(input1)
x = Dense(8, activation='relu')(x)
x = Dense(1, activation='sigmoid')(x)

model = Model(inputs=input1, outputs=x)

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Model Summary
model.summary()


rt = tf.ragged.constant([
    [[1, 2, 3], [5, 4, 6]], 
    [[2, 8, 9]]
])

features_set = rt.to_tensor()

labels = np.asarray([5, 8])

# Fit the model
model.fit(x=features_set, y=labels, epochs=150, batch_size=10, verbose=0)

输出 -

2.3.0
Model: "functional_35"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_18 (InputLayer)        [(None, 3)]               0         
_________________________________________________________________
dense_51 (Dense)             (None, 12)                48        
_________________________________________________________________
dense_52 (Dense)             (None, 8)                 104       
_________________________________________________________________
dense_53 (Dense)             (None, 1)                 9         
=================================================================
Total params: 161
Trainable params: 161
Non-trainable params: 0
_________________________________________________________________
WARNING:tensorflow:Model was constructed with shape (None, 3) for input Tensor("input_18:0", shape=(None, 3), dtype=float32), but it was called on an input with incompatible shape (None, 2, 3).
WARNING:tensorflow:Model was constructed with shape (None, 3) for input Tensor("input_18:0", shape=(None, 3), dtype=float32), but it was called on an input with incompatible shape (None, 2, 3).
<tensorflow.python.keras.callbacks.History at 0x7f181ad9e400>

推荐阅读