Wednesday 26 September 2018

Fix for Hintons mnistdeepauto

A Fix for the correction of HINTON's nmistdeepauto example
IMPORTANT NOTE: THERE IS A CORRECTION AT THE BOTTOM!

Mr. Hinton et all has published a deep learning example named mnistdeepauto
at his page: http://www.cs.toronto.edu/~hinton/MatlabForSciencePaper.html

I tried to run this example but encountered the below error
error: vertical dimensions mismatch (1x768320 vs 1x889840)
 although I did everything right.  This might happen because of a
 change in the test data of MNIST after this example is published.
 So it may not be the program but the data causing the error.

 In any case you can find my solution below.  The changes has to be done
 in the makebatches.m script.

 Cheers.

 Ali Riza SARAL


octave:15  digitdata=[];
octave:16  targets=[];
octave:17  clc
octave:18  clear all
octave:19  digitdata=[];
octave:20  targets=[];
octave:21  load test0; digitdata = [digitdata; D]; targets = [targets; repmat([1 0 0 0 0 0 0 0 0 0], size(D,1), 1)];
octave:22  load test1; digitdata = [digitdata; D]; targets = [targets; repmat([0 1 0 0 0 0 0 0 0 0], size(D,1), 1)];
error: vertical dimensions mismatch (1x768320 vs 1x889840)  <========================ERROR
octave:22  load test2; digitdata = [digitdata; D]; targets = [targets; repmat([0 0 1 0 0 0 0 0 0 0], size(D,1), 1)];
error: vertical dimensions mismatch (1x768320 vs 1x809088)
octave:22  load test3; digitdata = [digitdata; D]; targets = [targets; repmat([0 0 0 1 0 0 0 0 0 0], size(D,1), 1)];
error: vertical dimensions mismatch (1x768320 vs 1x791840)
octave:22  load test4; digitdata = [digitdata; D]; targets = [targets; repmat([0 0 0 0 1 0 0 0 0 0], size(D,1), 1)];
error: vertical dimensions mismatch (1x768320 vs 1x769888)
octave:22  load test5; digitdata = [digitdata; D]; targets = [targets; repmat([0 0 0 0 0 1 0 0 0 0], size(D,1), 1)];
error: vertical dimensions mismatch (1x768320 vs 1x699328)
octave:22  load test6; digitdata = [digitdata; D]; targets = [targets; repmat([0 0 0 0 0 0 1 0 0 0], size(D,1), 1)];
error: vertical dimensions mismatch (1x768320 vs 1x751072)
octave:22  load test7; digitdata = [digitdata; D]; targets = [targets; repmat([0 0 0 0 0 0 0 1 0 0], size(D,1), 1)];
error: vertical dimensions mismatch (1x768320 vs 1x805952)
octave:22  load test8; digitdata = [digitdata; D]; targets = [targets; repmat([0 0 0 0 0 0 0 0 1 0], size(D,1), 1)];
error: vertical dimensions mismatch (1x768320 vs 1x763616)
octave:22  load test9; digitdata = [digitdata; D]; targets = [targets; repmat([0 0 0 0 0 0 0 0 0 1], size(D,1), 1)];
error: vertical dimensions mismatch (1x768320 vs 1x791056)
octave:22  load test0;
octave:23  size(D)
ans =

        1   768320

octave:24  load test1; size(D)= 1   889840
octave:26  load test2; size(D)= 1   809088
octave:28  load test3; size(D)= 1   791840
octave:30  load test4; size(D)= 1   769888
octave:32  load test5; size(D)= 1   699328
octave:34  load test6; size(D)= 1   751072
octave:36  load test7; size(D)= 1   805952
octave:38  load test8; size(D)= 1   763616
octave:40  load test9; size(D)= 1   791056

octave:42  clc
octave:43  clear all
octave:44  digitdata=[];
octave:45  targets=[];
octave:46  load test0; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([1 0 0 0 0 0 0 0 0 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:47  size(digitdata)
ans =

   980   784

octave:48  size(targets)
ans =

   980    10

octave:49  load test1; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([0 1 0 0 0 0 0 0 0 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:50  size(digitdata)=  2115    784
octave:51  size(targets)= 2115     10

octave:52  load test2; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([0 0 1 0 0 0 0 0 0 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:54  size(digitdata)= 3147    784
octave:55  size(targets)= 3147     10

octave:56  diary off
octave:58  clc
octave:59  clear all
octave:60  digitdata=[];
octave:61  targets=[];
octave:62  load test0; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([1 0 0 0 0 0 0 0 0 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:63  load test1; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([0 1 0 0 0 0 0 0 0 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:64  load test2; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([0 0 1 0 0 0 0 0 0 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:65  load test3; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([0 0 0 1 0 0 0 0 0 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:66  load test4; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([0 0 0 0 1 0 0 0 0 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:67  load test5; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([0 0 0 0 0 1 0 0 0 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:68  load test6; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([0 0 0 0 0 0 1 0 0 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:69  load test7; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([0 0 0 0 0 0 0 1 0 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:70  load test8; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([0 0 0 0 0 0 0 0 1 0], size(reshape(D,size(D,2)/784,784),1),1)];
octave:71  load test9; digitdata = [digitdata; reshape(D,size(D,2)/784,784)]; targets = [targets; repmat([0 0 0 0 0 0 0 0 0 1], size(reshape(D,size(D,2)/784,784),1),1)];
octave:72  size(digitdata)
ans =

   10000     784

octave:73  size(targets)
ans =

   10000      10

octave:74  diary off

IMPORTANT NOTE:
I noticed that the program gives the below test output with my modifications suggested above:

The above algorithm destroys the test input data although it creates correct size batches.
The correct change is given below:
converter.m converts the mnist database data as below:
---------------------------------
for i=1:10,   % read number i 's 1000 raw labels and 784 pixel 1000 raw images , 1 to 10
  fprintf('.');
  rawimages = fread(f,28*28*n,'uchar');  %images
  rawlabels = fread(g,n,'uchar'); %labels
  rawimages = reshape(rawimages,28*28,n);  % 784 x 1000

  for j=1:n,
    fprintf(Df{rawlabels(j)+1},'%3d ',rawimages(:,j)); %fprintf to the Df recorded file pointer according to the raw label value,  number j's images.
% each number read is written to the corresponding testX.ascii file. 1000 cases and 784 pixels each
  end;
end;
fprintf(1,'\n');
-------------------------------------------------
It should be:
-------------------------------------------------
for i=1:10,   % read number i 's 1000 raw labels and 784 pixel 1000 raw images , 1 to 10
  fprintf('.');
  rawimages = fread(f,28*28*n,'uchar');  %images
  rawlabels = fread(g,n,'uchar'); %labels
  rawimages = reshape(rawimages,28*28,n);  % 784 x 1000

  for j=1:n,
    fprintf(Df{rawlabels(j)+1},'%3d ',rawimages(:,j)); %fprintf to the Df recorded file pointer according to the raw label value,  number j's images.
fprintf(Df{rawlabels(j)+1},'\n'); % each number read is written to the corresponding testX.ascii file. 1000 cases and 784 pixels each
  end;
end;

%fprintf(1,'\n');
--------------------------------------------------
The result is:
and  mnist_error file
---------------------------------------------------
# Created by Octave 3.4.3, Fri Oct 05 01:11:04 2018 Turkey Standard Time
# name: test_err
# type: scalar
36.63076254519869


# name: train_err
# type: scalar
36.96345981717504

Tuesday 4 September 2018

Gradient Descent


2.2 Gradient Descent
In this part, you will fit the linear regression parameters θ to our dataset using gradient descent.
ARS NOTLARI:
Bu bölümde amaç şehir nüfusu seçildiğinde kârın ne olacağını tahmin etmektir. Elimizdeki şehir nüfusu değerleri ve onlara ait kâr miktarları arasında  y = a + bx şeklinde doğrusal bir ilişki kurabilirsek X değerini seçtiğimizde buna karşı düşen kâr miktarını bulabiliriz.  

Burada sorun elimizdeki kâr değerlerinin doğrusal bir dağılıma sahip olmamasıdır.  Öyle ise amacımız eldeki tüm verileri dikkate alan, toplamda mümkün olan en haz hatalı doğruyu bulmaktır.   
Hinton’un  bahsettiği linear regression parameters θ(doğrusal ilişki parametreleri) y= a + bx doğrusal denklemindeki a ve b değerleridir.

Figure 1: Scatter plot of training data LG1

2.2.1 Update Equations
The objective of linear regression is to minimize the cost function
 

where the hypothesis hθ(x) is given by the linear model
 (y = a + bx  a= θ0 , b= θ1
ARS NOTLARI:
Seçtiğimiz a ve b değerlerine göre oluşan doğru üzerindeki değerler ile gerçek kâr değerleri arasındaki
farkların toplamı yaptığımız a ve b seçiminin maliyetini verir.  Bu toplama maliyet fonksiyonu(cost function)’u  denir.  Kurmaya çalıştığımız doğrusal ilişki’nin amacı maliyet fonksiyonu(cost function)’nu  mümkün olan en küçük değere indirmektir.
Yukarıda J(θ) seçtiğimiz θ değerlerine göre değişen maliyeti gösterir.
h0(xi)  seçtiğimiz ilk doğruyu  şehir nüfusuna göre x’in aldığı değerleri belirtir.
( h0(xi) - yi )2 seçtiğimiz ilk doğruya göre bulunan kâr değerleri ile yi gerçek kâr değerleri arasındaki
farktır.

Burada amaç seçilecek her doğru için bu hesaplamayı yaparak en uygun doğruyu bulmaktır.
Hinton’un bahsettiği model bu doğru ve onun denklemidir.

Recall that the parameters of your model are the θj values. These are the values you will adjust to minimize cost J(θ). One way to do this is to use the batch gradient descent algorithm.
Modelinizin parametrelerinin θj değerleri olduğunu hatırlayınız.  Bunlar J(θ) maliyeti minimize etmek için ayarlayacağımız değerlerdir.  Bu ayarlamayı yapmanın bir yolu gradient descent algoritmasıdır.

In batch gradient descent, each iteration performs the update
 


With each step of gradient descent, your parameters θj come closer to the
optimal values that will achieve the lowest cost J(θ)
Batch gradient descent algoritmasında her adım yukarıdaki güncellemeyi yapar. Gradient descent’in her adımıyla, θj parametreleriniz en düşük maliyeti sağlayacak optimal değerlere yaklaşacaktır.

ARS NOTLARI:
θj değeri  j’inci iterasyonda θ’nın aldığı değerdir.  θj yeni değerini bulmak için,  ( h0(xi) - yi )2 ‘nin türevi nin bütün şehirlerde aldığı değerlerin toplamını gene bütün şehirlerin sayısına bölüp bir yaklaşma hızı alfa ile çarparak, θj’nin eski değerinden  çıkartır.  Alfanın büyüklüğü sonuca yakınsama hızını etkilediği gibi fazla büyük alınırsa sonucu atlayıp ıraksamaya da yol açabilir.
Şekildeki  j indisi θj gradien descent hesaplama, yakınsama adımını, iterasyonu belirtir.  x(i) y(i) ‘deki i değişkeni ise geçmişte ölçüm yapılmış şehir nüfusu-kâr ikililerini belirtir.  Her θj yeni bir y = a + bx  a= θ0 , b= θ1 doğrusunu belirtir.  Amacımız bütün denek noktaları dikkat alındığında bu noktalara en yakın optimal geçen θ)= θ01x doğrusunu bulmaktır.

Implementation Note: We store each example as a row in the the X matrix in Octave. To take into account the intercept term (θ0), we add an additional first column to X and set it to all ones. This allows us to treat θ0 as simply another ‘feature’.
Uygulama Notu: Octave’de Xmatrixi içinde her örnek değeri bir satıra saklıyoruz.  (θ0), intercept terimini hesaba katmak için, X’e ek bir birinci sütun ekliyoruz ve satırlarının hepsinin değerlerini 1 yapıyoruz.  Bu bizim (θ0)’a bir  başka’ özellik’ gibi muamele etmemizi sağlıyor.


2.2.2 Implementation
In ex1.m, we have already set up the data for linear regression. In the following lines, we add another dimension to our data to accommodate the θ0 intercept term. We also initialize the initial parameters to 0 and the learning rate alpha to 0.01.

X = [ones(m, 1), data(:,1)];         % Add a column of ones to x
theta = zeros(2, 1);
 % initialize fitting parameters
iterations = 1500;
alpha = 0.01;
ex1.m’de doğrusal ilişki için veriyi hazırlamış bulunuyoruz.  Aşağıdaki satırlarda verimize intercept deyimini yerleştirmek için yeni bir sütun ekliyoruz.  Ayrıca başlangıç parametrelerinide 0 ve öğrenme oranı alpha’yı da 0.01 yapıyoruz.

ARS NOTLARI:
X = [ones(m, 1), data(:,1)];   Burada m elde bulunan şehir nüfusu/kâr değerlerinin (öğrenme seti) sayısıdır.
octave:1> data=[1,2;3,4;5,6]
data =
   1   2
   3   4
   5   6
octave:2> m=size(data,1)
m =  3
octave:3> ones(m,1)
ans =
   1
   1
   1
octave:4> data(:,1)
ans =
   1
   3
   5
octave:5> X=[ones(m, 1), data(:,1)];
octave:6> X
X =
   1   1
   1   3
1         5

2.2.3 Computing the cost J(θ)
As you perform gradient descent to learn minimize the cost function J(θ), it is helpful to monitor the convergence by computing the cost. In this section, you will implement a function to calculate J(θ) so you can check the convergence of your gradient descent implementation.
J(θ) Maliyet fonksiyonunu minimize etmeyi öğrenmek için Gradient descent’i çalıştırırken,  o durumdaki  maliyeti hesaplarak yakınsamayı izlemek faydalı olabilir.  Bu kısımda, J(θ)’yı hesaplamak için bir fonksiyon yapacaksınız, öyle ki yaptığınız gradient descent’ in yakınsamasını kontrol edebileceksiniz.

The variables X and y are not scalar values, but matrices whose rows represent the examples from the training set.
X ve y değişkenleri sayı değerleri değil, satırları öğrenme setinin örnekleri olan vektörlerdir.

ARS NOTLARI:
Maliyet, sistemde yapılacak küçük bir değişikliğin sistem çıktısında oluşturacağı değişikliktir.  Bu değişiklik olumlu yönde olabildiği gibi olumsuz yönde  de olabilir.  Bizim amacımız, elimizdeki öğrenme verilerinin hepsini kullanarak, deneme amaçlı seçtiğimiz doğrunun olumlu bir seçim olup olmadığını kontrol etmektir.  İşte bu amaç için maliyeti kontrol eden  J(θ) fonksiyonunu geliştireceğiz.

computeCost.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function J = computeCost(X, y, theta)
%COMPUTECOST Compute cost for linear regression
%   J = COMPUTECOST(X, y, theta) computes the cost of using theta as the
%   parameter for linear regression to fit the data points in X and y
ARSnotlar:
Ana programımız ex1 computeCost.m içinde duran harici  computeCost fonksiyonunu çağırır.
Maliyeti hesaplamak için X şehir nüfusları bilgileri vektörü, y bu şehir-nüfusları için kâr miktarları ve
Maliyetini ölçmek istediğimiz doğruyu belirten θ= θ01x vektörünü çağırdığımız computeCost fonksiyonuna geçirmemiz gerekir.  Unutmayınız ki X vektörüne intercept sütunu eklemiş durumdayız.

% Initialize some useful values
m = length(y);    % number of training examples

% You need to return the following variables correctly
J = 0;  % J maliyete başlangıç olarak 0 değerini veriniz.

% ============================================
% Instructions: Compute the cost of a particular choice of theta
%               You should set J to the cost.

% Loop implementation
%for i = 1:m,
%            J = J + (((X(i,:) * theta) - y(i)) ^ 2);
%end;
ARSnotları:
m  şehir nüfusları/bunlara karşı düşen kâr miktarları şeklinde elimizde bulunan öğrenme amaçlı ikililerin sayısını belirtir.  Dolayısıyla m defa  J = J + (((X(i,:) * theta) - y(i)) ^ 2); işlemi yapılacak
ve her defasında defa  J = J + ...  şeklinde daha önceki şehir-nüfuslarından kalan maliyet biriktirilecek ve toplam maliyet bulunacaktır. Theta’nın ilk değeri yukarıda
theta = zeros(2, 1);
0+0x ve boyutu 2 x 1  şeklinde verilmişti.
X ise X = [ones(m, 1), data(:,1)];     Burada m şehir-nüfus öğrenme örnekleri sayısı,
ones(m, 1),  θ01x’in θ0 intercepti nedeniyle eklenmiş sütun ,
data(:,1) ise şehir-nüfus değerlerini içeren input verisidir.
X m x 2 boyutundadır.

Böylece yukarıda vermiş olduğumuz maliyet fonksiyonunu gerçekleştirmiş oluruz.
% Vectorized implementation

J = sum(((X * theta) - y) .^ 2); 

J = 1 / (2 * m) * J;   % J= 32.073

end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Once you have completed the function, the next step in ex1.m will run computeCost once using θ initialized to zeros, and you will see the cost printed to the screen. You should expect to see a cost of 32.07. 

% compute and display initial cost
computeCost(X, y, theta)

Bir kere bu fonksiyonu tamamladıktan sonraki adım:  computeCost’u bir defa θ’ya başlangıçta 0 değerlerini vererek  çalıştıracaksınız, ve maliyetin ekrana yazıldığını göreceksiniz.  32.07 maliyetini görmeniz gerekir.




2.2.4 Gradient descent
Next, you will implement gradient descent in the file gradientDescent.m. The loop structure has been written for you, and you only need to supply the updates to θ within each iteration.
Daha sonra, gradientDescent.m dosyası içindeki gradient descent’i yapacaksınız. 

As you program, make sure you understand what you are trying to optimize and what is being updated. Keep in mind that the cost J(θ) is parameterized by the vector θ, not X and y. That is, we minimize the value of J(θ) by changing the values of the vector θ, not by changing X or y.
Neyi optimize ettiğinizi ve neyin güncellendiğini anladığınızdan emin olunuz.  Maliyet J(θ) ‘nın parametresi θ’dır, X ve y değil.  Yani  J(θ) değerini θ  vektörünün değerlerini değiştirerek minimize ediyoruz,  X ve y ‘yi değil.
A good way to verify that gradient descent is working correctly is to look at the value of J(θ) and check that it is decreasing with each step.
Bir gradient descent’in doğru çalıştığını kontrol etmenin iyi bir yolu J(θ) ‘nın değerine bakıp her iterasyon adımında azaldığını gözlemektir.

The starter code for gradientDescent.m calls computeCost on every iteration and prints the cost.
Başlangıçta gradientDescent.m  için verilen kod  her iterasyonda computeCostu çağırır ve maliyeti yazar.

% run gradient descent
theta = gradientDescent(X, y, theta, alpha, iterations);

% print theta to screen
fprintf('Theta found by gradient descent: ');
fprintf('%f %f \n', theta(1), theta(2));

ARSnotları:
gradientDescent fonksiyonu kendisini çağıran yere theta vektörünü 2 x 1 döndürür.
Alpha öğrenme hızını belirler.
İterations toplam iterasyon sayısını verir.
Çıktı yazdırılırken theta(1), theta(2)); θ01x değerlerini verir.
gradientDescent.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
%GRADIENTDESCENT Performs gradient descent to learn theta
%   theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by
%   taking num_iters gradient steps with learning rate alpha

% Initialize some useful values
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
ARSnotları:
m değişkeni  y kâr değerlerinin sayısıdır, bu aynı zamanda X şehir-nüfus değerlerinin sayısıdır.
Maliyet değerlerini  J_history vektörü içinde saklıyacağız, bunun uzunluğu toplam iterasyon sayısına (num_iters) eşittir.

for iter = 1:num_iters

    % ====================== YOUR CODE HERE ======================
    % Instructions: Perform a single gradient step on the parameter vector
    %               theta.

                % Nested loop implementation:
                % num_thetas = length(theta);  % theta vektörünün uzunluğu
                % theta_new = zeros(num_thetas,1);  % sonuç theta vektörü başlangıç theta ile aynı boyutta
                % for j = 1:num_thetas
                %            inner_sum = 0;
                %            for i = 1:m
                %                            inner_sum = inner_sum + ((X(i,:) * theta) - y(i)) * X(i,j);
                %            end
                %            theta_new(j) = theta(j) - (alpha / m * inner_sum);
                %end
ARSnotları:
% inner_sum = 0;
                %            for i = 1:m
                %                            inner_sum = inner_sum + ((X(i,:) * theta) - y(i)) * X(i,j);
                %            end
Yukarıda, % Loop implementation kısmında açıklanmıştı.
+ ((X(i,:) * theta) - y(i)) * X(i,j); değerleri  for i=1:m çevrimi içinde bütün şehir-nüfus değerleri
Ve bunlara ilişkin kâr değerleri için inner_sum içinde toplanır.
Bu işlem % for j = 1:num_thetas çevrimi içinde bütün  θ değerleri01x) için tekrarlanarak sonuç theta(j) - (alpha / m * inner_sum  ile hesaplanıp theta_new (j) içine konur.

    % Vectorized implementation:
                A = X * theta - y;                             % (m x 1 vector)   97 x 2 * 2 x 1  -  97 x 1
                delta = 1 / m * (A' * X)';                % ' ((n+1) x 1 vector)  (1 x 97 * 97 x 2)' = 2 x 1
                theta = theta - (alpha * delta);                 % ' ((n+1) x 1 vector) 2 x 1 - (alpha * 2 x 1)
                % printf(' tttt %s \r\n',"ARS");
                % printf('%4f \r\n',iter);
                 
    % ============================================================
ARSnotları:
X şehir-nüfus değerleri sayısı 97’dir.  X vektörüne bir sütun intercept eklemiştik.  Bunun amacı
θ01x ile uyumluluk sağlamaktır.  X * theta, 97 x 1 sonucu verir. Bundan kâr değerlerinin vektörünü (97 x 1) çıkartırız.

Delta  = 1 / m * (A' * X)'; yukarıda açıklanan

formulünden geliyor.  Özü, değişim miktarının ait olduğu değerle çarpılarak bütün bu çarpımların toplanması ve bütün değerlerin sayısına bölünmesine dayanır.

Bütün değerler vektör satırlarında ifade edildiği ve dikkate alındığı için bir çevrim gerekmemektedir.

    % Save the cost J in every iteration   
    J_history(iter) = computeCost(X, y, theta);

end
fprintf(' num_iters: %4.2f \r\n', num_iters);

end
ARSnotları:
Hesaplanan maliyet değerleri  iterasyon sayısı bazında    J_history(iter)’ye yazılır.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Assuming you have implemented gradient descent and computeCost correctly, your value of J(θ) should never increase, and should converge to a steady value by the end of the algorithm.
Eğer gradient descent ve computeCost’u doğru yaptıysanız  J(θ) değeriniz hiç bir zaman artmamalıdır, ve algoritma sonunda sabit bir değere yakınsamalıdır.

After you are finished, ex1.m will use your final parameters to plot the linear fit. The result should look something like Figure 2:
Bitirdikten sonra ex1.m son olarak ulaştığınız parametre değerlerini kullanır.  Sonuç şekil 2 deki gibi olmalıdır.

% Plot the linear fit
hold on;            % keep previous plot visible % eski şekli koru
plot(X(:,2), X*theta, '-') 
legend('Training data', 'Linear regression')
hold off          % don't overlay any more plots on this figure %bu şekil üzerine yeni noktalar koyma

Bulduğunuz en son  θ değerleri (yani doğrunun a+bx) katsayıları  35,000 ve 70,000 kişilik şehirlerde kârın ne olacağını tahmin etmek için kullanılır.

% Predict values for population sizes of 35,000 and 70,000
predict1 = [1, 3.5] *theta;
fprintf('For population = 35,000, we predict a profit of %f\n', predict1*10000);
predict2 = [1, 7] * theta;  % 1 x 2 * 2 x 1 = 1 x 1
fprintf('For population = 70,000, we predict a profit of %f\n',   predict2*10000);

2.3 Debugging
Here are some things to keep in mind as you implement gradient descent:   Octave array indices start from one, not zero. If you’re storing θ0 and θ1 in a vector called theta, the values will be theta(1) and theta(2).
Gradient descenti yaparken akılda tutmanız gereken birkaç şey:  Octave dizi(array) indexleri 1’den başlar, 0’dan değil.  Eğer θ0 ve θ1’i theta isimli bir vektöre saklıyorsanız değerleri theta(1) ve theta(2) olacaktır.

ˆ If you are seeing many errors at runtime, inspect your matrix operations to make sure that you’re adding and multiplying matrices of compatible dimensions. Printing the dimensions of variables with the size command will help you debug.
Programı çalıştırıken çok sayıda hata görüyorsanız, toplama ve çarpma yaptığınız matrislerin uyumlu boyutlara sahip olduğundan emin olmak için, matris işlemlerinizi gözden geçiriniz.  Değişkenlerin boyutlarını size komutu ile yazdırmanız hataları bulmanıza yardımcı olacaktır.


Figure 2: Training data with linear regression fit  LG2

ˆ By default, Octave interprets math operators to be matrix operators. This is a common source of size incompatibility errors. If you don’t want matrix multiplication, you need to add the “dot” notation to specify this to Octave. For example, A*B does a matrix multiply, while A.*B does an element-wise multiplication.
Default olarak, Octave matematik operatörlerini matrix operatörü olarak yorumlar.  Bu, uyumsuzluk hatalarının genel bir kaynağıdır.  Eğer matrix çarpımı istemiyorsanız, ‘nokta’ notasyonunu kullanınız.
2 * 2 yarine 2 .* 2   a *b yerine a .* b