2017-05-24 2 views
0

Je l'ai fait deux façons, pourquoi est la première manière (à partir de la ligne avec mu = moyenne (X) ne fonctionne pas? Quelle est la différence?régression linéaire avec le code de normalisation de fonction Matlab

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. 

    % You need to set these values correctly 
    X_norm = X; 
    mu = zeros(1, size(X, 2)); 
    sigma = zeros(1, size(X, 2)); 

    % ====================== YOUR CODE HERE ====================== 
    % Instructions: 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. 
    % 
    % Hint: You might find the 'mean' and 'std' functions useful. 
    %  

    %mu=mean(X) 
    %X_norm=X-mu; 
    %sigma=std(X_norm) 
    %X_norm(1)=X_norm(1)/sigma(1) 
    %X_norm(2)=X_norm(2)/sigma(2) 



    % Calculates mean and std dev for each feature 
    for i=1:size(mu,2) 
     mu(1,i) = mean(X(:,i)); 
     sigma(1,i) = std(X(:,i)); 
     X_norm(:,i) = (X(:,i)-mu(1,i))/sigma(1,i); 
    end 







    % ============================================================ 

    end 

Répondre

1

La raison est parce que vous essayez de soustraire un vecteur d'une matrice mean(X) vous donne un vecteur avec la moyenne dans les colonnes de X, dimension [1xC], et X est dimension [RxC] .Un moyen de résoudre ce problème dans un oneliner est

X = (X-repmat(mean(X,1),size(X,1),1))./repmat(std(X,0,1),size(X,1),1) 
+0

'X_norm = (X_norm-mu) ./ sigma;' cela fonctionnerait également? – Tyger