Advertisement
D_Pain

Training and Predicting using SVM.

Apr 4th, 2020
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.82 KB | None | 0 0
  1. import numpy as np
  2. from sklearn.svm import SVC
  3.  
  4.  
  5. DATASET = '../rsc/q2_dataset.txt'
  6.  
  7. # Read dataset and return 3 lists corresponding to classification, x and y
  8.  
  9.  
  10. def train_predict(constant, dataset):
  11.  
  12.   fid = open(dataset, 'r')
  13.  
  14.   x = []
  15.   y = []
  16.  
  17.   for line in fid:
  18.     x.append([float(line.split()[1][2:]), float(line.split()[2][2:])])
  19.     y.append(float(line.split()[0]))
  20.  
  21.   fid.close()
  22.  
  23.   clf = SVC(C=constant, kernel='linear')
  24.   clf.fit(np.array(x), np.array(y))
  25.  
  26.   # Predicting Random values.
  27.   val = clf.predict(np.array([[8, 8], [2, 8], [5, 6], [5, 3], [6, 8]]))
  28.  
  29.   alphas = np.abs(clf.dual_coef_)
  30.  
  31.   print(alphas)  # Alpha
  32.   print(clf.coef_)  # Weights
  33.   print(val)  # Predicted classifications.
  34.  
  35.  
  36. def main():
  37.   train_predict(1, DATASET)
  38.   print('-----')
  39.   train_predict(3, DATASET)
  40.  
  41.  
  42. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement