我必須執行一個簡單的函式,該函式減去兩個串列的元素,然后使用 TensorFlowfn_map函式將結果放入一個新串列中。沒有這個函式的代碼作業正常,但是當我使用fn_map以下錯誤修改它時發生:
Exception has occurred: ValueError
in user code:
/home/imene/ESS/ess.py:359 sup *
for el1 in inputs[0]:
/home/imene/anaconda3/envs/master/lib/python3.6/site-packages/tensorflow/python/autograph/operators/control_flow.py:420 for_stmt
iter_, extra_test, body, get_state, set_state, symbol_names, opts)
/home/imene/anaconda3/envs/master/lib/python3.6/site-packages/tensorflow/python/autograph/operators/control_flow.py:485 _known_len_tf_for_stmt
n = py_builtins.len_(iter_)
/home/imene/anaconda3/envs/master/lib/python3.6/site-packages/tensorflow/python/autograph/operators/py_builtins.py:249 len_
return _tf_tensor_len(s)
/home/imene/anaconda3/envs/master/lib/python3.6/site-packages/tensorflow/python/autograph/operators/py_builtins.py:277 _tf_tensor_len
'len requires a non-scalar tensor, got one of shape {}'.format(shape))
ValueError: len requires a non-scalar tensor, got one of shape []
File "/tmp/tmpgps8mh9_.py", line 33, in tf__sup
ag__.for_stmt(ag__.ld(inputs)[0], None, loop_body_1, get_state_1, set_state_1, (), {'iterate_names': 'el1'})
During handling of the above exception, another exception occurred:
File "/home/imene/ESS/ess.py", line 366, in supp
ss =tf.map_fn(sup, inputs, dtype = tf.float32)
File "/home/imene/ESS/ess.py", line 373, in <module>
ss = supp(ab)
這是代碼:
import tensorflow as tf
a = [1, 3, 5, 8]
b = [1, 5, 3, 60]
def supp(inputs):
def sup(inputs):
ss = []
for el1 in inputs[0]:
for el2 in inputs[1]:
ss.append(el1 - el2)
return ss
ss = tf.map_fn(sup, inputs, dtype=tf.float32)
return ss
a = tf.convert_to_tensor(a)
b = tf.convert_to_tensor(b)
ab = tf.convert_to_tensor([a, b])
ss = supp(ab)
print(ss)
問題是什么?
uj5u.com熱心網友回復:
也許只是嘗試對張量進行逐元素減法,a而b沒有任何回圈:
import tensorflow as tf
a = [1, 3, 5, 8]
b = [1, 5, 3, 60]
def supp(inputs):
def sup(inputs):
return tf.cast(inputs[0] - inputs[1], dtype=tf.float32)
ss = tf.map_fn(sup, inputs, dtype=tf.float32)
return ss
a = tf.convert_to_tensor(a)
b = tf.convert_to_tensor(b)
ss = supp([a, b])
print(ss)
# tf.Tensor([ 0. -2. 2. -52.], shape=(4,), dtype=float32)
print(ss.numpy())
# [ 0. -2. 2. -52.]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/336744.html
