2017-06-11 1 views
0

Ich habe derzeit einen Code, der es einem kombinatorischen (kartesischen) Produkt über eine bestimmte Achse ermöglicht. Dies ist in numpy und stammte aus einer früheren Frage Efficient axis-wise cartesian product of multiple 2D matrices with Numpy or TensorFlowTensorflow-Äquivalent dieses numply achsenweisen kartesischen Produkts für 2D-Matrizen

A = np.array([[1,2], 
       [3,4]]) 
B = np.array([[10,20], 
       [5,6]]) 
C = np.array([[50, 0], 
       [60, 8]]) 
cartesian_product([A,B,C], axis=1) 
>> np.array([[ 1*10*50, 1*10*0, 1*20*50, 1*20*0, 2*10*50, 2*10*0, 2*20*50, 2*20*0] 
      [ 3*5*60, 3*5*8, 3*6*60, 3*6*8, 4*5*60, 4*5*8, 4*6*60, 4*6*8]]) 

und die Lösung zu wiederholen:

L = [A,B,C] # list of arrays 
n = L[0].shape[0] 
out = (L[1][:,None]*L[0][:,:,None]).reshape(n,-1) 
for i in L[2:]: 
    out = (i[:,None]*out[:,:,None]).reshape(n,-1) 

Gibt es eine bestehende Methode, dies in tensorflow mit Rundfunk führen - ohne einen for-Schleife?

Antwort

0

Ok, also habe ich eine reine TF-basierte (Teil-) Antwort für zwei Arrays gefunden. Es ist derzeit nicht generalisierbar wie die numpige Lösung für M-Arrays, aber das ist für eine andere Frage (vielleicht eine tf.while_loop). Für diejenigen, die neugierig sind, passt sich die Lösung von Evaluate all pair combinations of rows of two tensors in tensorflow

a = np.array([[0, 1, 2, 3], 
       [4, 5, 6, 7], 
       [4, 5, 6, 7]]) 

b = np.array([[0, 1], 
       [2, 3], 
       [2, 3]]) 

N = a.shape[0] 

A = tf.constant(a, dtype=tf.float64) 
B = tf.constant(b, dtype=tf.float64) 

A_ = tf.expand_dims(A, axis=1) 
B_ = tf.expand_dims(B, axis=2) 
z = tf.reshape(tf.multiply(A_, B_), [N, -1]) 

>> tf_result 
Out[1]: 
array([[ 0., 0., 0., 0., 0., 1., 2., 3.], 
     [ 8., 10., 12., 14., 12., 15., 18., 21.], 
     [ 8., 10., 12., 14., 12., 15., 18., 21.]]) 

Lösungen für die Mehrfachanordnung Fall sind willkommen

Verwandte Themen