Python ValueError:无法将dtype资源的张量转换为NumPy数组
我试图通过参数矩阵来隔离一些特定于用户的参数,每个数组都将学习特定于该用户的参数 我想使用用户id索引矩阵,并将参数连接到其他功能 最后,使用一些完全连接的层来获得理想的结果 然而,我在代码的最后一行不断地遇到这个错误Python ValueError:无法将dtype资源的张量转换为NumPy数组,python,tensorflow,keras,tensorflow2.0,Python,Tensorflow,Keras,Tensorflow2.0,我试图通过参数矩阵来隔离一些特定于用户的参数,每个数组都将学习特定于该用户的参数 我想使用用户id索引矩阵,并将参数连接到其他功能 最后,使用一些完全连接的层来获得理想的结果 然而,我在代码的最后一行不断地遇到这个错误 --------------------------------------------------------------------------- ValueError Traceback (most recen
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-1-93de3591ccf0> in <module>
20 # combined = tf.keras.layers.Concatenate(axis=-1)([le_param, le])
21
---> 22 net = tf.keras.layers.Dense(128)(combined)
~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
793 # framework.
794 if build_graph and base_layer_utils.needs_keras_history(inputs):
--> 795 base_layer_utils.create_keras_history(inputs)
796
797 # Clear eager losses on top level model call.
~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in create_keras_history(tensors)
182 keras_tensors: The Tensors found that came from a Keras Layer.
183 """
--> 184 _, created_layers = _create_keras_history_helper(tensors, set(), [])
185 return created_layers
186
~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
229 constants[i] = backend.function([], op_input)([])
230 processed_ops, created_layers = _create_keras_history_helper(
--> 231 layer_inputs, processed_ops, created_layers)
232 name = op.name
233 node_def = op.node_def.SerializeToString()
~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
229 constants[i] = backend.function([], op_input)([])
230 processed_ops, created_layers = _create_keras_history_helper(
--> 231 layer_inputs, processed_ops, created_layers)
232 name = op.name
233 node_def = op.node_def.SerializeToString()
~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
227 else:
228 with ops.init_scope():
--> 229 constants[i] = backend.function([], op_input)([])
230 processed_ops, created_layers = _create_keras_history_helper(
231 layer_inputs, processed_ops, created_layers)
~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/backend.py in __call__(self, inputs)
3746 return nest.pack_sequence_as(
3747 self._outputs_structure,
-> 3748 [x._numpy() for x in outputs], # pylint: disable=protected-access
3749 expand_composites=True)
3750
~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/backend.py in <listcomp>(.0)
3746 return nest.pack_sequence_as(
3747 self._outputs_structure,
-> 3748 [x._numpy() for x in outputs], # pylint: disable=protected-access
3749 expand_composites=True)
3750
ValueError: Cannot convert a Tensor of dtype resource to a NumPy array.
我尝试过的事情很少:
import tensorflow as tf
num_uids = 50
input_uid = tf.Variable(tf.ones((32, 1), dtype=tf.int32))
params = tf.Variable(tf.random.normal((num_uids, 9)), trainable=True)
param = tf.gather_nd(params, input_uid)
input_shared_features = tf.Variable(tf.ones((32, 128), dtype=tf.float32))
combined = tf.concat([param, input_shared_features], axis=-1)
net = tf.keras.layers.Dense(128)(combined)
我将Tensorflow 2.1与Python 3.6.10结合使用,在Tensorflow 2.x中尝试使用Tensorflow表查找(
tf.lookup.StaticHashTable
)时,我遇到了类似的问题。最后我把它放在一个盒子里解决了。同样的解决方案似乎也适用于这个问题,至少直到问题中提到的版本。(我尝试使用TensorFlow 2.0、2.1和2.2,在所有这些版本中都能正常工作。)
将tensorflow导入为tf
num_uids=50
input\u uid=tf.keras.input(shape=(1),dtype=tf.int32)
input\u shared\u features=tf.keras.layers.input(shape=(128,),dtype=tf.float32)
类CustomLayer(tf.keras.layers.Layer):
定义初始化(self,num\u uids):
super(CustomLayer,self)。\uuuu init\uuuu(trainable=True,dtype=tf.int64)
self.num\u uids=num\u uids
def构建(自我,输入_形状):
self.params=tf.Variable(tf.random.normal((num_uids,9)),trainable=True)
自建=真实
def调用(自我、输入uid、输入共享功能):
param=tf.gather\u nd(self.params,input\u uid)
combined=tf.concat([param,input\u shared\u features],axis=-1)
合并收益
def get_配置(自身):
config=super(CustomLayer,self).get\u config()
config.update({'num\u uids':self.num\u uids})
返回配置
组合=自定义图层(num\u uid)(输入uid,输入共享功能)
净=tf.keras.layers.Dense(128)(合并)
model=tf.keras.model(inputs={'input'uid':input'uid,'input\u shared\u features':input\u shared\u features},outputs=net)
model.summary()
下面是模型摘要的样子:
Model: "model"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_1 (InputLayer) [(None, 1)] 0
__________________________________________________________________________________________________
input_2 (InputLayer) [(None, 128)] 0
__________________________________________________________________________________________________
custom_layer (CustomLayer) (None, 137) 450 input_1[0][0]
__________________________________________________________________________________________________
dense (Dense) (None, 128) 17664 custom_layer[0][0]
==================================================================================================
Total params: 18,114
Trainable params: 18,114
Non-trainable params: 0
有关更多信息,请参阅
如果您想参考表格查找问题和解决方案,请参阅以下链接:
- 虽然吉钦·吉斯的答案非常清楚,但下面显示的是一种使用
串联操作的稍微不同的解决方法:
import tensorflow as tf
num_uids = 50
#input_uid = tf.keras.layers.Input(shape=(1,), dtype=tf.int32, batch_size = 32)
#input_uid = tf.keras.layers.Input(shape=(1,), dtype=tf.int32)
#params = tf.Variable(tf.random.normal((num_uids, 9)), trainable=True)
#param = tf.gather_nd(params, input_uid)
indices = tf.keras.layers.Input(name='indices', shape=(), dtype='int32')
params = tf.Variable(params)
class GatherLayer(tf.keras.layers.Layer):
def call(self, indices, params):
return tf.gather(params, indices)
output = GatherLayer()(indices, params)
#input_shared_features = tf.keras.layers.Input(shape=(128,), dtype=tf.float32, batch_size = 32)
input_shared_features = tf.keras.layers.Input(shape=(128,), dtype=tf.float32)
combined = tf.concat([output, input_shared_features], axis=-1)
net = tf.keras.layers.Dense(128)(combined)
有关更多详细信息,请参阅此。组合的
输入的形状是什么?组合的是:@Gabe,我为此提出了一个Github问题。欢迎来到堆栈溢出!这是一篇非常好的第一篇文章。感谢您对本书给予如此多的关注和细节。感谢@JeremyCaney为您的鼓励性话语和整理答案。我希望我将来能为社会做出更大的贡献:)
import tensorflow as tf
num_uids = 50
#input_uid = tf.keras.layers.Input(shape=(1,), dtype=tf.int32, batch_size = 32)
#input_uid = tf.keras.layers.Input(shape=(1,), dtype=tf.int32)
#params = tf.Variable(tf.random.normal((num_uids, 9)), trainable=True)
#param = tf.gather_nd(params, input_uid)
indices = tf.keras.layers.Input(name='indices', shape=(), dtype='int32')
params = tf.Variable(params)
class GatherLayer(tf.keras.layers.Layer):
def call(self, indices, params):
return tf.gather(params, indices)
output = GatherLayer()(indices, params)
#input_shared_features = tf.keras.layers.Input(shape=(128,), dtype=tf.float32, batch_size = 32)
input_shared_features = tf.keras.layers.Input(shape=(128,), dtype=tf.float32)
combined = tf.concat([output, input_shared_features], axis=-1)
net = tf.keras.layers.Dense(128)(combined)