forked from joemehr/MachineLearning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
featureNormalize.m
47 lines (39 loc) · 1.58 KB
/
featureNormalize.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function [X_norm, mu, sigma] = featureNormalize(X)
%FEATURENORMALIZE Normalizes the features in X
% FEATURENORMALIZE(X) returns a normalized version of X where
% the mean value of each feature is 0 and the standard deviation
% is 1. This is often a good preprocessing step to do when
% working with learning algorithms.
X_norm = X;
% size(X, 2) = # of columns in matrix X
% mu and sigma = row vector of size 1xn where n is the # of
% rows in X (# of training data)
mu = zeros(1, size(X, 2));
sigma = zeros(1, size(X, 2));
% First, for each feature dimension, compute the mean
% of the feature and subtract it from the dataset,
% storing the mean value in mu. Next, compute the
% standard deviation of each feature and divide
% each feature by it's standard deviation, storing
% the standard deviation in sigma.
%
% Note that X is a matrix where each column is a
% feature and each row is an example. You need
% to perform the normalization separately for
% each feature.
% Parameter X: Any real mxn matrix
% Return: mu = 1xn row vector
% sigma = 1xn row vector sigma
% X_norm = mxn matrix which has been normalized
% with mu and sigma
numberOfColumnsInX_norm = columns(X_norm);
% works with input matrix X of any size
for i = 1:numberOfColumnsInX_norm,
meanOfCurrentFeatureInX = mean(X(:, i));
mu(:, i) = meanOfCurrentFeatureInX;
X_norm(:, i) = X_norm(:, i) .- mu(:, i);
standardDeviationOfCurrentFeatureInX = std(X(:, i));
sigma(:, i) = standardDeviationOfCurrentFeatureInX;
X_norm(:, i) = X_norm(:, i) ./ sigma(:, i);
end
end