numpy - Python: Using Tensordot for tensor x matrix multiplication -
hi im tying multiply tensor matrix in following fashion:
dimensions
w: a x b x c
v: a x c
i want z such that
z[i]=dot(w[i],v[i])
z of dimension a x ( (b x c) . (c x 1))
, (a x b)
ive tried numpy.tensordot
havent been able to. can want? if not how can without loops.
basically equivalent of
def f(w,v): z=[] in range(len(w)): z.append(dot(w[i],v[i])) return z
thanks
edit: achievable tensordot?
np.einsum("abc,ac -> ab", w, v)
:
import numpy np def z_loop(w,v): # define check `einsum()` gives necessary result z = np.empty(w.shape[:-1], dtype=w.dtype) in range(z.shape[0]): z[i,:] = np.dot(w[i,:], v[i,:]) return z w = np.random.uniform(size=(3,4,5)) v = np.random.uniform(size=w.shape[::2]) assert np.allclose(z_loop(w, v), np.einsum('abc,ac -> ab', w, v))
there might simpler variants (via dot()
, .reshape()
) einsum()
obvious task description.
def z_dot(w, v): z = np.dot(w, v[:,...,np.newaxis]) z = z.reshape(z.shape[:-1]) return np.diagonal(z, axis2=-1).t assert np.allclose(z_dot(w, v), np.einsum('abc,ac -> ab', w, v))
Comments
Post a Comment