lolamontes69

advancedclassify.py for Ch9 Programming Collective Intel...

Aug 25th, 2013
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.14 KB | None | 0 0
  1. import Gnuplot as Gnuplot
  2. import Gnuplot, Gnuplot.funcutils
  3. from numpy import *
  4. import urllib as urllib
  5. from HTMLParser import HTMLParser
  6. import math as math
  7.  
  8. class MyHTMLParser(HTMLParser):
  9.     count, head, result = 0, 'active', ''
  10.     def handle_starttag(self, tag, attrs):
  11.         if self.head=='passive':
  12.             if tag=='script':
  13.                 self.count=0
  14.         if tag=='title': self.count=1
  15.     def handle_endtag(self, tag):
  16.         if tag=="head":
  17.             self.count=1
  18.             self.head='passive'
  19.         if self.head=='passive':
  20.             if tag=='script':
  21.                 self.count=1
  22.         if tag=='title': self.count=0
  23.     def handle_data(self, data):
  24.         if self.count > 0:
  25.             if data!='':
  26.                 self.result = self.result + data
  27.  
  28. class matchrow:
  29.     def __init__(self,row,allnum=False):
  30.         if allnum:
  31.             self.data=[float(row[i]) for i in range(len(row)-1)]
  32.         else:
  33.             self.data=row[0:len(row)-1]
  34.         self.match=int(row[len(row)-1])
  35.  
  36. def loadmatch(f,allnum=False):
  37.     rows=[]
  38.     for line in file(f):
  39.         rows.append(matchrow(line.split(','),allnum))
  40.     return rows
  41.  
  42. def plotagematches(rows):
  43.     xdm,ydm=[r.data[0] for r in rows if r.match==1],\
  44.             [r.data[1] for r in rows if r.match==1]
  45.     xdn,ydn=[r.data[0] for r in rows if r.match==0],\
  46.             [r.data[1] for r in rows if r.match==0]
  47.     listm=[]
  48.     for fr in range(len(xdm)):
  49.         dep=(xdm[fr],ydm[fr])
  50.         listm.append(dep)
  51.     listn=[]
  52.     for fr in range(len(xdn)):
  53.         dep=(xdn[fr],ydn[fr])
  54.         listn.append(dep)
  55.     g = Gnuplot.Gnuplot(debug=1)
  56.     plot1 = Gnuplot.PlotItems.Data(listm, with_="points 1", title=None)
  57.     plot2 = Gnuplot.PlotItems.Data(listn, with_="points 3", title=None)  # No title
  58.     g.title('plotage matches')
  59.     g.plot(plot1,plot2)
  60.     wait=raw_input('Press <ENTER> to continue')
  61.  
  62. def lineartrain(rows):
  63.     averages={}
  64.     counts={}
  65.  
  66.     for row in rows:
  67.         # Get the class of this point
  68.         cl=row.match
  69.  
  70.         averages.setdefault(cl,[0.0]*(len(row.data)))
  71.         counts.setdefault(cl,0)
  72.  
  73.         # Add this point to the averages
  74.         for i in range(len(row.data)):
  75.             averages[cl][i]+=float(row.data[i])
  76.  
  77.         # Keep track of how many points in each class
  78.         counts[cl]+=1
  79.  
  80.     # Divide sums by counts to get the averages
  81.     for cl,avg in averages.items():
  82.         for i in range(len(avg)):
  83.             avg[i]/=counts[cl]
  84.  
  85.     return averages
  86.  
  87. def dotproduct(v1,v2):
  88.     return sum([v1[i]*v2[i] for i in range(len(v1))])
  89.  
  90. def dpclassify(point,avgs):
  91.     b=(dotproduct(avgs[1],avgs[1])-dotproduct(avgs[0],avgs[0]))/2
  92.     y=dotproduct(point,avgs[0])-dotproduct(point,avgs[1])+b
  93.     if y>0: return 0
  94.     else: return 1
  95.  
  96. def yesno(v):
  97.     if v=='yes': return 1
  98.     elif v=='no': return -1
  99.     else: return 0
  100.  
  101. def matchcount(interest1,interest2):
  102.     l1=interest1.split(':')
  103.     l2=interest2.split(':')
  104.     x=0
  105.     for v in l1:
  106.         if v in l2: x+=1
  107.     return float(x)         # Do as a float for rescaling purposes
  108.  
  109. def get_url(url):
  110.     try:
  111.         conn = urllib.urlopen(url).read()
  112.         parser = MyHTMLParser()
  113.         parser.feed(conn)
  114.         data = parser.result
  115.         data1=data.split('\n')
  116.         for a in data1:
  117.             if 'Latitute:' in a: lat=a.split(':')
  118.             elif 'Longitute:' in a: lon=a.split(':')
  119.         loc_cachequery = (float(lat[1]),float(lon[1]))
  120.         return loc_cachequery
  121.     except: return (None,None)
  122.  
  123. loc_cache={}
  124. def getlocation(address):
  125.     query1=address.replace(' ','+')
  126.     if query1 in loc_cache: return loc_cache[query1]
  127.     url="http://www.cs.indiana.edu/cgi-pub/markane/geo.cgi?address="
  128.     url+=query1
  129.     url+="&click=Geocode!"
  130.     loc_cache[query1] = get_url(url)
  131.     return loc_cache[query1]
  132.  
  133. def milesdistance(a1,a2):
  134.     lat1,long1=getlocation(a1)
  135.     lat2,long2=getlocation(a2)
  136.     if lat1==None or lat2==None or long1==None or long2==None:
  137.         print 'Unable to calculate distance between',a1,"and",a2
  138.         return 0
  139.     latdif=69.1*(lat2-lat1)
  140.     longdif=53.0*(long2-long1)
  141.     return (latdif**2+longdif**2)**0.5
  142.  
  143. def loadnumerical():
  144.     oldrows=loadmatch('matchmaker.csv')
  145.     newrows=[]
  146.     for row in oldrows:
  147.         d=row.data
  148.         data=[float(d[0]),yesno(d[1]),yesno(d[2]),
  149.               float(d[5]),yesno(d[6]),yesno(d[7]),
  150.               matchcount(d[3],d[8]),
  151.               milesdistance(d[4],d[9]),
  152.               row.match]
  153.         newrows.append(matchrow(data))
  154.     return newrows
  155.  
  156. def scaledata(rows):
  157.     low=[999999999.0]*len(rows[0].data)
  158.     high=[-999999999.0]*len(rows[0].data)
  159.     # Find the lowest and highest values
  160.     for row in rows:
  161.         d=row.data
  162.         for i in range(len(d)):
  163.             if d[i]<low[i]: low[i]=d[i]
  164.             if d[i]>high[i]: high[i]=d[i]
  165.  
  166.     # Create a function that scales data
  167.     def scaleinput(d):
  168.        return [(d[i]-low[i])/(high[i]-low[i])
  169.             for i in range(len(low))]
  170.  
  171.     # Scale all the data
  172.     newrows=[matchrow(scaleinput(row.data)+[row.match])
  173.              for row in rows]
  174.  
  175.     # Return the new data and the function
  176.     return newrows,scaleinput
  177.  
  178. def veclength(v):
  179.     return sum([p**2 for p in v])
  180.  
  181. def rbf(v1,v2,gamma=20):
  182.     dv=[v1[i]-v2[i] for i in range(len(v1))]
  183.     l=veclength(dv)
  184.     return math.e**(-gamma*l)
  185.  
  186. def nlclassify(point,rows,offset,gamma=10):
  187.     sum0=0.0
  188.     sum1=0.0
  189.     count0=0
  190.     count1=0
  191.  
  192.     for row in rows:
  193.         if row.match==0:
  194.             sum0+=rbf(point,row.data,gamma)
  195.             count0+=1
  196.         else:
  197.             sum1+=rbf(point,row.data,gamma)
  198.             count1+=1
  199.     y=(1.0/count0)*sum0-(1.0/count1)*sum1+offset
  200.  
  201.     if y>0: return 0
  202.     else: return 1
  203.  
  204. def getoffset(rows,gamma=10):
  205.     l0=[]
  206.     l1=[]
  207.     for row in rows:
  208.         if row.match==0: l0.append(row.data)
  209.         else: l1.append(row.data)
  210.     sum0=sum(sum([rbf(v1,v2,gamma) for v1 in l0]) for v2 in l0)
  211.     sum1=sum(sum([rbf(v1,v2,gamma) for v1 in l1]) for v2 in l1)
  212.  
  213.     return (1.0/(len(l1)**2))*sum1-(1.0/(len(l0)**2))*sum0
Advertisement
Add Comment
Please, Sign In to add comment