carebear
carebear

Reputation: 771

cPickle.load throwing ImportError in Python

I have Python 2.7.3 installed on my Windows 7 computer. When I run the following code

import nltk, json, cPickle, itertools

import numpy as np

from nltk.tokenize import word_tokenize
from pprint import pprint

t_given_a = json.load(open('conditional_probability.json','rb'))
a_unconditional = json.load(open('age.json','rb'))

t_unconditional = cPickle.load(open('freqdist.pkl','rb'))['distribution']

The command prompt gives me the error "ImportError: No Module named Multiarray."

I'm fairly new to Python and I'm not exactly sure why this error happened. I searched other threads and many suggested to use 'rb' instead of 'r'. I have rb to begin with and it's still throwing me that error. Any suggestion?

Upvotes: 2

Views: 1756

Answers (2)

shx2
shx2

Reputation: 64308

From the docs:

Note that functions (built-in and user-defined) are pickled by “fully qualified” name reference, not by value. This means that only the function name is pickled, along with the name of the module the function is defined in. Neither the function’s code, nor any of its function attributes are pickled. Thus the defining module must be importable in the unpickling environment, and the module must contain the named object, otherwise an exception will be raised.

Similarly, classes are pickled by named reference, so the same restrictions in the unpickling environment apply. Note that none of the class’s code or data is pickled

[...] These restrictions are why picklable functions and classes must be defined in the top level of a module

Upvotes: 2

Suor
Suor

Reputation: 3055

When you pickle an object in python it saves its class as a string of package name + class name. On unpickle python tries to import that module and find that class for you to recreate an object. And if you don't have that module importable you'll get an ImportError.

Just install that Multiarray module, and if you don't know which is it then ask whoever you got that pickle file from.

Upvotes: 4

Related Questions