How to manipulate each element in a tensor?
For example, a = [[1,1,1], [2,2,2], [3,3,3]]
and b = [0,0,0]
. Here I want to connect b before each element of a, which will become [[0,0,0,1,1,1], [0,0,0,2,2,2], [0,0,0,3,3,3]]
, is there a way to implement this without a loop since using loop is pretty slow in python while dealing with large data.
Many thanks.
CodePudding user response:
import numpy as np
import torch
a = np.array([[1,1,1], [2,2,2], [3,3,3]])
b = np.array([0, 0, 0])
result = np.array([np.array((*b, *row)) for row in a])
# Converting to torch
result = torch.from_numpy(result)
Result:
array([[0, 0, 0, 1, 1, 1],
[0, 0, 0, 2, 2, 2],
[0, 0, 0, 3, 3, 3]])
CodePudding user response:
You can use map()
:
a = [[1,1,1], [2,2,2], [3,3,3]]
b = [0,0,0]
result = list(map(lambda x: b x, a))
# Prints [[0, 0, 0, 1, 1, 1], [0, 0, 0, 2, 2, 2], [0, 0, 0, 3, 3, 3]]
print(result)
CodePudding user response:
In [185]: a = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
...: b = [0, 0, 0]
The obvious list comprenhensin:
In [186]: [b x for x in a]
Out[186]: [[0, 0, 0, 1, 1, 1], [0, 0, 0, 2, 2, 2], [0, 0, 0, 3, 3, 3]]
And array approach:
In [187]: np.concatenate((np.zeros((len(a), len(a[0])), int), np.array(a)), axis=1)
Out[187]:
array([[0, 0, 0, 1, 1, 1],
[0, 0, 0, 2, 2, 2],
[0, 0, 0, 3, 3, 3]])
for this small example the list approach is better:
In [188]: timeit [b x for x in a]
528 ns ± 12.7 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
In [189]: timeit np.concatenate((np.zeros((len(a), len(a[0])), int), np.array(a)), axis=1)
9.77 µs ± 95.4 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
If A
is already an array:
In [192]: %%timeit A = np.array(a)
...: np.concatenate((np.zeros(A.shape,A.dtype), A), axis=1)
6.26 µs ± 223 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
The last will scalar much better.
And the map
alternative:
In [194]: timeit list(map(lambda x: b x, a))
856 ns ± 31.6 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)