I am trying to follow the tensor flow
tutorial as described in this link
I am trying to print the predicted result as described :
print ("Predicted %d, Label: %d" % (classifier.predict(test_data[0]), test_labels[0]))
But I am not able to print the result. I am getting the following error.
print ("Predicted %d, Label: %d" % (classifier.predict(test_data[0]), test_labels[0]))
TypeError: %d format: a number is required, not generator
How do I print the generator
in python
.
I tried to write a loop and iterate over the elements it didn't work and I tried to use next
to print the generator. That also didn't work. How do I print it ?
This is how I solved it
new_samples = np.array([test_data[8]], dtype=float)
y = list(classifier.predict(new_samples, as_iterable=True))
print('Predictions: {}'.format(str(y)))
print ("Predicted %s, Label: %d" % (str(y), test_labels[8]))
No tensorflow
here, so let's mock up a generator and test it against your print
expression
In [11]: def predict(a, b):
...: for i in range(10):
...: yield i, i*i
...:
In [12]: print('a:%d, b:%d'%(predict(0, 0)))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-29ec761936ef> in <module>()
----> 1 print('a:%d, b:%d'%(predict(0, 0)))
TypeError: %d format: a number is required, not generator
So far, so good: I have the same problem that you've experienced.
The problem is, of course, that what you get when you call a generator function are not values but a generator object...
You have to iterate on the generator objects, using whatever is returned from each iteration, e.g.,
In [13]: print('\n'.join('a:%d, b:%d'%(i,j) for i, j in predict(0,0)))
a:0, b:0
a:1, b:1
a:2, b:4
a:3, b:9
a:4, b:16
a:5, b:25
a:6, b:36
a:7, b:49
a:8, b:64
a:9, b:81
or, if you don't like one-liners,
In [14]: for i, j in predict(0, 0):
...: print('a:%d, b:%d'%(i,j))
...:
a:0, b:0
a:1, b:1
a:2, b:4
a:3, b:9
a:4, b:16
a:5, b:25
a:6, b:36
a:7, b:49
a:8, b:64
a:9, b:81
In other words, you have to explicitly consume what the generator is producing.
From the documentation:
Runs inference to determine the class probability predictions.
(deprecated arguments)
SOME ARGUMENTS ARE DEPRECATED. They will be removed after 2016-09-15.
Instructions for updating: The default behavior of predict() is
changing. The default value for as_iterable will change to True, and
then the flag will be removed altogether. The behavior of this flag is
described below.
Try:
classifier.predict(x=test_data[0])