% Example 7.4
% Residual Plots - use the software testing data.

load software
% Transform the data.
X = log(prepage);
Y = log(defpage);
% Get an initial plot. Figure 7.7.
plot(X,Y,'.')
xlabel('Log [ PrepTime (mins) / Page ]')
ylabel('Log [ Defects / Page ]')

% Set up the parameters.
alpha = 0.5;
lambda = 2;
% Do the loess on this. 
x0 = linspace(min(X),max(X));
y0 = loess(X,Y,x0,alpha,lambda);
% Plot the curve and scatterplot. Figure 7.8.
plot(X,Y,'.',x0,y0)
xlabel('Log [ PrepTime (mins) / Page ]')
ylabel('Log [ Defects / Page ]')

% Get the residuals. 
% First find the loess values at 
% the observed X values.
yhat = loess(X,Y,X,alpha,lambda);
resid = Y - yhat;
% Now plot the residuals. figure 7.9 (top)
plot(1:length(resid),resid,'.')
ax = axis;
axis([ax(1), ax(2), -4 4])
xlabel('Index')
ylabel('Residuals')

% Plot the absolute value of the residuals
% against the fitted values. 
% Figure 7.9 (bottom)
r0 = linspace(min(yhat),max(yhat),30);
rhat = loess(yhat,abs(resid),r0,0.5,1);
plot(yhat,abs(resid),'.',r0,rhat)
xlabel('Fitted Values')
ylabel('| Residuals |')

% Now plot the residuals on the vertical
% and the independent values on the 
% horizontal. This is the residual 
% dependence plot. Include a loess curve.
% Figure 7.10
rhat = loess(X,resid,x0,.5,1)
plot(X,resid,'.',x0,rhat)
xlabel('Log [ PrepTime (mins) / Page ]')
ylabel('Residuals')


