Python:key error

dictionary, python, scikit-learn

Solution

Here you're assign value to dict by tuple (`c, cov` is equivalent to `(c, cov)`):

models[c,cov] = values = []

So, here you should access to dict values by tuple to:

for cov in covs:
    for c in class_names:
        for num in num_comp:
            models[(c, cov)].fit(training_data[c])

`AttributeError` throwing because you actually access to list: `models[(c,cov)]` is list that you created before (`values`)

update for comment, try this:

for c in class_names:
    models[c] = {}
    for cov in covs:
        models[c][cov] = values = []
        for num in num_comp:
            values.append(GMM(n_components=num,covariance_type=cov, init_params='wmc',n_init=1, n_iter=10))

but here you will get `list` in `models[c][cov]` anyway and should iterate it:

for cov in covs:
    for c in class_names:
        for num in num_comp:
            for f in models[c][cov]
                f.fit(training_data[c])

Problem

I'm using scikit-learn for GMM training and am trying to vary the number of mixture components. I ran into problems, which were fixed here. I ended up with this code: ``` from sklearn.mixture import GMM class_names = ['name1','name2','name3'] covs = ['spherical', 'diagonal', 'tied', 'full'] num_comp = [1,2,3] models = dict() for c in class_names: for cov in covs: models[c,cov] = values = [] for num in num_comp: values.append(GMM(n_components=num,covariance_type=cov, init_params='wmc',n_init=1, n_iter=10)) print models ``` I'm using the model dict() later on again and am running into problems because I don't know how to work with the dict. ``` training_data={'name1':'path2data1', 'name2': path2data2, 'name3': path2data3} for cov in covs: for c in class_names: for num in num_comp: models[c][cov].fit(training_data[c]) ``` I get the error "KeyError:'name1'" I tried models[c,cov].fit(training_data[c]) as well but then I get the error "AttributeError: 'list' object has no attribute 'fit'" Thanks in advance for any tips!

Original source