题目太长啦!文档下载【传送门

第1题

简述:设计一个5*5的单位矩阵。

function A = warmUpExercise()
A = [];
A = eye(5);
end

运行结果:

第2题

简述:实现单变量线性回归。

第1步:加载数据文件;

data = load('ex1data1.txt');
X = data(:, 1); y = data(:, 2);
m = length(y); % number of training examples
% Plot Data
% Note: You have to complete the code in plotData.m
plotData(X, y);

第2步:plotData函数实现训练样本的可视化;

function plotData(x, y)
figure;
plot(x,y,'rx','MarkerSize',10);
ylabel('Profit in $10,000s');
xlabel('Population of City in 10,000s');
end 

第3步:使用梯度下降函数计算局部最优解,并显示线性回归;

X = [ones(m, 1), data(:,1)]; % Add a column of ones to x
theta = zeros(2, 1); % initialize fitting parameters
% Some gradient descent settings
iterations = 1500;
alpha = 0.01;
% run gradient descent
theta = gradientDescent(X, y, theta, alpha, iterations);
% print theta to screen
fprintf('Theta found by gradient descent:\n');
fprintf('%f\n', theta);
% Plot the linear fit
hold on; % keep previous plot visible
plot(X(:,2), X*theta, '-')
legend('Training data', 'Linear regression')
hold off % don't overlay any more plots on this figure  

第4步:实现梯度下降gradientDescent函数;

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)

% Initialize some useful values
m = length(y); % number of training examples
J_history = zeros(num_iters, 1); for iter = 1:num_iters
theta = theta - alpha/length(y)*(X'*(X*theta-y));
% Save the cost J in every iteration
J_history(iter) = computeCost(X, y, theta);
end end

第5步:实现代价计算computeCost函数;

function J = computeCost(X, y, theta)
m = length(y); % number of training examples
J = 1/(2*m)*sum((X*theta-y).^2);
end

第6步:实现三维图、轮廓图的显示。

% Grid over which we will calculate J
theta0_vals = linspace(-10, 10, 100);
theta1_vals = linspace(-1, 4, 100); % initialize J_vals to a matrix of 0's
J_vals = zeros(length(theta0_vals), length(theta1_vals)); % Fill out J_vals
for i = 1:length(theta0_vals)
for j = 1:length(theta1_vals)
t = [theta0_vals(i); theta1_vals(j)];
J_vals(i,j) = computeCost(X, y, t);
end
end % Because of the way meshgrids work in the surf command, we need to
% transpose J_vals before calling surf, or else the axes will be flipped
J_vals = J_vals';
% Surface plot
figure;
surf(theta0_vals, theta1_vals, J_vals);
xlabel('\theta_0'); ylabel('\theta_1'); % Contour plot
figure;
% Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100
contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))
xlabel('\theta_0'); ylabel('\theta_1');
hold on;
plot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);

运行结果:

第3题

简述:实现多元线性回归。

第1步:加载数据文件;

data = load('ex1data2.txt');
X = data(:, 1:2);
y = data(:, 3);
m = length(y);
[X mu sigma] = featureNormalize(X);
% Add intercept term to X
X = [ones(m, 1) X];

第2步:均值归一化featureNormalize函数实现;

function [X_norm, mu, sigma] = featureNormalize(X)

X_norm = X;
mu = zeros(1, size(X, 2));
sigma = zeros(1, size(X, 2));
mu = mean(X,1);
sigma = std(X,0,1);
X_norm = (X_norm-mu)./sigma; end

第3步:使用梯度下降函数计算局部最优解,并显示线性回归;

% Choose some alpha value
alpha = 0.05;
num_iters = 100; % Init Theta and Run Gradient Descent
theta = zeros(3, 1);
[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters); % Plot the convergence graph
figure;
plot(1:numel(J_history), J_history, '-b', 'LineWidth', 2);
xlabel('Number of iterations');
ylabel('Cost J');

第4步:实现梯度下降gradientDescentMulti函数;

function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)

m = length(y); % number of training examples
J_history = zeros(num_iters, 1); for iter = 1:num_iters
theta = theta - alpha/m*(X'*(X*theta-y));
% Save the cost J in every iteration
J_history(iter) = computeCostMulti(X, y, theta);
end end

第5步:实现代价计算computeCostMulti函数;

function J = computeCostMulti(X, y, theta)
m = length(y); % number of training examples
J = 1/(2*m)*sum((X*theta-y).^2);%J=(X*theta-y)'*(X*theta-y)/(2*m);
end

运行结果:

第6步:使用上述结果对“the price of a 1650 sq-ft, 3 br house”进行预测;

X1 = [1,1650,3];
X1(2:3) = (X1(2:3)-mu)./sigma;
price = X1*theta;

预测结果: 

第7步:使用正规方程法求解;

%%Load Data
data = csvread('ex1data2.txt');
X = data(:, 1:2);
y = data(:, 3);
m = length(y); % Add intercept term to X
X = [ones(m, 1) X]; % Calculate the parameters from the normal equation
theta = normalEqn(X, y);

第8步:实现normalEqn函数;

function [theta] = normalEqn(X, y)
theta = zeros(size(X, 2), 1);
theta = (X'*X)^(-1)*X'*y;
end

第9步:使用上述结果对“the price of a 1650 sq-ft, 3 br house”再次进行预测;

price = [1,1650,3]*theta;

预测结果:(与梯度下降法结果很接近)

机器学习作业(一)线性回归——Matlab实现的更多相关文章

  1. Andrew Ng机器学习课程笔记--week1(机器学习介绍及线性回归)

    title: Andrew Ng机器学习课程笔记--week1(机器学习介绍及线性回归) tags: 机器学习, 学习笔记 grammar_cjkRuby: true --- 之前看过一遍,但是总是模 ...

  2. 机器学习:单元线性回归(python简单实现)

    文章简介 使用python简单实现机器学习中单元线性回归算法. 算法目的 该算法核心目的是为了求出假设函数h中多个theta的值,使得代入数据集合中的每个x,求得的h(x)与每个数据集合中的y的差值的 ...

  3. 機器學習基石(Machine Learning Foundations) 机器学习基石 作业四 Q13-20 MATLAB实现

    大家好,我是Mac Jiang,今天和大家分享Coursera-NTU-機器學習基石(Machine Learning Foundations)-作业四 Q13-20的MATLAB实现. 曾经的代码都 ...

  4. Coursera-AndrewNg(吴恩达)机器学习笔记——第二周编程作业(线性回归)

    一.准备工作 从网站上将编程作业要求下载解压后,在Octave中使用cd命令将搜索目录移动到编程作业所在目录,然后使用ls命令检查是否移动正确.如: 提交作业:提交时候需要使用自己的登录邮箱和提交令牌 ...

  5. 机器学习作业(五)机器学习算法的选择与优化——Matlab实现

    题目下载[传送门] 第1步:读取数据文件,并可视化: % Load from ex5data1: % You will have X, y, Xval, yval, Xtest, ytest in y ...

  6. 机器学习作业(一)线性回归——Python(numpy)实现

    题目太长啦!文档下载[传送门] 第1题 简述:设计一个5*5的单位矩阵. import numpy as np A = np.eye(5) print(A) 运行结果: 第2题 简述:实现单变量线性回 ...

  7. 机器学习作业(八)异常检测与推荐系统——Matlab实现

    题目下载[传送门] 第1题 简述:对于一组网络数据进行异常检测. 第1步:读取数据文件,使用高斯分布计算 μ 和 σ²: % The following command loads the datas ...

  8. 机器学习作业(七)非监督学习——Matlab实现

    题目下载[传送门] 第1题 简述:实现K-means聚类,并应用到图像压缩上. 第1步:实现kMeansInitCentroids函数,初始化聚类中心: function centroids = kM ...

  9. 机器学习作业(六)支持向量机——Matlab实现

    题目下载[传送门] 第1题 简述:支持向量机的实现 (1)线性的情况: 第1步:读取数据文件,可视化数据: % Load from ex6data1: % You will have X, y in ...

随机推荐

  1. bs 网站获取电子秤重量方案

    1:开发一个winform小程序专门用来读取电子秤数据 电子秤链接串口开发需要注意的是 端口名称跟波特率,校验位 (本样例设置的是7)一定要对,不然取出来的是错的, 还有串口取出来数据是反的,需要转过 ...

  2. RMAN中MAXSETSIZE和MAXPIECESIZE的用法

    MAXSETSIZE跟MAXPIECESIZE用法 区别:maxpiecesize设置的是备份完成后的备份片大小,对备份整体的大小没有影响,比如一个G的备份完成文件,maxpiecesize设置为10 ...

  3. springboot整合WebService简单版

    一.什么是webservice 关于webservice的介绍摘自百度百科,上面的介绍很详细.(链接:https://baike.baidu.com/item/Web%20Service/121503 ...

  4. 数据分析----天气预报走向(pygal)

    #!usr/bin/env python #-*- coding:utf-8 _*- """ @author:Administrator @file: 可视化天气预报.p ...

  5. WPF 控件功能重写(ComboBox回车搜索)

    前言:在我们日常使用软件的时候,Combobox会让用户很方便的选择出需要的东西,但是ComboBox中的下拉行数过多时就不那么好用了. 如果在项目中有很多这样的ComboBox控件的话,我们可以考虑 ...

  6. SpringBoot项目自定义浏览器选项卡左上角图标(favicon.ico)-sunziren

    favicon.ico是浏览器选项卡左上角的图标,可以放在静态资源路径下或者类路径下面.静态资源路径下的favicon.ico优先级高于类路径下的favicon.ico. 可以使用在线转换网站http ...

  7. Spring Boot源码(五):BeanFactoryPostProcessor和BeanPostProcessor

    BeanFactoryPostProcessor是spring BeanFactory加载Bean后调用, BeanPostProcessor是Bean初始化前后调用. BeanFactoryPost ...

  8. 【Thread】java线程之对象锁、类锁、线程安全

    说明: 1.个人技术也不咋滴.也没在项目中写过线程,以下全是根据自己的理解写的.所以,仅供参考及希望指出不同的观点. 2.其实想把代码的github贴出来,但还是推荐在初学的您多亲自写一下,就没贴出来 ...

  9. 畅通工程 HDU - 1232 并查集板子题

    #include<iostream> #include<cstring> using namespace std; ; int p[N]; int find(int x) { ...

  10. Bad Hair Day【单调栈】

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAzMAAANgCAIAAACX06G4AAAgAElEQVR4Aey9e5RlW13fuw40HORxfI ...