Matplotlib does not support generators as input ошибка

I’m using fuzzy art algorithm to be applying on my data and everything works fine in case of results but when it come to plot the result the interpreter says: RuntimeError: matplotlib does not support generators as input.

By the way, i’m using python as a programming language and matplotlib to plot the results.

import numpy as np
from sys import argv
import matplotlib.pyplot as plt
from random import shuffle

def scaledList(list):
    min = None
    max = None
    for i in range(len(list)):
        if min is None or min > list[i]:
            min = list[i]
        if max is None or max < list[i]:
            max = list[i]
    for i in range(len(list)):
        list[i] = (float)(list[i] - min)/(max - min)
    #print "min = " + str(min) + ", max = " + str(max)
    return list

def complementCodedConversion(list1, list2):
    list = []
    for i in range(len(list1)):
        complementVector = (list1[i], list2[i], 1-list1[i], 1-list2[i])
        list.append(complementVector)
    return list

def fuzzyAnd(tuple1, tuple2):
    ls = []
    for i in range(len(tuple1)):
        minimum = min(tuple1[i], tuple2[i])
        ls.append(minimum)
    #print(ls)
    return ls


def printData(list):
    for i in range(len(list)):
        print (list[i])


def myPlot(dataList, boxList):
    x = map(lambda item:item[0], dataList)
    y = map(lambda item:item[1], dataList)

    plt.scatter(x, y)
    for i in range(len(boxList)):
        (a,b,c,d) = boxList[i]
        plt.plot([a,c,c,a,a], [b, b, d, d, b])

    plt.show()



training = np.loadtxt(fname="C:\\Users\\Ali\Desktop\\fuzzy-art-neural-network-master\\TrainingData.txt")
testing = np.loadtxt(fname="C:\\Users\\Ali\Desktop\\fuzzy-art-neural-network-master\\TestingData.txt")

trainingData = complementCodedConversion(scaledList(training[:, 2].tolist()), scaledList(training[:, 3].tolist()))
testingData = complementCodedConversion(scaledList(testing[:, 2].tolist()), scaledList(testing[:, 3].tolist()))

#printData(trainingData)

#parameters setting
#learning rate
beta = 1
#vigilance
rho = 0.8
alpha = 0.000001
categoryList = []
#shuffle(trainingData)

while True:
    #shuffle(trainingData)
    len1 = len(categoryList)
    for i in range(len(categoryList)):
        tjList = []
        for j in range(len(categoryList)):
            summation1 = fuzzyAnd(trainingData[i], categoryList[j])
            #summation2 = summation1[i] / (alpha+sum(categoryList[j]))
            ss1 = sum(categoryList[j])
            ss2 = alpha + ss1
            summation2 = summation1[i] / ss2
            tjList.append((summation2))

        tjList = sorted(tjList, key=lambda item:item[1])
        noMatchFlag = True
        while len(tjList) != 0 :
            (index, value) = tjList.pop(0)
            if sum(fuzzyAnd(trainingData[i], categoryList[index]))/sum(trainingData[i]) >= rho :
                categoryList[index] = map(lambda x, y: x*beta + y*(1-beta),
                                          fuzzyAnd(trainingData[i], categoryList[index]), categoryList[index])
                noMatchFlag = False
                break
        if noMatchFlag:
            categoryList.append(trainingData[i])

    novellist = []
    for i in range(len(testingData)):
        tjList = []
        for j in range(len(categoryList)):
            tjList.append((j, sum(fuzzyAnd(testingData[i], categoryList[j]))/(alpha+sum(categoryList[j]))))
        tjList = sorted(tjList, key=lambda item:item[1])
        noMatchFlag = True
        while len(tjList) != 0 :
            (index, value) = tjList.pop(0)
            if sum(fuzzyAnd(testingData[i], categoryList[index]))/sum(testingData[i]) >= rho :
                noMatchFlag = False
                break
        if noMatchFlag:
            novellist.append(i)

    print ("***************")
    printData(categoryList)
    print ("***************")
    print ("Novel list:")
    print (novellist)
    myPlot(trainingData, categoryList)
    #print "novelist: ", len(novellist)
    len2 = len(categoryList)
    if len2 == len1 :
        break

#print "number of centers: ", len2

The result of the interpreter in the image below:

enter image description here

How can i solve this problem to plot my results.
Thanks in advance

Answer by Della Pham

the function map defines a generator instead of returning an object such as a list or a tuple. ,In that example there is a line which produces a list in python 2.7 but in python 3 it is just a generator. The «map» is strange anyways, so I’d recommend to replace that line.,I’m using fuzzy art algorithm to be applying on my data and everything works fine in case of results but when it come to plot the result the interpreter says: RuntimeError: matplotlib does not support generators as input.,

What is the difference between these two structure declarations?

the function map defines a generator instead of returning an object such as a list or a tuple.

map

Answer by Noor Correa

Search Answer Titles

list or tuple should be appropriate input for matplotlib.

A fixed length generator can always be converted to a list. 

vals_list = list(vals_generator)

Answer by Bradley McFarland

Example: matplotlib does not support generators as input

list or tuple should be appropriate input for matplotlib.

A fixed length generator can always be converted to a list. 

vals_list = list(vals_generator)

Answer by Anahi Pierce

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.,Our community of experts have been thoroughly vetted for their expertise and industry experience.,© 1996-2021 Experts Exchange, LLC. All rights reserved. Covered by US Patent,Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

 coordinat_y [('289', '98'), ('304', '105'), ('289', '174'), ('921', '111'), ('786', '116'), ('772', '129'), ('740', '139'), ('633', '148'), ('469', '311'), ('466', '304'), ('443', '137'), ('439', '200'), ('444', '339'), ('433', '225'), ('429', '185'), ('424', '166'), ('423', '191'), ('424', '281'), ('421', '329'), ('409', '250'), ('397', '218'), ('388', '245'), ('383', '348'), ('366', '323'), ('347', '275'), ('325', '321'), ('304', '389'), ('269', '330'), ('237', '357'), ('190', '444'), ('162', '400'), ('77', '490'), ('4', '486'), ('326', '267'), ('271', '107'), ('114', '130'), ('85', '232'), ('46', '328'), ('573', '96'), ('573', '282'), ('559', '148'), ('460', '132'), ('461', '301'), ('442', '218'), ('429', '155'), ('396', '184'), ('392', '269'), ('381', '288'), ('177', '111'), ('167', '208'), ('102', '192'), ('518', '106'), ('563', '256'), ('779', '94'), ('846', '360'), ('875', '169'), ('349', '119'), ('363', '291'), ('361', '234'), ('393', '107'), ('415', '327'), ('418', '182'), ('513', '99'), ('582', '362'), ('613', '146'), ('365', '231'), ('342', '157'), ('269', '95'), ('268', '281'), ('256', '294'), ('233', '190'), ('218', '137'), ('203', '129'), ('195', '168'), ('186', '254'), ('179', '353'), ('171', '259'), ('165', '233'), ('161', '274'), ('363', '214'), ('356', '209'), ('311', '133'), ('307', '266'), ('271', '102'), ('245', '116'), ('235', '221'), ('218', '276'), ('389', '162'), ('395', '292'), ('388', '240'), ('328', '94'), ('321', '180'), ('302', '297'), ('273', '174'), ('110', '93'), ('14', '401'), ('503', '103'), ('520', '103'), ('537', '156'), ('539', '206'), ('450', '434'), ('296', '236')]

conn = sqlite3.connect("deez.sqlite")
cur = conn.cursor()
results_x = cur.fetchall()
#Cocur.execute("SELECT xcoor FROM Vect_Table")
#ordinate_x = str(results_x).replace(')','').replace('(','').replace("'","").replace(",","")
#print("results", results_y)
cur.execute("SELECT xcoor, ycoor FROM Vect_Table")
results_y = cur.fetchall()
#Coordinates = str(results_y).replace(')','').replace('(','').replace("'","")
Coordinate_y = str(results_y).replace(')','').replace('(','').replace("'","").replace(",","")
print("results after replace ", Coordinate_y)
cur.close()
conn.close()


x = list(results_x)
y = list(results_y)
Coordinate_x = (map(int,x))
Coordinate_y = (map(int,y))

print("coordinat_y",y )


plt.plot(Coordinate_y)
plt.ylabel(Coordinate_x)
plt.show()

results after replace  [289 98 304 105 289 174 921 111 786 116 772 129 740 139 633 148 469 311 466 304 443 137 439 200 444 339 433 225 429 185 424 166 423 191 424 281 421 329 409 250 397 218 388 245 383 348 366 323 347 275 325 321 304 389 269 330 237 357 190 444 162 400 77 490 4 486 326 267 271 107 114 130 85 232 46 328 573 96 573 282 559 148 460 132 461 301 442 218 429 155 396 184 392 269 381 288 177 111 167 208 102 192 518 106 563 256 779 94 846 360 875 169 349 119 363 291 361 234 393 107 415 327 418 182 513 99 582 362 613 146 365 231 342 157 269 95 268 281 256 294 233 190 218 137 203 129 195 168 186 254 179 353 171 259 165 233 161 274 363 214 356 209 311 133 307 266 271 102 245 116 235 221 218 276 389 162 395 292 388 240 328 94 321 180 302 297 273 174 110 93 14 401 503 103 520 103 537 156 539 206 450 434 296 236]

ValueError: invalid literal for int() with base 10: '[(289, 98), (304, 105), (289, 174), (921, 111), (786, 116), (772, 129), (740, 139), (633, 148), (469, 311), (466, 304), (443, 137), (439, 200), (444, 339), (433, 225), (429, 185), (424, 166), (423, 1

TypeError: float() argument must be a string or a number, not 'list'

Answer by Paisley Noble

Ask longer questions at https://discourse.matplotlib.org

c:\anaconda3\lib\site-packages\matplotlib\cbook.py in safe_first_element(obj)
   2545 def safe_first_element(obj):
   2546     if isinstance(obj, collections.Iterator):
-> 2547         raise RuntimeError("matplotlib does not support generators "
   2548                            "as input")
   2549     return next(iter(obj))

RuntimeError: matplotlib does not support generators as input

Answer by Andrea Booth

来源:stackoverflow:question,在运行github上的一个例子时,https://github.com/vsmolyakov/experiments_with_python/blob/master/chp01/ensemble_methods.ipynb,,

Python中出现:RunTimeError:implement_array_function method already has a docstring.异常解决

16613

进行代码检测,报错了使用Python3.x版本。

plt.figure()
(_, caps, _) = plt.errorbar(num_est, bg_clf_cv_mean, yerr=bg_clf_cv_std, c='blue', fmt='-o', capsize=5)
for cap in caps:
    cap.set_markeredgewidth(1)                                                                                                                                
plt.ylabel('Accuracy'); plt.xlabel('Ensemble Size'); plt.title('Bagging Tree Ensemble');
plt.show()

实际上在这个例子中,有一行num_est = map(int, np.linspace(1,100,20)),这个在Python的2.7版本中产生的是一个List,而在Python3.x中产生的是一个Generators,所有建议把这一个替换成:

num_est = np.linspace(1,100,20).astype(int)

Answer by Zoe Torres

matplotlib does not support generators as input

list or tuple should be appropriate input for matplotlib.

A fixed length generator can always be converted to a list. 

vals_list = list(vals_generator)

I am trying to generate a chart that shows the top 5 spending categories.

I’ve got it working up to a certain point and then it says «matplotlib does not support generators as input». I am pretty new to python in general but am trying to learn more about it.

Up to this point in the code it works:

import Expense
import collections
import matplotlib.pyplot as plt

expenses = Expense.Expenses()
expenses.read_expenses(r"C:\Users\budget\data\spending_data.csv")

spending_categories = []


for expense in expenses.list:
    spending_categories.append(expense.category)


spending_counter = collections.Counter(spending_categories)

top5 = spending_counter.most_common(5)

If you did a print(top5) on the above it would show the following results:
[(‘Eating Out’, 8), (‘Subscriptions’, 6), (‘Groceries’, 5), (‘Auto and Gas’, 5), (‘Charity’, 2)]

Now I was trying to separate the items (the count from the category) and I guess I’m messing up on that part.

The rest of the code looks like this:

categories = zip(*top5)
count = zip(*top5)

fig, ax = plt.subplots()

ax.bar(count,categories)
ax.set_title('# of Purchases by Category')
plt.show()

This is where the error is occurring. I can get something to show if I make count and categories a string but it doesn’t actually plot anything and doesn’t make sense.

The error shows (the name of this .py file I’m working in is FrequentExpenses.py)

Traceback (most recent call last):
  File "C:\Users\budget\data\FrequentExpenses.py", line 24, in <module>
    ax.bar(count,categories)
  File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\__init__.py", line 1447, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\axes\_axes.py", line 2407, in bar
    self._process_unit_info(xdata=x, ydata=height, kwargs=kwargs)
  File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\axes\_base.py", line 2189, in _process_unit_info
    kwargs = _process_single_axis(xdata, self.xaxis, 'xunits', kwargs)
  File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\axes\_base.py", line 2172, in _process_single_axis
    axis.update_units(data)
  File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\axis.py", line 1460, in update_units
    converter = munits.registry.get_converter(data)
  File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\units.py", line 210, in get_converter
    first = cbook.safe_first_element(x)
  File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\cbook\__init__.py", line 1669, in safe_first_element
    raise RuntimeError("matplotlib does not support generators "
RuntimeError: matplotlib does not support generators as input

The «Expense» import is another another file (Expense.py) which looks like this that create two classes (Expenses & Expense) and also has a method of read_expenses()

import csv
from datetime import datetime

class Expense():
    def __init__(self, date_str, vendor, category, amount):
        self.date_time = datetime.strptime(date_str, '%m/%d/%Y %H:%M:%S')
        self.vendor = vendor
        self.category = category
        self.amount = amount


class Expenses():
    def __init__(self):
        self.list = []
        self.sum = 0

    # Read in the December spending data, row[2] is the $$, and need to format $$
    def read_expenses(self,filename):
        with open(filename, newline='') as csvfile:
            csvreader = csv.reader(csvfile, delimiter=',')
            for row in csvreader:
                if '-' not in row[3]:
                    continue
                amount = float((row[3][2:]).replace(',',''))
                self.list.append(Expense(row[0],row[1], row[2], amount))
                self.sum += amount

    def categorize_for_loop(self):
            necessary_expenses = set()
            food_expenses = set()
            unnecessary_expenses = set()
            for i in self.list:
                if (i.category == 'Phone'    or i.category == 'Auto and Gas' or 
                    i.category == 'Classes'  or i.category == 'Utilities' or 
                    i.category == 'Mortgage'): 
                    necessary_expenses.add(i)
                elif(i.category == 'Groceries' or i.category == 'Eating Out'):
                    food_expenses.add(i)
                else:
                    unnecessary_expenses.add(i)
            
            return [necessary_expenses, food_expenses, unnecessary_expenses]

I know this seems pretty simple to most, can anyone help me? I appreciate all the help and I’m looking forward to learning much more about python!

I am trying to generate a chart that shows the top 5 spending categories.

I’ve got it working up to a certain point and then it says «matplotlib does not support generators as input». I am pretty new to python in general but am trying to learn more about it.

Up to this point in the code it works:

import Expense
import collections
import  matplotlib.pyplot as plt

expenses =  Expense.Expenses()
expenses.read_expenses(r"C:\Users\budget\data\spending_data.csv")

spending_categories  = []


for expense in expenses.list:
     spending_categories.append(expense.category)


spending_counter  =  collections.Counter(spending_categories)

top5  = spending_counter.most_common(5)

If you did a print(top5) on the above it would show the following results:
[(‘Eating Out’, 8), (‘Subscriptions’, 6), (‘Groceries’, 5), (‘Auto and Gas’, 5), (‘Charity’, 2)]

Now I was trying to separate the items (the count from the category) and I guess I’m messing up on that part.

The rest of the code looks like this:

categories = zip(*top5)
count =  zip(*top5)

fig, ax =  plt.subplots()

ax.bar(count,categories)
ax.set_title('#  of Purchases by Category')
plt.show()

This is where the error is occurring. I can get something to show if I make count and categories a string but it doesn’t actually plot anything and doesn’t make sense.

The error shows (the name of this .py file I’m working in is FrequentExpenses.py)

Traceback (most recent call last):
   File  "C:\Users\budget\data\FrequentExpenses.py",  line 24, in <module>
     ax.bar(count,categories)
  File  "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\__init__.py",  line 1447, in inner
    return func(ax,  *map(sanitize_sequence, args),  **kwargs)
  File  "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\axes\_axes.py",  line 2407, in bar
     self._process_unit_info(xdata=x,  ydata=height, kwargs=kwargs)
  File  "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\axes\_base.py",  line 2189, in _process_unit_info
     kwargs = _process_single_axis(xdata,  self.xaxis, 'xunits', kwargs)
  File  "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\axes\_base.py",  line 2172, in _process_single_axis
     axis.update_units(data)
  File  "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\axis.py",  line 1460, in update_units
    converter  = munits.registry.get_converter(data)
   File  "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\units.py",  line 210, in get_converter
    first =  cbook.safe_first_element(x)
  File  "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\matplotlib\cbook\__init__.py",  line 1669, in safe_first_element
     raise RuntimeError("matplotlib does not  support generators "
RuntimeError:  matplotlib does not support generators  as input

The «Expense» import is another another file (Expense.py) which looks like this that create two classes (Expenses & Expense) and also has a method of read_expenses()

import csv
from datetime import  datetime

class Expense():
    def  __init__(self, date_str, vendor,  category, amount):
         self.date_time =  datetime.strptime(date_str, '%m/%d/%Y  %H:%M:%S')
        self.vendor = vendor
         self.category = category
         self.amount = amount


class  Expenses():
    def __init__(self):
         self.list = []
        self.sum = 0

     # Read in the December spending data,  row[2] is the $$, and need to format $$
     def read_expenses(self,filename):
         with open(filename, newline='') as  csvfile:
            csvreader =  csv.reader(csvfile, delimiter=',')
             for row in csvreader:
                 if '-' not in row[3]:
                     continue
                amount =  float((row[3][2:]).replace(',',''))
                  self.list.append(Expense(row[0],row[1],  row[2], amount))
                 self.sum += amount

    def  categorize_for_loop(self):
             necessary_expenses = set()
             food_expenses = set()
             unnecessary_expenses = set()
             for i in self.list:
                if  (i.category == 'Phone'    or i.category  == 'Auto and Gas' or 
                     i.category == 'Classes'  or i.category  == 'Utilities' or 
                     i.category == 'Mortgage'): 
                     necessary_expenses.add(i)
                 elif(i.category == 'Groceries'  or i.category == 'Eating Out'):
                     food_expenses.add(i)
                 else:
                     unnecessary_expenses.add(i)
             
            return [necessary_expenses,  food_expenses, unnecessary_expenses]

I know this seems pretty simple to most, can anyone help me? I appreciate all the help and I’m looking forward to learning much more about python!

28

Answers 1 : of Error: matplotlib does not support generators as input in python code

Python knows a data type called “generators” which is a thing which generates values when asked (similar to an iterator). Very often it is cheaper to have a generator than to have a list produced up front. One example is that zip() function. Instead of returning a list of tuples it returns a generator which in turn would return one tuple after the other:

zip([1,2,3],[4,5,6])
<zip object at  0x7f7955c6dd40>

If you iterate over such a generator it will generate one value after the other, so in this case it behaves like a list:

for q in zip([1,2,3],[4,5,6]):
   print(q)
(1, 4)
(2, 5)
(3, 6)

But in other contexts it doesn’t behave like the list, e.g. if it is being asked for the length of the result. A generator (typically) doesn’t know that up front:

len(zip([1,2,3],[4,5,6]))
Traceback  (most recent call last):
  File  "<stdin>", line 1, in  <module>
TypeError: object of type  'zip' has no len()

This is mostly to save time during execution and is called lazy evaluation. Read more about generators in general.

In your case, you can simply skip the performance optimization by constructing a true list out of the generator by calling list(…) explicitly:

r = list(zip([1,2,3],[4,5,6]))

Then you can also ask for the length of the result:

len(r)
3

The matlib library will probably do this internally as well, so it accepts lists as input but not generators. Pass it a list instead of a generator, and you will be fine.

Answer Link

mRahman

i am running the notebook at this site https://github.com/vsmolyakov/experiments_with_python/blob/master/chp01/ensemble_methods.ipynb to practice ensemble methods with python, and getting an error when running this part of the code in python 3:

plt.figure()
(_, caps, _) = plt.errorbar(num_est, bg_clf_cv_mean, yerr=bg_clf_cv_std, c='blue', fmt='-o', capsize=5)
for cap in caps:
    cap.set_markeredgewidth(1)                                                                                                                                
plt.ylabel('Accuracy'); plt.xlabel('Ensemble Size'); plt.title('Bagging Tree Ensemble');
plt.show()

The error is «matplotlib does not support generators as input»
what is the solution?
best regards

Понравилась статья? Поделить с друзьями:
  • Matlab ошибка лицензии
  • Matlab ошибка 114
  • Matiz ошибка p0335
  • Mathtype ошибка при установке
  • Mathcad трассировка ошибок