导入GeneticAlgorithm ModuleNotFoundError:没有名为'libs.GeneticAlgorithm'的模块

时间:2019-02-24 22:07:25

标签: python genetic-algorithm traveling-salesman

我一直在尝试运行找到的代码,但出现这种错误。我不知道该如何处理,因为我是python的新手,正试图了解TSP问题的概念。 任何帮助,将不胜感激 下面的代码

from libs.GeneticAlgorithm import GeneticAlgorithm

def main():
    poland = Country()
    poland.add([
        City('Gorlice', (49.655299, 21.159769)),
        City('Sosnowiec', (50.286263, 19.104078)),
        City('Łódź', (51.760229, 19.457209)),
        City('Wrocław', (51.108314, 17.037802)),
        City('Poznań', (52.406376, 16.925167)),
        City('Toruń', (53.013790, 18.598444)),
        City('Zielona Góra', (51.935619, 15.506186)),
        City('Szczecin', (53.428543, 14.552812)),
        City('Rzeszów', (50.041187, 21.999121)),
        City('Kraków', (50.049683, 19.944544)),
        City('Olsztyn', (53.770226, 20.490189)),
        City('Lublin', (51.245376, 22.568278))
    ])
    print('Cities:', end=' ')
    print(*(city for city in poland.cities), sep=', ')
    ga = GeneticAlgorithm(100, mutation_rate=0.5, ptype=Route, args=(poland.cities,))
    ga.run(seconds=10)
    fittest = ga.alltime_best
    best_fitness = fittest.fitness
    print('Best route:', fittest)
    print('Best fitness:', best_fitness)
    print('Generations:', ga.generation)


if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:1)

如果您“找到”了此代码(很可能是在互联网上找到的),那么发布此代码的人的计算机中就有一个libs文件夹,其中包含一个GeneticAlgorhythm.py模块,因此您要么找到此GeneticAlgorhythm模块,否则您将无法成功运行此代码。

看到的话,在python from baz.bar import Foo中,Python将在bar文件夹中寻找baz模块,并从其中导入类Foo。因此,您需要在PC上安装baz模块,否则该错误就会出现

答案 1 :(得分:1)

它来自以下存储库:https://github.com/reconndev/Genetic-Algorithm-TSP。为了使其运行,只需克隆或下载存储库。然后,在主(根)文件夹中,运行python TSP-Text.py

python TSP-Text.py 
Cities: Gorlice, Sosnowiec, Łódź, Wrocław, Poznań, Toruń, Zielona Góra, Szczecin, Rzeszów, Kraków, Olsztyn, Lublin
Best route: Toruń->Olsztyn->Łódź->Lublin->Rzeszów->Gorlice->Sosnowiec->Kraków->Wrocław->Zielona Góra->Szczecin->Poznań
Best fitness: 0.4219619417258425
Generations: 807