Search code examples
pythonc++numpysyntaxnotation

What does the greater-than symbol mean in this piece of python code?


I am trying to implement a restricted boltzmann machine in C++. I am using this Python code as a guide: https://github.com/echen/restricted-boltzmann-machines/blob/master/rbm.py

This is Line 37:

pos_hidden_states = pos_hidden_probs > np.random.rand(num_examples, self.num_hidden + 1)

pos_hidden_states and pos_hidden_probs are both 2D matrices, of type vector<vector<double>> in C++, and num_examples and num_hidden are both integers.

Could anyone explain what the greater-than symbol means here?


Solution

  • Probably not easy to translate numpy into C++, lot's of abstraction in numpy. Anyway, it's acting as a vectorized comparison, because np.random.rand(...) returns a np.ndarray, which if pos_hidden_probs is either a scalar or a np.ndarray it will behave in a vectorized (i.e. elementwise) manner:

    >>> rand_array = np.random.rand(2, 2)
    >>> rand_array
    array([[ 0.1807726 ,  0.67617382],
           [ 0.84396805,  0.04450794]])
    >>> 0.5 > rand_array
    array([[ True, False],
           [False,  True]], dtype=bool)
    >>>
    

    If pos_hidden_probs is some sort of np.ndarray, the behavior might be influenced by broadcasting, a feature of numpy:

    >>> np.array([0.5, 0.5]) > rand_array
    array([[ True, False],
           [False,  True]], dtype=bool)
    >>> np.array([0.5, .9]) > rand_array
    array([[ True,  True],
           [False,  True]], dtype=bool)
    >>>