zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    面向对象程序设计寒假作业2
    终于开通了园子里的贴号
    java中与类继承相关的知识点
    动态代理机制之查看一个类或接口中有哪些方法
    动态代理
    xml与html的区别
    深入理解linux i节点(inode)
    netstat命令
    关于C++ const 的全面总结
    linux 下 进程和线程的区别
  • 原文地址:https://www.cnblogs.com/E-Dreamer-Blogs/p/13840427.html
Copyright © 2011-2022 走看看