Advertisement
Guest User

Untitled

a guest
Feb 14th, 2016
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. #coding:utf-8
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import pandas as pd
  5. from scipy.spatial import distance as dis
  6.  
  7. class TSP:
  8. def __init__(self,path=None,n_gene = 256,n_parent = 10,change_ratio = 0.1):
  9. """ 初期化を行う関数 """
  10. self.n_gene = n_gene # 一世代の遺伝子の個数
  11. self.n_parent = 10 # 親として残す個体数
  12. self.change_ratio = change_ratio # 突然変異で変化させる場所の数
  13. if path is not None:
  14. self.set_loc(np.array(pd.read_csv(path)))
  15.  
  16. def init_genes(self,):
  17. """ 遺伝子をランダムに初期化 """
  18. self.genes = np.zeros((self.n_gene,self.n_data),np.int)
  19. order = np.arange(self.n_data)
  20. for i in range(self.n_gene):
  21. np.random.shuffle(order)
  22. self.genes[i] = order.copy()
  23. self.sort()
  24.  
  25. def set_loc(self,locations):
  26. """ 位置座標を設定する関数 """
  27. self.loc = locations # x,y座標
  28. self.n_data = len(self.loc) # データ数
  29. self.dist = dis.squareform(dis.pdist(self.loc)) # 距離の表を作成
  30. self.init_genes() # 遺伝子を初期化
  31.  
  32. def cost(self,order):
  33. """ 指定された順序のコスト計算関数 """
  34. return np.sum( [ self.dist[order[i],order[(i+1)%self.n_data]] for i in np.arange(self.n_data) ] )
  35.  
  36. def plot(self,order=None):
  37. """ 指定された順序でプロットする関数 """
  38.  
  39. if order is None:
  40. plt.plot(self.loc[:,0],self.loc[:,1])
  41. else:
  42. plt.plot(self.loc[order,0],self.loc[order,1])
  43. plt.show()
  44.  
  45. def solve(self,n_step=1000):
  46. """ 遺伝的アルゴリズムで解く関数 """
  47. for i in range(n_step):
  48. print("Generation ... %d, Cost ... %lf" % (i,self.cost(self.genes[0])))
  49. self.step()
  50. self.result = self.genes[0]
  51.  
  52. return self.result
  53.  
  54. def step(self):
  55. """ 遺伝子を一世代分進化させる関数 """
  56. # 突然変異
  57. for i in range(self.n_parent,self.n_gene):
  58. self.genes[i] = self.mutation( np.random.randint(self.n_parent) )
  59. self.sort() # ソートする
  60.  
  61. def sort(self):
  62. """ 遺伝子を昇順にする関数 """
  63. # コストを計算し,ソート
  64. gene_cost = np.array([self.cost(i) for i in self.genes])
  65. self.genes = self.genes[ np.argsort(gene_cost) ]
  66.  
  67. def mutation(self,index):
  68. """ 突然変異を起こした遺伝子を返す関数 """
  69. n_change = int(self.change_ratio * self.n_data)
  70. gene = self.genes[index].copy()
  71.  
  72. for i in range(n_change):
  73. # n_changeの個数だけ値を入れ替える
  74. left = np.random.randint(self.n_data)
  75. right = np.random.randint(self.n_data)
  76.  
  77. temp = gene[left]
  78. gene[left] = gene[right]
  79. gene[right] = temp
  80.  
  81. return gene
  82.  
  83. if __name__=="__main__":
  84. #tsp = TSP(path="input.csv")
  85. tsp.set_loc(np.random.random_sample((30,2)))
  86. tsp.plot()
  87. tsp.solve()
  88. tsp.plot(tsp.result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement