Bonjour,

J'essaye depuis pas mal de temps de modifier un fichier qui contient une comparaison entre l'algo PMC (Perceptron Multi Couche) et une méthode Bayesienne de classification.

En fait j'ai deux problèmes:
1- Je doit modifier ce code pour mettre l'algo RBF (Réseaux à Fonctions de Base Radiales) à la place de la méthode Bayesienne.
2- (Facultatif) Pouvoir lire les données dans un fichier (.data) au lieu de les générer aléatoirement.

Voici le fichier en question:

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
 
%DEMMLP2 Demonstrate simple classification using a multi-layer perceptron
%
%	Description
%	The problem consists of input data in two dimensions drawn from a
%	mixture of three Gaussians: two of which are assigned to a single
%	class.  An MLP with logistic outputs trained with a quasi-Newton
%	optimisation algorithm is compared with the optimal Bayesian decision
%	rule.
%
%	See also
%	MLP, MLPFWD, NETERR, QUASINEW
%
 
%	Copyright (c) Ian T Nabney (1996-2001)
 
 
% Set up some figure parameters
AxisShift = 0.05;
ClassSymbol1 = 'r.';
ClassSymbol2 = 'y.';
PointSize = 12;
titleSize = 10;
 
% Fix the seeds
rand('state', 423);
randn('state', 423);
 
clc
disp('This demonstration shows how an MLP with logistic outputs ')
disp('and cross entropy error function can be trained to model the')
disp('posterior class probabilities in a classification problem.')
disp('The results are compared with the optimal Bayes rule classifier,')
disp('which can be computed exactly as we know the form of the generating')
disp('distribution.')
disp(' ')
disp('Press any key to continue.')
pause
 
fh1 = figure;
set(fh1, 'Name', 'True Data Distribution');
whitebg(fh1, 'k');
 
% 
% Generate the data
% 
n=200;
 
% Set up mixture model: 2d data with three centres
% Class 1 is first centre, class 2 from the other two
mix = gmm(2, 3, 'full');
mix.priors = [0.5 0.25 0.25];
mix.centres = [0 -0.1; 1 1; 1 -1];
mix.covars(:,:,1) = [0.625 -0.2165; -0.2165 0.875];
mix.covars(:,:,2) = [0.2241 -0.1368; -0.1368 0.9759];
mix.covars(:,:,3) = [0.2375 0.1516; 0.1516 0.4125];
 
[data, label] = gmmsamp(mix, n);
 
% 
% Calculate some useful axis limits
% 
x0 = min(data(:,1));
x1 = max(data(:,1));
y0 = min(data(:,2));
y1 = max(data(:,2));
dx = x1-x0;
dy = y1-y0;
expand = 5/100;			% Add on 5 percent each way
x0 = x0 - dx*expand;
x1 = x1 + dx*expand;
y0 = y0 - dy*expand;
y1 = y1 + dy*expand;
resolution = 100;
step = dx/resolution;
xrange = [x0:step:x1];
yrange = [y0:step:y1];
% 					
% Generate the grid
% 
[X Y]=meshgrid([x0:step:x1],[y0:step:y1]);
% 
% Calculate the class conditional densities, the unconditional densities and
% the posterior probabilities
% 
px_j = gmmactiv(mix, [X(:) Y(:)]);
px = reshape(px_j*(mix.priors)',size(X));
post = gmmpost(mix, [X(:) Y(:)]);
p1_x = reshape(post(:, 1), size(X));
p2_x = reshape(post(:, 2) + post(:, 3), size(X));
 
% 
% Generate some pretty pictures !!
% 
colormap(hot)
colorbar
subplot(1,2,1)
hold on
plot(data((label==1),1),data(label==1,2),ClassSymbol1, 'MarkerSize', PointSize)
plot(data((label>1),1),data(label>1,2),ClassSymbol2, 'MarkerSize', PointSize)
contour(xrange,yrange,p1_x,[0.5 0.5],'w-');
axis([x0 x1 y0 y1])
set(gca,'Box','On')
title('The Sampled Data');
rect=get(gca,'Position');
rect(1)=rect(1)-AxisShift;
rect(3)=rect(3)+AxisShift;
set(gca,'Position',rect)
hold off
 
subplot(1,2,2)
imagesc(X(:),Y(:),px);
hold on
[cB, hB] = contour(xrange,yrange,p1_x,[0.5 0.5],'w:');
set(hB,'LineWidth', 2);
axis([x0 x1 y0 y1])
set(gca,'YDir','normal')
title('Probability Density p(x)')
hold off
 
drawnow;
clc;
disp('The first figure shows the data sampled from a mixture of three')
disp('Gaussians, the first of which (whose centre is near the origin) is')
disp('labelled red and the other two are labelled yellow.  The second plot')
disp('shows the unconditional density of the data with the optimal Bayesian')
disp('decision boundary superimposed.')
disp(' ')
disp('Press any key to continue.')
pause
fh2 = figure;
set(fh2, 'Name', 'Class-conditional Densities and Posterior Probabilities');
whitebg(fh2, 'w');
 
subplot(2,2,1)
p1=reshape(px_j(:,1),size(X));
imagesc(X(:),Y(:),p1);
colormap hot
colorbar
axis(axis)
set(gca,'YDir','normal')
hold on
plot(mix.centres(:,1),mix.centres(:,2),'b+','MarkerSize',8,'LineWidth',2)
title('Density p(x|red)')
hold off
 
subplot(2,2,2)
p2=reshape((px_j(:,2)+px_j(:,3)),size(X));
imagesc(X(:),Y(:),p2);
colorbar
set(gca,'YDir','normal')
hold on
plot(mix.centres(:,1),mix.centres(:,2),'b+','MarkerSize',8,'LineWidth',2)
title('Density p(x|yellow)')
hold off
 
subplot(2,2,3)
imagesc(X(:),Y(:),p1_x);
set(gca,'YDir','normal')
colorbar
title('Posterior Probability p(red|x)')
hold on
plot(mix.centres(:,1),mix.centres(:,2),'b+','MarkerSize',8,'LineWidth',2)
hold off
 
subplot(2,2,4)
imagesc(X(:),Y(:),p2_x);
set(gca,'YDir','normal')
colorbar
title('Posterior Probability p(yellow|x)')
hold on
plot(mix.centres(:,1),mix.centres(:,2),'b+','MarkerSize',8,'LineWidth',2)
hold off
 
% Now set up and train the MLP
nhidden=6;
nout=1;
alpha = 0.2;	% Weight decay
ncycles = 60;	% Number of training cycles. 
% Set up MLP network
net = mlp(2, nhidden, nout, 'logistic', alpha);
options = zeros(1,18);
options(1) = 1;                 % Print out error values
options(14) = ncycles;
 
mlpstring = ['We now set up an MLP with ', num2str(nhidden), ...
    ' hidden units, logistic output and cross'];
trainstring = ['entropy error function, and train it for ', ...
    num2str(ncycles), ' cycles using the'];
wdstring = ['quasi-Newton optimisation algorithm with weight decay of ', ...
    num2str(alpha), '.'];
 
% Force out the figure before training the MLP
drawnow;
disp(' ')
disp('The second figure shows the class conditional densities and posterior')
disp('probabilities for each class. The blue crosses mark the centres of')
disp('the three Gaussians.')
disp(' ')
disp(mlpstring)
disp(trainstring)
disp(wdstring)
disp(' ')
disp('Press any key to continue.')
pause
 
% Convert targets to 0-1 encoding
target=[label==1];
 
% Train using quasi-Newton.
[net] = netopt(net, options, data, target, 'quasinew');
y = mlpfwd(net, data);
yg = mlpfwd(net, [X(:) Y(:)]);
yg = reshape(yg(:,1),size(X));
 
fh3 = figure;
set(fh3, 'Name', 'Network Output');
whitebg(fh3, 'k')
subplot(1, 2, 1)
hold on
plot(data((label==1),1),data(label==1,2),'r.', 'MarkerSize', PointSize)
plot(data((label>1),1),data(label>1,2),'y.', 'MarkerSize', PointSize)
% Bayesian decision boundary
[cB, hB] = contour(xrange,yrange,p1_x,[0.5 0.5],'b-');
[cN, hN] = contour(xrange,yrange,yg,[0.5 0.5],'r-');
set(hB, 'LineWidth', 2);
set(hN, 'LineWidth', 2);
Chandles = [hB(1) hN(1)];
legend(Chandles, 'Bayes', ...
  'Network', 3);
 
axis([x0 x1 y0 y1])
set(gca,'Box','on','XTick',[],'YTick',[])
 
title('Training Data','FontSize',titleSize);
hold off
 
subplot(1, 2, 2)
imagesc(X(:),Y(:),yg);
colormap hot
colorbar
axis(axis)
set(gca,'YDir','normal','XTick',[],'YTick',[])
title('Network Output','FontSize',titleSize)
 
clc
disp('This figure shows the training data with the decision boundary')
disp('produced by the trained network and the network''s prediction of')
disp('the posterior probability of the red class.')
disp(' ')
disp('Press any key to continue.')
pause
 
% 
% Now generate and classify a test data set
% 
[testdata testlabel] = gmmsamp(mix, n);
testlab=[testlabel==1 testlabel>1];
 
% This is the Bayesian classification
tpx_j = gmmpost(mix, testdata);
Bpost = [tpx_j(:,1), tpx_j(:,2)+tpx_j(:,3)];
[Bcon Brate]=confmat(Bpost, [testlabel==1 testlabel>1]);
 
% Compute network classification
yt = mlpfwd(net, testdata);
% Convert single output to posteriors for both classes
testpost = [yt 1-yt];
[C trate]=confmat(testpost,[testlabel==1 testlabel>1]);
 
fh4 = figure;
set(fh4, 'Name', 'Decision Boundaries');
whitebg(fh4, 'k');
hold on
plot(testdata((testlabel==1),1),testdata((testlabel==1),2),...
  ClassSymbol1, 'MarkerSize', PointSize)
plot(testdata((testlabel>1),1),testdata((testlabel>1),2),...
  ClassSymbol2, 'MarkerSize', PointSize)
% Bayesian decision boundary
[cB, hB] = contour(xrange,yrange,p1_x,[0.5 0.5],'b-');
set(hB, 'LineWidth', 2);
% Network decision boundary
[cN, hN] = contour(xrange,yrange,yg,[0.5 0.5],'r-');
set(hN, 'LineWidth', 2);
Chandles = [hB(1) hN(1)];
legend(Chandles, 'Bayes decision boundary', ...
  'Network decision boundary', -1);
axis([x0 x1 y0 y1])
title('Test Data')
set(gca,'Box','On','Xtick',[],'YTick',[])
 
clc
disp('This figure shows the test data with the decision boundary')
disp('produced by the trained network and the optimal Bayes rule.')
disp(' ')
disp('Press any key to continue.')
pause
 
fh5 = figure;
set(fh5, 'Name', 'Test Set Performance');
whitebg(fh5, 'w');
% Bayes rule performance
subplot(1,2,1)
plotmat(Bcon,'b','k',12)
set(gca,'XTick',[0.5 1.5])
set(gca,'YTick',[0.5 1.5])
grid('off')
set(gca,'XTickLabel',['Red   ' ; 'Yellow'])
set(gca,'YTickLabel',['Yellow' ; 'Red   '])
ylabel('True')
xlabel('Predicted')
title(['Bayes Confusion Matrix (' num2str(Brate(1)) '%)'])
 
% Network performance
subplot(1,2, 2)
plotmat(C,'b','k',12)
set(gca,'XTick',[0.5 1.5])
set(gca,'YTick',[0.5 1.5])
grid('off')
set(gca,'XTickLabel',['Red   ' ; 'Yellow'])
set(gca,'YTickLabel',['Yellow' ; 'Red   '])
ylabel('True')
xlabel('Predicted')
title(['Network Confusion Matrix (' num2str(trate(1)) '%)'])
 
disp('The final figure shows the confusion matrices for the')
disp('two rules on the test set.')
disp(' ')
disp('Press any key to exit.')
pause
whitebg(fh1, 'w');
whitebg(fh2, 'w');
whitebg(fh3, 'w');
whitebg(fh4, 'w');
whitebg(fh5, 'w');
close(fh1); close(fh2); close(fh3);
close(fh4); close(fh5);
clear all;

Et voici une demonstration de RBF:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
 
%DEMRBF1 Demonstrate simple regression using a radial basis function network.
%
%	Description
%	The problem consists of one input variable X and one target variable
%	T with data generated by sampling X at equal intervals and then
%	generating target data by computing SIN(2*PI*X) and adding Gaussian
%	noise. This data is the same as that used in demmlp1.
%
%	Three different RBF networks (with different activation functions)
%	are trained in two stages. First, a Gaussian mixture model is trained
%	using the EM algorithm, and the centres of this model are used to set
%	the centres of the RBF.  Second, the output weights (and biases) are
%	determined using the pseudo-inverse of the design matrix.
%
%	See also
%	DEMMLP1, RBF, RBFFWD, GMM, GMMEM
%
 
%	Copyright (c) Ian T Nabney (1996-2001)
 
 
% Generate the matrix of inputs x and targets t.
randn('state', 42);
rand('state', 42);
ndata = 20;			% Number of data points.
noise = 0.2;			% Standard deviation of noise distribution.
x = (linspace(0, 1, ndata))';
t = sin(2*pi*x) + noise*randn(ndata, 1);
mu = mean(x);
sigma = std(x);
tr_in = (x - mu)./(sigma);
 
clc
disp('This demonstration illustrates the use of a Radial Basis Function')
disp('network for regression problems.  The data is generated from a noisy')
disp('sine function.')
disp(' ')
disp('Press any key to continue.')
pause
% Set up network parameters.
nin = 1;			% Number of inputs.
nhidden = 7;			% Number of hidden units.
nout = 1;			% Number of outputs.
 
clc
disp('We assess the effect of three different activation functions.')
disp('First we create a network with Gaussian activations.')
disp(' ')
disp('Press any key to continue.')
pause
% Create and initialize network weight and parameter vectors.
net = rbf(nin, nhidden, nout, 'gaussian');
 
disp('A two-stage training algorithm is used: it uses a small number of')
disp('iterations of EM to position the centres, and then the pseudo-inverse')
disp('of the design matrix to find the second layer weights.')
disp(' ')
disp('Press any key to continue.')
pause
disp('Error values from EM training.')
% Use fast training method
options = foptions;
options(1) = 1;		% Display EM training
options(14) = 10;	% number of iterations of EM
net = rbftrain(net, options, tr_in, t);
 
disp(' ')
disp('Press any key to continue.')
pause
clc
disp('The second RBF network has thin plate spline activations.')
disp('The same centres are used again, so we just need to calculate')
disp('the second layer weights.')
disp(' ')
disp('Press any key to continue.')
pause
% Create a second RBF with thin plate spline functions
net2 = rbf(nin, nhidden, nout, 'tps');
 
% Re-use previous centres rather than calling rbftrain again
net2.c = net.c;
[y, act2] = rbffwd(net2, tr_in);
 
% Solve for new output weights and biases from RBF activations
temp = pinv([act2 ones(ndata, 1)]) * t;
net2.w2 = temp(1:nhidden, :);
net2.b2 = temp(nhidden+1, :);
 
disp('The third RBF network has r^4 log r activations.')
disp(' ')
disp('Press any key to continue.')
pause
% Create a third RBF with r^4 log r functions
net3 = rbf(nin, nhidden, nout, 'r4logr');
 
% Overwrite weight vector with parameters from first RBF
net3.c = net.c;
[y, act3] = rbffwd(net3, tr_in);
temp = pinv([act3 ones(ndata, 1)]) * t;
net3.w2 = temp(1:nhidden, :);
net3.b2 = temp(nhidden+1, :);
 
disp('Now we plot the data, underlying function, and network outputs')
disp('on a single graph to compare the results.')
disp(' ')
disp('Press any key to continue.')
pause
% Plot the data, the original function, and the trained network functions.
plotvals = [x(1):0.01:x(end)]';
inputvals = (plotvals-mu)./sigma;
y = rbffwd(net, inputvals);
y2 = rbffwd(net2, inputvals);
y3 = rbffwd(net3, inputvals);
fh1 = figure;
 
plot(x, t, 'ob')
hold on
xlabel('Input')
ylabel('Target')
axis([x(1) x(end) -1.5 1.5])
[fx, fy] = fplot('sin(2*pi*x)', [x(1) x(end)]);
plot(fx, fy, '-r', 'LineWidth', 2)
plot(plotvals, y, '--g', 'LineWidth', 2)
plot(plotvals, y2, 'k--', 'LineWidth', 2)
plot(plotvals, y3, '-.c', 'LineWidth', 2)
legend('data', 'function', 'Gaussian RBF', 'Thin plate spline RBF', ...
  'r^4 log r RBF');
hold off
 
disp('RBF training errors are');
disp(['Gaussian ', num2str(rbferr(net, tr_in, t)), ' TPS ',  ...
num2str(rbferr(net2, tr_in, t)), ' R4logr ', num2str(rbferr(net3, tr_in, t))]);
 
disp(' ')
disp('Press any key to end.')
pause
close(fh1);
clear all;
Merci.