我有一个大小为N的numpy数组,它包含x,y个像素位置。我想在x和y方向上稍微移动每个像素。我想要实现的是使用每个x值作为平均值,并从具有可配置sigma的正态分布中随机选择周围的新值。对于新的y值也会执行同样的操作
我的问题是,我必须对每个像素进行循环,并乏味地使用以下代码:
for i in range(len(pixels)):
pixel = pixels[i]
x = pixel[0]
y = pixel[1]
new_x = numpy.random.normal(x, std_deviation_x)
new_y = numpy.random.normal(y, std_deviation_y)
pixel[i][0] = new_x
pixel[i][1] = new_y
我想知道是否有一种方法或任何随机函数实现可以接受均值列表和sigma列表,以返回N个样本的列表,其中每个样本在列表中具有相应的均值和sigma
发布于 2018-01-24 10:15:14
scipy.stats.norm
接受向量参数:
>>> from scipy import stats
>>>
# mean = 0, 1, -1 - std = 1, 2, 2
# we draw 10,000 samples per parameter set to validate the mean ...
>>> stats.norm([0, 1, -1], [1, 2, 2]).rvs((10000, 3)).mean(axis=0)
array([ 0.02597611, 1.01131576, -0.9446429 ])
# ... and the std
>>> stats.norm([0, 1, -1], [1, 2, 2]).rvs((10000, 3)).std(axis=0)
array([ 0.99299587, 2.0055516 , 1.99656472])
# if you need just one sample per parameter set:
>>> stats.norm([0, 1, -1], [1, 2, 2]).rvs()
array([-1.23528454, 3.77990026, -3.49572846])
发布于 2018-01-24 10:09:53
您可以仅从均值为0的正态分布中采样,然后将值移动到新均值。
稍微清理和改进你的代码,它应该看起来像这样。
# We create all new (x,y) in one go
rand_x = numpy.random.normal(0, std_deviation_x, len(pixels))
rand_y = numpy.random.normal(0, std_deviation_y, len(pixels))
for i in range(len(pixels)):
x, y = pixels[i] # using unpacking
# now we shift the mean
new_x = x + rand_x[i]
new_y = y + rand_y[i]
# reasignment
pixels[i][0] = new_x
pixels[i][1] = new_y
当然,这可以进一步改进和优化,仍然有相当多的多余的任务。
https://stackoverflow.com/questions/48419408
复制相似问题