Monday 11 January 2016

Implement a simple linear regressor with a single neuron model .... MATLAB Code

// data.txt file


166, 54.00
195, 82.00
200, 72.00
260, 72.00
265, 90.00
335, 124.00
370, 94.00
450, 118.00


//    .m file for linear regression

%Load the data from our text file
data = load('/home/svcet/Desktop/data.txt');
% Define x and y
x = data(:,2);
y = data(:,1);
% Create a function to plot the data
function plotData(x,y)
plot(x,y,'rx','MarkerSize',8); % Plot the data
end
% Plot the data
plotData(x,y);
xlabel('Cost of Book'); % Set the x-axis label
ylabel('Number of Pages'); % Set the y-axis label
fprintf('Program paused. Press enter to continue.\n');
pause;
% Count how many data points we have
m = length(x);
% Add a column of all ones (intercept term) to x
X = [ones(m, 1) x];
% Calculate theta
theta = (pinv(X'*X))*X'*y
% Plot the fitted equation we got from the regression
hold on; % this keeps our previous plot of the training data visible
plot(X(:,2), X*theta, '-')
legend('Training data', 'Linear regression')
hold off % Don't put any more plots on this figure


No comments:

Post a Comment