I have a the beginnings of a class (in this case for a NeuralNet).
I'm not very happy with how I am initializing self.ws, seems a bit off. What is the pythonic way to do this?

import numpy as np
class NeuralNet:
    def __init__(self,layerSizes):
        self.ws = self._generateStartingWeights(layerSizes)

    def _generateStartingWeights(self,layerSizes):
        def randMatrix(szThis,szNext): return np.matrix(np.random.normal(0,0.01,(szThis,szNext)))
       return [randMatrix(szThis,szNext) for (szThis,szNext) in pairwise(layerSizes)]
  • \$\begingroup\$ Fixed, thanks. That was not what was feeling wrong though. \$\endgroup\$ Jan 14, 2014 at 7:14

1 Answer 1


I think the primary question here is one of whether _generateStartingWeights or randMatrix are reusable; the secondary question is of naming conventions.

If _generateStartingWeights is not reusable, there's little reason not to write __init__ without the layers of helpers (and that's assuming there's not some better way to use numpy for this). Oh, and if it is reusable, you can just return this from it, instead of using a locally defined helper function:

def __init__(self, layerSizes):
    self.ws = [np.matrix(np.random.normal(0, 0.01, pair)) for pair in pairwise(layerSizes)]

On the flip side, if randMatrix is reusable, it needs to be somewhere other than local to another function.

As for naming conventions, a potentially heated subject, lots of people refer to PEP-8 (which I want to clarify is not a requirement for third party code unless you want to make it one). However due to its prevelance in the Python community, there seems to be a general preference for underscore_separated instead of camelCase names. Since it's not even always followed in the standard library, your project's preferences can overrule it. I only bring it up since I personally find camelCase names to be less in line with my view of "pythonic."


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.