Professional Documents
Culture Documents
Next Contents
[ Files ]
ex1.m
19 % For this exercise, you will not need to change any code in this f
20 % or any other files other than those mentioned above.
21 %
22 % x refers to the population size in 10,000s
23 % y refers to the profit in $10,000s
24 %
25
26 %% Initialization
27 clear ; close all; clc
28
29 %% ==================== Part 1: Basic Function ====================
30 % Complete warmUpExercise.m
31 fprintf('Running warmUpExercise ... \n');
32 fprintf('5x5 Identity Matrix: \n');
33 warmUpExercise()
34
35 fprintf('Program paused. Press enter to continue.\n');
36 pause;
37
38 %% ======================= Part 2: Plotting =======================
39 fprintf('Plotting Data ...\n')
40 data = load('ex1data1.txt');
41 X = data(:, 1); y = data(:, 2);
42 m = length(y); % number of training examples
43
44 % Plot Data
45 % Note: You have to complete the code in plotData.m
46 plotData(X, y);
47
48 fprintf('Program paused. Press enter to continue.\n');
49 pause;
50
51 %% =================== Part 3: Gradient descent ===================
52 fprintf('Running Gradient Descent ...\n')
53
54 X = [ones(m, 1), data(:,1)]; % Add a column of ones to x
55 theta = zeros(2, 1); % initialize fitting parameters
56
57 % Some gradient descent settings
58 iterations = 1500;
59 alpha = 0.01;
60
61 % compute and display initial cost
62 computeCost(X, y, theta)
63
64 % run gradient descent
65 theta = gradientDescent(X, y, theta, alpha, iterations);
66
67 % print theta to screen
68 fprintf('Theta found by gradient descent: ');
69 fprintf('%f %f \n', theta(1), theta(2));
70
71 % Plot the linear fit
72 hold on; % keep previous plot visible
73 plot(X(:,2), X*theta, '-')
74 legend('Training data', 'Linear regression')
75 hold off % don't overlay any more plots on this figure
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 2/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
76
77 % Predict values for population sizes of 35,000 and 70,000
78 predict1 = [1, 3.5] *theta;
79 fprintf('For population = 35,000, we predict a profit of %f\n',...
80 predict1*10000);
81 predict2 = [1, 7] * theta;
82 fprintf('For population = 70,000, we predict a profit of %f\n',...
83 predict2*10000);
84
85 fprintf('Program paused. Press enter to continue.\n');
86 pause;
87
88 %% ============= Part 4: Visualizing J(theta_0, theta_1) ===========
89 fprintf('Visualizing J(theta_0, theta_1) ...\n')
90
91 % Grid over which we will calculate J
92 theta0_vals = linspace(-10, 10, 100);
93 theta1_vals = linspace(-1, 4, 100);
94
95 % initialize J_vals to a matrix of 0's
96 J_vals = zeros(length(theta0_vals), length(theta1_vals));
97
98 % Fill out J_vals
99 for i = 1:length(theta0_vals)
100 for j = 1:length(theta1_vals)
101 t = [theta0_vals(i); theta1_vals(j)];
102 J_vals(i,j) = computeCost(X, y, t);
103 end
104 end
105
106 % Because of the way meshgrids work in the surf command, we need to
107 % transpose J_vals before calling surf, or else the axes will be fli
108 J_vals = J_vals';
109 % Surface plot
110 figure;
111 surf(theta0_vals, theta1_vals, J_vals)
112 xlabel('\theta_0'); ylabel('\theta_1');
113
114 % Contour plot
115 figure;
116 % Plot J_vals as 15 contours spaced logarithmically between 0.01 and
117 contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))
118 xlabel('\theta_0'); ylabel('\theta_1');
119 hold on;
120 plot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);
ex1_multi.m
warmUpExercise.m
1 function A = warmUpExercise()
2 %WARMUPEXERCISE Example function in octave
3 % A = WARMUPEXERCISE() is an example function that returns the 5x5
4
5 A = [];
6 % ============= YOUR CODE HERE ==============
7 % Instructions: Return the 5x5 identity matrix
8 % In octave, we return values by defining which variabl
9 % represent the return values (at the top of the file)
10 % and then set them accordingly.
11
12 A = eye(5);
13
14 % ===========================================
15
16 end
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 6/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
plotData.m
1 function plotData(x, y)
2 %PLOTDATA Plots the data points x and y into a new figure
3 % PLOTDATA(x,y) plots the data points and gives the figure axes lab
4 % population and profit.
5
6 % ====================== YOUR CODE HERE ======================
7 % Instructions: Plot the training data into a figure using the
8 % "figure" an
9 % the "xlabel&quot
10 % population and revenue data have been passed in
11 % as the x and y arguments of this function.
12 %
13 % Hint: You can use the 'rx' option with plot to have the markers
14 % appear as red crosses. Furthermore, you can make the
15 % markers larger by using plot(..., 'rx', 'MarkerSize', 10);
16
17 figure; % open a new figure window
18
19 plot(x, y, 'rx', 'MarkerSize', 10); % Plot the data
20 ylabel('Profit in $10,000s'); % Set the y?axis label
21 xlabel('Population of City in 10,000s'); % Set the x?axis label
22
23 % ============================================================
24
25 end
gradientDescent.m
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 7/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
computeCost.m
computeCostMulti.m
gradientDescent.m
gradientDescentMulti.m
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 9/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
featureNormalize.m
24 % each feature.
25 %
26 % Hint: You might find the 'mean' and 'std' functions useful.
27 %
28
29 mn = mean(X);
30 sd = std(X);
31 X_norm = bsxfun(@minus,X_norm,mn);
32 X_norm = bsxfun(@rdivide,X_norm,sd);
33
34 % ============================================================
35
36 end
normalEqn.m
submit.m
1 function submit()
2 addpath('./lib');
3
4 conf.assignmentSlug = 'linear-regression';
5 conf.itemName = 'Linear Regression with Multiple Variables';
6 conf.partArrays = { ...
7 { ...
8 '1', ...
9 { 'warmUpExercise.m' }, ...
10 'Warm-up Exercise', ...
11 }, ...
12 { ...
13 '2', ...
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 11/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
14 { 'computeCost.m' }, ...
15 'Computing Cost (for One Variable)', ...
16 }, ...
17 { ...
18 '3', ...
19 { 'gradientDescent.m' }, ...
20 'Gradient Descent (for One Variable)', ...
21 }, ...
22 { ...
23 '4', ...
24 { 'featureNormalize.m' }, ...
25 'Feature Normalization', ...
26 }, ...
27 { ...
28 '5', ...
29 { 'computeCostMulti.m' }, ...
30 'Computing Cost (for Multiple Variables)', ...
31 }, ...
32 { ...
33 '6', ...
34 { 'gradientDescentMulti.m' }, ...
35 'Gradient Descent (for Multiple Variables)', ...
36 }, ...
37 { ...
38 '7', ...
39 { 'normalEqn.m' }, ...
40 'Normal Equations', ...
41 }, ...
42 };
43 conf.output = @output;
44
45 submitWithConfiguration(conf);
46 end
47
48 function out = output(partId)
49 % Random Test Cases
50 X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))'];
51 Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2));
52 X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25];
53 Y2 = Y1.^0.5 + Y1;
54 if partId == '1'
55 out = sprintf('%0.5f ', warmUpExercise());
56 elseif partId == '2'
57 out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]'));
58 elseif partId == '3'
59 out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01
60 elseif partId == '4'
61 out = sprintf('%0.5f ', featureNormalize(X2(:,2:4)));
62 elseif partId == '5'
63 out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4
64 elseif partId == '6'
65 out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -
66 elseif partId == '7'
67 out = sprintf('%0.5f ', normalEqn(X2, Y2));
68 end
69 end
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 12/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
ex1data1.txt
1 6.1101,17.592
2 5.5277,9.1302
3 8.5186,13.662
4 7.0032,11.854
5 5.8598,6.8233
6 8.3829,11.886
7 7.4764,4.3483
8 8.5781,12
9 6.4862,6.5987
10 5.0546,3.8166
11 5.7107,3.2522
12 14.164,15.505
13 5.734,3.1551
14 8.4084,7.2258
15 5.6407,0.71618
16 5.3794,3.5129
17 6.3654,5.3048
18 5.1301,0.56077
19 6.4296,3.6518
20 7.0708,5.3893
21 6.1891,3.1386
22 20.27,21.767
23 5.4901,4.263
24 6.3261,5.1875
25 5.5649,3.0825
26 18.945,22.638
27 12.828,13.501
28 10.957,7.0467
29 13.176,14.692
30 22.203,24.147
31 5.2524,-1.22
32 6.5894,5.9966
33 9.2482,12.134
34 5.8918,1.8495
35 8.2111,6.5426
36 7.9334,4.5623
37 8.0959,4.1164
38 5.6063,3.3928
39 12.836,10.117
40 6.3534,5.4974
41 5.4069,0.55657
42 6.8825,3.9115
43 11.708,5.3854
44 5.7737,2.4406
45 7.8247,6.7318
46 7.0931,1.0463
47 5.0702,5.1337
48 5.8014,1.844
49 11.7,8.0043
50 5.5416,1.0179
51 7.5402,6.7504
52 5.3077,1.8396
53 7.4239,4.2885
54 7.6031,4.9981
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 13/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
55 6.3328,1.4233
56 6.3589,-1.4211
57 6.2742,2.4756
58 5.6397,4.6042
59 9.3102,3.9624
60 9.4536,5.4141
61 8.8254,5.1694
62 5.1793,-0.74279
63 21.279,17.929
64 14.908,12.054
65 18.959,17.054
66 7.2182,4.8852
67 8.2951,5.7442
68 10.236,7.7754
69 5.4994,1.0173
70 20.341,20.992
71 10.136,6.6799
72 7.3345,4.0259
73 6.0062,1.2784
74 7.2259,3.3411
75 5.0269,-2.6807
76 6.5479,0.29678
77 7.5386,3.8845
78 5.0365,5.7014
79 10.274,6.7526
80 5.1077,2.0576
81 5.7292,0.47953
82 5.1884,0.20421
83 6.3557,0.67861
84 9.7687,7.5435
85 6.5159,5.3436
86 8.5172,4.2415
87 9.1802,6.7981
88 6.002,0.92695
89 5.5204,0.152
90 5.0594,2.8214
91 5.7077,1.8451
92 7.6366,4.2959
93 5.8707,7.2029
94 5.3054,1.9869
95 8.2934,0.14454
96 13.394,9.0551
97 5.4369,0.61705
ex1data2.txt
1 2104,3,399900
2 1600,3,329900
3 2400,3,369000
4 1416,2,232000
5 3000,4,539900
6 1985,4,299900
7 1534,3,314900
8 1427,3,198999
9 1380,3,212000
10 1494,3,242500
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 14/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
11 1940,4,239999
12 2000,3,347000
13 1890,3,329999
14 4478,5,699900
15 1268,3,259900
16 2300,4,449900
17 1320,2,299900
18 1236,3,199900
19 2609,4,499998
20 3031,4,599000
21 1767,3,252900
22 1888,2,255000
23 1604,3,242900
24 1962,4,259900
25 3890,3,573900
26 1100,3,249900
27 1458,3,464500
28 2526,3,469000
29 2200,3,475000
30 2637,3,299900
31 1839,2,349900
32 1000,1,169900
33 2040,4,314900
34 3137,3,579900
35 1811,4,285900
36 1437,3,249900
37 1239,3,229900
38 2132,4,345000
39 4215,4,549000
40 2162,4,287000
41 1664,2,368500
42 2238,3,329900
43 2567,4,314000
44 1200,3,299000
45 852,2,179900
46 1852,4,299900
47 1203,3,239500
[ ex1.m Output ]
10 0 0 0 0 1
11
12 Program paused. Press enter to continue.
Plotting data
Figure 1
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 16/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
Figure 2
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 17/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
Figure 3
[ Lib ]
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 18/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
Files
makeValidFieldName.m
submitWithCon guration.m
18 else
19 pos=regexp(str,'[^0-9A-Za-z_]');
20 if(isempty(pos)) return; end
21 str0=str;
22 pos0=[0 pos(:)' length(str)];
23 str='';
24 for i=1:length(pos)
25 str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(p
26 end
27 if(pos(end)~=length(str))
28 str=[str str0(pos0(end-1)+1:pos0(end))];
29 end
30 end
[ Unit Testing ]
computeCost:
gradientDescent
Test Case 1:
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 20/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
For debugging, here are the rst few theta values computed in the gradientDescent()
for-loop for this test case:
1 % first iteration
2 theta =
3 0.032500
4 0.107500
5 % second iteration
6 theta =
7 0.060375
8 0.194887
9 % third iteration
10 theta =
11 0.084476
12 0.265867
13 % fourth iteration
14 theta =
15 0.10550
16 0.32346
he values can be inspected by adding the “keyboard” command within your for-
loop. This exits the code to the debugger, where you can inspect the values. Use the
“return” command to resume execution.
Test Case 2:
This test case is similar, but uses a non-zero initial theta value.
featureNormalize():
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 21/24
5/3/2018 o1 Octave Programming: Linear Regression & Linear regression with multiple variables – Tutorials For IoT-Makers
1 >> X = [ 2 1 3; 7 1 9; 1 8 1; 3 7 4 ];
2 >> computeCostMulti( X, [ 2; 5; 5; 6 ], [ 0.4; 0.8; 0.8 ] )
3 ans = 7.5500
4
5 >>gradientDescentMulti([3 5 6; 1 2 3; 9 4 2],[1 6 4]',[0 0 0]',0
6 ans =
7 1.2123
8 -2.9458
9 2.3219
Advertisements
Pianoforall - Pianoforall -
Incredible New Incredible New
Way To Learn Way To Learn
Piano & Keyboard Piano & Keyboard
US$199 US$199
US$14.99 US$14.99
Share this:
Like
Be the first to like this.
Author: iotmaker
I am interested in IoT, robot, gures & leadership. Also, I have spent almost every day of the
past 15 years making robots or electronic inventions or computer programs.
View all posts by iotmaker
https://iotmakerblog.wordpress.com/2016/06/17/o1-octave-programming-linear-regression-linear-regression-with-multiple-variables/ 24/24