用惯了matlab中的操作,每次用numpy操作矩阵时总有些想不起来,这里总结一下,便于记忆和后期查找。
matrix_a = [1 2 3; 4 5 6; 7 8 9] % in matlab
matrix_b = [3,2,1]
matrix_c = [2 3 1; 4 6 5; 1 2 3]
matrix_a = np.matrix([[1,2,3],[4,5,6], [7,8,9]], dtype = int) # in python, 默认dtype为int
matrix_b = np.matrix([3,2,1])
matrix_c = np.matrix([[2,3,1],[4,6,5], [1,2,3]])
%获取matrix_a 的行列数, in matlab
m = size(matrix_a, 1)
n = size(matrix_a, 2)
#获取matrix_a的行列数, in nmupy
m = np.size(matrix_a, 0)
n = np.size(matrix_b, 1)
m = matrix_a.shape[0] # in python
n = matrix_a.shape[1]
% matlab
% marix_b.shape = [1,3], matrix_b_t.shape =[3,1]
matrix_b_t = matrix_b'
#numpy
matrix_b_t = np.transpose(matrix_b)
matrix_b_t = matrix_b.T #python可用 [.T]进行矩阵转置
% matlab
%求marix_a的逆矩阵
a_inv = inv(matrix_a)
#python
a_inv = matrix_a.I
*测试结果不一致,暂时先记录下
% Matlab
% 计算matrix_a , matrix_b 的乘积
matrix_d = matrix_a * matrix_b'
% 计算matrix_a , matrix_c 的点乘
matrix_e = matrix_a .* matrix_b
#numpy
matrix_d = np.dot(matrix_a, matrix.T)
matrix_e = np.multiply(matrix_a, matrix_c)
% Matlab
%求矩阵 matrix_a 内元素的2次幂运算
result = matrix_a.^2
#numpy
result = np.power(matrix_a, 2)
result = matrix_a ** 2 # in python
%Matlab
%求矩阵 matrix_a所有元素和
s_result = sum(sum(matrix_a))
s_row = sum(matrix_a, 1)
s_column = sum(matrix_a, 2)
#numpy
s_result = np.sum(matrix_a)
s_row = np.sum(matrix_a, 0)
s_column = np.sum(matrix_a, 1)
%在matrix_a 的第一列前插入一列元素
new_matrix_a = [ones[m,1], matrix_a] % matlab
nwe_matrix_a = np.insert(matrix_a, 0, values =1 ,axis =1) # numpy
假设你有一个二分类训练数据 : data如下。现分别取出正,负样本对于的特征值。
x1 | x2 | y |
5 | 4 | 1 |
3 | 2 | 0 |
5 | 3 | 1 |
10 | 5 | 0 |
#注意python小标从0开始,matlab从1开始
% Matlab
pos = find(data[:, 3] == 1) %正样本
neg = find(data[:, 3] == 0) %负样本
data[pos, 1] % 所有正样本 x1 的值
data[pos, 2] % 所有正样本 x2 的值
data[neg, 1] % 所有负样本 x1 的值
data[neg, 2] % 所有负样本 x2 的值
#numpy
pos = np.array(data[:, 2] == 1)
neg = np.array(data[:, 2] == 0)
# matlab 的find 函数返回的下标, 这里是将符合条件(==1)的转换为布尔值(掩码),再通过布尔值进行取值。
data[pos, 0]
data[pos, 1]
data[neg, 0]
data[pos, 1]
1)水平组合(x):result = np.hstack((matrix_a, matrix_c)) shape of result is (6, 3)
2) 垂直组合 (y): result = np.vstack((matrix_a, matrix_c)) shape of result is (3, 6)
3) 深度组合 (z): result = np.dstack((matrix_a, matrix_c)) shape of result is (3, 3, 2)