matplotlib中add_subplot出错

以下代码是天文包astroML中的例子,运行时出错,调试发现是 一起
fig = plt.figure(figsize=(5, 1.66)) 与 ax = fig.add_subplot(131)
一起运行时出错。但不知道为什么?
还有很奇怪的时以前可以运行的代码,在运行完下面代码出错后,在运行也会出同样的错误
代码:

"""
EM example: Gaussian Mixture Models
-----------------------------------
Figure 6.6

A two-dimensional mixture of Gaussians for the stellar metallicity data. The
left panel shows the number density of stars as a function of two measures of
their chemical composition: metallicity ([Fe/H]) and alpha-element abundance
([alpha/Fe]). The right panel shows the density estimated using mixtures of
Gaussians together with the positions and covariances (2-sigma levels) of
those Gaussians. The center panel compares the information criteria AIC
and BIC (see Sections 4.3.2 and 5.4.3).
"""
# Author: Jake VanderPlas
# License: BSD
#   The figure produced by this code is published in the textbook
#   "Statistics, Data Mining, and Machine Learning in Astronomy" (2013)
#   For more information, see http://astroML.github.com
#   To report a bug or issue, use the following forum:
#    https://groups.google.com/forum/#!forum/astroml-general

from __future__ import print_function

import numpy as np
from matplotlib import pyplot as plt

from sklearn.mixture import GaussianMixture

from astroML.datasets import fetch_sdss_sspp
from astroML.utils.decorators import pickle_results
from astroML.plotting.tools import draw_ellipse

#----------------------------------------------------------------------
# This function adjusts matplotlib settings for a uniform feel in the textbook.
# Note that with usetex=True, fonts are rendered with LaTeX.  This may
# result in an error if LaTeX is not installed on your system.  In that case,
# you can set usetex to False.
if "setup_text_plots" not in globals():
    from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)

#------------------------------------------------------------
# Get the Segue Stellar Parameters Pipeline data
data = fetch_sdss_sspp(cleaned=True)
X = np.vstack([data['FeH'], data['alphFe']]).T

# truncate dataset for speed
X = X[::5]

#------------------------------------------------------------
# Compute GaussianMixture models & AIC/BIC
N = np.arange(1, 14)


@pickle_results("GMM_metallicity.pkl")
def compute_GaussianMixture(N, covariance_type='full', max_iter=1000):
    models = [None for n in N]
    for i in range(len(N)):
        print(N[i])
        models[i] = GaussianMixture(n_components=N[i], max_iter=max_iter,
                                    covariance_type=covariance_type)
        models[i].fit(X)
    return models

models = compute_GaussianMixture(N)

AIC = [m.aic(X) for m in models]
BIC = [m.bic(X) for m in models]

i_best = np.argmin(BIC)
gmm_best = models[i_best]
print("best fit converged:", gmm_best.converged_)
print("BIC: n_components =  %i" % N[i_best])

#------------------------------------------------------------
# compute 2D density
FeH_bins = 51
alphFe_bins = 51
H, FeH_bins, alphFe_bins = np.histogram2d(data['FeH'], data['alphFe'],
                                          (FeH_bins, alphFe_bins))

Xgrid = np.array(list(map(np.ravel,
                          np.meshgrid(0.5 * (FeH_bins[:-1]
                                             + FeH_bins[1:]),
                                      0.5 * (alphFe_bins[:-1]
                                             + alphFe_bins[1:]))))).T
log_dens = gmm_best.score_samples(Xgrid).reshape((51, 51))

#------------------------------------------------------------
# Plot the results
fig = plt.figure(figsize=(5, 1.66))
fig.subplots_adjust(wspace=0.45,
                    bottom=0.25, top=0.9,
                    left=0.1, right=0.97)

# plot density
ax = fig.add_subplot(131)
ax.imshow(H.T, origin='lower', interpolation='nearest', aspect='auto',
          extent=[FeH_bins[0], FeH_bins[-1],
                  alphFe_bins[0], alphFe_bins[-1]],
          cmap=plt.cm.binary)
ax.set_xlabel(r'$\rm [Fe/H]$')
ax.set_ylabel(r'$\rm [\alpha/Fe]$')
ax.xaxis.set_major_locator(plt.MultipleLocator(0.3))
ax.set_xlim(-1.101, 0.101)
ax.text(0.93, 0.93, "Input",
        va='top', ha='right', transform=ax.transAxes)

# plot AIC/BIC
ax = fig.add_subplot(132)
ax.plot(N, AIC, '-k', label='AIC')
ax.plot(N, BIC, ':k', label='BIC')
ax.legend(loc=1)
ax.set_xlabel('N components')
plt.setp(ax.get_yticklabels(), fontsize=7)

# plot best configurations for AIC and BIC
ax = fig.add_subplot(133)
ax.imshow(np.exp(log_dens),
          origin='lower', interpolation='nearest', aspect='auto',
          extent=[FeH_bins[0], FeH_bins[-1],
                  alphFe_bins[0], alphFe_bins[-1]],
          cmap=plt.cm.binary)

ax.scatter(gmm_best.means_[:, 0], gmm_best.means_[:, 1], c='w')
for mu, C, w in zip(gmm_best.means_, gmm_best.covariances_, gmm_best.weights_):
    draw_ellipse(mu, C, scales=[1.5], ax=ax, fc='none', ec='k')

ax.text(0.93, 0.93, "Converged",
        va='top', ha='right', transform=ax.transAxes)

ax.set_xlim(-1.101, 0.101)
ax.set_ylim(alphFe_bins[0], alphFe_bins[-1])
ax.xaxis.set_major_locator(plt.MultipleLocator(0.3))
ax.set_xlabel(r'$\rm [Fe/H]$')
ax.set_ylabel(r'$\rm [\alpha/Fe]$')

plt.show()

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
这个python监控cpu的小程序中 应用 了回调函数callback add_callback 什么意思

这个python监控cpu的小程序中 应用 了回调函数callback add_callback 什么意思 为什么之后又要清空回调信息 ``` import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager import psutil as p POINTS =60 fig,ax = plt.subplots(2) #一个图上画多个表https://blog.csdn.net/htuhxf/article/details/82986440 #fig,ax = plt.subplots(2,facecolor='#FF1493')#设置上下两个图、面板色。颜色的网站www.cnblogs.com/darkknightzh/p/6117528.html fig.canvas.set_window_title(u'电脑性能(cpu、内存、网速)实时监测')#设置窗口标题 fig.canvas.toolbar.destroy()#取消工具栏 fig.canvas.callbacks.callbacks.clear()#清除回调信息 #ax为列表,分别设置 ax[0].set_ylim([0, 100]) ax[0].set_xlim([0, POINTS]) ax[0].set_autoscale_on(False) ax[0].set_xticks([]) ax[0].set_yticks(range(0, 101, 10)) #ax[0].set_facecolor('#A9A9A9')#可设置底色,支持'black')#matplotlib颜色分层设置(表的颜色) ax[0].grid(True) #ax[1].set_ylim([-5, 50])#设置0线上浮 ax[1].set_ylim([-5, 50])#设置0线上浮 ax[1].set_xlim([0, POINTS]) ax[1].set_autoscale_on(False) ax[1].set_xticks([]) #ax[1].set_yticks(range(0, 51, 10)) ax[1].set_yticks(range(0, 101, 10))#线的 ax[1].grid(True) # 设置CPU、内存横坐标数据位 cpu = [None] * POINTS mem=[None] * POINTS # 设置接收字节(下载)横坐标数据位 down = [None] * POINTS #设置第一个图 cpu_l, = ax[0].plot(range(POINTS), cpu, label='Cpu%',color = 'red') mem_l, = ax[0].plot(range(POINTS), mem, label='Mem%') ax[0].legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10))#打标 #设置第二个图 down_l, = ax[1].plot(range(POINTS), down, label='Down(M)') ax[1].legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10)) before =p.net_io_counters().bytes_recv#获取网络字节数 def get_delta():#获取下载变化值 global before now = p.net_io_counters().bytes_recv delta = (now-before)/102400#变成K再除100,大致相当于多少M宽带。 before = now return delta #返回改变量 def OnTimer(ax): global cpu, mem, down tmp = get_delta()#得到下载字节数的变化值 cpu_p=p.cpu_percent()#读取CPU使用百分比 cpu = cpu[1:] + [cpu_p]#加入到数据末尾 mem_p=p.virtual_memory().percent#读取内存使用百分比 mem =mem[1:] + [mem_p]#加入到数据末尾 cpu_l.set_ydata(cpu)#设置新数据 mem_l.set_ydata(mem)#设置新数据 down = down[1:] + [tmp] down_l.set_ydata(down)#设置新数据 ax.figure.canvas.draw()#刷新画布 def start_monitor(): timer = fig.canvas.new_timer(interval=1000)#1秒刷新一次 timer.add_callback(OnTimer, ax[1])#只加一个即可 #timer.add_callback(OnTimer, ax[0]) timer.start() plt.show() if __name__ == '__main__': start_monitor() ```

python运行后显示matplotlib包有问题

程序运行后有结果,也可以显示出图像,可是图像显示的不是正确结果,而且会报错, 错误如下,有没有懂这是什么错啊,是需要重新安装matplotlib包吗?我已经安装了好几次了,但还是一直显示有错误。 D:\Program Files\Anaconda3\lib\site-packages\matplotlib\font_manager.py:1241: UserWarning: findfont: Font family ['serif'] not found. Falling back to DejaVu Sans. (prop.get_family(), self.defaultFamily[fontext])) ![图片说明](https://img-ask.csdn.net/upload/201811/20/1542686965_312793.png) ![图片说明](https://img-ask.csdn.net/upload/201811/20/1542686995_886745.png)

用matplotlib画个图这简单的四行代码都能出错?

以下是代码: import matplotlib.pyplot as plt plt.plot(range(1,6),[1,2,3,4,5],'bo',lable='Training') plt.plot(range(1,6),[1,0,0,0,2],'bo',lable='Test') plt.legend() plt.show() ``` 以下是错误提示: Traceback (most recent call last): File "test.py", line 3, in <module> plt.plot(range(1,6),[1,2,3,4,5],'bo',lable='Training') File "D:\Anaconda\lib\site-packages\matplotlib\pyplot.py", line 3161, in plot ret = ax.plot(*args, **kwargs) File "D:\Anaconda\lib\site-packages\matplotlib\__init__.py", line 1818, in inner return func(ax, *args, **kwargs) File "D:\Anaconda\lib\site-packages\matplotlib\axes\_axes.py", line 1382, in plot for line in self._get_lines(*args, **kwargs): File "D:\Anaconda\lib\site-packages\matplotlib\axes\_base.py", line 381, in _grab_next_args for seg in self._plot_args(remaining, kwargs): File "D:\Anaconda\lib\site-packages\matplotlib\axes\_base.py", line 369, in _plot_args seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs) File "D:\Anaconda\lib\site-packages\matplotlib\axes\_base.py", line 276, in _makeline seg = mlines.Line2D(x, y, **kw) File "D:\Anaconda\lib\site-packages\matplotlib\lines.py", line 380, in __init__ self.update(kwargs) File "D:\Anaconda\lib\site-packages\matplotlib\artist.py", line 859, in update raise AttributeError('Unknown property %s' % k) AttributeError: Unknown property lable ``` 最后两行是什么意思?? 画的图也没有显示label。 # 我试了一下删掉plot后面的label参数,即 import matplotlib.pyplot as plt plt.plot(range(1,6),[1,2,3,4,5],'bo') plt.plot(range(1,6),[1,0,0,0,2],'bo') plt.legend() plt.show() ``` 虽然能把图画出来,但是会有以下警告: D:\Anaconda\lib\site-packages\matplotlib\axes\_axes.py:531: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots. warnings.warn("No labelled objects found. " ``` 意思是我需要添加一个label=‘...’ 但是添加之后又会有上面那个错误,这到底该咋整啊。。。。。。?

【python】为什么matplotlib的ax.set_xticklabel()放在类的__init__()里就没用?

因为要画很多图就写了个画图类,但是初始化的时候加上ax.set_xticklabels()就会没用。 ```python class DrawCharts: def __init__(self, title='', xlabel='', ylabel='', xticks=None, yticks=None, xticklabels=None, yticklabels=None, xscale='linear', yscale='linear', autofmt_x=True): self.title = title self.xlabel = xlabel self.ylabel = ylabel self.xticks = xticks self.yticks = yticks self.xticklabels = xticklabels self.yticklabels = yticklabels self.xscale = xscale self.yscale = yscale self.autofmt_x = autofmt_x # 解决中文显示问题 self.font = {'family': 'SimHei', # 字体:黑体 'size': '16'} # 字号:16 plt.rc('font', **self.font) # 设置字体的更多属性 plt.rc('axes', unicode_minus=False) # 解决坐标轴负数的负号显示问题 self.fig, self.ax = plt.subplots() self.ax.set_title(self.title) self.ax.set_xlabel(self.xlabel) self.ax.set_ylabel(self.ylabel) if self.xticks is not None: self.ax.set_xticks(self.xticks) if self.yticks is not None: self.ax.set_yticks(self.yticks) if self.xticklabels is not None: self.ax.set_xticklabels(self.xticklabels) if self.yticklabels is not None: self.ax.set_yticklabels(self.yticklabels) self.ax.set_xscale(self.xscale) # 坐标轴:线性:'linear',指数:'symlog' self.ax.set_yscale(self.yscale) if self.autofmt_x == True: self.fig.autofmt_xdate() def show_figs(self): plt.show() def draw_plot(self, xdata, ydata, color='dodgerblue', label=''): self.ax.plot(xdata, ydata, color=color, label=label) if __name__ == "__main__": x = [1, 2, 3] y = [1, 5, 7] chart = DrawCharts('图形', 'x标签', 'y标签',xticks=[1, 2, 3], xticklabels=['a', 'b', 'c']) chart.draw_plot(x, y) chart.show_figs() ``` 这样执行出来就完全没有自定义标签。 ![xticklabels无效](https://img-ask.csdn.net/upload/201905/12/1557664449_438887.png) 但是这样的话,就能显示了。 ```python if __name__ == "__main__": x = [1, 2, 3] y = [1, 5, 7] chart = DrawCharts('图形', 'x标签', 'y标签') chart.ax.set_xticks([1, 2, 3]) chart.ax.set_xticklabels(['a', 'b', 'c']) chart.draw_plot(x, y) chart.show_figs() ``` ![xticklabels显示](https://img-ask.csdn.net/upload/201905/12/1557664122_13764.png) 想问下大佬们为什么。

Mac下的Anaconda 无法使用matplotlib.pyplot

File "/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py", line 891, in __getitem__ from matplotlib import pyplot as plt File "/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py", line 32, in <module> import matplotlib.colorbar File "/anaconda3/lib/python3.6/site-packages/matplotlib/colorbar.py", line 28, in <module> import matplotlib.artist as martist AttributeError: module 'matplotlib' has no attribute 'artist'

matplotlib模块有问题,重装了也没用?

错误提示 Traceback (most recent call last): File "**", line 13, in <module> import matplotlib.pyplot as plt File "C:\ProgramData\Anaconda3\envs\tensorflow\lib\site-packages\matplotlib\pyplot.py", line 32, in <module> import matplotlib.colorbar File "C:\ProgramData\Anaconda3\envs\tensorflow\lib\site-packages\matplotlib\colorbar.py", line 28, in <module> import matplotlib.artist as martist File "C:\ProgramData\Anaconda3\envs\tensorflow\lib\site-packages\matplotlib\artist.py", line 11, in <module> from .path import Path File "C:\ProgramData\Anaconda3\envs\tensorflow\lib\site-packages\matplotlib\path.py", line 17, in <module> from . import _path, rcParams ImportError: cannot import name '_path'

python matplotlib显示单色图问题

``` def initArray(num): img = np.zeros((256,256)) for x in range(0,256): for y in range(0,256): img[x][y] = num return img fig = plt.figure() ax = fig.add_subplot() ax.imshow(initArray(20),cmap='gray') plt.show() ``` 按说initArray的参数变化,显示的图片应该是不同的单色图,可是显示显示的全是黑色怎么回事?

各位朋友好,请教ubuntu系统python3.4环境下安装matplotlib报错的解决办法

具体的问题是这样的: 我的系统是Ubuntu14.04 的64位系统,python3.4版本下,想使用matplotlib来做图。 由于matplotlib依赖numpy和python的图像库PIL,因此我先安装numpy和PIL然后,再安装matplotlib, 这里附上我的安装matplotlib的shell命令 #安装科学计算库numpy sudo pip3 install numpy #安装图像处理库PIL sudo apt-get install python3.4-dev -y sudo apt-get install libjpeg8-dev zlib1g-dev libfreetype6-dev -y sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib sudo apt-get install python3-pil #安装画图库matplotlib sudo pip3 install matplotlib 但是发现虽然安装成功(在python3的shell交互环境下, import matplotlib 是可以的),但是 执行如下语句 from matplotlib import pyplot as plt 报错: "/usr/local/lib/python3.4/dist-packages/matplotlib-1.5.1-py3.4-linux-x86_64.egg/matplotlib/backends/backend_gtk3.py", line 58, in <module> cursors.MOVE : Gdk.Cursor.new(Gdk.CursorType.FLEUR), TypeError: constructor returned NULL 希望各位朋友能指点一下,十分感谢

有没有那位大佬如何解决这个wen't

有没有那位大佬如何解决这个 import jieba import wordcloud f=open("新时代中国特色社会主义.txt","r",encoding="utf-8") t=f.read() f.close() ls=jieba.lcut(t) txt=" ".join(ls) w=wordcloud.WordCloud(font_path="msyh.ttc",\ width=1000,height=700,background_color="white",\ ) w.generate(txt) w.to_file("grwordcloud.png") pycharm错误提示如下: D:\xiangmu\venv\Scripts\python.exe D:/xiangmu/ciyun.py Traceback (most recent call last): File "D:/xiangmu/ciyun.py", line 3, in <module> import wordcloud File "D:\xiangmu\wordcloud\__init__.py", line 1, in <module> from .wordcloud import (WordCloud, STOPWORDS, random_color_func, File "D:\xiangmu\wordcloud\wordcloud.py", line 19, in <module> import matplotlib File "D:\xiangmu\matplotlib\__init__.py", line 139, in <module> from . import cbook, rcsetup File "D:\xiangmu\matplotlib\cbook\__init__.py", line 32, in <module> import numpy as np File "D:\xiangmu\numpy\__init__.py", line 142, in <module> from . import core File "D:\xiangmu\numpy\core\__init__.py", line 24, in <module> from . import multiarray File "D:\xiangmu\numpy\core\multiarray.py", line 14, in <module> from . import overrides File "D:\xiangmu\numpy\core\overrides.py", line 16, in <module> add_docstring( RuntimeError: implement_array_function method already has a docstring

python用matplotlib画K线

import matplotlib.pyplot as plt import matplotlib.finance as mpf with open('SH#600004.txt') as obj: text=obj.readlines() baseinfo=text[0] dayinfo=text[2:-1] date_list =[dayinfo[i].split(',')[0] for i in range(len(dayinfo))] open_list =[dayinfo[i].split(',')[1] for i in range(len(dayinfo))] high_list =[dayinfo[i].split(',')[2] for i in range(len(dayinfo))] low_list =[dayinfo[i].split(',')[3] for i in range(len(dayinfo))] close_list=[dayinfo[i].split(',')[4] for i in range(len(dayinfo))] quotes=zip(date_list,open_list,high_list,low_list,close_list) #N=100 #open_list[:N],high_list[:N],low_list[:N],close_list[:N] fig,ax=plt.subplots() mpf.candlestick_ohlc(ax,quotes,width=0.6,colorup='r',colordown='green') plt.title(baseinfo) plt.xlabel(date_list) plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 plt.show() **#以下是报错信息 C:\ProgramData\Anaconda3\python.exe G:/python/test/test.py C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py:106: MatplotlibDeprecationWarning: The finance module has been deprecated in mpl 2.0 and will be removed in mpl 2.2. Please use the module mpl_finance instead. warnings.warn(message, mplDeprecation, stacklevel=1) Traceback (most recent call last): File "G:/python/test/test.py", line 18, in <module> mpf.candlestick_ohlc(ax,quotes,width=0.6,colorup='r',colordown='green') File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\finance.py", line 737, in candlestick_ohlc alpha=alpha, ochl=False) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\finance.py", line 794, in _candlestick height = open - close TypeError: unsupported operand type(s) for -: 'str' and 'str'** 我搜了下知道日期格式转换需要用到date2num这个函数 我的文本里面日期格式是XXXX/XX/XX的形式 请问quotes一项里日期需求的格式是什么?

matplotlib,日期,画图,显示不正确

有2个问题 问题1:连线出现很奇怪的现象,那几条从左到右的连线是什么原因出现? ![图片说明](https://img-ask.csdn.net/upload/201901/07/1546863739_154000.png) ``` #生成figure对象 fig = MP.figure() #生成axis对象 ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d')) ax.xlim = (0,20000) #设置x轴坐标值和标签旋转45°的显示方式 MP.xticks(P.date_range(dataset.index[0],dataset.index[-1],freq = 'Y'),rotation = 45) #x轴为dataset.index,也就是‘受理日期’,y轴为数量,颜色设置为红色 ax.plot(dataset.index,dataset['V100']) #plt.show() ``` 问题2:如图,日期都集中在中间显示,如何从x轴左到右显示? ![图片说明](https://img-ask.csdn.net/upload/201901/07/1546863989_394045.png) ``` #生成figure对象 fig = MP.figure() #生成axis对象 ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d')) ax.xlim = (0,20000) #设置x轴坐标值和标签旋转45°的显示方式 MP.xticks(P.date_range(dataset.index[0],dataset.index[-1],freq = 'Y'),rotation = 45) #x轴为dataset.index,也就是‘受理日期’,y轴为数量,颜色设置为红色 ax.scatter(dataset.index,dataset['V100']) #plt.show() ``` 坐等大神指导

python安装matplotlib报错

,安装scipy显示no lapack/blas resources found ,这个该怎么解决?![报错图片](https://img-ask.csdn.net/upload/201606/10/1465554674_381736.png)

ubuntu16.04 python2.7环境下使用matplotlib不能画图

刚安装了matplotlib,试了下下面几行代码,但不能画图,请问该怎么解决呢? ``` >>> import matplotlib.pyplot as plt >>> plt.bar(left = (0,1),height = (1,0.5)) <Container object of 2 artists> >>> plt.show() (.:14956): GLib-GIO-CRITICAL **: g_dbus_connection_register_object: assertion 'G_IS_DBUS_CONNECTION (connection)' failed (.:14956): GLib-GIO-CRITICAL **: g_dbus_connection_register_object: assertion 'G_IS_DBUS_CONNECTION (connection)' failed (.:14956): GLib-GIO-CRITICAL **: g_dbus_connection_get_unique_name: assertion 'G_IS_DBUS_CONNECTION (connection)' failed Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3.py", line 339, in idle_draw self.draw() File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3.py", line 332, in draw self.get_property("window").process_updates (False) TypeError: Couldn't find foreign struct converter for 'cairo.Context' ```

python用matplotlib显示图片出错

源代码: import os from PIL import Image import matplotlib.pyplot as plt img = Image.open(os.path.join('', 'Testsample' + '.png')) plt.figure("Image") # 图像窗口名称 plt.imshow(img) plt.axis('on') # 关掉坐标轴为 off plt.title('image') # 图像题目 plt.show() 去掉plt.show(),就没有错误 错误提示: AttributeError: 'numpy.ndarray' object has no attribute 'mask'![图片说明](https://img-ask.csdn.net/upload/201803/19/1521467447_98280.png)

如何使用matplotlib可视化此元学习过程中的损失函数?

# 问题描述: 新手题主看到了 https://github.com/ikostrikov/pytorch-meta-optimizer 中作者基于Pytorch实现Learning to learn by gradient descent by gradient descent 第二个MNIST实验的代码。 遗憾的是其只输出了每次训练后的损失函数值,并没有可视化训练过程中损失函数的变化。 **题主想得到原文中所示的最优损失函数的下降曲线** ![图片说明](https://img-ask.csdn.net/upload/202004/24/1587737332_926090.png) 使用matplotlib应该添加哪些代码呢? main.py文件如下: ``` import argparse import operator import sys import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import matplotlib.pyplot as plt import numpy as np from data import get_batch from meta_optimizer import MetaModel, MetaOptimizer, FastMetaOptimizer from model import Model from torch.autograd import Variable from torchvision import datasets, transforms parser = argparse.ArgumentParser(description='PyTorch REINFORCE example') parser.add_argument('--batch_size', type=int, default=32, metavar='N', help='batch size (default: 32)') parser.add_argument('--optimizer_steps', type=int, default=100, metavar='N', help='number of meta optimizer steps (default: 100)') parser.add_argument('--truncated_bptt_step', type=int, default=20, metavar='N', help='step at which it truncates bptt (default: 20)') parser.add_argument('--updates_per_epoch', type=int, default=10, metavar='N', help='updates per epoch (default: 100)') parser.add_argument('--max_epoch', type=int, default=1000, metavar='N', help='number of epoch (default: 10000)') parser.add_argument('--hidden_size', type=int, default=10, metavar='N', help='hidden size of the meta optimizer (default: 10)') parser.add_argument('--num_layers', type=int, default=2, metavar='N', help='number of LSTM layers (default: 2)') parser.add_argument('--no-cuda', action='store_true', default=False, help='enables CUDA training') args = parser.parse_args() args.cuda = not args.no_cuda and torch.cuda.is_available() assert args.optimizer_steps % args.truncated_bptt_step == 0 kwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {} train_loader = torch.utils.data.DataLoader( datasets.MNIST('../data', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])), batch_size=args.batch_size, shuffle=True, **kwargs) test_loader = torch.utils.data.DataLoader( datasets.MNIST('../data', train=False, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])), batch_size=args.batch_size, shuffle=True, **kwargs) def main(): # Create a meta optimizer that wraps a model into a meta model # to keep track of the meta updates. meta_model = Model() if args.cuda: meta_model.cuda() meta_optimizer = FastMetaOptimizer(MetaModel(meta_model), args.num_layers, args.hidden_size) if args.cuda: meta_optimizer.cuda() optimizer = optim.Adam(meta_optimizer.parameters(), lr=1e-3) for epoch in range(args.max_epoch): decrease_in_loss = 0.0 final_loss = 0.0 train_iter = iter(train_loader) for i in range(args.updates_per_epoch): # Sample a new model model = Model() if args.cuda: model.cuda() x, y = next(train_iter) if args.cuda: x, y = x.cuda(), y.cuda() x, y = Variable(x), Variable(y) # Compute initial loss of the model f_x = model(x) initial_loss = F.nll_loss(f_x, y) for k in range(args.optimizer_steps // args.truncated_bptt_step): # Keep states for truncated BPTT meta_optimizer.reset_lstm( keep_states=k > 0, model=model, use_cuda=args.cuda) loss_sum = 0 prev_loss = torch.zeros(1) if args.cuda: prev_loss = prev_loss.cuda() for j in range(args.truncated_bptt_step): x, y = next(train_iter) if args.cuda: x, y = x.cuda(), y.cuda() x, y = Variable(x), Variable(y) # First we need to compute the gradients of the model f_x = model(x) loss = F.nll_loss(f_x, y) model.zero_grad() loss.backward() # Perfom a meta update using gradients from model # and return the current meta model saved in the optimizer meta_model = meta_optimizer.meta_update(model, loss.data) # Compute a loss for a step the meta optimizer f_x = meta_model(x) loss = F.nll_loss(f_x, y) loss_sum += (loss - Variable(prev_loss)) prev_loss = loss.data # Update the parameters of the meta optimizer meta_optimizer.zero_grad() loss_sum.backward() for param in meta_optimizer.parameters(): param.grad.data.clamp_(-1, 1) optimizer.step() # Compute relative decrease in the loss function w.r.t initial # value decrease_in_loss += loss.item() / initial_loss.item() final_loss += loss.item() #plt.plot(final_loss,label='LSTM') #plt.yscale('log') #plt.title('Loss') #plt.pause(0.5) #plt.show() print("Epoch: {}, final loss {}, average final/initial loss ratio: {}".format(epoch, final_loss / args.updates_per_epoch, decrease_in_loss / args.updates_per_epoch)) if __name__ == "__main__": main() ```

安装matplotlib出现了问题

一直提示 ImportError: cannot import name '_backports' from 'matplotlib.cbook' 怎么解决啊,我是个菜鸟,能有详细过程吗da'lao

在python 2.7shell中出现如下错误

>>> import matplotlib >>> import matplotlib.pyplot as plt Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> import matplotlib.pyplot as plt File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 29, in <module> from matplotlib.figure import Figure, figaspect File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 36, in <module> from matplotlib.axes import Axes, SubplotBase, subplot_class_factory File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 20, in <module> import matplotlib.dates as _ # <-registers a date unit converter File "C:\Python27\lib\site-packages\matplotlib\dates.py", line 119, in <module> from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, File "C:\Python27\lib\dateutil\rrule.py", line 16, in <module> from six.moves import _thread ImportError: cannot import name _thread >>>

第一次用matplotlib.pyplot,按着视频上把代码敲出来,但是我就是跑不出那根拟合曲线,大哥们帮忙看一下

为什么我的没有那个红色的线呢? ``` import tensorflow as tf import numpy as np import matplotlib.pyplot as plt def add_layer(inputs,in_size,out_size,activation_function=None): Weights = tf.Variable(tf.random_normal([in_size,out_size])) biases = tf.Variable(tf.zeros([1,out_size])+0.1) Wx_plus_b = tf.matmul(inputs,Weights)+biases if activation_function is None: outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b) return outputs x_data = np.linspace(-1,1,300)[:,np.newaxis] noise = np.random.normal(0,0.05,x_data.shape) y_data = np.square(x_data)-0.5 + noise xs = tf.placeholder(tf.float32,[None,1]) ys = tf.placeholder(tf.float32,[None,1]) l1 = add_layer (xs,1,10,activation_function= tf.nn.relu) prediction = add_layer(l1,10,1,activation_function= None) loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices= [1])) train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.scatter(x_data,y_data) plt.ion() plt.show(block=False) #block=False for i in range (1000): sess.run(train_step,feed_dict={xs:x_data,ys:y_data}) if i % 50 == 0: #print(sess.run(loss,feed_dict={xs:x_data,ys:y_data})) try: ax.lines.remove(lines[0]) except Exception: pass prediction_value = sess.run(prediction,feed_dict={xs:x_data}) lines = ax.plot(x_data,prediction_value,'y-',lw=10) plt.pause(0.1) ``` ![图片说明](https://img-ask.csdn.net/upload/201905/18/1558162247_285456.jpg)

在Web应用程序服务器(php)中使用matplotlib时出现问题

<div class="post-text" itemprop="text"> <p>I have a python program that starts with: </p> <pre><code>from optparse import OptionParser import math #import wx import os import numpy as np import matplotlib.pyplot as plt from pylab import * from numpy import * import scipy as scipy from scipy import * from scipy import constants import scipy.signal as signal import matplotlib.pyplot as plt </code></pre> <p>It gives me error when I try to open it with php. I have googled and apparently if I do this before importing pylab or pyplot:</p> <pre><code>import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt </code></pre> <p>Problem should be solved. But the error I get is:</p> <pre><code> /usr/lib/pymodules/python2.7/matplotlib/__init__.py:923: UserWarning: This call to matplotlib.use() has no effect because the the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time </code></pre> <p>Any idea what's going on??</p> </div>

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《Oracle Java SE编程自学与面试指南》最佳学习路线图2020年最新版(进大厂必备)

正确选择比瞎努力更重要!

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

字节跳动面试官竟然问了我JDBC?

轻松等回家通知

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

阿里面试官让我用Zk(Zookeeper)实现分布式锁

他可能没想到,我当场手写出来了

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

立即提问
相关内容推荐