Is this an attribute?
Peter Otten
__peter__ at web.de
Tue Jan 19 15:51:27 EST 2016
Robert wrote:
> Hi,
>
> When I read a code snippet below, I find I don't know what
> 'self.framelogprob' is on the child class.
>
>
>
> ////// parent class
> class _BaseHMM(BaseEstimator):
> def __init__(self, n_components=1,
> startprob_prior=1.0, transmat_prior=1.0,
> algorithm="viterbi", random_state=None,
> n_iter=10, tol=1e-2, verbose=False,
> params=string.ascii_letters,
> init_params=string.ascii_letters):
> self.n_components = n_components
> ......
>
> def score_samples(self, X, lengths=None):
> X = check_array(X)
> n_samples = X.shape[0]
> logprob = 0
> posteriors = np.zeros((n_samples, self.n_components))
> for i, j in iter_from_X_lengths(X, lengths):
> framelogprob = self._compute_log_likelihood(X[i:j])
> .......
> return logprob, posteriors
>
> ////// child class
> class StubHMM(_BaseHMM):
> def _compute_log_likelihood(self, X):
> return self.framelogprob
> -------------
>
> On Python web, it says that things after dot, such as a class name, are
> attributes. From this definition, 'framelogprob' is an attribute. But when
> I run the command on Canopy:
>
> h.framelogprob
>
---------------------------------------------------------------------------
> AttributeError Traceback (most recent call
> last) <ipython-input-19-970ee2f3402c> in <module>()
> ----> 1 h.framelogprob
>
> AttributeError: 'StubHMM' object has no attribute 'framelogprob'
>
>
> it doesn't recognize it as an attribute. What is wrong with my
> understanding?
When you are reading a book, do you expect to be able to understand every
arbitrarily picked sentence without any idea about the surrounding text?
Widen your view a bit -- the StubHMM class is in a file test_base.py and
therefore it is likely that it is supposed to help with testing rather than
to be used standalone. When you read the complete module to understand more
of the context or just use a tool like grep you'll find the following
snippets:
h = StubHMM(2)
h.transmat_ = [[0.7, 0.3], [0.3, 0.7]]
h.startprob_ = [0.5, 0.5]
h.framelogprob = self.framelogprob
h = StubHMM(n_components)
h.framelogprob = self.framelogprob
So the attribute is set "from the outside". I wouldn't do that, I'd rather
add initializer arguments, but that wasn't the question...
More information about the Python-list
mailing list