Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. import math
  2. import matplotlib.pyplot as mplot
  3.  
  4. def kNearestNeighbor(dataPoints, x, y, k):
  5.     distances = {}
  6.    
  7.     # go through each data point and compute distances
  8.     for key in dataPoints.keys():
  9.         dataPoint = dataPoints[key]
  10.         distance = math.sqrt(math.pow(x - float(dataPoint[0]),2) + math.pow(y - float(dataPoint[1]),2))
  11.         distances[distance] = float(dataPoint[2])
  12.    
  13.     total = 0
  14.    
  15.     for key in sorted(distances.keys())[0:k]:
  16.         total += distances[key]
  17.  
  18.     return total//k
  19.        
  20.  
  21. print("Input a k value:")
  22. kVal = input()
  23.  
  24. kVal = int(kVal)
  25.  
  26. usOutline = open("us_outline.csv", "r");
  27. data = open("data.csv", "r");
  28.  
  29. usX = []
  30. usY = []
  31. dataX = []
  32. dataY = []
  33. migration = []
  34.  
  35. migrationTable = {}
  36.  
  37. # draw US outline
  38.  
  39. for line in usOutline:
  40.     coordinates = line.split(",")
  41.    
  42.     xCoord = float(coordinates[0])
  43.     yCoord = float(coordinates[1])
  44.    
  45.     usX.append(xCoord)
  46.     usY.append(yCoord)
  47.    
  48. # create a hash table to look up information for each data point.
  49.    
  50. for line in data:
  51.     line = line.replace("\n",'')
  52.    
  53.     if len(line) != 0:
  54.         locationInfo = line.split(",")
  55.         migrationTable[locationInfo[0] + "," + locationInfo[1]] = locationInfo
  56.  
  57. # perform reconstruction
  58.  
  59. resultX = []
  60. resultY= []
  61. resultValue = []
  62.  
  63. for y in range(121):
  64.     for x in range (195):
  65.         resultX.append(x)
  66.         resultY.append(y)
  67.         point = str(x) + "," + str(y)
  68.        
  69.         if point in migrationTable:
  70.             resultValue.append(migrationTable[point][2])
  71.         else:
  72.             resultValue.append(kNearestNeighbor(migrationTable, x, y, kVal))
  73.        
  74. mplot.plot(usX, usY,'-ok', marker=".")
  75.  
  76. mplot.scatter(resultX, resultY, c=resultValue, cmap="viridis", marker=".")
  77.  
  78. mplot.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement