import time
import math
import argparse
import sys
from datetime import timedelta
from pants import World, Edge
from pants import Solver
import csv
import random
import math
import operator
a=b=c=d=e=f=g=h=0
def loadDataset(filename,trainingSet=[],testSet=[]):
with open(filename, 'rt') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
z = len(dataset)-1
for x in range(len(dataset)-2):
for y in range(8,9):
dataset[x][y] = float(dataset[x][y])
trainingSet.append(dataset[x])
for y in range(8,9):
dataset[z][y] = float(dataset[z][y])
testSet.append(dataset[z])
def euclideanDistance(instance1, instance2):
distance = 0
X= (float(instance1[9]) - float(instance2[9])) +(float(instance1[8]) - float(instance2[8]))
distance += pow(X, 2)
return math.sqrt(distance)
def getNeighbors(trainingSet, testInstance, k):
distances = []
for x in range(len(trainingSet)):
dist = euclideanDistance(testInstance, trainingSet[x])
distances.append((trainingSet[x], dist))
distances.sort(key=operator.itemgetter(1))
neighbors = []
for x in range(k):
neighbors.append(distances[x][0])
return neighbors
def main():
trainingSet=[]
testSet=[]
loadDataset('D:\ex.csv', trainingSet, testSet)
print ('Train set: ' + repr(len(trainingSet)))
print ('Test set: ' + repr(len(testSet)))
k = 4
neighbors = getNeighbors(trainingSet, testSet[0], k)
l=m=n=0
print(' Nearest Neighbour is '+a+ ' whose latitude difference is: '+b+ ' and longitude differnce is '+c )
a=neighbors[0][8]
b=neighbors[0][9]
c=neighbors[1][8]
d=neighbors[1][9]
e=neighbors[2][8]
f=neighbors[2][9]
g=neighbors[3][8]
h=neighbors[3][9]
# Real-world latitude longitude coordinates.
TEST_COORDS_33 = [(a, b), (c, d), (e, f), (g,h)]
# 45-45-90 triangle with unit length legs.
TEST_COORDS_3 = [(0, 0), (1, 0), (0, 1)]
# Unit square with diagonals.
TEST_COORDS_4 = [(0, 0), (1, 0), (0, 1), (1, 1)]
# Same as above except with additional node in center of left edge.
TEST_COORDS_5 = [(0, 0), (1, 0), (0, 1), (1, 1), (0, 0.5)]
def dist(a, b):
"""Return the distance between two points represeted as a 2-tuple."""
return math.sqrt((a[1] - b[1]) ** 2 + (a[0] - b[0]) ** 2)
def run_demo(nodes, *args, **kwargs):
world = World(nodes, dist)
solver = Solver(**kwargs)
columns = "{!s:<25}\t{:<25}"
divider = "-" * (25 + 25)
header = columns.format("Time Elapsed", "Distance")
columns = columns.replace('<', '>', 1)
fastest = None
start_time = time.time()
for i, ant in enumerate(solver.solutions(world)):
fastest = ant
fastest_time = timedelta(seconds=(time.time() - start_time))
print(columns.format(fastest_time, ant.distance))
total_time = timedelta(seconds=(time.time() - start_time))
print("Best solution:")
for i, n in zip(fastest.visited, fastest.tour):
print(" {:>8} = {}".format(i, n))
if __name__ == '__main__':
epilog = "\n".join([
'For best results:',
' * 0.5 <= A <= 1',
' * 1.0 <= B <= 5',
' * A < B',
' * L >= 2000',
' * N > 1',
'',
('For more information, please visit '
'https://github.com/rhgrant10/Pants.')
])
parser = argparse.ArgumentParser(
description='Script that demos the ACO-Pants package.',
epilog=epilog,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'-V', '--version',
action='version',
version='%(prog)s 0.5.1',
)
parser.add_argument(
'-a','--alpha',
type=float, default=1,
help='relative importance placed on pheromones; default=%(default)s',
metavar='A'
)
parser.add_argument(
'-b', '--beta',
type=float, default=3,
help='relative importance placed on distances; default=%(default)s',
metavar='B'
)
parser.add_argument(
'-l', '--limit',
type=int, default=100,
help='number of iterations to perform; default=%(default)s',
metavar='L')
parser.add_argument(
'-p', '--rho',
type=float, default=0.8,
help=('ratio of evaporated pheromone (0 <= P <= 1);''default=%(default)s'),
metavar='P'
)
parser.add_argument(
'-e', '--elite',
type=float, default=0.5,
help='ratio of elite ant\'s pheromone; default=%(default)s',
metavar='E'
)
parser.add_argument(
'-q', '--Q',
type=float, default=1,
help=('total pheromone capacity of each ant (Q > 0);''default=%(default)s'),
metavar='Q'
)
parser.add_argument(
'-t', '--t0',
type=float, default=0.01,
help=('initial amount of pheromone on every edge (T > 0); ''default=%(default)s'),
metavar='T'
)
parser.add_argument(
'-c', '--count',dest='ant_count',
type=int, default=10,
help=('number of ants used in each iteration (N > 0); ''default=%(default)s'),
metavar='N'
)
parser.add_argument(
'-d', '--dataset',
type=int, default=33,choices=[3, 4, 5, 33],
help='specify a particular set of demo data; default=%(default)s',
metavar='D'
)
args = parser.parse_args()
nodes = {
3: TEST_COORDS_3 ,
4: TEST_COORDS_4 ,
5: TEST_COORDS_5 ,
33: TEST_COORDS_33
}[args.dataset]
run_demo(nodes, **args.__dict__)
main()
Screenshot Of Error 我正在尝试在数据集上实现knn并使用其结果作为实现蚁群算法的输入,但是由于它们在单独执行时工作完全正常,但是在最后几个小时时我们停留了sincs但是同时实现这两个代码时几乎没有错误。实际上我已经尝试了各种方式,但我无法在我的代码中推断出任何合法的问题。
Traceback (most recent call last):
File "C:/sam.py", line 178, in <module>
main()
File "C:/sam.py", line 49, in main
loadDataset('D:\ex.csv', trainingSet, testSet)
File "C:/sam.py", line 22, in loadDataset
dataset[x][y] = float(dataset[x][y])
IndexError: list index out of range