matlab写一个神经网络
时间: 2023-11-21 11:47:19 浏览: 58
作为AI语言模型,我可以为您提供一个简单的MATLAB神经网络代码示例:
% 设置训练数据
X = [0 0 1; 0 1 1; 1 0 1; 1 1 1];
Y = [0; 1; 1; 0];
% 设置神经网络结构
input_layer_size = 3;
hidden_layer_size = 4;
output_layer_size = 1;
% 初始化权重参数
epsilon_init = 0.12;
Theta1 = rand(hidden_layer_size, input_layer_size + 1) * 2 * epsilon_init - epsilon_init;
Theta2 = rand(output_layer_size, hidden_layer_size + 1) * 2 * epsilon_init - epsilon_init;
% 迭代训练
num_iterations = 10000;
alpha = 0.01;
for i = 1:num_iterations
% 前向传播
a1 = [ones(size(X, 1), 1) X];
z2 = a1 * Theta1';
a2 = [ones(size(z2, 1), 1) sigmoid(z2)];
z3 = a2 * Theta2';
h = sigmoid(z3);
% 计算代价函数
J = (1 / size(X, 1)) * sum(sum(-Y .* log(h) - (1 - Y) .* log(1 - h)));
% 反向传播
delta3 = h - Y;
delta2 = (delta3 * Theta2(:, 2:end)) .* sigmoidGradient(z2);
Delta1 = delta2' * a1;
Delta2 = delta3' * a2;
Theta1_grad = (1 / size(X, 1)) * Delta1;
Theta2_grad = (1 / size(X, 1)) * Delta2;
% 更新权重参数
Theta1 = Theta1 - alpha * Theta1_grad;
Theta2 = Theta2 - alpha * Theta2_grad;
end
% 预测结果
a1 = [ones(size(X, 1), 1) X];
z2 = a1 * Theta1';
a2 = [ones(size(z2, 1), 1) sigmoid(z2)];
z3 = a2 * Theta2';
h = sigmoid(z3);
predicted_output = h
% 定义sigmoid函数和sigmoid函数的导数
function g = sigmoid(z)
g = 1 ./ (1 + exp(-z));
end
function g = sigmoidGradient(z)
g = sigmoid(z) .* (1 - sigmoid(z));
end
阅读全文