• Numpy 的广播机制高效计算矩阵之间两两距离


    利用numpy可以很方便的计算两个二维数组之间的距离。二维数组之间的距离定义为:X的维度为(a,c),Y的维度为(b,c),Z为X到Y的距离数组,维度为(a,b)。且Z[0,0]是X[0]到Y[0]的距离。Z(m,n)为X[m]到Y[n]的距离。

    例如: 计算 m*2 的矩阵 与  n * 2 的矩阵中,m*2 的每一行到  n*2 的两两之间欧氏距离。 

    #computer the distance between text point x and train point x_train
    import numpy as np
    X = np.random.random((3,2))
    X_train = np.random.random((5,2))
    print('X:')
    print(X)
    print('X_train:')
    print(X_train)
    
    dist = np.zeros((X.shape[0],X_train.shape[0]))
    print('--------------------')
    #way 1:use two loops ,使用两层循环
    for i in range(X.shape[0]):
        for j in range(X_train.shape[0]):
            dist[i,j] = np.sum((X[i,:]-X_train[j,:])**2)
    print('way 1 result:')
    print(dist)
    
    #way 2:use one loops ,使用一层循环
    for i in range(X.shape[0]):
        dist[i,:] = np.sum((X_train-X[i,:])**2,axis=1)
    print('--------------------')
    print('way 2 result:')
    print(dist)
    
    #way 3:use no loops,不使用循环
    dist = np.reshape(np.sum(X**2,axis=1),(X.shape[0],1))+ np.sum(X_train**2,axis=1)-2*X.dot(X_train.T)
    print('--------------------')
    print('way 3 result:')
    print(dist)
  • 相关阅读:
    filter_input() 函数
    php get_magic_quotes_gpc()函数用法介绍
    echo、print、sprint、sprintf输出
    nl2br() 函数
    chop函数
    in_array 查询数组中是否存在某个值
    SQL技巧
    运算符(一)
    JS数据类型
    JS的基本语法与字面量和变量
  • 原文地址:https://www.cnblogs.com/E-Dreamer-Blogs/p/13840427.html
Copyright © 2020-2023  润新知