【问题标题】:linear regression with feature normalization matlab code具有特征归一化matlab代码的线性回归
【发布时间】:2017-10-24 03:19:03
【问题描述】:

我做了两种方法,为什么第一种方法(从 mu=mean(X) 开始行不行?有什么区别?

 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

【问题讨论】:

  • 你的for循环错了,应该是for i = 1: size(X,2) 因为你想动态循环遍历数据集中的特征个数

标签: matlab regression linear-regression normalization


【解决方案1】:

您需要遍历X。您可以使用normalize(X)进一步验证上述代码的输出

for i = 1: size(X, 2)
    mu = mean(X(:, i));
    sigma = std(X(:, i));
    X_norm(:, i) = (X(:, i) - mu) ./ sigma
end

【讨论】:

    【解决方案2】:

    原因是你试图从矩阵中减去一个向量。 mean(X) 为您提供了一个向量,其平均值在 X 的列中,维度为 [1xC],X 为维度 [RxC]。在 oneliner 中解决这个问题的一种方法是

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

    【讨论】:

    • X_norm = (X_norm-mu)./sigma; 这也可以吗?
    猜你喜欢
    • 2018-01-02
    • 2021-05-14
    • 2020-05-19
    • 2021-05-22
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2019-10-15
    相关资源
    最近更新 更多