matplotlib.pyplot 常用指令收集(持续更新)

import matplotlib.pyplot as plt
  • plt.figure():创建一个新的图像:参数figsize表示图像大小

  • plt.imshow(x):x为(行像素,列像素):参数cmap为图像颜色:cmap=plt.cm.binary为黑白色

  • plt.plot():绘制曲线,有属性label:为某一曲线打标签

  • subplot(nrows, ncols, index):将一个大图分成几部分来显示小图

  • plt.xticks([]),plt.yticks([]):去掉x和y轴的坐标值

  • plt.ylabel():y轴的标签

  • plt.xlable():x轴的标签

  • plt.title():绘图的标题

  • plt.show():显示图像

  • plt.colorbar():显示色条

  • plt.grid(True):显示网格

  • plt.legend(loc, shadow):添加图像说明,会自动将图中曲线的标签打印在图上

  • plt.scatter(x, y, c):输入x轴和y轴信息,图中点的区分依靠c的值

  • plt.bar():画柱形图

  • plt.hist(arr, bins):画直方图,bins为将数据分成几个直方

  • plt.contourf():绘制等高线

  • axes = plt.gca():返回坐标轴的实体,便于操作坐标轴

  • axes.set_xlim([maxX, minX]):设置横坐标范围

  • axes.set_ylim([maxY, minY]):设置纵坐标范围

  • np.arange(min, max, h):返回范围[min, max)相隔h的值

  • np.linspace(min, max, c):将范围[min,max]等分为c部分,并返回值

  • xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)):用于绘制边界

  • xx.ravel():将矩阵变为一维向量

    绘制分类边界:机制是通过预测图上每个点,输出True或False,根据不同结果绘制不同颜色

    def plot_decision_boundary(model, X, y):
        # Set min and max values and give it some padding
        x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1
        y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1
        h = 0.01
        # Generate a grid of points with distance h between them
        xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
        # Predict the function value for the whole grid
        Z = model(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        # Plot the contour and training examples
        plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
        plt.ylabel('x2')
        plt.xlabel('x1')
        plt.scatter(X[0, :], X[1, :], c=np.squeeze(y[0,:]), cmap=plt.cm.Spectral)
        plt.show()
    plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)

     

  • plt.colorbar() 显示一个色彩条状图

  • plt.grid(True) 显示网格

  • plt.imshow() 显示2维的图像

  • plt.xticks([]); plt.yticks([]) 不显示图像的x和y轴坐标

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
制作Mininst格式的数据,研究sklearn库等机器学习算法与库用得到。C++的VS2017测试通过。适用于车牌和数字识别。下面是Skearn测试程序。 #导入必备的包 import numpy as np import struct import matplotlib.pyplot as plt import os ##加载svm模型 from sklearn import svm ###用于做数据预处理 from sklearn import preprocessing import time #加载数据的路径 path='.' def load_mnist_train(path, kind='train'): labels_path = os.path.join(path,'%s-labels-idx1-ubyte'% kind) images_path = os.path.join(path,'%s-images-idx3-ubyte'% kind) with open(labels_path, 'rb') as lbpath: magic, n = struct.unpack('>II',lbpath.read(8)) labels = np.fromfile(lbpath,dtype=np.uint8) with open(images_path, 'rb') as imgpath: magic, num, rows, cols = struct.unpack('>IIII',imgpath.read(16)) images = np.fromfile(imgpath,dtype=np.uint8).reshape(len(labels), 784) return images, labels def load_mnist_test(path, kind='t10k'): labels_path = os.path.join(path,'%s-labels-idx1-ubyte'% kind) images_path = os.path.join(path,'%s-images-idx3-ubyte'% kind) with open(labels_path, 'rb') as lbpath: magic, n = struct.unpack('>II',lbpath.read(8)) labels = np.fromfile(lbpath,dtype=np.uint8) with open(images_path, 'rb') as imgpath: magic, num, rows, cols = struct.unpack('>IIII',imgpath.read(16)) images = np.fromfile(imgpath,dtype=np.uint8).reshape(len(labels), 784) return images, labels train_images,train_labels=load_mnist_train(path) test_images,test_labels=load_mnist_test(path) X=preprocessing.StandardScaler().fit_transform(train_images) X_train=X[0:60000] y_train=train_labels[0:60000] print(time.strftime('%Y-%m-%d %H:%M:%S')) model_svc = svm.LinearSVC() #model_svc = svm.SVC() model_svc.fit(X_train,y_train) print(time.strftime('%Y-%m-%d %H:%M:%S')) ##显示前30个样本的真实标签和预测值,用图显示 x=preprocessing.StandardScaler().fit_transform(test_images) x_test=x[0:10000] y_pred=test_labels[0:10000] print(model_svc.score(x_test,y_pred)) y=model_svc.predict(x) fig1=plt.figure(figsize=(8,8)) fig1.subplots_adjust(left=0,right=1,bottom=0,top=1,hspace=0.05,wspace=0.05) for i in range(100): ax=fig1.add_subplot(10,10,i+1,xticks=[],yticks=[]) ax.imshow(np.reshape(test_images[i], [28,28]),cmap=plt.cm.binary,interpolation='nearest') ax.text(0,2,"pred:"+str(y[i]),color='red') #ax.text(0,32,"real:"+str(test_labels[i]),color='blue') plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值