【问题标题】:Pytorch: How to generate random vectors with length in a certain range?Pytorch:如何生成长度在一定范围内的随机向量?
【发布时间】:2022-08-10 15:59:45
【问题描述】:

我想要一个k by 3 by n 张量代表k 批次n 随机3d 向量,每个向量的大小(欧几里得范数)在ab 之间。除了在 for 循环中将随机 kx3xn 张量的条目重新缩放为 n 随机长度之外,还有更好/更惯用的方法吗?

  • 您是否尝试限制张量的条目或其中的向量。如果是后者,您在写作时指的是哪个规范震级向量(欧几里得等)?
  • @7shoe 我试图约束欧几里得规范。

标签: python numpy random pytorch


【解决方案1】:

假设a < b,由于规范,您现在对第三个随机数有一个约束。即 sqrt(a^2 - x^2 - y^2) < z < sqrt(b^2 - x^2 - y^2)

现在a^2 - x^2 - y^2 > 0 这意味着x^2 + y^2 < a^2

我们需要两组生成数字,例如x^2 + y^2 < a^2

import numpy as np

def rand_generator(a,b,n,k):

    req_array = np.zeros((n,k,3))
    # first generate random numbers for x i.e 0<x<a
    
    req_array[:,:,0] = np.random.rand(n,k)*a
    
    # now generate random numbers for y such that 0 < y < a^-x2

    req_array[:,:,1] = np.random.rand( n,k) * np.sqrt(a**2 - req_array[:,:,0]**2)
    
    norm_temp = np.linalg.norm(req_array,axis=2)

    a1 = np.sqrt(a**2 - norm_temp**2) 

    b1 = np.sqrt(b**2 - norm_temp**2)
    
    # generate numbers for z such that they are inbetween a1 and b1

    req_array[:,:,2] = a1 + np.random.rand(n,k)*(b1-a1)

    return req_array


ll = rand_generator(2,5,10,12)
lp = np.linalg.norm(ll,axis=2)

print(np.all(lp>2) and np.all(lp<5))

##output: True

您也可以为此使用球坐标(与上面完全相同) x = rsin(theta)cos(phi)y = rsin(theta)sin(phi)z = rcos(theta) a&lt; r &lt;b 0&lt;theta&lt;pi/20&lt;phi&lt;pi/2

import numpy as np

def rand_generator(a,b,n,k):

    req_array = np.zeros((n,k,3))
    # first generate random numbers for r in [a,b)
    
    r = a + np.random.rand(n,k)*(b-a)
    
    # now generate random numbers for theta in [0,pi/2)

    theta = np.random.rand( n,k) * np.pi/2
    
    # now generate random numbers for phi in [0,pi/2)

    phi = np.random.rand( n,k) * np.pi/2

    req_array[:,:,0] = r*np.sin(theta)*np.cos(phi)
 
    req_array[:,:,1] = r*np.sin(theta)*np.sin(phi)
    
    req_array[:,:,2] = r*np.cos(theta)
    
    return req_array


ll = rand_generator(2,5,10,12)
lp = np.linalg.norm(ll,axis=2)

print(np.all(lp>2) and np.all(lp<5))

##output: True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    相关资源
    最近更新 更多