Created
May 18, 2018 07:53
-
-
Save shijianjian/36c33e903fca79f070aa11bdbb033706 to your computer and use it in GitHub Desktop.
Manual Implementation for np.tile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import types | |
import numpy as np | |
def test_tile(x, multiplier): | |
x = np.array(x) | |
if isinstance(multiplier, list): | |
raise ValueError("multiplier must be a List or numpy array") | |
multiplier = np.array(multiplier) | |
if len(multiplier.shape) > 1: | |
raise ValueError("multiplier must be a 1-D Vector") | |
expand_shape = len(multiplier) - len(x.shape) | |
# Make array and multiplyiers to be the same sized | |
if expand_shape > 0: | |
init_mul = np.concatenate([np.ones(expand_shape, dtype=np.int32), list(x.shape)], axis=0) | |
x = x*np.ones(init_mul) | |
else: | |
multiplier = np.concatenate([np.ones(-expand_shape, dtype=np.int32), multiplier], axis=0) | |
for i, dim_mul in enumerate(multiplier): | |
# if i < len(x.shape) and dim_mul == 1: | |
# continue | |
print(i) | |
_dim_mul = np.insert(list(x.shape), i, dim_mul) | |
print("_dim_mul", _dim_mul) | |
intermedia = np.expand_dims(x, i) | |
intermedia = intermedia*np.ones(_dim_mul) | |
print("intermedia", intermedia.shape) | |
_squeeze_mul = list(x.shape) | |
_squeeze_mul[i] = dim_mul*x.shape[i] | |
_squeeze_mul = np.insert(_squeeze_mul, i, -1) | |
print("_squeeze_mul", _squeeze_mul) | |
intermedia = intermedia.reshape(_squeeze_mul) | |
print("intermedia", intermedia.shape) | |
x = np.squeeze(intermedia, i) | |
print("x.shape",x.shape) | |
print() | |
return x | |
if __name__ == '__main__': | |
aaa = np.random.rand(5, 4096, 9) | |
bbb = np.array([9, 5, 1]) | |
print("ooooooooooooooo") | |
a = np.tile(aaa, bbb) | |
print(a.shape) | |
print("ooooooooooooooo") | |
b = test_tile(aaa, bbb) | |
print(b.shape) | |
print("ooooooooooooooo") | |
print(np.array_equal(a, b)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment