Author: Not specified Language: python
Description: Not specified Timestamp: 2018-06-11 02:53:14 +0000
View raw paste Reply
  1. class_means_dict = dict()
  2. preds_dict = dict()
  3. k=0
  4. # K means for different values.
  5. for K in range(2,6):
  6.     pred = np.zeros(shape = (N,K))
  7.     class_means = np.zeros(shape=(K,r))
  8.     # Initialize Class Means from different values from the dataset.
  9.     #First get the random indices.
  10.     initial_indices = np.random.choice(N,K)
  11.     #Pick the random values from the dataset based on random initialize indices.
  12.     for k in range(K):
  13.         class_means[k,:] = Z[initial_indices[k],:]
  14.     old_class_means = np.zeros(shape=(K,r))
  15.    
  16.     while np.linalg.norm(old_class_means-class_means)/np.linalg.norm(class_means) > 0.001:
  17.         old_class_means = np.array(class_means)
  18.         for i in range(N): # Iterate over the dataset.
  19.             distances_to_mean = np.zeros(K)
  20.             # For each point in dataset compute the distance from the means.
  21.             for k in range(K):
  22.                 distances_to_mean[k] = np.linalg.norm(class_means[k]-Z[i])
  23.             nearest_mean = np.argmin(distances_to_mean)
  24.             #Re-intialize the means
  25.             pred[i,:]=np.zeros(K)
  26.             # Update the means.
  27.             pred[i,nearest_mean]=1
  28.         #compute the new class means.
  29.         for k in range(K):
  30.             class_means[k] = np.mean(Z[np.where(pred[:,k]==1)],axis=0)
  31.  
  32.     class_means_dict[K] = class_means
  33.     preds_dict[K] = pred
  34.     np.set_printoptions(precision=2)
  35.     probabilities = np.ndarray((3,K))
  36.     print K
  37.     for predicted in range(K):
  38.         for true_label in range(3):
  39.             probabilities[true_label,predicted]=np.intersect1d(np.where(labels[:,true_label]==1),np.where(pred[:,predicted]==1)).size/float(np.where(labels[:,true_label]==1)[0].size)
  40.             print "%.2f" %probabilities[true_label,predicted],
  41.         print '\n'  
View raw paste Reply