matlab - Matlab错误使用错误-矩阵尺寸必须一致

标签 matlab matrix compiler-errors dimensions

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

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

最佳答案

请在方法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));

关于matlab - Matlab错误使用错误-矩阵尺寸必须一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19709636/

相关文章:

python - 如何将带有网格网格和数组的 Matlab 代码转换为 Python 代码?

python - Numpy 数组,数据必须是一维的

java - 图矩阵项目(静态中的非静态)

c++ - iPhone项目中很多C++编译错误

android - buildozer 虚拟机的问题

image - 如何计算图像的 L1 范数?

matlab - 如何绘制看起来像散点图的零一矩阵?

python - 通过在 Python 中加权来按行组合矩阵

c++ - FLENS 的自定义存储

ios - Xcode 崩溃后的 RestKit 错误