In numpy, what is the fastest way to multiply the second dimension of a 3 dimensional array by a 1 dimensional array?
By : ShammyLevva
Date : March 29 2020, 07:55 AM
hope this fix your issue Use broadcasting: code :
A*B[:,np.newaxis]
In [47]: A=np.arange(24).reshape(2,3,4)
In [48]: B=np.arange(3)
In [49]: A*B[:,np.newaxis]
Out[49]:
array([[[ 0, 0, 0, 0],
[ 4, 5, 6, 7],
[16, 18, 20, 22]],
[[ 0, 0, 0, 0],
[16, 17, 18, 19],
[40, 42, 44, 46]]])

Making comparisons of a mdimensional array and an (m1)dimensional array repeated along an arbitrary dimension
By : pedroparra
Date : March 29 2020, 07:55 AM
this one helps. Assuming that you meant (I'm assuming this because otherwise m3d  m2d.z.3d doesn't work): code :
m3d = outer(m2d, items3, "*") # note how I switched the arguments
m3d  c(m2d)
all.equal(m3d  c(m2d), m3d  m2d.z.3d)
# [1] TRUE
funOuter < function() {
m2d.z.3d = outer(
m2d,
rep(1, length(items3)), "*"
)
m3d  m2d.z.3d
}
funRecycle < function() m3d  c(m2d)
funLoop < function() apply(m3d, 3, "", m2d) # this does not appear correct because `apply` doesn't reconstruct dimensions like `sapply`
funSweep < function() sweep(m3d, c(1, 2), m2d) # this is the same type of thing but works properly
library(microbenchmark)
microbenchmark(funOuter(), funRecycle(), funLoop(), funSweep())
Unit: milliseconds
expr min lq mean median
funOuter() 2.297287 2.673768 3.232277 2.835404
funRecycle() 1.327101 1.485082 2.093252 1.599543
funLoop() 22.579010 24.586667 27.211804 26.840069
funSweep() 11.251656 12.012664 13.516147 13.736908
all.equal(funOuter(), funRecycle())
# [1] TRUE
all.equal(funOuter(), funSweep())
# [1] TRUE
all.equal(funOuter(), funLoop())
# Nope, not equal

Extracting portions of lowdimensional numpy array into final axes of higherdimensional array
By : Katarzyna Leszczyńsk
Date : March 29 2020, 07:55 AM

Construction of two dimensional numpy array from unequally shaped one dimensional arrays  Numpy
By : user621459
Date : March 29 2020, 07:55 AM
I wish this help you In python have three one dimensional arrays of different shapes (like the ones given below) , You can use numpy stack functions to speed up: code :
aa = [a0, a1, a2]
np.hstack(tuple(np.vstack((np.full(ai.shape, i), ai)) for i, ai in enumerate(aa))).T

Convert multidimensional Numpy array to 2dimensional array based on color values
By : sutenm
Date : March 29 2020, 07:55 AM
To fix the issue you can do You could use giant lookup table. Let cls be [[0,0,0], [0,0,255], ...] of dtype=np.uint8. code :
LUT = np.zeros(size=(256,256,256), dtype='u1')
LUT[cls[:,0],cls[:,1],cls[:,2]] = np.arange(cls.shape[1])+1
img_as_cls = LUT[img[...,0],img[...,1], img[...,2]]
def scalarize(x):
# compute x[...,2]*65536+x[...,1]*256+x[...,0] in efficient way
y = x[...,2].astype('u4')
y <<= 8
y +=x[...,1]
y <<= 8
y += x[...,0]
return y
LUT = np.zeros(2**24, dtype='u1')
LUT[scalarize(cls)] = 1 + np.arange(cls.shape[0])
simg = scalarize(img)
img_to_cls = LUT[simg]

