Fisher线性判别的代码
第一次写啊我好像目录都乱七八糟,模板都用错了(灬ꈍ ꈍ灬)
1. mean() mean()函数功能:求取均值
经常操作的参数为axis,以m * n矩阵举例: axis 不设置值,对 mn 个数求均值,返回一个实数 axis = 0:压缩行,对各列求均值,返回 1 n 矩阵 axis =1 :压缩列,对各行求均值,返回 m *1 矩阵
举例:
def Fisher(X1, X2, n, c): # 计算三类样本的类均值向量 m1 = (np.mean(X1, axis=0)) m2 = (np.mean(X2, axis=0)) m1 = m1.reshape(n, 1) # 将行向量转换为列向量以便于计算 m2 = m2.reshape(n, 1)补充 a=a.reshape(size,1)将行向量a(1*n)转为列向量 行向量转列向量Numpy学习
2.两矩阵相乘.dot
代码如下
if c == 0: # 第一种情况 for i in range(0, 49):#每一类50组数据 S1 += (X1[i].reshape(n, 1) - m1).dot((X1[i].reshape(n, 1) - m1).T) for i in range(0, 50): S2 += (X2[i].reshape(n, 1) - m2).dot((X2[i].reshape(n, 1) - m2).T)** 3.zeros**
# 计算类内离散度矩阵 S1 = np.zeros((n, n)) # m1 = within_class_scatter_matrix1 S2 = np.zeros((n, n)) # m2 = within_class_scatter_matrix2zeros用法
.dot 和.multiply 及*用法 4.np.linalg.inv():矩阵求逆
W = np.linalg.inv(S_w).dot(m1 - m2)5。导入CSV数据并设置参数
导入iris.all-data数据集 iris = pd.read_csv('D:\data\iris.csv', header=None, sep=',') # 对无表头的数据需设置header=None否则第一行数据被作为表头 iris1 = iris.iloc[0:150, 0:4] iris2 = np.mat(iris1)读取csv时header设置
csv读取参数详解
索引数据iloc,loc等 6.python运行后查看变量 MATLAB运行之后很便捷查看变量python如何操作? 如何在pycharm运行之后查看变量
7.矩阵 数组索引
for i in range(100): if i <= 49: test = P1[i] test = test.reshape(4, 1)#转成列矩阵矩阵与数组索引的区别
numpy.mat的使用
8.删除元素or矩阵 python中del()和numpy.delete的使用
delete概念
delete举例说明
上例子里出现np.delete(a,np.s_[::2],1) 步进为2 参考:numpy数组切片
9.设置坐标范围
import matplotlib.pyplot as plt y1 = np.zeros(50) y2 = np.zeros(50) plt.figure(1) plt.ylim((-0.5, 0.5)) # y坐标的范围坐标轴设定笔记
10画散点图scatter中alpha含义 表示透明0~不透明1
# 画散点图 plt.scatter(G121, y1, c='red', alpha=1, marker='.') plt.scatter(G122, y2, c='k', alpha=1, marker='.') plt.xlabel('Class:1-2') plt.savefig('iris 1-2.png', dpi=2000)scatter详解1
详解2(更具体阐述各参数)
savefig和scatter大全(可使图片更好看)
11pycharm画图保存
代码正确但是画不出图,放在Spyder上可以画出来,网上的方法试了几个,还是直接存图更为方便。
# 画相关的图 import matplotlib.pyplot as plt x = np.arange(1, 61, 1) plt.xlabel('dimension') plt.ylabel('Accuracy') plt.ylim((0.5, 0.8)) # y坐标的范围 # 画图 plt.plot(x, Accuracy, 'b') plt.savefig('sonar fisher.png', dpi=2000)plt.savefig(‘sonar fisher.png’, dpi=2000) 直接存下图片即可