Python梯度下降绘图报错:matplotlib不支持生成器输入
解决matplotlib不支持generator作为plot输入的问题
你遇到的这个报错很典型——Python 3里的map()函数返回的是生成器对象,而matplotlib的plot()方法不接受生成器作为数据输入,它需要的是像列表、numpy数组这类明确的序列类型。而range()之所以能正常工作,是因为它本身是一个可迭代的序列对象(不是生成器),matplotlib对其做了兼容处理。
要在保留map()函数的前提下解决这个问题,只需要把map()的结果转换成列表即可,用list()包裹住map()调用就行。
修改后的完整代码如下:
import math import matplotlib.pyplot as plt from functools import partial def difference_quotient(f,x,h): return(f(x+h)-f(x))/h def square(x): return x*x def derivative(x): return 2*x derivative_estimate = partial(difference_quotient,square,h=0.0001) x = range(-10,10) plt.title("actual vs estimation") # 把map结果转成列表,供matplotlib识别 plt.plot(x, list(map(derivative,x)), 'rx', label="actual") plt.plot(x, list(map(derivative_estimate,x)), 'b+', label="estimate") plt.legend() # 新增该行,让图例正常显示 plt.show() print(len(list(map(derivative,x))))
这样修改后,list(map(...))会把生成器里的元素一次性提取出来转换成列表,matplotlib就能正常识别并绘图了。
内容的提问来源于stack exchange,提问作者Ariya Susanto
相关产品推荐
相关产品推荐

