all!
I'm establishing a class with Python. In one of the function in the class, I need to subtract two large arrays, here is the code:
def gradient(x, h, data):
u = (x - data) / h ** 2
c = np.exp(- (h ** 2 / 2) * np.sum(u ** 2, axis=-1))
c = c.reshape(-1, 1)
g = -(u.transpose().dot(c)) / np.sum(c)
return g
where x is a 1d numpy array of length n, data is an 2d numpy array with shape = (N, n) (in other word, a matrix of size N * n).
I test the speed of this function when N = 30,000, n = 10,000. The time cost is between 20s~100s (I also don't understand why the time cost could vary so much) And the 1st line -- subtraction of x and data is the main part of the time cost. (p.s. In numpy, if x is a 1d array of size n, data is a 2d array of size (N, n), then x - data will be automatically regard as the row-wise subtraction of data from x.)
from time import time
data = np.random.normal(size = 30000 * 10000).reshape(30000, 10000)
x = np.random.normal(size = 10000)
h = 0.2
start_time = time()
gradient(x, h, data)
print("Elapsed time is: ", time() - start_time)
Elapsed time is: 36.4828040599823
This is too low to serve the purpose of my class. Any method that could boost the speed of this 4-line function in the class? The ideal time for this function should be around 2s~10s, is that possible to reach this goal? Great thanks in advance for any suggestions/ideas