在将数据的运算转化为向量化运算时,有种快捷方法:
根据想要得到的结果的维数,和当前数据矩阵/向量的维数来构建关系式。
比如结果是一个n*1的向量h,现在有的数据是一个m*n的矩阵X和一个m*1的向量theta,那么很有可能:
h = X' * theta (这里的X‘表示X的转置)
向量化可以简化代码,提高运算效率~ Vectorization is highly recommended!
----------------------------------------------------------
顺便再记一个用matlab写特征规范化代码时遇到的知识点:
You can use the mean() and sigma() functions to get the mean and std deviation for each column of X. These are returned as row vectors (1 x n)
Now you want to apply those values to each element in every row of the X matrix. One way to do this is to duplicate these vectors for each row in X, so they're the same size.
One method to do this is to create a column vector of all-ones - size (m x 1) - and multiply it by the mu or sigma row vector (1 x n). Dimensionally, (m x 1) * (1 x n) gives you a (m x n) matrix, and every row of the resulting matrix will be identical. (这个方法很妙!)
Now that X, mu, and sigma are all the same size, you can use element-wise operators to compute X_normalized.
Try these commands in your workspace:
1 X = [1 2 3; 4 5 6] 2 % creates a test matrix 3 mu = mean(X) 4 % returns a row vector 5 sigma = std(X) 6 % returns a row vector 7 m = size(X, 1) 8 % returns the number of rows in X 9 mu_matrix = ones(m, 1) * mu 10 sigma_matrix = ones(m, 1) * sigma
概括一下,就是说你有一个m*n的矩阵X(比如[1,2,3;4,5,6;7,8,9]),和一个1*n的向量v(比如[1,2,3]),你想让X的每一列都减去v对应列里的数值(结果为[0,0,0;3,3,3;6,6,6]),但它们维度不同,怎么办呢?构建一个和X维数相同,且每行都等同v的矩阵v_matrix(即变为[1,2,3;1,2,3;1,2,3])。那么有个巧妙地方法是,先构建一个m*1维的全1向量o(如[1;1;1]),那么o*v就可以得到v_matrix矩阵。
除法也类似,不过要用 ./ (element-wise运算)而不是 / 。
而在我的matlab R2018b版本里,可以直接X-v 或 X./v 来得到同样的结果,非常方便,但不一定适用于其他版本。所以还是把上面的构建ones列向量并与原行向量相乘的方法记牢比较好。