我们从Python开源项目中,提取了以下4个代码示例,用于说明如何使用scipy.genfromtxt()。
def PlotMultipleRuns(Alg, nruns=20, fname=None): '''Plot "nruns" runs of a given algorithm to show performance and variability across runs.''' if fname: runs = scipy.genfromtxt(fname) else: runs = [] for i in range(nruns): bestSol, fitHistory = tsp.TSP(200, Alg, 3000, 30, seed=None, coordfile='tmp.txt') runs.append(fitHistory) fname = 'MultRuns-' + str(Alg) + '.txt' runs = scipy.array(runs) scipy.savetxt(fname, runs) # plotting Xs = scipy.linspace(0, runs.shape[1] * 1000, runs.shape[1]) for i in range(runs.shape[0]): pl.plot(Xs, runs[i, :]) pl.show()
def LongMC3(fname=None): '''Plot a single long MC3 run to demonstrate high performance but slow convergence.''' if fname: run = scipy.genfromtxt(fname) else: bestSol, run = tsp.TSP(200, 'MC3', 20000, 10, seed=None, coordfile='tmp.txt') fname = 'ExampleOutput/MC3-Long.txt' run = scipy.array(run) scipy.savetxt(fname, run) # plotting Xs = range(0, run.shape[0] * 1000, 1000) pl.plot(Xs, run) pl.show()
def LongSA(fname=None): '''Plot a single long SA run to demonstrate performance under slower cooling schedule.''' if fname: run = scipy.genfromtxt(fname) else: bestSol, run = tsp.TSP(200, 'SA', 20000, 'placeholder', seed=None, coordfile='tmp.txt') fname = 'ExampleOutput/SA-Long.txt' run = scipy.array(run) scipy.savetxt(fname, run) # plotting Xs = range(0, run.shape[0] * 1000, 1000) pl.plot(Xs, run) pl.show()
def TSP(stops, Alg, steps, param, seed=None, coordfile='xycoords.txt'): '''A wrapper function that attempts to optimize the traveling salesperson problem using a specified algorithm. If coordfile exists, a preexisting set of coordinates will be used. Otherwise, a new set of "stops" coordinates will be generated for the person to traverse, and will be written to the specified file.''' # Create the distance matrix, which will be used to calculate # the fitness of a given path if os.path.isfile(coordfile): coords = scipy.genfromtxt(coordfile) distMat = DistanceMatrix(coords) else: distMat = GenerateMap(stops, fname=coordfile, seed=seed) if Alg == 'HC': # param is the number of solutions to try per step bestSol, fitHistory = hc.HillClimber(steps, param, distMat, seed) elif Alg == 'SA': # param is a placeholder bestSol, fitHistory = sa.SimulatedAnnealing( steps, param, distMat, seed) elif Alg == 'MC3': # param is the number of chains bestSol, fitHistory = mc3.MCMCMC(steps, param, distMat, seed) elif Alg == 'GA': # param is the population size bestSol, fitHistory = ga.GeneticAlgorithm(steps, param, distMat, seed) else: raise ValueError('Algorithm must be "HC", "SA", "MC3", or "GA".') outfname = coordfile + '-' + Alg + '-' + \ str(steps) + '-' + str(param) + '.txt' scipy.savetxt(outfname, scipy.array(bestSol), fmt='%i') return bestSol, fitHistory