原因:

函数里用的是局部变量,从而函数调用结束后会被销毁。如果不声明是全局变量,那么就会报错:(注意灰色字体注释的地方)

def load_data():
    from keras.datasets import mnist
   # global train_image, train_lable , test_image, test_lable
    (train_image, train_lable), (test_image, test_lable) = mnist.load_data()
    print('训练数据个数:%d' % len(train_image))
    print('测试数据个数:%d' % len(test_image))
   
    return train_image,train_lable,test_image,test_lable

def image_show(image):
    fig = plt.gcf()
    fig.set_size_inches(2, 2)
    plt.imshow(image,cmap = 'binary')
    plt.show()

load_data()
image_show(train_image[0])

报错:

 

解决方法:

加上关键字:global

def load_data():
    from keras.datasets import mnist
    global train_image, train_lable , test_image, test_lable
    (train_image, train_lable), (test_image, test_lable) = mnist.load_data()
    print('训练数据个数:%d' % len(train_image))
    print('测试数据个数:%d' % len(test_image))
    return train_image,train_lable,test_image,test_lable

def image_show(image):
    fig = plt.gcf()
    fig.set_size_inches(2, 2)
    plt.imshow(image,cmap = 'binary')
    plt.show()

load_data()
image_show(train_image[0])

搞定:

 


后来又遇到了问题:

def load_data():
    from keras.datasets import mnist
    global train_image, train_lable , test_image, test_lable
    (train_image, train_lable), (test_image, test_lable) = mnist.load_data()
    print('训练数据个数:%d' % len(train_image))
    print('测试数据个数:%d' % len(test_image))
    return train_image,train_lable,test_image,test_lable

def image_show(image):
    fig = plt.gcf()
    fig.set_size_inches(2, 2)
    plt.imshow(image,cmap = 'binary')
    plt.show()

def data_preprocessing():
    train_image = train_image.reshape(60000,784)
    test_image = test_image.reshape(10000,784)
    train_image = train_image.astype('float32')
    test_image = test_image.astype('float32')
    train_image /= 255
    test_image /= 255
    print(train_image[0])

load_data()
data_preprocessing()

报错:

 

我已经在def load_data()函数里声明了全局变量,为什么还有这个错误呢?

 

原因:

如果在函数内部设置变量的值,则python会将其理解为使用该名称创建局部变量,此局部变量会掩盖全局变量。

解决:

可以通过将全局变量放入到需要用到的函数中,来明确表示它是全局变量。

修改def data_preprocessing():

def data_preprocessing():
    global train_image, train_lable, test_image, test_lable
    train_image = train_image.reshape(60000,784)
    test_image = test_image.reshape(10000,784)
    train_image = train_image.astype('float32')
    test_image = test_image.astype('float32')
    train_image /= 255
    test_image /= 255
    print(train_image[0])

搞定。

 

 

 

 

 

 

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐