我有一个数据集,其中每个样本的结构都与此类似
X=[ [[],[],[],[]], [[],[]] , [[],[],[]] ,[[][]]]
例如:
X=np.array([ [ [1,2,3], [2,4,5] ,[2,3,4] ] , [ [5,6], [6,6] ] , [[2,3,1],[2,3,10],[23,1,2],[1,4,5]] ] ,"object")
Y=np.array([ [ [12,14,15] ,[12,13,14] ] , [ [15,16], [16,16] ] , [[22,23,21],[32,33,11],[12,44,55]] ] ,"object")
所以对于每个样本,我需要计算 x 的每个元素与相同索引的 y 的相应元素之间的点积,并将结果求和。IE:
result=0
for i in range(3):
for n,m in itertools.product(X[i],Y[i]):
print "%s, %s" % (n,m)
result+=np.dot(n,m)
.....:
[1, 2, 3], [12, 14, 15]
[1, 2, 3], [12, 13, 14]
[2, 4, 5], [12, 14, 15]
[2, 4, 5], [12, 13, 14]
[2, 3, 4], [12, 14, 15]
[2, 3, 4], [12, 13, 14]
[5, 6], [15, 16]
[5, 6], [16, 16]
[6, 6], [15, 16]
[6, 6], [16, 16]
[2, 3, 1], [22, 23, 21]
[2, 3, 1], [32, 33, 11]
[2, 3, 1], [12, 44, 55]
[2, 3, 10], [22, 23, 21]
[2, 3, 10], [32, 33, 11]
[2, 3, 10], [12, 44, 55]
[23, 1, 2], [22, 23, 21]
[23, 1, 2], [32, 33, 11]
[23, 1, 2], [12, 44, 55]
[1, 4, 5], [22, 23, 21]
[1, 4, 5], [32, 33, 11]
[1, 4, 5], [12, 44, 55]
这是我的整个代码:
print "***build kernel***"
K = np.zeros((n_samples, n_samples))
for i in range(n_samples):
for j in range(n_samples):
K[i,j] = self.kernel(X[i], X[j])
def kernel(x1,x2):
N=8 #number of objects
result=0
for i in xrange(N):
for n,m in itertools.product(x1[i],x2[i]):
result+=np.dot(n,m)
return result
如您所见,该算法的复杂性太高,而且我的样本也比这大得多。所以即使是一个很小的数据集,即包含 400 个样本,我也必须等待 4 个小时才能得到结果。我正在寻找一种更好的方法来实现这个算法。PS:我在考虑多线程或多进程,但我不确定它是否有帮助?!
我很感激任何建议!