So matplotlib is really neat and powerful yet elegant and easy to use. Here we have this simple hist with all you need:

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
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('TkAgg')
import numpy as np
import pylab

# read file
with open('.../nums.txt', 'r') as f:
    data = f.readlines()
    nums = []
    for line in data:
        nums.append(int(line))

#find central tendency measures
mu = np.mean(nums)
median = np.median(nums)
sigma = np.std(nums)

#plot
fig, ax = plt.subplots(1)
ax.hist(nums, bins = 30, color = 'c')
ax.axvline(np.mean(nums), color='b', linestyle='dashed', linewidth=2)
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
textstr = '$\mu=%.2f$\n$\mathrm{median}=%.2f$\n$\sigma=%.2f$'%(mu, median, sigma)
ax.text(0.65, 0.95, textstr, transform=ax.transAxes, fontsize=14,
        verticalalignment='top', bbox=props)
pylab.show()

Which produces this: Histogram

PS nums.txt it’s just a file with numbers.

(Read More...)

Binary search is extremely easy to explain, but very tricky to write:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public int binary_search(List<Integer> list, int value) {
		int lo = 0;
		int hi = list.size() - 1;
		while (lo <= hi){
			//because mid = (hi + lo)/2 might overflow memory
			int mid = lo + (hi - lo) / 2;
			if (value == list.get(mid)) 
				return mid;			
			else if (value > list.get(mid)) 
				lo = mid + 1; //otherwise will stuck on non existing values
			else 
				hi = mid - 1;
		}
		return -1;
	}
(Read More...)

I started to love quick sort. The reason being…it’s quick! Quick to code, quick to sort. Easy to understand. So.. here it is in Java.

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
public List<Integer> qsort(List<Integer> list){
		//base case
		if (list.size() < 2){
			return list;
		}
		
		//choose pivot 
		int pivot = list.get(0);		
	
		//find low, pivots and high elems
		List<Integer> low = new ArrayList<Integer>();
		List<Integer> high = new ArrayList<Integer>();
		List<Integer> pivots = new ArrayList<Integer>();
		for (int i : list){
			if (i < pivot){
				low.add(i);
			}else if (i == pivot){
				pivots.add(i);
			}
			else{
				high.add(i);
			}
		}
		
		//qsort on low and high recursively
		low = qsort(low);
		high = qsort(high);
		
		//get here eventually after all recursive calls
		low.addAll(pivots);
		low.addAll(high);
		return low;		
	}
(Read More...)

GDA is an example of generative learining. It works very simple:

  1. We make assumption about the type of distributions of our data - in given example: Normal Distribution
  2. For each class we learn (on training data) the parametrs of distribution: mu, sd
  3. We model each class’ distribution via Likelihood
  4. For new data example we calculate the likelihood of belonging to each of the classes
  5. Finally, we choose the maximimum likelihood to predict the class.

Here is the simplyfied code for Matlab:

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
function gda()
    train_data = load('vowel.train');

    % extract the target and the predictor variables for all the data
    x = train_data(:,2:11);
    y = train_data(:,1);

    [m,n] = size(x);

    % find out the number of classes
    unique_classes = unique(y);
    k = length(unique_classes);

    % estimate the prior probability of each class
    phi = zeros(num_classes, 1);
    for i = 1:k
        class = unique_classes(i);
        phi(i) = length(y(y==class)) / m;
    end

    % estimate the mean for each class
    mu = zeros(k, n);
    for i = 1:k
        class = unique_classes(i);
        x_in_class = x(y == class,:);
        mu(i, :) = mean(x_in_class);
    end

    % estimate the common covariance matrix for the data centered on its
    % respective means
    sigma = eye(n, n);
    for i = 1:k
        class = unique_classes(i);
        x_in_class = x(y == class,:);
        diff = x_in_class - repmat(mu(i, :), length(x_in_class(:,1)), 1);
        sigma = sigma + diff'*diff;
    end
    % Normalize sigma
    sigma = sigma / m;
    
    % precompute the inverse of sigma for later use
    sigma_inv = inv(sigma);

    % make predictions on the train data
    % intialize conf -- the k*k confusion matrix, where entry conf(i,j) is the
    % number of times the true class i was predicted as class j
    conf = zeros(k, k);

    coef = 1/((2*pi)^(n/2) * sqrt(det(sigma)));
    for i = 1:m
        p = zeros(k, 1);
        for class = 1:k
            diff = x(i, :) - mu(class, :);
            pxy = coef * exp( -1/2 * diff * sigma_inv * diff');
            py = phi(class);
            p(class) = pxy * py;         
        end
        p = p / sum(p);

        % find the most probable class
        [max_prob, predicted_class] = max(p);

        % update the confusion matrix for this example's prediction
        conf(y(i), predicted_class) = conf(y(i), predicted_class) + 1;
    end
    
    % compute the accuracy of all predictions
    accuracy = sum(diag(conf)) / sum(sum(conf))

    % compute the precision per class
    per_class_precision = diag(conf) ./ sum(conf, 2)

    % compute the base rate accuracy
    base_rate = max(sum(conf, 2)) ./ sum(sum(conf))
(Read More...)

While linear regression allows to draw a line to fit into the data in such a way to minimize Squared Error, weighted regression takes into account the significance of training examples: it makes sense that those data points that are closer to x, that we are trying to predict on, have more influence on it.

The analogy is - sliding window. When we predict on x - we look in the window: what’s around x? Further away it is - less influence it has on our beliefs about x.

Here is python code to do that. To demonstrate - we plot a resulting line:

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
#weighted linear regression
def wls(x, y, tau=0.3):
    """
    :param x: feature matrix
    :param y: target vector
    :param tau: smoothing factor - Gaussian bump's width
    :return: plot of matplotlib
    """
    x = np.mat(x).T
    y = np.mat(y).T
    m = x.shape[0] #number of examples

    dummy = np.mat(np.ones((m,), dtype=np.int))
    X = np.hstack((dummy.T, x)) #design matrix

    #try predicting on new possible examples
    xpred = np.linspace(x.min(), x.max(), 200)
    ypred = np.zeros(200)

    for i in xrange(len(xpred)):
        xval = xpred[i]

        W = np.eye(m) #weights for current ith example
        theta = np.zeros(m) #thetas for that

        #fill weights via Gaussian sigmoid
        for j in xrange(m):
            W[j][j] = np.exp(-np.linalg.norm(x[j] - xval)**2 / 2*tau**2)

        #calc theta
        theta = np.linalg.inv(X.T * W * X) * (X.T * (W*y))

        #make prediction
        ypred[i] = np.mat([1, xval]) * theta

    plt.plot(x, y, 'ro', xpred, ypred, 'b-')
    pylab.show()
    return plt
(Read More...)