Reputation: 1585
Basically i would like to create a class with a bunch of helper functions. how do i pass variables to methods inside my class. I managed to do it with the simple addition. I am struggling to do it with the plot_images. what am i missing?
#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.
This is my helper function class
#!/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()
The error message I am getting is
(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>
What am i missing?
Upvotes: 0
Views: 596
Reputation: 7414
Python is a whitespace significant language and your indentation is incorrect. The variable images
is only available within the plot_images block.
Here is the correctly indented version.
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()
As a side note, I'd suggest naming your variables better, and that the Helpers
class inherit from object
explicitly.
Upvotes: 2
Reputation: 4135
First of all, you haven't shown the full code. But as I can see
images[]
is a list which you have not defined.
Do like this.
Call your plot_images
function with right parameters.
# 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)
Upvotes: 0