向量化 Vectorization

在將數據的運算轉化爲向量化運算時,有種快捷方法:

根據想要得到的結果的維數,和當前數據矩陣/向量的維數來構建關係式。

比如結果是一個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列向量並與原行向量相乘的方法記牢比較好。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章