lolamontes69

Ch8 Ex2-Programming Collective Intelligence

Aug 12th, 2013
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. """ Chapter 8 Exercise 2: Leave-one-out cross-validation.
  2.  
  3.    Leave-one-out cross-validation is an alternative method of calculating prediction error that treats every row in the dataset individually as a test set, and treats the rest of the data as a training set.
  4.    Implement a function to do this.
  5.    How does it compare to the method described in this chapter.
  6.  
  7.    loo_crossvalidate() returns an absolute value whilst crossvalidate() returns a value dependent upon the random selection made in dividedata(), and is faster because it makes less calls to algf. (Unless you set trials=2 in crossvalidate():D ).
  8.    See end for Usage
  9. """
  10.  
  11. def loo_crossvalidate(algf,data):
  12.     error=0.0
  13.     for row in range(len(data)):
  14.         trainset = []
  15.         trainset = trainset+data
  16.         testset=[]
  17.         testset.append(data[row])
  18.         trainset.remove(data[row])
  19.         error+=testalgorithm(algf,trainset,testset)
  20.     return error/len(data)
  21.  
  22.  
  23. """
  24.    Usage
  25.    *****
  26. Add function to numpredict
  27. import numpredict as numpredict
  28.  
  29. data=numpredict.wineset1()
  30. numpredict.loo_crossvalidate(numpredict.knnestimate,data)
  31. numpredict.crossvalidate(numpredict.knnestimate,data)
  32. numpredict.loo_crossvalidate(numpredict.weightedknn,data)
  33. numpredict.crossvalidate(numpredict.weightedknn,data)
  34.  
  35. def knninverse(d,v):
  36.    return numpredict.weightedknn(d,v,weightf=numpredict.inverseweight)
  37.  
  38. numpredict.loo_crossvalidate(knninverse,data)
  39. numpredict.crossvalidate(knninverse,data)
  40. """
Advertisement
Add Comment
Please, Sign In to add comment