2017-03-27 5 views
2

I는 L2 거리를 가진변환 Theano 유클리드 거리

def distance(square=False): 
    X = T.fmatrix('X') 
    Y = T.fmatrix('Y') 
    squared_euclidean_distances = (X ** 2).sum(1).reshape((X.shape[0], 1)) + (Y ** 2).sum(1).reshape \ 
    ((1, Y.shape[0])) - 2 * X.dot(Y.T) 
    if square: 
     return theano.function([X, Y], T.sqrt(squared_euclidean_distances)) 
    else: 
     return theano.function([X, Y], squared_euclidean_distances) 

source

print(distance()([[1, 0], [1, 1]], [[1, 0]])) 

결과를 계산하기 위해 theano에 다음 코드를 가지고 [0] [ 1.]]

왼쪽 세트 (tw o 벡터 - [1, 0], [1, 1]) 및 단일 벡터 [1,0]을 포함하는 오른쪽 집합.

이것은 X와 Y가 위와 같이 다른 dim를 가지고 있더라도 theano와 잘 작동합니다. 같은 결과를 내기 위해 일반적인 keras 함수를 얻고 싶습니다.

def distance_matrix(vects): 
    x, y = vects 
    # <x,x> + <y,y> - 2<x,y> 
    x_shape = K.int_shape(x) 

    y_shape = K.int_shape(y) 

    return K.reshape(K.sum(K.square(x), axis=1), (x_shape[0], 1)) + \ 
     K.reshape(K.sum(K.square(y), axis=1), (1, y_shape[0])) - \ 
     2 * K.dot(x, y) 

을하지만, 다음 코드는 올바른 결과를 생성하지 않습니다 : 나는 시도

x = K.variable(np.array([[1, 0], [1, 1]])) 
y = K.variable(np.array([[1, 0]])) 
obj = distance_matrix 
objective_output = obj((x, y)) 
print (K.eval(objective_output)) 

결과

ValueError: Shape mismatch: x has 2 cols (and 4 rows) but y has 4 rows (and 2 cols) 
Apply node that caused the error: Dot22Scalar(/variable, /variable, TensorConstant{2.0}) 
Toposort index: 0 
Inputs types: [TensorType(float32, matrix), TensorType(float32, matrix), TensorType(float32, scalar)] 
Inputs shapes: [(4, 2), (4, 2),()] 
Inputs strides: [(8, 4), (8, 4),()] 
Inputs values: ['not shown', 'not shown', array(2.0, dtype=float32)] 
Outputs clients: [[Elemwise{Composite{((i0 + i1) - i2)}}[(0, 2)](InplaceDimShuffle{0,x}.0, InplaceDimShuffle{x,0}.0, Dot22Scalar.0)]] 

편집

과 : 추가 출력

+0

당신이 문제에 대한 자세한 내용을 제공 할 수있다 : 나는 (vects)

데프 distance_matrix Y transpose를 잊으 셨나요? 예 : 정확히 무엇이 제대로 작동하지 않습니까? –

+0

@ MarcinMożejko – oak

+1

@ MarcinMożejko 위의 두 가지 유스 케이스의 출력 예제를 추가했습니다. 실수를 발견 한 덕분에 Y를 Y 전각으로 깜박했습니다. – oak

답변

1

을 코드를 나는 그 실수를 발견했다.

x, y = vects 
# <x,x> + <y,y> - 2<x,y> 
x_shape = K.int_shape(x) 

y_shape = K.int_shape(y) 

return K.reshape(K.sum(K.square(x), axis=1), (x_shape[0], 1)) +\ 
    K.reshape(K.sum(K.square(y), axis=1), (1, y_shape[0])) - \ 
2 * K.dot(x,K.transpose(y)) 
관련 문제