Quiz 1 (q15-20)
>>> import math,random
>>> from pylab import*
>>> def getList(fname): # Read the .txt file that contains the training examples(x_n, y_n), processing it to a list of lists in float.
F = open(fname)
L_strings = F.readlines() # returns a list of strings, each line in file is a string needs to be processed
L_float_lists = []
for l in L_strings:
t1 = l.strip()
t2 = t1.split()
for i in range(len(t2)):
t2[i] = float(t2[i])
L_float_lists.append(t2)
return L_float_lists
>>> a = getList('C:\\Users\logic\Desktop\Q15.txt')
>>> def input_array(List): # Converts the raw list of training examples to a list of input arrays with -1 as an extra attribute value for w's threshold.
array_list = []
for l in List:
L = array(l)
L[-1] = -1
array_list.append(L)
return array_list
>>> def labels(List): # saves the y_n of sample into a list
label = []
for l in List:
label.append(l[-1])
return label
>>> def PLA(inputs, labels):
if len(inputs)!=len(labels):
raise ValueError('# of inputs and outputs do not match!')
N = len(labels)
T = 0
w = array([0,0,0,0,0])
for i in range(N):
match = False
product = inputs[i]*w
scalar = product.sum()
if scalar*labels[i]>0:
match = True
elif scalar==0 and labels[i]<0:
match = True
while not match: # Boolean flag + while loop
w = w + labels[i]*inputs[i] # PLA update
T+=1
p = inputs[i]*w
s = p.sum()
if s*labels[i]>0:
match = True
elif s=