【问题标题】:Matlab error error using - matrix dimensions must agreeMatlab错误错误使用 - 矩阵尺寸必须一致
【发布时间】:2013-11-11 15:25:51
【问题描述】:

我正在尝试编写用于数据分类的代码。我尝试实现一个 sigmoid 函数,然后我尝试使用该函数来计算成本。我不断收到错误,我感觉这是因为 sigmoid 函数。我希望 sigmoid 函数返回一个向量。但是它不断返回一个标量。

function g = sigmoid(z)
%SIGMOID Compute sigmoid functoon
%   J = SIGMOID(z) computes the sigmoid of z.

% You need to return the following variables correctly 

g=zeros(size(z));
m=ones(size(z));
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the sigmoid of each value of z (z can be a matrix,
%               vector or scalar).


g=1/(m+exp(-z));

这是我的成本函数:

m = length(y); % number of training examples

% You need to return the following variables correctly 
grad=(1/m)*((X*(sigmoid(X*theta)-y)));//this is the derivative in gradient descent
J=(1/m)*(-(transpose(y)*log(sigmoid((X*theta))))-(transpose(1-y)*log(sigmoid((X*theta)))));//this is the cost function

X 的维度是 100,4; theta 的值为 4,1;y 为 100,1。

谢谢。

错误:

Program paused. Press enter to continue.

 sigmoid answer: 0.500000Error using  - 
Matrix dimensions must agree.

Error in costFunction (line 11)
grad=(1/m)*((X*(sigmoid(X*theta)-y)));

Error in ex2 (line 69)
[cost, grad] = costFunction(initial_theta, X, y);

【问题讨论】:

    标签: matlab matrix compiler-errors dimensions


    【解决方案1】:

    请在您的方法 sigmoid 中将 g=1/(m+exp(-z)); 替换为 g=1./(m+exp(-z));

    z = [2,3,4;5,6,7] ;
    %SIGMOID Compute sigmoid functoon
    %   J = SIGMOID(z) computes the sigmoid of z.
    
    % You need to return the following variables correctly 
    
    g=zeros(size(z));
    m=ones(size(z));
    % ====================== YOUR CODE HERE ======================
    % Instructions: Compute the sigmoid of each value of z (z can be a matrix,
    %               vector or scalar).
    
    
    g=1./(m+exp(-z));
    

    【讨论】:

    • 它仍然给了我同样的答案。
    • 我尝试了上面的代码,它对我有用。我尝试了标量、向量和矩阵,没有发现任何问题。
    • 我的成本函数和 sigmoid 存在问题。所以我不知道您所做的更改有何不同。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    相关资源
    最近更新 更多