np.mgrid和np.stack

我来补充一下Iris数据绘图时用到的几个函数

一、 np.mgrid

# np.mgrid
import numpy as np
x1 = np.mgrid[1:5:1]
print(x1, '\n')
  • 最原始的np.mgrid:创建一维数组,x = np.mgrid[a: b: c] 其中a和b表示左闭右开区间[a,b),c(实数)表示步长
结果:[1 2 3 4]
x2 = np.mgrid[1:5:5j]
print(x2, '\n')
  • np.mgrid[a: b: cj],加了一个j表示cj是一个复数(虚数),此时a和b构成闭区间[a.b],c表示[a.b]内的点数
结果:[1. 2. 3. 4. 5.] 
x, y = np.mgrid[1:5:5j, 1:4:4j]
print(x, '\n\n', y)
  • 用 x, y = np.mgrid[a1:b1:c1j, a2:b2:c2j] 创建二维数组:x横坐标就是逗号前面的,每行的横坐标一样,从上到下依次为[a1:b1:c1j]表示的数列。y纵坐标,每列纵坐标一样,从左到右依次为[a2:b2:c2j]表示的数列。
结果:
[[1. 1. 1. 1.]
 [2. 2. 2. 2.]
 [3. 3. 3. 3.]
 [4. 4. 4. 4.]
 [5. 5. 5. 5.]] 

 [[1. 2. 3. 4.]
 [1. 2. 3. 4.]
 [1. 2. 3. 4.]
 [1. 2. 3. 4.]
 [1. 2. 3. 4.]]
  • 更高维数组在加多一个坐标变量即可(比如三维坐标)

二、np.stack

np.stack中的stack就是堆叠的意思,可以将两个(几个)数组(arrays)堆叠在一起生成一个坐标集

np.stack常和np.mgrid结合使用,用np.mgrid从数据库中提取出属性的值生成坐标值x和y,再用np.stack将x和y堆叠生成(x,y)坐标集

详细用法见代码中的备注:

x1 = np.arange(4)
x2 = np.array([0, 1, 2])
# print(x2.shape, x1.shape)测试用
# 用array.shape查看该array的shape

x3 = np.arange(1, 5)
# 用np.arrange(起点,终点)生成左闭右开序列[起点,终点)
# print(x1, x3)测试用

x4 = np.stack((x1, x3), axis=0)
x5 = np.stack((x1, x3), axis=1)
'''
基本用法:np.stack((array1, array2, array3...arrayn), axis=k)
array1~n,表示n个要参与堆叠的数组;
axis=k,表示要堆叠第k维,得到的结果array中第k+1维变成n;
若axis=0,表示堆叠第1维(数组中0是第一个),即行的堆叠,array1和array2都排成行,一行行堆叠下去,故行数为2,第一维变成2
若axis=1,表示堆叠第二维,即列的堆叠,array1和array2都打竖排成列,再一列列排下去,故列数为2,第二维变成2
注意:all input arrays must have the same shape,所以x1和x2不能stack
'''
print(x4, '\n', x5, '\n')

y1 = np.array([[1, 2, 0], [3, 4, 0]])
y2 = np.array([[5, 6, 9], [7, 8, 9]])
y4 = np.array([[0, 6, 9], [7, 8, 9]])
# print(y1.shape, y2.shape)测试
# print(y2)测试
y3 = np.stack((y1, y2, y4), axis=0)
print(y3)
print(y3.shape)
# 可见第一维变成了3,因为按行堆叠了三个array,后面的2和3就是被堆叠array的原维数
分析以下代码#!/usr/bin/python # -*- coding:utf-8 -*- import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt from sklearn import svm from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # 'sepal length', 'sepal width', 'petal length', 'petal width' iris_feature = u'花萼长度', u'花萼宽度', u'花瓣长度', u'花瓣宽度' if __name__ == "__main__": path = 'D:\\iris.data' # 数据文件路径 data = pd.read_csv(path, header=None) x, y = data[range(4)], data[4] y = pd.Categorical(y).codes x = x[[0, 1]] x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, train_size=0.6) # 分类器 clf = svm.SVC(C=0.1, kernel='linear', decision_function_shape='ovr') # clf = svm.SVC(C=0.8, kernel='rbf', gamma=20, decision_function_shape='ovr') clf.fit(x_train, y_train.ravel()) # 准确率 print (clf.score(x_train, y_train)) # 精度 print ('训练集准确率:', accuracy_score(y_train, clf.predict(x_train))) print (clf.score(x_test, y_test)) print ('测试集准确率:', accuracy_score(y_test, clf.predict(x_test))) # decision_function print ('decision_function:\n', clf.decision_function(x_train)) print ('\npredict:\n', clf.predict(x_train)) # 画图 x1_min, x2_min = x.min() x1_max, x2_max = x.max() x1, x2 = np.mgrid[x1_min:x1_max:500j, x2_min:x2_max:500j] # 生成网格采样点 grid_test = np.stack((x1.flat, x2.flat), axis=1) # 测试点 # print 'grid_test = \n', grid_test # Z = clf.decision_function(grid_test) # 样本到决策面的距离 # print Z grid_hat = clf.predict(grid_test) # 预测分类值 grid_hat = grid_hat.reshape(x1.shape) # 使之与输入的形状相同 mpl.rcParams['font.sans-serif'] = [u'SimHei'] mpl.rcParams['axes.unicode_minus'] = False cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF']) cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b']) plt.figure(facecolor='w') plt.pcolormesh(x1, x2, grid_hat, shading='auto', cmap=cm_light) plt.scatter(x[0], x[1], c=y, edgecolors='k', s=50, cmap=cm_dark) # 样本 plt.scatter(x_test[0], x_test[1], s=120, facecolors='none', zorder=10) # 圈中测试集样本 plt.xlabel(iris_feature[0], fontsize=13) plt.ylabel(iris_feature[1], fontsize=13) plt.xlim(x1_min, x1_max) plt.ylim(x2_min, x2_max) plt.title(u'鸢尾花SVM二特征分类', fontsize=16) plt.grid(b=True, ls=':') plt.tight_layout(pad=1.5) plt.show()
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值