简体   繁体   中英

Bernoulli distribution in Python/Scipy

I'm trying to use the Bernoulli distribution to generate a matrix in which each line cell has a probability of line_id/total_lines to be 1.0 .

That's my code:

from scipy.stats import bernoulli
import numpy

img_size = 100
img_number = 100

res = numpy.zeros((img_number+1, 6))

image_files = []
for i in range(1):
    image_base = Dt.Data(xd=img_size, yd=img_size)
    for p in numpy.arange(0.0, 1.0, 1.0/img_size):
        s = bernoulli.rvs(p, size=img_size)
        image_base.data[int(p * img_size), ...] = s
        if not s.any() == True:
            print int(p * img_size), s
    if i == 0:
        Dv.DataVisualization.plot_data(image_base, 'bin'+str(i))
    image_files.append(image_base)

from PIL import Image

def plot_data(data, file_path):
    output = Image.fromarray(numpy.uint8(data.data * 255))
    output.save(file_path + '.png', 'PNG')

However, for each image generated I'm getting a line (that's not the first one), fulfilled by zeros. That's a least odd:

在此处输入图片说明在此处输入图片说明在此处输入图片说明

This:

if not s.any() == True:
    print int(p * img_size), s

printed just the first line. However, I still can see three lines (always the same lines) fulfilled by 0 over all images.

I think that you may be misusing Numpy's all() and any() . The expression s.any() evaluates to a boolean.

If I want to determine whether I have a Numpy array whose elements are all zero, I should check the condition not s.any() == True .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM