gusucode.com > Matlab脸部识别程序源码 > code/code/initialize_weights175.m
function w = initialize_weights175(data,targets,method,random_seed); %function w = initialize_weights175(data,targets,method,random_seed); % % A simple function to select initial weights for perceptron training. % Assignment 3, CS 175 % % NOTE: there is no error-checking in this code % % INPUTS: % data: n x (d+1) matrix of data values (n examples, d features % and the d+1th column is the constant input (all 1's)) % targets: n x 1 matrix of +1 or -1 target values (class labels) % method: an integer (1, 2 or 3) that indicates which initialization method to use. % 1: random assignment of weights % 2: chooses an orthogonal line halfway between a random point % in group 1 and a random point in group 2. % 3: chooses an orthogonal line halfway between the mean (or centroid) % of group 1 and the the mean (or centroid) of group 2. % % OUTPUT: % w: a 1 x d+1 vector of weights % % if no random seed is supplied then select one using the system clock, % otherwise "seed" the random number generator with "random_seed" if nargin<4 rand('state',sum(100*clock)); % use the current clock value to "seed" the random number generator else rand('state',random_seed); % otherwise use the supplied "seed". end cols = size(data,2); % find out how many columns the matrix data has data = data(:,1:cols-1); % remove the rightmost column since we don't need it % in the initialization procedures below [n d] = size(data); % select the method for calculating an initial weight vector switch method case {1} % generate a random weight vector with small weights w = rand(1,d+1)/d; case {2} % a line half way between 2 randomly chosen points in each group index = find(targets==1); % find the indices of points in group 1 i = randperm(length(index)); x1 = data(index(i(1)),:); % select a random point from group 1 index = find(targets==-1); % find the indices of points in group 1 i = randperm(length(index)); x2 = data(index(i(1)),:); % select a random point from group 2 w12 = x1 - x2; % this line and the next is the equation for the desired line w0 = -0.5*w12*(x1+x2)'; w = [w12 w0]; % construct the weight vector case {3} % a line halfway between the 2 centroids i = find(targets==1); % find the indices of points in group 1 x1 = mean(data(i,:)); % get the mean or centroid from group 1 i = find(targets==-1); % find the indices of points in group 2 x2 = mean(data(i,:)); % get the mean or centroid from group 2 w12 = x1 - x2; % this line and the next is the equation for the desired line w0 = -0.5*w12*(x1+x2)'; w = [w12 w0]; % construct the weight vector end