将参数传递给类方法python

时间:2016-12-18 00:07:20

标签: python

基本上我想用一堆辅助函数创建一个类。我如何将变量传递给我的类中的方法。 我设法通过简单的添加来做到这一点。我正在努力做到这一点 plot_images。我错过了什么?

#Imports
import matplotlib.pyplot as plt
import tensorflow as tf
from Helpers import Helpers 
import numpy as np
from sklearn.metrics import confusion_matrix
import time
from datetime import timedelta
import math
import os

#Load Data
from tensorflow.examples.tutorials.mnist import input_data
data = input_data.read_data_sets('data/MNIST/', one_hot=True)

print("Size of:")
print("- Training-set:\t\t{}".format(len(data.train.labels)))
print("- Test-set:\t\t{}".format(len(data.test.labels)))
print("- Validation-set:\t{}".format(len(data.validation.labels)))

#Configuration of Neural Network
# Convolutional Layer 1.
filter_size1 = 5          # Convolution filters are 5 x 5 pixels.
num_filters1 = 16         # There are 16 of these filters.

# Convolutional Layer 2.
filter_size2 = 5          # Convolution filters are 5 x 5 pixels.
num_filters2 = 36         # There are 36 of these filters.

# Fully-connected layer.
fc_size = 128             # Number of neurons in fully-connected layer.


data.test.cls = np.argmax(data.test.labels, axis=1)
data.validation.cls = np.argmax(data.validation.labels, axis=1)

#Data Dimensions
# We know that MNIST images are 28 pixels in each dimension.
img_size = 28

# Images are stored in one-dimensional arrays of this length.
img_size_flat = img_size * img_size

# Tuple with height and width of images used to reshape arrays.
img_shape = (img_size, img_size)

# Number of colour channels for the images: 1 channel for gray-scale.
num_channels = 1

# Number of classes, one class for each of 10 digits.
num_classes = 10

#Helper function for plotting images

#Plot a few images
# Get the first images from the test-set.
images = data.test.images[0:9]

# Get the true classes for those images.
cls_true = data.test.cls[0:9]

#Helpers().plot_images(images=images, cls_true=cls_true)
print(Helpers().addition(1,2))
# Plot the images and labels using our helper-function above.

这是我的助手功能类

#!/usr/bin/env python3
from __main__ import *
from tensorflow.examples.tutorials.mnist import input_data

class Helpers:

def __init__(self):
    self.n = 1

def addition(self,x,y):
    return x + y

def plot_images(self,images, cls_true, cls_pred=None):
                assert len(images) == len(cls_true) == 9

# Create figure with 3x3 sub-plots.
fig, axes = plt.subplots(3, 3)
fig.subplots_adjust(hspace=0.3, wspace=0.3)

for i, ax in enumerate(axes.flat):
    # Plot image.
    ax.imshow(images[i].reshape(img_shape), cmap='binary')

    # Show true and predicted classes.
    if cls_pred is None:
        xlabel = "True: {0}".format(self.cls_true[i])
    else:
        xlabel = "True: {0}, Pred: {1}".format(cls_true[i], cls_pred[i])

    # Show the classes as the label on the x-axis.
    ax.set_xlabel(xlabel)

    # Remove ticks from the plot.
    ax.set_xticks([])
    ax.set_yticks([])

# Ensure the plot is shown correctly with multiple plots
# in a single Notebook cell.
plt.show()

我收到的错误消息是

(py35) E:\python scripts>python breakdown.py
Traceback (most recent call last):
  File "breakdown.py", line 4, in <module>
    from Helpers import Helpers
  File "E:\python scripts\Helpers.py", line 5, in <module>
    class Helpers:
  File "E:\python scripts\Helpers.py", line 22, in Helpers
    ax.imshow(images[i].reshape(img_shape), cmap='binary')
NameError: name 'images' is not defined

(py35) E:\python scripts>

我缺少什么?

2 个答案:

答案 0 :(得分:2)

Python是一种空白重要语言,并且您的缩进不正确。变量images仅在plot_images块中可用。

这是正确的缩进版本。

def plot_images(self,images, cls_true, cls_pred=None):
    assert len(images) == len(cls_true) == 9

    # Create figure with 3x3 sub-plots.
    fig, axes = plt.subplots(3, 3)
    fig.subplots_adjust(hspace=0.3, wspace=0.3)

    for i, ax in enumerate(axes.flat):
        # Plot image.
        ax.imshow(images[i].reshape(img_shape), cmap='binary')

        # Show true and predicted classes.
        if cls_pred is None:
            xlabel = "True: {0}".format(self.cls_true[i])
        else:
            xlabel = "True: {0}, Pred: {1}".format(cls_true[i], cls_pred[i])

        # Show the classes as the label on the x-axis.
        ax.set_xlabel(xlabel)

        # Remove ticks from the plot.
        ax.set_xticks([])
    ax.set_yticks([])

    # Ensure the plot is shown correctly with multiple plots
    # in a single Notebook cell.
    plt.show()

作为旁注,我建议您更好地命名变量,Helpers类明确地从object继承。

参考

  1. Python style guide

  2. Old style vs. new style classes in Python

答案 1 :(得分:0)

首先,您还没有显示完整的代码。但正如我所见

images[]是您尚未定义的列表。

这样做。

使用正确的参数调用plot_images函数。

# Create instance
helper_obj = Helpers()
images = data.test.images[0:9]
# Get the true classes for those images.
cls_true = data.test.cls[0:9]
# Call plot_images
helper_obj.plot_images(images,cls_true)