How to fix AttributeError: 'module' object has no attribute 'function'?

时间:2019-04-08 13:07:35

标签: python python-2.7 python-import

I'm totally new to Python and I currently working on the program in Michael Nielsen's online book: "neural-networks-and-deep-learning", while I'm trying to run a pre-made module named mnist_loader.py, a function named load_data_wrapper() within the module is not attributed.

The link of the code can be found here: https://github.com/mnielsen/neural-networks-and-deep-learning/blob/master/src/mnist_loader.py

Here's the code for the module, mnist_loader.py:

import cPickle

import gzip

import numpy as np

def load_data():
    f = gzip.open('../data/mnist.pkl.gz', 'rb')
    training_data, validation_data, test_data = cPickle.load(f)
    f.close()
    return (training_data, validation_data, test_data)

def load_data_wrapper():
    tr_d, va_d, te_d = load_data()
    training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]
    training_results = [vectorized_result(y) for y in tr_d[1]]
    training_data = zip(training_inputs, training_results)
    validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]
    validation_data = zip(validation_inputs, va_d[1])
    test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]
    test_data = zip(test_inputs, te_d[1])
    return (training_data, validation_data, test_data)

def vectorized_result(j):
    e = np.zeros((10, 1))
    e[j] = 1.0
    return e

While I'm trying the run the following code:

>>> import mnist_loader
>>> training_data, validation_data, test_data = \
... mnist_loader.load_data_wrapper()

The interpreter shows:

AttributeError: 'module' object has no attribute 'load_data_wrapper'

I check the directory and the mnist_loader.py module has no error itself. Then I tried to take the function load_data_wrapper out and use it by itself by using:

from mnist_loader import load_data_wrapper 

and it shows:

ImportError: cannot import name load_data_wrapper

I expect the code to load the mnist.pkl.gz file and output MNIST data.

1 个答案:

答案 0 :(得分:0)

You need to store it in the same directory, where stored your file, in which you try import.

Oh, if you are using JupyterLab, perhaps, you need to do something like this:

$ # Imports the workspace file `file_name.json`.
$ jupyter lab workspaces import file_name.json
Saved workspace: <workspaces-directory>/labworkspacesfoo-54d5.jupyterlab-workspace

Items 7.2 & 7.6 here: JupyterLab manual