Bernoulli distribution in Python/Scipy

3.3k views Asked by At

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:

enter image description here enter image description here enter image description here

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.

1

There are 1 answers

0
PatternMatching On

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.