当前位置: 首页>>代码示例>>Python>>正文


Python NN类代码示例

本文整理汇总了Python中NN的典型用法代码示例。如果您正苦于以下问题:Python NN类的具体用法?Python NN怎么用?Python NN使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了NN类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: train

def train(inputs, outputs, size, participants, victors, generations, threshold, cRate, mRate, printFile=False):
    '''Create and start training the NN via evolution strategy. Selection, crossover, mutation, evaluation.''' 
    global hero
    global OrigAnswers
    OrigAnswers = copy.deepcopy(outputs)
    EvaluationNN = GA.create_net(inputs, outputs)
    population = init_pop(EvaluationNN, inputs, outputs, size)
    # Test each citizen and determine initial fitness
    GA.evaluate(EvaluationNN, population, inputs, outputs)

    if printFile: f = open('ES.csv', 'w')
    gen = 0
    children = []
    # loop until a hero is found or we've reached max generations
    while gen <= generations and hero == 0:
        # Select our parents using tournament selection
        parents = GA.tournament(population, participants, victors)
        # Have our parents mate (Crossover)
        children = GA.mate(parents, cRate)
        # Have the children experience the world (Mutate)
        for child in children:
            mutate(child, mRate)
        # Test each child's fitness
        GA.evaluate(EvaluationNN, children, inputs, outputs)
        children = GA.tournament(children, participants, victors)
        population = sorted(population + children,
                            key=itemgetter(-1))[:-victors]
        if GA.heroFound(population, threshold):
            break
        else:
            print("Training: {:2.2%}".format(
                population[0][-1]), "{:2.2%}     ".format(gen / generations), end="\r")
            if printFile: f.write('%f,' % population[0][-1])
            if printFile: f.write('\n')
        gen += 1
    if printFile: f.close()
    if hero == 0:
        gen -= 1
        hero = sorted(population, key=itemgetter(-1))[0]
    EvaluationNN.SetNNWeights(hero[:-1])  # Load hero into NN, prep for usage.

    # Evaluate the hero on the inputs and outputs
    print('Generations: %d' % gen, ' ' * 20)
    print("Error Relative: {:2.5%}".format(NN.calcRelativeError(EvaluationNN, inputs, OrigAnswers)))
    print("Least Squares: %d" % NN.calcLeastSquaresError(EvaluationNN, inputs, OrigAnswers))
    print("Loss Squared: %d" % NN.calcLossSquared(EvaluationNN, inputs, OrigAnswers))
    #for x in inputs:
    #    EvaluationNN.SetStartingNodesValues(x)
    #    EvaluationNN.CalculateNNOutputs()
    #    print(x, EvaluationNN.GetNNResults(), EvaluationNN.GetNNResultsInt(), OrigAnswers[inputs.index(x)])
    print()

    return EvaluationNN
开发者ID:Keydrain,项目名称:CSCI447-2015,代码行数:53,代码来源:ES.py

示例2: start_thread

def start_thread(inp, activation, out_activ, outp, learn, thresh, mmntm, logger):
    global count
    training_inputs = []
    training_data = []
    count += 1
    print(out_activ)
    testNN = NN.main(inp, activation, out_activ, outp, learn, thresh, mmntm)
    print("DONE TRAINING")
    for i in inp:
        for j in i:
            training_inputs.append(random.randint(0, 4))  # create random inputs for testing
        training_data.append(training_inputs)
        training_inputs = []
    logger.info("ACTIVATION SET: ")
    logger.info(activation)
    logger.info("OUTPUT ACTIVATION: %s" % out_activ)
    logger.info("TESTING INPUT: ")
    logger.info(training_data)
    logger.info("OUTPUT: ")
    for x in training_data:
        testNN.SetStartingNodesValues(x)
        testNN.CalculateNNOutputs()
        logger.info(str(x))
        logger.info(testNN.GetNNResults())
        logger.info("RB OUTPUT: %s" % rb_test.rb_test(x))
开发者ID:Keydrain,项目名称:CSCI447-2015,代码行数:25,代码来源:2-1-handler.py

示例3: evaluate

def evaluate(NNWorking, population, inputs, outputs):
    '''Tests each citizen in the population against a NN topology with inputs
    and outputs to generate an cumulitive fitness measurement, which should be
    minimized'''
    for citizen in population:
        citizen[-1] = 0
        NNWorking.SetNNWeights(citizen[:-1])  # Load weights into the NN
        for i in range(len(inputs)):
            NNWorking.SetStartingNodesValues(inputs[i])  # Load inputs into NN
            NNWorking.CalculateNNOutputs()  # Run the NN once
            # Calculate the fitness value and let the citizen track it
            # for j in range(len(NN.GetNNResults())):
            #    citizen[-1] += ((outputs[i][j] - NN.GetNNResults()[j]))**2
            citizen[-1] += NN.calcRelativeError(NNWorking,
                                                inputs, outputs) / len(inputs)
开发者ID:Keydrain,项目名称:CSCI447-2015,代码行数:15,代码来源:GA.py

示例4: start_thread

def start_thread(inp, activation, out_activ, outp, learn, thresh, mmntm, logger):
    global count
    training_inputs = []
    training_data = []
    count += 1
    
    testNN = NN.main(inp, activation, out_activ, outp, learn, thresh, mmntm)
    print ("DONE TRAINING")
    for i in inp:
        for j in i:
            training_inputs.append(random.randint(0,4)) #create random inputs for testing
        training_data.append(training_inputs)
        training_inputs = []
    for x in training_data:
        testNN.SetStartingNodesValues(x)
        testNN.CalculateNNOutputs()
        logger.info(str(x))
        logger.info(testNN.GetNNResults())
开发者ID:Keydrain,项目名称:CSCI447-2015,代码行数:18,代码来源:handler_NN.py

示例5: train

def train(inputs, outputs, size, participants, victors,
          generations, threshold, cRate, mRate, printFile=False):
    '''The train method takes in a set of inputs and outputs which will be
    compared against a hardcoded NN topology. The size, participants, and
    victors are with regard to tournament selection and elitism selection
    techniques. Generations is the max number of generations allowed while
    threshold is the accuracy needed. cRate and mRate are the rate of
    crossover and rate of mutation respectively. '''
    global hero
    global OrigAnswers
    EvaluationNN = create_net(inputs, outputs)
    population = generatePopulation(EvaluationNN, inputs, outputs, size)
    # Test each citizen and determine initial fitness
    evaluate(EvaluationNN, population, inputs, outputs)
    if printFile: f = open('GA.csv', 'w')
    gen = 0
    children = []
    # loop until a hero is found or we've reached max generations
    while gen <= generations and hero == 0:
        # Select our parents using tournament selection
        parents = tournament(population, participants, victors)
        # Have our parents mate (Crossover)
        children = mate(parents, cRate)
        # Have the children experience the world (Mutate)
        for child in children:
            mutate(child, mRate)
        # Test each child's fitness
        evaluate(EvaluationNN, children, inputs, outputs)
        # We were to prolific, thus children must fight to the death via draft
        # call. Make participants len(children) to have all of them fight
        # This might not be a good idea as late generation counts result in not
        # keeping the children.
        children = tournament(children, participants, victors)
        # purging of population is determined by elitism inverted on fitness
        # level (cowardace is greater number).
        # Take number of children equal to number of tournament victors and
        # reintroduce to the population
        population = sorted(population + children,
                            key=itemgetter(-1))[:-victors]
        # Determine if a child is a hero (<threshold) and if so, return child
        if heroFound(population, threshold):
            break
        else:
            print("Training: {:2.2%}".format(
                population[0][-1]), "{:2.2%}     ".format(gen / generations), end="\r")
            if printFile: f.write('%f,' % population[0][-1])
            if printFile: f.write('\n')
        gen += 1
    # return best hero if max generations is met and hero hasn't been selected.
    if printFile: f.close()
    if hero == 0:
        gen -= 1
        hero = sorted(population, key=itemgetter(-1))[0]
    EvaluationNN.SetNNWeights(hero[:-1])  # Load hero into NN, prep for usage.

    # Evaluate the hero on the inputs and outputs
    print('Generations: %d' % gen, ' ' * 20)
    print("Error Relative: {:2.5%}".format(NN.calcRelativeError(EvaluationNN, inputs, OrigAnswers)))
    print("Least Squares: %d" % NN.calcLeastSquaresError(EvaluationNN, inputs, OrigAnswers))
    print("Loss Squared: %d" % NN.calcLossSquared(EvaluationNN, inputs, OrigAnswers))
    #for x in inputs:
    #    EvaluationNN.SetStartingNodesValues(x)
    #    EvaluationNN.CalculateNNOutputs()
    #    print(x, EvaluationNN.GetNNResults(), EvaluationNN.GetNNResultsInt(), OrigAnswers[inputs.index(x)])
    print()

    return EvaluationNN
开发者ID:Keydrain,项目名称:CSCI447-2015,代码行数:67,代码来源:GA.py

示例6: len

    sample_dirs.sort()
    if nsmpl != len(sample_dirs):
        print '{0:*>20}: num_samples in in.fitpot is wrong.'.format(' Error')
        exit()
    read_pos()

    #.....initial data
    gather_ref_data(maindir)
    #.....read bases data if needed
    if potential in ('linreg') and not fmethod in ('test','TEST'):
        read_bases(maindir)
        if regularize:
            vars= scale_vars(vars,bmax)
    elif potential in ('NN') and not fmethod in ('test','TEST'):
        NN.init(maindir,params,sample_dirs,samples,nprcs,fmatch \
                ,ergrefs,frcrefs,fmethod,parfile,runmode,rcut,pranges \
                ,vranges)

    #.....1st call of func
    func(vars,maindir)
    if potential in ('linreg') and not fmethod in ('test','TEST'):
        ergs,frcs= calc_ef_from_bases(vars,maindir)
    elif potential in ('NN') and not fmethod in ('test','TEST'):
        ergs,frcs= NN.calc_ef_from_bases(vars)
    else:
        ergs,frcs= gather_smd_data(maindir)

    if fmethod in ('test','TEST') and potential in ('NN'):
        NN.init(maindir,params,sample_dirs,samples,nprcs,fmatch \
                ,ergrefs,frcrefs,fmethod,parfile,runmode \
                ,rcut,pranges,vranges)
开发者ID:,项目名称:,代码行数:31,代码来源:

示例7: func

def func(x,*args):
    """evaluate function L=sum_{samples}[E(pmd)-E(ref)]^2.
    
    This will be called from scipy.optimize.fmin_cg().
    The 1st argument x should be 1-D array of variables.
    """
    global _valmin
    
    t0= time.time()
    #.....write parameters to in.params.????? file
    dir= args[0]

    if fmethod in ('test','TEST','check_grad') or \
       not potential in ('linreg','NN'):
        #.....store original file
        os.system('cp '+dir+'/'+parfile+' '+dir+'/'+parfile+'.tmp')
        write_params(dir+'/'+parfile,x)
        #.....run smd in all sample directories
        os.chdir(dir)
        #print os.getcwd(),dir
        if runmode in ('serial','Serial','SERIAL','sequential','single'):
            os.system('./serial_run_smd.sh '+parfile)
        elif runmode in ('parallel','Parallel','PARALLEL'):
            os.system('python ./parallel_run_smd.py '+parfile)
        else:
            print "{0:*>20}: no such run_mode !!!".format(' Error', runmode)
            exit()
        os.chdir(cwd)
        #.....restore original file
        os.system('cp '+dir+'/'+parfile+' '+dir+'/'+parfile+'.current')
        os.system('cp '+dir+'/'+parfile+'.tmp'+' '+dir+'/'+parfile)
        #.....gather smd results
        ergs,frcs=gather_smd_data(dir)
    elif potential in ('linreg'):
        #.....calc ergs and frcs from bases data and x (variables)
        read_bases(dir)
        ergs,frcs=calc_ef_from_bases(x,*args)
    elif potential in ('NN'):
        #.....now it is possible to compute only from bases
        ergs,frcs= NN.calc_ef_from_bases(x,*args)

    #.....calc function value of L
    val= eval_L(ergs,frcs,ergrefs,frcrefs,samples)
    #.....output temporal results
    output_energy_relation(ergs,ergrefs,samples,sample_dirs, \
                               fname='out.erg.pmd-vs-dft.tmp')
    output_force_relation(frcs,frcrefs,samples,sample_dirs, \
                              fname='out.frc.pmd-vs-dft.tmp')

    print
    print ' L value=',val

    if penalty in ('ridge','Ridge','RIDGE') and potential in ('linreg'):
        p= 0.0
        lx= len(x)
        for n in range(lx):
            p += math.sqrt(x[n]**2)
        print ' penalty value=',p*pweight
        val += p*pweight
        print ' total L value=',val

    elif penalty in ('lasso','LASSO') and potential in ('linreg'):
        p= 0.0
        lx= len(x)
        for n in range(lx):
            p += abs(x[n])
        print ' penalty value=',p*pweight
        val += p*pweight
        print ' total L value=',val
    sys.stdout.flush()

    #.....if L value is minimum ever, store this parameter file
    if val < _valmin:
        _valmin= val
        if potential in ('linreg','NN'):
            write_params(dir+'/'+parfile+'.min',x)
        else:
            os.system('cp '+dir+'/'+parfile+'.current' \
                          +' '+dir+'/'+parfile+'.min')
        
    print ' ===> time func: {0:12.3f} sec'.format(time.time()-t0) \
          +', {0:12.3f} sec'.format(time.time()-_init_time)
    return val
开发者ID:,项目名称:,代码行数:83,代码来源:

示例8: predictPollution

import weather
import NN as nn 
get_pm5_prediction = nn.setup()
# SAMPLE usage, Delete before using it as library
def predictPollution(precipitation_prob, relative_humidity, temp, wind_direction, wind_speed):
    O3PreictedVal = 5.03704930e+01 + (precipitation_prob * 9.66895471e-02) + (relative_humidity * -2.99780572e-03) + (temp * -2.26017118e-01) + (wind_direction * -8.96663780e-03) + (wind_speed *  9.98339351e+00)
    PM25PredictedVal = 1.36006991e+01 +  (temp * -9.32461073e-02)  +   (wind_direction * -3.35510810e-04) +   (wind_speed * -7.50369156e-01)
    nnPrediction = get_pm5_prediction(TMP = temp,WDIR = wind_direction,WSPD = wind_speed)
    #3.6 is average
    if abs(nnPrediction - PM25PredictedVal) > 7.2:
        if abs(nnPrediction - 3.6) > abs(PM25PredictedVal - 3.6):
            return O3PreictedVal, PM25PredictedVal
        else:
            return O3PreictedVal, nnPrediction
    return O3PreictedVal, (nnPrediction + PM25PredictedVal)/2
        
    
def pollutionAPi(lat, lon, offset):
    return predictPollution(*weather.get_weather(lat, lon, offset))

#offset -> [0,2], 0 means now, 1 means one hour from now, and 2 means 2 hour from now
print pollutionAPi(51.0123, 0.3, 0)
开发者ID:davidbuniat,项目名称:luftwagen-ml,代码行数:22,代码来源:pollutionApi.py

示例9: NN

#################################################  
# Title  : Male or Female?
# Method : Back-Propagation Neural Networks
# Author : yang xiaolong  
#################################################  


from NN import *
from autonorm import* 
import time  
  
startTime = time.time()   
# create a network with two input, one hidden, and one output nodes
n = NN(2, 1, 1)
opts = {'iterations': 50, 'learning rate': 0.25, 'momentum factor': 0.1} 
def loadData():  
    te=[];te_x=[];te_y=[]
    fileIn = open('data.txt')  
    for line in fileIn.readlines():  
        lineArr = line.strip().split()  
        te_x.append([float(lineArr[0]),float(lineArr[1])])
        te_y.append([float(lineArr[2])])
        te.append([[float(lineArr[0]),float(lineArr[1])],[float(lineArr[2])]])
    return te_x,te_y,te

tex,tey,te= loadData()
tex1=AutoNorm(tex)
tey1=tey
te1=[]
for i in range(len(tex1)):
    te1.append([tex1[i],tey1[i]])
开发者ID:Glasssix,项目名称:Notes,代码行数:31,代码来源:main_NN.py

示例10: train

def train(inputs, outputs, size, generations, threshold, cRate, mRate, printFile=False):
    """The train method creates a neural netwrok from the sets of 
    inputs and outputs. A population vector of size, is initialized 
    with ranodm weight vectors associated with the weights between 
    nodes in the neural network and will be the values being trained.
    Generations is the max number of generations allowed while 
    threshold is the accuracy needed. cRate and mRate are the 
    crossover and mutation rates respectively."""
    global hero
    global OrigAnswers

    OrigAnswers = copy.deepcopy(outputs)
    # set up NN
    EvaluationNN = GA.create_net(inputs, outputs)

    # initialize population of size as random weights of NN
    population = GA.generatePopulation(EvaluationNN, inputs, outputs, size)

    if printFile:
        f = open("DE.csv", "w")
    gen = 0
    trialV = []
    offspringV = []

    # evaluate the entire population
    GA.evaluate(EvaluationNN, population, inputs, outputs)

    # loop until a hero is found or we've reached max generations
    while gen <= generations and hero == 0:
        for i in range(size):
            # mutate with DE/x/1/bin
            trialV = mutate(population, i, mRate)
            # perform binomial crossover
            offspringV = crossover(population[i], trialV, cRate)
            # evaluation of offspring
            GA.evaluate(EvaluationNN, [offspringV], inputs, outputs)
            # selection of better vector
            if population[i][-1] > offspringV[-1]:
                population[i] = offspringV
        population = sorted(population, key=itemgetter(-1))
        # check for hero in population
        if GA.heroFound(population, threshold):
            break
        else:
            print("Training: {:2.2%}".format(population[0][-1]), "{:2.2%}     ".format(gen / generations), end="\r")
            if printFile:
                f.write("%f," % population[0][-1])
            if printFile:
                f.write("\n")
        gen += 1
    # return best hero if max generations is met and hero hasn't been selected.
    # hero = sorted(population, key=itemgetter(-1))[0]  # default to best in
    # population if no hero steps forward
    if printFile:
        f.close()
    if hero == 0:
        gen -= 1
        hero = sorted(population, key=itemgetter(-1))[0]
    EvaluationNN.SetNNWeights(hero[:-1])  # Load hero into NN, prep for usage.

    # Evaluate the hero on the inputs and outputs
    print("Generations: %d" % gen, " " * 20)
    print("Error Relative: {:2.5%}".format(NN.calcRelativeError(EvaluationNN, inputs, OrigAnswers)))
    print("Least Squares: %d" % NN.calcLeastSquaresError(EvaluationNN, inputs, OrigAnswers))
    print("Loss Squared: %d" % NN.calcLossSquared(EvaluationNN, inputs, OrigAnswers))
    # for x in inputs:
    #    EvaluationNN.SetStartingNodesValues(x)
    #    EvaluationNN.CalculateNNOutputs()
    #    print(x, EvaluationNN.GetNNResults(), EvaluationNN.GetNNResultsInt(), OrigAnswers[inputs.index(x)])
    print()

    return EvaluationNN
开发者ID:Keydrain,项目名称:CSCI447-2015,代码行数:72,代码来源:DE.py

示例11: NN2board

    return tmp

'''
Convert neural network data to game situation.
'''
def NN2board(li):
    tmp = ["X" if x==1 else ("O" if x==-1 else " ") for x in li]
    tmp = np.array(tmp)
    tmp.shape = (7,6)
    tmp = tmp.T
    return tmp

################################################################

try:
    nn = NN.openNN()
    print "NN successfully opened"

except:
    print "not able to open NN"
    print "create new one"

    inp = []
    out = []

    fobj = open("database.txt")
    counter=0

    for line in fobj:
        #print line.rstrip()
        #displayStr(line.rstrip())
开发者ID:ajendrosch,项目名称:connect-4,代码行数:31,代码来源:NN4Connect4.py

示例12: open

trainingdatafile = open('newdata.txt', 'r')

inputdata= readRecords(trainingdatafile)
datasize = len(inputdata)

# Randomly splits the file in 80-20 split for test and train data
trainingbatch , testbatch = train_test_split(inputdata, test_size=0.2)

# Values for the no of hidden, input and output neurons
numHiddenCells = 64
numInputCells = 9
numOutputCells = len(inputdata[0]) - numInputCells


nn = NN.neuralNet(numInputCells, numHiddenCells, numOutputCells)

errTrain = nn.train(trainingbatch)
errPred = 0

for test in testbatch:
	output = nn.predict(test[:numInputCells])
	#print output, np.argmax(test[numInputCells:]) + 1
	if (output != np.argmax(test[numInputCells:]) + 1) :
		errPred =  errPred + 1

print errTrain, len(trainingbatch)
print errPred, len(testbatch)


开发者ID:swatzgarg,项目名称:NeuralNet,代码行数:27,代码来源:runner.py

示例13: range

                #interneuron
                NN.Matrix([5,1],[5,1],sigmaR=sigmaR),
                NN.Addition([5,1],sigmaR=sigmaR),
                NN.ComponentwiseFunction(),
                # interneuron 2
                NN.Matrix([5,1],[5,1],sigmaR=sigmaR),
                NN.Addition([5,1],sigmaR=sigmaR),
                NN.ComponentwiseFunction(),
                # output
                #Matrix([5,1],[2,1],sigmaR=sigmaR),
                #Addition([2,1],sigmaR=sigmaR) 
                NN.Matrix([5,1],[3,1],sigmaR=sigmaR),
                NN.Addition([3,1],sigmaR=sigmaR) 
                ])
# a nice simple interface
nn = NN.makeStandardNeuralNet(inputDim=2,outputDim=3,interDim=20,nInter=5,sigmaR=sigmaR)
# simple training set in 2D
n = 100
x = np.zeros([2,1,n])
z = np.zeros([2,1,n])
for i in range(n):
    off = np.random.rand() > 0.5
    x[:,:,i] = np.random.randn(2,1) + off*3
    z[0,:,i] = float(off)
    z[1,:,i] = 1.0 - float(off)
    
n = 200
x = np.zeros([2,1,n])
z = np.zeros([3,1,n])
for i in range(n):
    category = np.random.randint(3)
开发者ID:dtward,项目名称:NeuralNets,代码行数:31,代码来源:test1.py

示例14: train_test

def train_test():
    global cRate, mRate, threshold, generations, size, participants, victors, inFile, algo, dataset, resultsFile
    inputs = []
    outputs = []
    evolve()
    
    resultsFile.write("DATASET: " + dataset + "\n")
    #resultsFile.write("ALGORITHM | Generations | Size | Participants | Victors | mRate | cRate | Threshold \n")
    #resultsFile.write("   " + str(algo) + "      |     " + str(generations) + "      |  " +
    #          str(size) + "  |     " + str(participants) + "       |    " + str(victors) + 
    #          "    |  " + str(mRate) + "  |  " + str(cRate) + "  |   " + str(threshold) + "     \n")

    dataIn = dataHandler()
    inputs = dataIn[0]
    outputs = dataIn[1]
    testInput = []
    testOutput = []
    learnrate = 0.3
    momentum = 0.5
    # Need 20% of inputs for testing
    for i in range((int(len(inputs)*0.8)+1), len(inputs)):
        x = random.choice(inputs)
        testInput.append(x)
        testOutput.append(outputs[inputs.index(x)])
        del outputs[inputs.index(x)]
        del inputs[inputs.index(x)]
    resultsFile.write("\nTest inputs: \n")
    for i in range(len(testInput)):
        resultsFile.write("%s " % testInput[i])
    resultsFile.write("\nTest expected outputs: \n")
    for i in range(len(testOutput)):
        resultsFile.write("%s " % testOutput[i])
    # Which algorithm gets chosen to run
    if algo in 'G':
        print("DOING GA TRAINING...")
        resultsFile.write("\nALGORITHM | Generations | Size | Participants | Victors | mRate | cRate | Threshold \n")
        resultsFile.write("   " + str(algo) + "      |     " + str(generations) + "      |  " + str(size) + "  |     " + str(participants) + "       |    " + str(victors) + "    |  " + str(mRate) + "  |  " + str(cRate) + "  |   " + str(threshold) + "     \n")
        testNN = GA.train(inputs, outputs, size, participants, victors, generations, threshold, cRate, mRate)
    elif algo in 'E':
        print("DOING ES TRAINING...")
        resultsFile.write("\nALGORITHM | Generations | Size | Participants | Victors | mRate | cRate | Threshold \n")
        resultsFile.write("   " + str(algo) + "      |     " + str(generations) + "      |  " + str(size) + "  |     " + str(participants) + "       |    " + str(victors) + "    |  " + str(mRate) + "  |  " + str(cRate) + "  |   " + str(threshold) + "     \n")
        testNN = ES.train(inputs, outputs, size, participants, victors, generations, threshold, cRate, mRate)
    elif algo in 'D':
        print("DOING DE TRAINING...")
        resultsFile.write("\nALGORITHM | Generations | Size | mRate | cRate | Threshold \n")
        resultsFile.write("   " + str(algo) + "      |     " + str(generations) + "      |  " +  str(size) + "    |  " + str(mRate) + "  |  " + str(cRate) + "  |   " + str(threshold) + "     \n")
        testNN = DE.train(inputs, outputs, size, generations, threshold, cRate, mRate)
    elif algo in 'B':
        print("DOING BP TRAINING...")
        resultsFile.write("\nALGORITHM | Generations | learnrate | momentum | Threshold \n")
        resultsFile.write("   " + str(algo) + "      |     " + str(generations) + "      |  " + str(learnrate) + "  |  " + str(momentum) + "  |   " + str(threshold) + "     \n")
        testNN = NN.main(inputs, [['S','S','S'], ['S','S']], ['S'], outputs, generations, learnrate, threshold, momentum)
    else:
        print("Unrecognized algorithm!")
        sys.exit()
    # Print test input/expected output - could be made prettier in a table
    # Start testing testNN
    for x in testInput:
        resultsFile.write("\nSet starting node vals\n")
        resultsFile.write("%s \n" % testNN.SetStartingNodesValues(x))
        testNN.CalculateNNOutputs()
        resultsFile.write("\nTest Input: " + str(x) + "\n")
        resultsFile.write("\nTest results: %s\n" % testNN.GetNNResults())
    resultsFile.write("\nRelative Error: {:2.2%} \n".format(NN.calcRelativeError(testNN, testInput, testOutput)))
    resultsFile.write("\nLeast Squares Error: %s \n" % NN.calcLeastSquaresError(testNN, testInput, testOutput))
    resultsFile.write("\nLoss Squared Error: %s \n" % NN.calcLossSquared(testNN, testInput, testOutput))
    resultsFile.write("\nPercent Misidentified: {:2.2%} \n".format(NN.calcPercentIncorrect(testNN, testInput, testOutput)))
    resultsFile.close()
开发者ID:Keydrain,项目名称:CSCI447-2015,代码行数:69,代码来源:handler.py

示例15: print

  print('Attempting to open {}.'.format(filename))
  im = readImage(filename)
  if (max(im.size) > 600):
    im = im.resize((int(600*(float(im.size[0])/max(im.size))), int(600*(float(im.size[1])/max(im.size)))))
  print('Opened.')

  print('Attempting to stipple...')
  cellSize = 2

  # Create a stippled version of the image; limit 6000 px.
  lst = stipple(im, cellSize, 0)
  while (len(lst) > 6000):
    cellSize += 1
    lst = stipple(im, cellSize, 0)
  lst = stipple(im, cellSize, 8)
  print('There are {} points.'.format(len(lst)))
  print('Stippled!')

  print('Attempting TSP with naive NN...')
  lst = NN.tsp(lst)

  print('Now converting to list of segments...')
  segSet = createSegSet(lst)

  ## Let's make sure all of our segments share a point...
  print('Correcting any overlaps...')
  drawSegSet(segSet, im.size, 'start.jpg')
  segSet = correct(segSet, im)
  drawSegSet(segSet, im.size, 'end.jpg')
  print('Done.')
开发者ID:apnorton,项目名称:tsp-art,代码行数:30,代码来源:TSPArt.py


注:本文中的NN类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。