我们从Python开源项目中,提取了以下8个代码示例,用于说明如何使用scipy.savetxt()。
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 GenerateMap(stops, fname=None, seed=None): '''Generate a map with "stops" stops for the salesman to traverse. Write coordinates to file if "fname" is specified. Return the distance matrix for all coordinates.''' random.seed(seed) # randomly place stop coordinates in the unit square xs = [random.uniform(0, 1) for x in range(stops)] ys = [random.uniform(0, 1) for x in range(stops)] coords = scipy.array([xs, ys]) # calculate matrix of distances distMat = DistanceMatrix(coords) if fname is not None: scipy.savetxt(fname, coords) return distMat
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
def dump(self, fname): sp.savetxt(fname, self.reference_series)
def saveConfusion(self): """ Open window and save confusion shown in qtableview """ fileName = QFileDialog.getSaveFileName(self.dockwidget, "Select output file",self.lastSaveDir,"CSV (*.csv)") self.rememberLastSaveDir(fileName) fileName,fileExtension=os.path.splitext(fileName) if fileExtension != '.csv': fileName=fileName+'.csv' # save to CSV try : sp.savetxt(fileName,self.lastConfusionMatrix ,delimiter=',',fmt='%1.4d') except : QtGui.QMessageBox.warning(self, 'Missing confusion matrix ? ', 'Cannot save confusion matrix. Are you sure to have generated it before ?', QtGui.QMessageBox.Ok)
def instigator(self, chain, post, saveplace, kplanets): def mk_header(kplanets): h = [] kepler = ['Amplitude ', 'Period ', 'Phase ', 'Longitude ', 'Eccentricity ', 'Minimum Mass ', 'SemiMajor Axis '] telesc = ['Jitter ', 'Offset '] mov_ave = ['MA Coef ', 'Timescale '] for i in range(kplanets): for item in kepler: h.append(item) h.append('Acceleration ') for j in range(self.nins): for item in telesc: h.append(item) for c in range(self.MOAV): h.append(mov_ave[0]+str(c)+' ') h.append(mov_ave[1]+str(c)+' ') for jj in range(self.totcornum): h.append('Stellar Activity'+str(jj)) h = ' '.join(h) return h def savechain(chain): for i in range(self.ntemps): sp.savetxt(saveplace + '/chain_'+str(i)+'.dat', chain[i], header=mk_header(kplanets)) pass def savepost(post): for i in range(self.ntemps): sp.savetxt(saveplace + '/posterior_'+str(i)+'.dat', post[i], header=mk_header(kplanets)) pass savechain(chain) savepost(post) pass