【发布时间】:2014-03-26 18:40:42
【问题描述】:
我过去在这个网站上问过一些关于神经网络的问题,并得到了很好的答案,但我仍在努力为自己实现一个。这是一个相当长的问题,但我希望它可以作为其他人在 MATLAB 中创建自己的基本神经网络的指南,所以它应该是值得的。
到目前为止我所做的可能是完全错误的。我正在学习 Andrew Y. Ng 教授的在线斯坦福机器学习课程,并尽我所能将他所教的内容付诸实践。
您能否告诉我我的代码的前馈和成本函数部分是否正确,以及我在最小化(优化)部分中哪里出错了?
我有一个 feed 2 层前馈神经网络。
前馈部分的 MATLAB 代码为:
function [ Y ] = feedforward2( X,W1,W2)
%This takes a row vector of inputs into the neural net with weight matrices W1 and W2 and returns a row vector of the outputs from the neural net
%Remember X, Y, and A can be vectors, and W1 and W2 Matrices
X=transpose(X); %X needs to be a column vector
A = sigmf(W1*X,[1 0]); %Values of the first hidden layer
Y = sigmf(W2*A,[1 0]); %Output Values of the network
Y = transpose(Y); %Y needs to be a column vector
例如,具有两个输入和两个输出的两层神经网络看起来有点像这样:
a1
x1 o--o--o y1 (all weights equal 1)
\/ \/
/\ /\
x2 o--o--o y2
a2
如果我们输入:
X=[2,3];
W1=ones(2,2);
W2=ones(2,2);
Y = feedforward2(X,W1,W2)
我们得到输出:
Y = [0.5,0.5]
这表示神经网络图中显示的y1和y2值
平方误差成本函数的 MATLAB 代码为:
function [ C ] = cost( W1,W2,Xtrain,Ytrain )
%This gives a value seeing how close W1 and W2 are to giving a network that represents the Xtrain and Ytrain data
%It uses the squared error cost function
%The closer the cost is to zero, the better these particular weights are at giving a network that represents the training data
%If the cost is zero, the weights give a network that when the Xtrain data is put in, The Ytrain data comes out
M = size(Xtrain,1); %Number of training examples
oldsum = 0;
for i = 1:M,
H = feedforward2(Xtrain,W1,W2);
temp = ( H(i) - Ytrain(i) )^2;
Sum = temp + oldsum;
oldsum = Sum;
end
C = (1/2*M) * Sum;
end
示例
例如,如果训练数据是:
Xtrain =[0,0; Ytrain=[0/57;
1,2; 3/57;
4,1; 5/57;
5,2; 7/57; a1
3,4; 7/57; %This will be for a two input one output network x1 o--o y1
5,3; 8/57; \/ \_o
1,5; 6/57; /\ /
6,2; 8/57; x2 o--o
2,1; 3/57; a2
5,5;] 10/57;]
我们从初始随机权重开始
W1=[2,3; W2=[3,2]
4,1]
如果我们输入:
Y= feedforward2([6,2],W1,W2)
我们得到
Y = 0.9933
这与训练数据所说的相差甚远(8/57 = 0.1404)。所以最初的随机权重 W1 和 W2 在那里一个不好的猜测。
为了准确衡量对随机权重的猜测有多差/多好,我们使用成本函数:
C= cost(W1,W2,Xtrain,Ytrain)
这给出了值:
C = 6.6031e+003
最小化成本函数
如果我们通过搜索所有可能的变量 W1 和 W2 来最小化成本函数,然后选择最低的,这将给出最接近训练数据的网络
但是当我使用代码时:
[W1,W2]=fminsearch(cost(W1,W2,Xtrain,Ytrain),[W1,W2])
它给出一条错误消息。它说:“使用 horzcat 时出错。CAT 参数尺寸不一致。”为什么会出现此错误,我该如何解决?
您能否告诉我我的代码的前馈和成本函数部分是否正确,以及我在最小化(优化)部分中哪里出错了?
谢谢!!!
【问题讨论】:
标签: matlab machine-learning neural-network