在python中成对减去数组

时间:2018-03-09 17:59:56

标签: python numpy knn

我有两个矩阵,A形状512 * 3和B形状1024 * 3 我想计算它们的行之间的成对减法,因此结果将是512 * 1024 * 3

的形状

(它们实际上是3D点坐标的数组:x,y,z和我最终想要找到从B到A中每个点的k个最近点)

我不能用于循环。有没有pythonic方式来做到这一点? 谢谢你。

2 个答案:

答案 0 :(得分:0)

区别:

diff = A[:, np.newaxis] - B[np.newaxis, :]

k中每个点B中最近的A点:

k = 5
dists = np.sum(np.square(A[:, np.newaxis] - B[np.newaxis, :]), axis=-1)
top_k = np.argpartition(dists, k, axis=1)[:, :k]

top_k并未按距离排序。您可以稍后对其进行排序或改为:

top_k = np.argsort(dists, axis=1)[:, :k]

效率较低但更简单。

答案 1 :(得分:0)

根据我之前评论中链接的参考文献:

http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc

你正试图这样做。

enter image description here

只需按照示例操作,如:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    // Register
    public function create(Request $request)
    {
        // Form Validation
        $this->validate(request(), [
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'phonenumber' => 'required|regex:/^[0-9]{10}$/|unique:users',
            'street_address' => 'required',
            'city' => 'required',
            'region' => 'required',
            'zip' => 'required',
            'password' => 'required|confirmed'
        ]);

        // Create and save the user.
        $user = User::create([
            'name' => request('name'),
            'email' => request('email'),
            'phonenumber' => request('phonenumber'),
            'street_address' => request('street_address'),
            'city' => request('city'),
            'state' => request('state'),
            'zip' => request('zip'),
            'password' => bcrypt(request('password'))
        ]);

        // Sign in the user.
        //auth()->login($user);

        return redirect('/test');
    }

    // Login
    public function store()
    {
        if (auth()->attempt(request(['email', 'password'])))
        {
            return redirect('/');
        } 
        else 
        {
            return Redirect::back()->withErrors(['Invalid email or password!']);
        }       
    }

    // Logout
    public function destroy()
    {
        auth()->logout();

        return redirect('/user/login');
    }
}