Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- trainFile = open("E:\\Studies\\4-2\\Pattern Recognition Sessional\\Train.txt", "r")
- dataSet = []
- weights = []
- numOfFeatures = 3;
- numOfClasses = 3;
- LABEL_INDEX = numOfFeatures + 1;
- PUNISH = -1;
- REWARD = 1;
- RO = 1;
- def findLabel (sample, weights):
- label = 0;
- maxVal = -math.inf
- for i in range (numOfClasses):
- val = 1;
- for j in range(numOfFeatures + 1):
- val += sample[j]*weights[i][j]
- if val > maxVal:
- label = i;
- maxVal = val;
- return label+1 #classes are 1,2.. || you calculated 0,1...
- def updateWeight (weightID, sample, type): #type : punish = -1, reward = +1
- for i in range (numOfFeatures + 1):
- weights[weightID][i] += RO*type*sample[i]
- def prepareDataset():
- count = 0;
- for line in trainFile:
- count+=1;
- if(count==1): #dont take the first line
- continue
- sample = []
- for s in line.split():
- try:
- sample.append(float(s))
- except ValueError:
- pass
- if(len(sample)==numOfFeatures+1):
- sample.insert(numOfFeatures, 1) #bias
- dataSet.append(sample)
- def inintializeWeights():
- for i in range (numOfClasses):
- w = []
- for j in range (numOfFeatures):
- w.append(0)
- w.append(1)
- weights.append(w)
- def main ():
- prepareDataset()
- inintializeWeights()
- for sample in dataSet:
- result = findLabel(sample, weights)
- print(sample, result)
- if (result != sample[LABEL_INDEX]):
- updateWeight(int(result)-1, sample, PUNISH)
- updateWeight(int(sample[LABEL_INDEX])-1, sample, REWARD)
- print("So the final vectors are:")
- for w in weights:
- print(w)
- #main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement