BP实现函数拟合

%%
clc;
clear all;
close all;

%% 生成正弦曲线
x = linspace(-2*pi, 2*pi, 100);
y = sin(x);
% 对目标值加入噪声
n = 0.1 * rand(1, length(x));
y = y + n;

% figure();
% plot(x, y, 'b-');

%% 数据归一化,创建测试数据集
[x_, ps] = mapminmax(x);
data_input = x_;
data_target = y;

% figure();
% plot(data_input, data_target, 'b-');

data_test = linspace(-5, 5, 50);
data_true = sin(data_test);
data_t = mapminmax('apply', data_test, ps);

% figure();
% plot(data_t, data_true, 'b-');

%% 创建神经网络(也可打开nntool,在matlab中使用gui创建神经网络)
hidden_layer_size = 10;
net = feedforwardnet(hidden_layer_size);
[net, tr] = train(net, data_input, data_target);

%% 拟合结果
data_y = sim(net, data_t);
% data_y = net(data_t);
figure();
e = 0.5 * (data_true - data_y) .^ 2;
plot(e);
xlabel('x axis');
ylabel('y axis');
legend('error');

figure();
hold on;
plot(data_test, data_y, '*');
plot(x, y, 'b');
xlabel('x axis');
ylabel('y axis');
legend('prediction', 'real value');
posted @ 2021-09-01 23:46  py佐料  阅读(253)  评论(0编辑  收藏  举报