-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMachineLearning.m
2736 lines (1964 loc) · 85.6 KB
/
MachineLearning.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[Machine Learning]
# Machine Learning is the science of getting computers to learn, without being explicitly programmed
-- Additional Material
- https://share.coursera.org/wiki/index.php/ML:Main
-- Week 1
INTRODUCTION
[Supervised Learning]
- Supervised Learning --> 'right answers' are given
- Regression --> predict continuous valued output (price) # housing price example
- Classification --> discrete valued output (0 or 1; there can be more discrete categories than 2) # breast cancer tumor example
[Unsupervised Learning]
- All data has the same label, no right or wrong
- Here is the dataset, can you find some structure?
+ Clustering Algorithms
+ Cocktail party algorithm # [W,s,v] = svd((repmat(sum(x.*x,1),size(x,1),1).*x)*x');
LINEAR REGRESSION WITH ONE VARIABLE
m = number of training examples
x's = 'input' variable / features
y's = 'output' variable / 'target' variable
(x, y) = a single training example
(x^(i), y^(i)) = refers to the i'th training example --> index, no exponantiation!
ML Flow:
1 - Training Set --> Learning Algorithm --> h (hypothesis; in the form of a function)
1.1 - Size of House (x) --> h --> Estimated Price (y) # h maps from x's to y's
How do we represent h?
- h0(x) = θ0 + θ1x # shorthand: h(x)
- Linear regression with one variable / univariate linear regression.
θi's = parameters
How to choose θi's?
- Idea: Choose θ0 & θ1 so that hθ(x) is close to y for our training examples (x, y)
- 1 / '2m' * Σ(h0(x^(i)) - y^(i))^2 (m Σ i = 1) is as small as possible (the distance of the data points to the line)
- Squared error function
Hypothesis: hθ(x) = θ0 + θ1x
Parameters: θ0, θ1
Cost Function: J(θ0, θ1) = 1 / '2m' * Σ(h0(x^(i)) - y^(i))^2
Goal: minimize J(θ0, θ1) # Simplified: minimize J(θ1)
θ0, θ1
You basically plot several lines using various values for θ1 and use the J(θ1) function to determine the distances of the square of the actual values.
You select the value of θ1 where the distance is as little as possible.
- Contour plots/figures
[Gradient Descent]
- Algorithm for minimizing cost function J (see above)
- Outline:
+ Start with some θ0, θ1 (or θ0, θ1, ... θn) --> usually you initiate them at 0
+ Keep changing θ0, θ1 to reduce J(θ0, θ1) until we hopefully end up at a minimum
repeat until convergence {
θj := θj - α*((∂/∂θj) * J(θ0, θ1)) (for j = 0 and j = 1, our 2 θ's)
}
α = learning rate, how big the step is we take each time
((∂/∂θj) * J(θ0, θ1)) = derivative term
∂ = partial derivative (when you have more than 1 parameter)
d = derivative (1 parameter)
a := b --> assignment
a = b --> truth assertion
Simultaneous Update
Correct
+ temp0 := θ0 - α*((∂/∂θ0) * J(θ0, θ1))
+ temp1 := θ1 - α*((∂/∂θ1) * J(θ0, θ1))
+ θ0 = temp0
+ θ1 = temp1
Incorrect
- temp0 := θ0 - α*((∂/∂θ0) * J(θ0, θ1))
- θ0 = temp0
- temp1 := θ1 - α*((∂/∂θ1) * J(θ0, θ1))
- θ1 = temp1
Derivative Term
- What is the slope (height/width) of a line that just tangent to the point where we are?
Simplified (1 parameter) # in our example the slope is positive
J(θ1)
θ1 := θ1 - α*((∂/∂θ1) * J(θ1))
θ1 := θ1 - α * (some positive number) # hence we go to the left (negative)
If α is too small, gradient descent can be slow.
If α is too large, gradient descent can overshoot the minimum. It may fail to converge, or even diverge.
Gradient descent can converge to a local minimum, even with th learning rate α fixed
As we approach a local minimum, gradient descent will automatically take smaller steps (since the slope becomes smaller with every step towards the minimum).
So no need to decrease α over time.
Gradient descent can optimise any cost function, but we will use it now to optimise our linear regression cost function (squared error cost function).
((∂/∂θj) * J(θ0, θ1)) = ((∂/∂θj) * 1 / '2m' * Σ(h0(x^(i)) - y^(i))^2 = ((∂/∂θj) * 1 / '2m' * Σ(θ0, θ1x^(i) - y^(i))^2
^(i) != exponantiation, simply indexing!
http://math.stackexchange.com/questions/70728/partial-derivative-in-gradient-descent-for-two-variables
Gradient descent algorithm
repeat until convergence {
θ0 := θ0 - α * 1/m * Σ(hθ(x^(i)) - y^(i)) # ∂/∂θ0 J(θ0,θ1)
θ1 := θ1 - α * 1/m * Σ(hθ(x^(i)) - y^(i)) * x^(i) # ∂/∂θ1 J(θ0,θ1)
} # update θ0 & θ1 simultaneously!
Since the regression cost function is a 'bow' shaped one (a 'Convex function') there is only one optimal spot in this case
(since gradient descent can lead to differing outcomes depending on the starting position, when there are differing local optimums).
'Batch' Gradient Descent
'Batch': Each step of gradient descent uses all the training examples (sometimes people prefer to only use subsets of the training data).
There is an alternative to gradient descent for determining the optimum, via solving an equation, which is called the 'normal equations method'.
Gradient descent scales better for large datasets.
[Linear Regression with Multiple Variables] # Multivariate linear regression
Notation
n = number of features
m = number of rows/training examples
x^(i) = input (features) of i'th training example (in case of multiple features this is a vector; an n dimensional vector)
xj^(i) = value of feature j in i'th training example
Hypothesis
- Previously: hθ(x) = θ0 + θ1x
- Now: hθ(x) = θ0 + θ1x1 + θ2x2 + θ3x3 + θ4x4 ... + θnxn
For convenience of notation, define x0 = 1 (x0^(i) = 1)
x = [x0, x1, x2, ..., xn] # n+1 dimensional vector, indexed from 0
θ = [θ0, θ1, θ2, ..., θn] # another n+1 zero-indexed vector
Hence:
hθ(x) = θ0x0 + θ1x1 + ... + θnxn == θ0 + θ1x1 + θ2x2 + θ3x3 + θ4x4 ... + θnxn # θ0x0 == θ0 since x0 = 1
hθ(x) = θ^Tx # transpose θ * x --> you transpose so you can use vector multiplication
[θ0, θ1, θ2, ..., θn] * [ x0
x1
...
xn ] # etc.
-- Gradient descent for multiple variables
Hypothesis: θ^T * x
Parameters = (θ0, θ1, ..., θn) = θ # n+1-dimensional vector
Cost function = J(θ) = 1 / '2m' * Σ(h0(x^(i)) - y^(i))^2
Gradient descent:
New algorithm (n >= 1):
Repeat {
θj := θj - α * 1/m * Σ(hθ(x^(i)) - y^(i)) * xj^(i)
} # simultaneously θj
And remember: x0^(i) = 1, so even if now you carry something down from the differential (because we introduced x0, it is no longer a constant), we simply multiply by 1. It is the same as == θ0 := θ0 - α * 1/m * Σ(hθ(x^(i)) - y^(i))
-- Gradient descent in practice I: Feature scaling --> make gradient run much faster and converge sooner
Feature Scaling (divide number by the maximum value)
- Idea: make sure features are on a similar scale.
Example:
x1 = size (0-2000 feet^2)
x2 = number of bedrooms (1-5)
Scaled:
x1 = size (feet^2) / 2000 # 0 <= x1 <= 1
x2 = number of bedrooms / 5 # 0 <= x2 <= 1
Get every feature into approximately a -1 <= xi <= 1 range; not much bigger or smaller.
This helps gradient descent find an optimum fast, if ranges differ a lot it may take very long.
In addition to scaling: Mean Normalization
- Replace x^i with x^i - μ to make features have approximately zero mean (do not apply to x^0 = 1)
Example:
x1 = (size-1000) / 2000
x2 = #bedrooms-2 / 5
Then (approximately): -0.5 <= x1 <= 0.5, -0.5 <= x2 <= 0.5
x1 <- x1 - μ1 / s # s = std or (max - min)
-- Gradient descent in practice II: Learning Rate
θj := θj - α * ∂/∂θj of J(θ)
- Debugging: how to make sure gradient descent is working correctly.
+ Plot the value of J(θ) on the Y-axis, the number of iterations on the X-axis: the curve should go down (with more iterations you get to a lower end value; i.e. optimum)
+ Where the slope becomes flat first, you have reached convergence (at that number of iterations).
+ Alternative: declare convergence if J(θ) decreases by less than 10^-3 (example; arbitrary number epsilon) in one iteration # example of an automatic convergence test
- How to choose learing rate α.
+ If the slope of the plot (described above) is actually increasing (when it overshoots the minimum), use a smaller α.
+ Similar if the slope goes up/down/up/down, etc., use smaller α.
- For sufficiently small α, J(θ) should decrease on every iteration.
- But if α is too small, gradient descent can be slow to converge.
Summary:
- If α is too small: slow convergence.
- If α is too large: J(θ) may not decrease on every iteration; may not converge.
- Plot J(θ) over the # of iterations to see what is going on.
To choose α, try a range of values: 0.001, 0.01, 0.1, 1
Better: 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 0.1 --> every increase is about '3X'
-- Features and Polynomial Regression
Housing Prices Prediction
Creating/defining new features:
1 - hθ(x) = θ0 + θ1 * frontage + θ2 * depth
2 - Land Area --> x = frontage * depth
3 - hθ(x) = θ0 + θ1x # x = land area, which uses/combines the two prior features
Polynomial Regression
Quadratic function --> θ0 + θ1x + θ2x^2 # goes up and goes back down (TODO: check why quadratic function go down again?)
Cubic function --> θ0 + θ1x + θ2x^2 + θ3x^3
Root function --> θ0 + θ1x + θ2x^0.5 # never slopes down again
Therefore having insights into how functions shape lines can be useful to choose the correct model.
hθ(x) = θ0 + θ1x1 + θ2x2 + θ3x3
= θ0 + θ1(size) + θ2(size)^2 + θ3(size)^3
x1 = (size)
x2 = (size)^2
x3 = (size)^3
Size: 1 - 1,000
Size^2: 1 - 1,000,000
Size^3: 1 - 10^9
--> Therefore scaling becomes important!
[Normal Equation] % method to solve for θ analytically
Intuition: If 1 D (θ is real value / scalar, not a vector of parameters):
J(θ) = aθ^2 + bθ + c
∂/∂θ J(θ) = 0 % to get the minimum set the derivative of J(θ) to 0 (zero)
In the case when θ is a n+1 dimensional vector, you take the partial derivates of all θ's and set those to 0. Finally you can combine those values to get the final result.
X = matrix with x0 ... xn % m*(n+1) dimensional matrix
y = m-dimensional vector
θ = (X^T * X)^-1 * X^T * y
(X^T*X)^-1 is the inverse of matrix X^T*X
Octave: pinv(X'*X)*X'*y % X' == X^T
When using this method:
- Feature scaling is unnecessary, large variations in range are o.k.
When to use which: % m training examples, n features
A - Gradient Descent
- Need to choose α
- Needs many iterations
+ Works well even when n is large
B - Normal Equation
+ No need to choose α
+ Don't need to iterate
- Need to compute (X^TX)^-1 % this is an n*n matrix
- Slow if n is very large
n = 100 % NE
n = 1000 % NE
n = 10000 % GD / NE
n > 10000 % GD
[Octave Tutorial]
- Octave is a good prototyping language. Large scale implementation can follow in a different language.
-- [1] Basic Operations
% is comment
Basic math operators: + - * / ^
Logical - equality: ==
Logical - Non-Equality: ~=
&& = AND % 1 && 0 = 0
|| = OR % 1 || 0 = 1
xor(1,0) = 1
PS1('>> '): % use to change the prompt to '>> '.
>> Variable assignment: a = 3
>> a = 3
>> a = 3; % semicolon suppresses print output
>> b = 'hi'
>> c = (3>=1);
>> c
>> c = 1 % evaluates to true
>> a = pi;
>> a
>> 3.1416
>> disp(a) % display a
>> 3.1416
>> disp(sprintf('2 decmals: %0.2f', a)) % sprintf creates a string, substitute %0.2f with a using only 2 decimals
>> 2 decimals: 3.14
>> disp(sprintf('6 decimals: %0.6f', a))
>> 6 decimals: 3.141593
>> format long % causes numbers to be displayed with many decimal numbers
>> a
>> a = 3.141592665358979
>> format short % restores the default shorter version
>> a
>> a = 3.1416
>> A = [1 2; 3 4; 5 6] % semicolon means 'go to the next row'
>> A = % 3x2 matrix
1 2
3 4
5 6
>> v = [1 2 3]
>> v = % 1x3 matrix / 3-dimensional row vector
1 2 3 % row vector
>> v = [1; 2; 3;]
>> v = % 3x1 matrix / 3-dimensional column vector
1
2
3
>> v = 1:0.1:2 % start with 1, increment with 0.1, up to 2
>> v = 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0 % row vector, 1x11 matrix
>> v = 1:6
>> 1 2 3 4 5 6
>> ones(2,3)
ans =
1 1 1
1 1 1
>> C = 2 * ones(2,3) % == [2 2 2; 2 2 2]
>> C =
2 2 2
2 2 2
>> w = ones(1,3)
>> w =
1 1 1
>> w = zeros(1,3)
>> w =
0 0 0
>> w = rand(1,3) % gives random numbers between 0 and 1 (from the uniform distribution) --> rand(rows,cols)
>> w =
0.91477 0.14359 0.8460
>> rand(3,3)
ans =
0.390426 0.264057 0.683559
0.041555 0.314703 0.506769
0.521893 0.739979 0.387001
>> w = randn(1,3) % uses gaussian distribution, with mean zero and variance/stdev 1 --> randn(rows,cols)
>> w = -6 + sqrt(10) * (randn(1,10000));
>> hist(w) % produces historigram
>> hist(w, 50) % use more bins (50)
>> eye(4) % 4x4 identity matrix
ans =
Diagonal Matrix
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
>> help eye % brings up the help function for eye, etc.
-- [2] Moving Data Around
>> A = [1 2; 3 4; 5 6]
A =
1 2
3 4
5 6
>> size(A) % returns a 1x2 matrix
>> ans =
3 2
>> size(A,1)
ans = 3 % first item of size(A) --> rows
>> size(A,2) % second item of size(A) --> columns
>> v = [1 2 3 4];
>> length(v)
ans = 4
>> length(A) % it alwasy returns the length of the longest dimension (rows/columns)
ans = 3
>> pwd % shows the current directory / path that Octave is in
ans = C:\Octave\3.2.cc-4.4.0\bin
>> cd 'C:\Users\ang\Desktop' % change directory
>> pwd
ans = C:\Users\ang\Desktop
>> ls % lists files/directories in pwd
>> load featuresX.dat
>> load priceY.dat
>> load('featuresX.dat') % similar as above
>> who % shows which variables are in your Octave workspace
>> size(priceY)
ans =
47 1
>> size(featuresX)
ans =
47 2
>> whos % gives detailed view of files in workspace
>> clear featuresX % removes featuresX from scope
>> v = priceY(1:10) % returns a vector with the first 10 elements of priceY (1x10)
>> save hello.mat v; % save variable v as hello.mat + saves it as binary data (so very compressed)
>> clear % without variable after 'clear', this clear everything from your workspace
>> save hello.txt v -ascii % now it will save it in human-readable form, ascii (text)
>> A = [1 2; 3 4; 5 6]
A =
1 2
3 4
5 6
>> A(3,2) % indexing, third row, second column
ans = 6
>> A(2,:) % everything from row 2 --> ':' means every element along that row/column
ans = 3 4
>> A(:,2)
ans =
2
4
6
>> A([1,3], :)
ans =
1 2
5 6
>> A(:,2) = [10; 11; 12]
ans =
1 10
3 11
5 12
>> A = [A, [100; 101; 102]] % append another column vector to the right
ans =
1 10 100
3 11 101
5 12 102
>> A(:) % put all elements of A into a single vector
ans = % 9x1 matrix
1
3
5
10
11
12
100
101
102
>> A = [1 2; 3 4; 5 6];
>> B = [11 12; 13 14; 15 16];
>> C = [A B] % simply concatenates A & B adjacent; SAME AS [A, B]
C = % 3x4 matrix
1 2 11 12
3 4 13 14
5 6 15 16
>> C = [A;B] % semicolon means put it at the bottom, as before
C = % 6x2 matrix
1 2
3 4
5 6
11 12
13 14
15 16
-- [3] Computing on Data
>> A = [1 2; 3 4; 5 6];
>> B = [11 12; 13 14; 15 16];
>> C = [1 1; 2 2];
>> A * C % normal matrix multiplication
>> A .* C % element wise multiplication
ans =
11 24
39 56
75 96
% in general the period '.' tends to mean "element-wise" operations in Octave
>> A .^ 2
ans =
1 4
9 16
25 36
>> v = [1; 2; 3]
>> 1 ./ v
ans =
1.000
0.500
0.333
>> log(v)
ans =
0.00000
0.69315
1.09861
>> exp(v) % e^1, e^2, e^3 (since v contains 1, 2 & 3)
>> abs(v) % take the absolute values of v
>> -v % gives the v * -1
>> v + ones(length(v), 1) % == v + 1
ans =
2
3
4
>> A' % transpose
ans =
1 3 5
2 4 6
>> a = [1 15 2 0.5]
>> val = max(a)
val = 15
>> [val, ind] = max(a) % give me the value and index of max(a)
val = 15
ind = 2 % index
>> max(A) % where A is a matrix --> gives column-wise maximum
ans =
5 6
>> a
a = 1.000 15.000 2.0000 0.5000
>> a < 3 % element wise comparison
ans =
1 0 1 1
>> find(a < 3)
ans =
1 3 4 % the first/third/fourth element are < 3
>> A = magic(3) % magic squars: all rows, diagnoals and columns sum up to the same thing
A =
8 1 6
3 5 7
4 9 2
>> [r, c] = find(A >= 7)
r =
1
3
2
c =
1
2
3
>> A(2,3)
ans = 7
>> sum(a) %returns the sum of a
ans = 18.5000
>> prod(a) % returns the product of a
ans = 15
>> floor(a) % rounds down the elements of a
ans =
1 15 2 0
>> ceil(a) % round up the elemnts of a
ans =
1 15 2 1
>> max(rand(3), rand(3))' % will return a random 3x3 matrix, where it constantly picked the higher of two random items (so all random numbers tend to be higher)
>> max(A, [], 1) % 1 == take the max along the columns, returns a row vector / same as max(A)
ans =
8 9 7
>> max(A, [], 2) % 2 == take the max along the rows, returns a column vector
ans =
8
9
7
>> max(max(A)) % maximum value of matrix (max of the max per column)
ans = 9
>> max(A(:)) % A(:) returns all matrix values in one column vector
ans = 9
>> A = magic(9)
>> sum(A,1) % sum per columns, returns column vector
>> sum(A,2) % sum per row, returns row vector
>> A .* eye(9) % this will basically multiply all elements on the diagonal with 1, all others with 0 --> eye returns identity matrix
>> sum(sum(a .* eye(9)))
ans = 369
>> sum(sum(A.*flipud(eye(9)))) % flips the identity matrix so that we can check for the second diagonal / flip Up Down == flipud
1 0 0 0 0 1
0 1 0 --> flipud --> 0 1 0
0 0 1 1 0 0
>> A = magic(3)
A =
8 1 6
3 5 7
4 9 2
>> pinv(A) % pseudo-inverser, returns the inverse
>> temp = pinv(A)
>> temp * A --> returns identity matrix
-- [4] Plotting Data
>> t = [0:0.01:0.98];
>> y1 = sin(2*pi*4*t);
>> plot(t, y1);
>> y2 = cos(2*pi*4*t)
>> plot(t, y2)
>> hold on;
>> plot(t, y1, 'r'); % 'r' == red
>> xlabel('time')
>> ylabel('value')
>> legend('sin', 'cos')
>> title('my plot')
>> print -dpng 'myplot.png'
>> help plot
>> close % closes plot window
>> figure(1); plot(t,y1);
>> figure(2); plot(t,y2); % now 2 windows with plots are open
>> subplot(1,2,1); % sub-divivides plot to a 1x2 grid, access first element (1x2x1)
>> plot(t,y1);
>> subplot(1,2,2);
>> plot(t,y2);
>> axis([0.5 1 -1 1]);
>> clf; % clears figure
>> a = magic(5)
>> imagesc(A) % plots a 5x5 grid of colors
>> imagesc(A), colorbar, colormap gray;
>> imagesc(magic(15)), colorbar, colormap gray; % comma-chaining function calls --> piping
>> a=1, b=2, c=3
a = 1
b = 2
c = 3
-- [5] For, while, if statements, and functions
>> v = zeros(10,1)
>> for i = 1:10,
> v(i) = 2^i;
> end;
v =
2
4
8
16
32
64
128
256
512
1024
>> indices = 1:10;
indices =
1 2 3 4 5 6 7 8 9 10
>> for i = indices,
> disp(i);
> end; % break & continue also work
>> i = 1;
>> while i <=5,
> v(i) = 100;
> i = i+1;
> end;
>> v
v =
100
100
100
100
100
64
128
256
512
1024
>> i = 1;
>> while true,
> v(i) = 999;
> i = i + 1;
> if i == 6,
> break;
> end;
> end;
v =
999
999
999
999
999
64
128
256
512
1024
>> v(1)
ans = 999
>> v(1) = 2;
>> if v(1) == 1,
> disp('The value is one');
> elseif v(1) == 2;
> disp('The value is two');
> else
> disp('The value is not one or two.');
> end;
The value is two
>> exit % exits octave
>> quit % quits octave
-- Defining functions in Octave
+ Create a different text file containing function, e.g. squareThisNumber.m
function y = squareThisNumber(x)
y = x^2;
>> squareThisNumber(5)
error: 'squareThisNumber' undefined near line 18 column 1
>> pwd % check & change diretory to where file is located
>> squareThisNumber(5)
ans = 25
>> % Octave search path (advanced/optional)
>> addpath('C:\Users\ang\Desktop') % adds path to list of paths for Octave to check
>> cd 'C:\'
>> squareThisNumber(5)
ans = 25 % even now we switched directory, we can still find the function
% Within octave you can create functions that return multiple values
function[y1,y2] = squareAndCubeThisNumber(x)
y1 = x^2;
y2 = x^3;
>> [a,b] = squareAndCubeThisNumber(5);
>> a
a = 25
>> b
b = 125
% Goal: Define a function to compute the cost function J(θ)
>> X = [1 1; 1 2; 1 3]
X =
1 1
1 2
1 3
>> y = [1; 2; 3]
y =
1
2
3
theta = [0;1]
function J = costFunctionJ(X, y, theta)
% X is the "design" matrix containing our training examples
% y is the class labels
m = size(X,1) % number of training examples, size(X,2) would count columns I think
predictions = X * theta; % predictions of hypothesis on all m examples
sqrErrors = (predictions-y).^2; % squared errors
J = 1/(2*m) * sum(sqrErrors);
>> j = costFunctionJ(X,y,theta)
j = 0 % since theta = [0,1] corresponds to exactly the 45 degree line
>> theta = [0;0]
>> j = costFunctionJ(X,y,theta)
j = 2.3333
>> (1^2 + 2^2 + 3^2) * (2*3)
ans = 2.3333
-- [6] Vectorization
Assume: h(θ)x = Σ(0 j*x j) == θ^T * x
Unvectorized implementation
prediction = 0.0;
for j = 1:n+1,
prediction = prediction + theta(j) * x(j)
end;
Vectorized Implementation
prediction = theta' * x
QUIZ Vectorized Implementation
θ := θ - α * ∂
where ∂ == 1/m * Σ(hθ(x^(i)-y^(i))) * x^(i) --> NOTHING GETS SQUARED HERE! You are at the derivate! Hence the (squared is gone!) 1/2m is gone --> 2 * 1/2m == 1/m!!
- both θ & ∂ are n+1 dimensional vectors
-- [7] Normal equation and non-invertibility
θ = (X^T*X)^-1 * X^T * y
- What if X^T*X is non-invertible (singular/degenerate)?
- Octave: pinv(X'*X)*X'*y
pinv: pseudo-inverse % will return the correct result even if X^T*X is non-invertible
inv: inverse
What if X^T*X is non-invertible?
- Redundant features (linearly dependent).
+ E.g. x1 = size in feet^2
+ x2 = size in m^2
% lm = 3.28 feet
% x1 = (3.28)^2*x2 --> if you can show a linear connection between two variables the matrix is non-invertible
- Too many features (e.g. m <= n)
+ Delete some features, or use regularization
-- Working on and Submitting Programming Assignments
>> submit()
Enter your choise [1-9]: 1
Login (Email address):
Password:
QUIZ
for i = 1:7
for j = 1:7
A(i, j) = log(X(i, j));
B(i, j) = X(i, j) ^ 2;
C(i, j) = X(i, j) + 1;
D(i, j) = X(i, j) / 4;
end
end
--> looping throughs rows and columns of a matrix
-- Week 3
== Classification and Representation ==
[Classification]
- Email: Spam/Not-Spam
- Online Transactions: Fraudulent (Yes/No)?
- Tumor: Malignant/Benign
y = {1, 0} % binary classification
0: 'Negative Class' % 0 is abscence
1: 'Positive Class' % 1 is presence
multi-class classification: y = {0, 1, 2, 3}
hθ(x) = θ^T*x
Threshold classifer output hθ(x) at 0.5:
- If hθ(x) >= 0.5, predict 'y=1'
- If hθ(x) < 0.5, predict 'y=0'
Classification y = 0 or 1 % whereas:
Normal Regression: hθ(x) can be > 1 or < 0 % however:
Logistic Regression: 0 <= hθ(x) <= 1 % output logistic regression always between 0 and 1 | it is a classification algorithm
[Logistic Regression: Hypothesis Representation]
hθ(x) = θ^T*x % normal regression
hθ(x) = g(θ^T*x) % logistic regression
g(z) = 1 / 1 + e^-z % Sigmoid/Logistic Function --> z = θ^T*x
hθ(x) = 1 / (1 + e^(-θ^T*x)) % rewritten logistic regression function
Interpretation of Hypothesis Output
- hθ(x) = estimated probability that y = 1 on input x.
- Example:
If x = [ x0 ] = [ 1 ]
[ x1 ] [ tumorSize ]
hθ(x) = 0.7
Tell patient that 70 percent chance of tumor being malignant (y = 1).
hθ(x) = P(y=1|x;θ) % probability of y=1, given x is parameterized by θ
P(y=0|x;θ) + P(y=1|x;θ) = 1
P(y=0|x;θ) = 1 - P(y=1|x;θ)
[Decision Boundary]
hθ(x) = g(θ^T*x) % outputs P(y=1|x;θ)
g(z) = 1 / (1+e^-z) % z = θ^T*x
Suppose predict 'y = 1' if hθ(x) >= 0.5
predict 'y = 0' if hθ(x) < 0.5
g(z) >= 0.5 when z >= 0
hθ(x) = g(θ^T*x) >= 0.5 whenever θ^T*x >= 0 % θ^T*x = z
vice-versa
g(z) < 0.5 when z < 0
hθ(x) = g(θ^T*x) whenever θ^T*x < 0 % θ^T*x = z
hθ(x) = g(θ0 + θ1x1 + θ2x2)
[ -3 ]
θ = [ 1 ]
[ 1 ]
Predict 'y = 1' if -3 + x1 + x2 >= 0 % θ0 = -3, θ1 = 1, θ2 = 1, hence this equals θ^T*x
This is the same as: x1 + x2 >= 3 % you can plot a straight line where: x1 + x2 = 3 --> this line is called the "Decision Boundary"
Non-Linear Decision Boundaries
hθ(x) = g(θ0 + θ1x1 + θ2x2 + θ3x1^2 + θ4x2^2)
[ -1 ]
[ 0 ]
θ = [ 0 ]
[ 1 ]
[ 1 ]
Predict 'y = 1' if -1 + x1^2 + x2^2 >= 0 % x1^2 + x2^2 >= 1 --> x1^2 + x2^2 = 1 | Decision boundary (circle shaped)
- The Decision Boundary is a property of the parameters theta, NOT the underlying data.