【问题标题】:Converting Theano Euclidean distance to keras engine format将 Theano Euclidean 距离转换为 keras 引擎格式
【发布时间】:2017-08-20 00:10:13
【问题描述】:

我在theano 中有以下代码,用于计算L2 距离

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]]))

结果: [[ 0。] [1.]]

这是左侧集合(两个向量 - [1, 0], [1, 1])与包含单个向量 [1,0] 的右侧集合之间的距离矩阵。

即使 X 和 Y 具有与上述不同的暗淡,这也适用于 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)]]

编辑: 将输出添加到代码中

【问题讨论】:

  • 您能否提供有关您的问题的更多详细信息?例如。究竟是什么工作不正常?
  • @MarcinMożejko 我已经添加了上面两个用例的输出示例
  • @MarcinMożejko,谢谢我发现了错误,我忘了转置Y
  • 太好了:)

标签: tensorflow theano keras keras-layer


【解决方案1】:

我发现了错误。我忘了transposeY

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,K.transpose(y))

【讨论】:

    猜你喜欢
    • 2012-10-16
    • 1970-01-01
    • 2011-08-14
    • 2018-11-01
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多