[英]Operation between two 2D numpy array
I am trying to operate on two 2D numpy arrays, such that my first numpy array's each row operate on all of the rows of second numpy array. I am trying to operate on two 2D numpy arrays, such that my first numpy array's each row operate on all of the rows of second numpy array.
Array1阵列1
test[] = [[0.54131721 0.52305685 0.42921551, 0.37434461 0.52591475 0.36184407]
[0.53091097 0.3000469 0.39346106, 0.29261769 0.3806552 0.33904193]
[0.29331853 0.44518117 0.41390863, 0.2510257 0.50481932 0.43607184]]
Array2数组2
train[] =[[0.5301304, 0.62645837, 0.44524917, 0.40806674 0.46013734 0.61033772]
[0.43333892 0.46062429 0.56937923, 0.6451305 0.33103777 0.35859095]
[0.60879428 0.72451976 0.2661216, 0.38850336 0.41685737 0.57226228]]
This is how I am saving both array:这就是我保存两个数组的方式:
import numpy as np
trainingData = np.genfromtxt('trainingData.csv', delimiter=',')
inTraining = trainingData[:, :-1]
print(inTraining)
testData = np.genfromtxt('testData.csv', delimiter=',')
inTest = testData[:, :-1]
print(inTest)
This is what I tried, which seems to be not even close:这是我尝试过的,似乎还没有接近:
def euclideanDistance( c1, c2):
d1 = inTraining[]
d2 = inTest[]
a = math.sqrt( (d1[0]-d2[0])**2 + (d1[1]-d2[1])**2 )
print(a)
return a
Expected output should be like first list containing result of operation between:预期的 output 应该类似于包含以下操作结果的第一个列表:
[0.54131721 0.52305685 0.42921551, 0.37434461 0.52591475 0.36184407] and [[0.5301304, 0.62645837, 0.44524917, 0.40806674 0.46013734 0.61033772]
[0.43333892 0.46062429 0.56937923, 0.6451305 0.33103777 0.35859095]
[0.60879428 0.72451976 0.2661216, 0.38850336 0.41685737 0.57226228]]
IIUC, you want to compute distance between each row of test
to each rows of train
. IIUC,您想计算每行
test
到每行train
之间的距离。 That's distance_matrix
:那是
distance_matrix
:
from scipy.spatial import distance_matrix
distance_matrix(test,train)
Output: Output:
array([[0.27979822, 0.38277359, 0.35792442],
[0.44997152, 0.43972939, 0.51706358],
[0.3833412 , 0.48532177, 0.49455157]])
If you want numpy only code, you can look at the code of distance_matrix
to see what's happening.如果您只想要 numpy 代码,您可以查看
distance_matrix
的代码以了解发生了什么。 Basically, it's a broadcasting action:基本上,这是一个广播动作:
def dist_mat(x,y):
return np.sqrt(np.sum((x- y[:,None])**2, axis=-1))
dist_mat(train,test)
Output: Output:
array([[0.27979822, 0.38277359, 0.35792442],
[0.44997152, 0.43972939, 0.51706358],
[0.3833412 , 0.48532177, 0.49455157]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.