TypeError:无法解压缩不可迭代的NoneType对象

时间:2018-12-08 08:41:30

标签: python python-3.x

我知道之前曾有人问过这个问题,但我似乎无法让我工作。有人可以帮我吗?

import numpy as np


def load_dataset():
    def download(filename, source="http://yaan.lecun.com/exdb/mnist/"):
        print ("Downloading ",filename)
        import urllib
        urllib.urlretrieve(source+filename,filename)

    import gzip

    def load_mnist_images(filename):
        if not os.path.exists(filename):
            download(filename)
        with gzip.open(filename,"rb") as f:
            data=np.frombuffer(f.read(), np.uint8, offset=16)

            data = data.reshape(-1,1,28,28)

            return data/np.float32(256)

        def load_mnist_labels(filename):
            if not os.path.exists(filename):
                download(filename)
            with gzip.open(filename,"rb") as f:
                data = np.frombuffer(f.read(), np.uint8, offset=8)
            return data

        X_train = load_mnist_images("train-images-idx3-ubyte.gz")
        y_train = load_mnist_labels("train-labels-idx1-ubyte.gz")
        X_test = load_mnist_images("t10k-images-idx3-ubyte.gz")
        y_test = load_mnist_labels("t10k-labels-idx1-ubyte.gz")

        return X_train, y_train, X_test, y_test


X_train, y_train, X_test, y_test = load_dataset()


import matplotlib
matplotlib.use("TkAgg")

import matplotlib.pyplot as plt
plt.show(plt.imshow(X_train[3][0]))

这是我得到的错误:

Traceback (most recent call last):
  File "C:\Users\nehad\Desktop\Neha\Non-School\Python\Handwritten Digits 
Recognition.py", line 38, in <module>
    X_train, y_train, X_test, y_test = load_dataset()
TypeError: cannot unpack non-iterable NoneType object

我是机器学习的新手。我只是想念一些简单的事情吗?我正在为我的学校科学展览尝试“手写数字识别”项目。

谢谢!

4 个答案:

答案 0 :(得分:8)

None(属于NoneType)执行多重分配时,会出现此错误。例如:

X_train, y_train, X_test, y_test = None

TypeError:无法解包不可迭代的NoneType对象

因此,如果您得到此提示,则错误很可能是作业的右侧部分与您期望的不一样(没什么)。

答案 1 :(得分:1)

将多个分配拆分/中断为 None 可解决此问题。

例如这不起作用:

test_set_raw, test_set_transformed, train_set_raw, train_set_transformed = None

这确实有效(没有错误):

test_set_raw = None
test_set_transformed = None
train_set_raw = None
train_set_transformed = None

答案 2 :(得分:0)

我认为您的X_train, y_train, X_test, y_test是在load_mnist_images函数中定义的,因此没有为您的load_dataset函数定义。

您应该从X_train = ...return X_train, ...缩进5行,然后您的代码可能会更好。

答案 3 :(得分:-1)

因为load_dataset()返回None。

运行此命令,您将得到相同的错误: X_train,y_train,X_test,y_test =无