2013-10-31 218 views
1

我想写一个代码分类的数据。我尝试实现一个sigmoid函数,然后尝试在计算成本时使用该函数。我不断收到错误,并且我有一种感觉,那是因为sigmoid函数。我希望sigmoid函数返回一个vector.But它不断返回一个标量。Matlab错误错误使用 - 矩阵尺寸必须一致

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; θ是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); 

回答

2

请在你的方法乙状结肠

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)); 
+0

它仍然给我相同的答案取代g=1/(m+exp(-z));g=1./(m+exp(-z));。 – LoveMeow

+0

我试过上面的代码,它为我工作。我试过标量,矢量和矩阵,没有发现问题。 – User1551892

+0

在我的成本函数和sigmoid中存在一个问题。所以我看到了你所做的改变的不同。谢谢 – LoveMeow

相关问题