def Thickness(power, ref_front, index, min_blank, f1_sag, thick, minthickness): nameArray = ['<td>CR-39</td>', '<td>Trivex</td>', '<td>Spectralite</td>', '<td>Polycarbonate</td>', '<td>MR-6</td>', '<td>MR-8</td>', '<td>MR-7</td>', '<td>MR-10</td>', '<td>MR 174</td>'] ref_back = power - ((ref_front)/(1 - (((thick/1000)/index))*ref_front)) f2_radius = ((1-index)/ref_back)*1000 f2_sag = f2_radius - (sign(f2_radius) * math.sqrt(math.pow(f2_radius,2) - math.pow(min_blank,2))) #'ref back ' + str(ref_back) f1_radius = ((index - 1)/ref_front)*1000 #def weight(f1_sag, r_1,f2_sag, r_2, min_blank, et ) if power > 0: #print 'CT: ' + str(f1_sag - f2_sag + minthickness) + '\n' + 'ET: ' + str(minthickness) ct = f1_sag - f2_sag + minthickness et = minthickness ct = round(ct, 2) et = round(et, 2) #thickArray.insert(0,et) #thickArray.insert(1, ct) aweight = weight.weight(f1_sag, f1_radius, f2_sag, f2_radius, min_blank, et, index) htmlString = "<td>" + str(index) + " heD</td><td>" + str(et) + " mm</td><td>" + str(ct) + " mm</td><td>" + str(aweight) + " grams</td>" return htmlString else: #print 'ET: ' + str(f2_sag - f1_sag + minthickness) + '\n' + 'CT: ' + str(minthickness) ct = minthickness et = f2_sag - f1_sag + minthickness #thickArray.insert(0,et) #thickArray.insert(1, ct) #return lens_thick #return "<h2>Edge Thickness </h2>" + str(et) + "<br>" + "<h2>Center Thickness </h2>" + str(ct) aweight = weight.weight(f1_sag, f1_radius, f2_sag, f2_radius, min_blank, et, index) htmlString = "<td>" + str(index) + " heD</td><td>" + str(et) + " mm</td><td>" + str(ct) + " mm</td><td>" + str(aweight) + " grams</td>" return htmlString i = i + 1
def init_weights(self): self.net += [ weight(65536) ] # feature for line [0 1 2 3] includes 16*16*16*16 possible self.net += [ weight(65536) ] # feature for line [4 5 6 7] includes 16*16*16*16 possible return
def init_weights(self): self.net += [ weight(16**6) ] # feature for line [0 1 4 5 8 9] includes 16*16*16*16*16*16 possible self.net += [ weight(16**6) ] # feature for line [1 2 5 6 9 10] includes 16*16*16*16*16*16 possible self.net += [ weight(16**6) ] # feature for line [2 6 10 9 14 13] includes 16*16*16*16*16*16 possible self.net += [ weight(16**6) ] # feature for line [3 7 11 10 15 14] includes 16*16*16*16*16*16 possible return
def init_weights(self): self.net += [ weight(16**6) ] # feature for line [0, 1, 2, 3, 4, 5] includes 16*16*16*16 possible self.net += [ weight(16**6) ] # feature for line [4, 5, 6, 7, 8, 9] includes 16*16*16*16 possible self.net += [ weight(16**6) ] # feature for line [0, 1, 2, 4, 5, 6] includes 16*16*16*16 possible self.net += [ weight(16**6) ] # feature for line [4, 5, 6, 8, 9, 10] includes 16*16*16*16 possible self.feature_idx = [[0, 1, 2, 3, 4, 5], [4, 5, 6, 7, 8, 9], [0, 1, 2, 4, 5, 6], [4, 5, 6, 8, 9, 10]] return
def __init__(self, options=""): super().__init__(options) self.net = [] self.tuple_list = [ [0, 1, 2, 3], # 4 rows [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [0, 4, 8, 12], # 4 column [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [0, 1, 4, 5], # 9 cube [1, 2, 5, 6], [2, 3, 6, 7], [4, 5, 8, 9], [5, 6, 9, 10], [6, 7, 10, 11], [8, 9, 12, 13], [9, 10, 13, 14], [10, 11, 14, 15] ] load = self.property("load") if load is not None: self.load_weights(load) else: for _ in range(len(self.tuple_list)): self.net += [weight(65536)] return
def load_weights(self, path): input = open(path, 'rb') size = array('L') size.fromfile(input, 1) size = size[0] for i in range(size): self.net += [weight()] self.net[-1].load(input) return
def init_weights(self): self.net += [weight(16777216)]*4 self.tuples.append([0,1,2,3,4,5]) self.tuples.append([4,5,6,7,8,9]) self.tuples.append([0,1,2,4,5,6]) self.tuples.append([4,5,6,8,9,10]) self.len_tuples = len(self.tuples) return
def __init__(self, day_temp, night_temp, water_times): self.day_temp = day_temp self.night_temp = night_temp self.water_times = water_times self.light = 1 self.ac = 0 self.water = 1 self.weight = weight.weight() self.minute = datetime.datetime.now().minute self.counter = datetime.datetime.now().hour self.temp = temperature.temp(1, 10, 3.3) #Error checking to confirm plant isn't over watered if (self.water_times > 18): print "Error too many watering times" self.water_times = 18 self.water_shift = 18 / self.water_times output.light(self.light) output.water(self.water) output.ac(self.ac)
def init_weights(self, info): for i in info.split(','): # comma-separated sizes, e.g., "65536,65536" self.net += [weight(int(i))] return
def train(path, weightPath1, weightPath2, hiddenNodes, epochs, learningRate, proceed): # read sequences and their measured binding affinities allSequences, allTargets = fileUtils.readHLA(path) # log transform the data to fit between 0 and 1 allTargets = logTransform.transform(allTargets) # divide the data into training set, validation set and evaluation set numOfSequences = len(allSequences) indexes = np.arange(numOfSequences) np.random.shuffle(indexes) numOfTrain = (int) (numOfSequences * 0.7) # 70 % is for training trainSequence = allSequences[indexes[0:numOfTrain]] trainTarget = allTargets[indexes[0:numOfTrain]] numOfVal = (int) (numOfSequences * 0.2) # 20 % is for vaidation valSequence = allSequences[indexes[numOfTrain:(numOfTrain + numOfVal)]] valTarget = allTargets[indexes[numOfTrain:(numOfTrain + numOfVal)]] evalSequence = allSequences[indexes[(numOfTrain + numOfVal):numOfSequences]] evalTarget = allTargets[indexes[(numOfTrain + numOfVal):numOfSequences]] evalPrediction = np.zeros(len(evalSequence)) trainError = np.zeros(epochs) valError = np.zeros(epochs) # længden af sekvensbiderne og antallet er mulige aminosyrer. Der er 20 normale. mer = 9 numOfAminoAcids = 20 # create weight matrix with random values or load the files if(proceed): weight1 = np.load(weightPath1) weight2 = np.load(weightPath2) else: weight1 = weight(hiddenNodes, numOfAminoAcids * mer + 1) # plus 1 for bias weight2 = weight(1, hiddenNodes + 1) # plus 1 for bias bestWeight1 = weight1 bestWeight2 = weight2 bestError = 999 # just a large number so any validation will be better bestEpoch = 0 print("Starting training and validation.") for epoch in range(epochs): # train on training set # make scrampled order of sequences indexes = np.arange(numOfTrain) np.random.shuffle(indexes) error = np.zeros(numOfTrain) for index in indexes: # convert peptide sequence to quasi-binary inputLayer = sequenceUtils.createInputLayer(trainSequence[index]) # run the forward function hiddenLayer, outputLayer = forward(inputLayer, weight1, weight2) # save the error error[index] = 1/2 * (outputLayer - trainTarget[index])**2 errorDelta = outputLayer - trainTarget[index] # backpropagation outputDelta = backpropagation.backward(outputLayer, 1, errorDelta) weight2 = backpropagation.updateWeight(hiddenLayer, weight2, outputDelta, learningRate) hiddenDelta = backpropagation.backward(hiddenLayer, weight2, outputDelta) # bias is not a part of calculating the weights for the input hiddenDelta = hiddenDelta[0,0:hiddenNodes] weight1 = backpropagation.updateWeight(inputLayer, weight1, hiddenDelta, learningRate) trainError[epoch] = error.mean() # validation error = np.zeros(numOfVal) for index in range(numOfVal): # convert peptide sequence to quasi-binary inputLayer = sequenceUtils.createInputLayer(valSequence[index]) # run the forward function hiddenLayer, outputLayer = forward(inputLayer, weight1, weight2) # save the error error[index] = 1/2 * (outputLayer - valTarget[index])**2 valError[epoch] = error.mean() # find the best weight matrices so far if(valError[epoch] < bestError): bestWeight1 = weight1 bestWeight2 = weight2 bestError = valError[epoch] bestEpoch = epoch if(epoch % 10 == 0): percent = (int) (epoch/epochs*100) print("Training error: {:.8f}. Validation error: {:.8f}. {:2}% complete." .format(trainError[epoch], valError[epoch], percent)) print("Training and validation complete.") # plot error pyplot.plot(trainError, label = "Training set") pyplot.plot(valError, label = "Validation set") pyplot.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0) pyplot.xlabel("epoch") pyplot.ylabel("error") pyplot.title("Validation") pyplot.savefig('validation.png', bbox_inches='tight') pyplot.show() # save the best weight matrices np.save(weightPath1, bestWeight1) np.save(weightPath2, bestWeight2) print("The minimum error of the validation set is at epoch {}. The validation error is {}." .format(bestEpoch, bestError)) #evaluation print("Predicting on evaluation set.") for index in range(len(evalSequence)): # convert peptide sequence to quasi-binary inputLayer = sequenceUtils.createInputLayer(evalSequence[index]) # run the forward function hiddenLayer, outputLayer = forward(inputLayer, bestWeight1, bestWeight2) evalPrediction[index] = outputLayer # plot comparison of prediction and target for evaluation set pyplot.plot(evalTarget, evalPrediction, '.') pyplot.xlabel("target") pyplot.ylabel("prediction") pyplot.title("Evaluation") pyplot.savefig('evaluationLog.png', bbox_inches='tight') pyplot.show() # how correlated is it? corr = np.corrcoef(evalTarget, evalPrediction)[1,0] print("The Pearson correlation coefficient is {}.".format(corr)) # plot comparison again, now inverse log transfomed back but with a logarithmic scale evalPrediction = logTransform.invTransform(evalPrediction) evalTarget = logTransform.invTransform(evalTarget) pyplot.axes().set_xscale('log') pyplot.axes().set_yscale('log') pyplot.plot(evalTarget, evalPrediction, '.') pyplot.xlabel("target") pyplot.ylabel("prediction") pyplot.title("Evaluation") pyplot.savefig('evaluation.png', bbox_inches='tight') pyplot.show()
def init_weights(self, info): print("Init ") self.net = [weight(16777216)] * 16 return
def train(): global kesi kesi = 0 alpha_all = [] for i, name in enumerate(['out']): model_path = 'model_merge_%d_/model.ckpt'%i model_path_read = 'model_merge_%d_0'%i if i == 0: w = np.zeros(12 * 12) #第一次赋予样本的权重为1/144 for x in range(w.shape[0]): w[x] = 1 / float(w.shape[0]) print w w_before = w w = w.reshape(12, 12) w_tensor = tf.convert_to_tensor(w, tf.float32) data_long, data_mid, data_short, data_label = inputs(is_train = True) data_long = tf.transpose(data_long, [0, 2, 3, 1]) data_mid = tf.transpose(data_mid, [0, 2, 3, 1]) data_short = tf.transpose(data_short, [0, 2, 3, 1]) data_label = tf.transpose(data_label, [0, 2, 3, 1]) prediction = inference(data_long, data_mid, data_short) losses = loss(prediction, data_label) losses = tf.reduce_mean(tf.multiply(losses, w_tensor)) with tf.variable_scope('learning_rate'): lr = tf.Variable(learning_rate, trainable=False) tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(losses, tvars), 5) with tf.name_scope('optimizer'): optimizer = tf.train.AdamOptimizer(lr) with tf.variable_scope('optimizer', reuse = tf.AUTO_REUSE) as scope: train_op = optimizer.apply_gradients(zip(grads, tvars)) init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) saver=tf.train.Saver(max_to_keep=5) with tf.Session() as sess: sess.run(init_op) tf.train.start_queue_runners(sess = sess) tl.layers.initialize_global_variables(sess) # ckpt = tf.train.get_checkpoint_state(model_path_read) # saver.restore(sess, ckpt.model_checkpoint_path) step = 0 total_cost = 0 while step < 5100: _loss, _ = sess.run([losses, train_op]) total_cost += _loss if step % 85 == 0 and step != 0: print 'epoch %d train loss: %f'%(step / 85, total_cost / 85.) total_cost = 0 saver.save(sess, model_path, global_step = step) step += 1 error_all = weight.error(model_path_read, name) if i == 0: kesi_1, alpha_1 = weight.kesi_alpha(w_before, error_all) alpha_all.append(alpha_1) kesi = kesi_1 print alpha_1 w = weight.weight(error_all, kesi, w_before) w_before = w print w print kesi else: kesi, alpha = weight.kesi_alpha(w_before, error_all) alpha_all.append(alpha) w = weight.weight(error_all, kesi, w_before) w_before = w print alpha print w print kesi return alpha_all
def __init__(self): super(Constrained_MDO,self).__init__() # -------------- # | | # | | # -------------- # | # | # | # | # | # ------|------ # ------------- ------------- # -------- | | | --------- # --- | --- # | | | | | # | # | | | | | # | # | | | | | # ------- | ------- # ----------- | | | --------- # ------------------------------ # 1 2 3 4 5 # ====================================== Params =============================================== # self.add('b_wing',IndepVarComp('b_wing',2.5)) # Wing Span self.add('C_r',IndepVarComp('C_r',0.603)) # Root Airfoil Cord (at 1) self.add('t2',IndepVarComp('t2',0.9506)) # Taper ratio at 2 self.add('t3',IndepVarComp('t3',0.9517)) # Taper ratio at 3 self.add('t4',IndepVarComp('t4',0.9558)) # Taper ratio at 4 self.add('t5',IndepVarComp('t5',0.8117)) # Taper ratio at 5 self.add('dist_LG',IndepVarComp('dist_LG',0.07)) # Distance between the CG and the Landing Gear self.add('b_htail',IndepVarComp('b_htail',1.0)) # Horizontail Tail Span self.add('C_r_t',IndepVarComp('C_r_t',0.228)) # Tail Root airfoil Cord # self.add('b_vtail',IndepVarComp('b_vtail',0.3)) # Vertical Tail Span self.add('boom_len',IndepVarComp('boom_len',0.5)) # Boom Length #[ 1 2 3 4 5 ] self.add('camber', IndepVarComp('camber', np.array([0.13, 0.13, 0.13, 0.13, 0.13]))) # Camber % at each position self.add('max_camb_pos', IndepVarComp('max_camb_pos', np.array([0.45, 0.45, 0.45, 0.45, 0.45]))) # Max Camber Position % at each position self.add('thickness', IndepVarComp('thickness', np.array([0.14, 0.14, 0.14, 0.14, 0.14]))) # Thickness % at each position self.add('max_thick_pos', IndepVarComp('max_thick_pos', np.array([0.29, 0.29, 0.29, 0.29, 0.29]))) # Max Thickness Postion % at each position # Add Componets self.add('weight', weight()) self.add('obj', obj()) self.add('Plot', Plot(geo1, geo2, A, writer, fig)) # ====================================== Connections ============================================ # self.connect('b_wing.b_wing',['weight.b_wing','obj.b_wing']) self.connect('C_r.C_r',['weight.C_r']) self.connect('t2.t2',['weight.t2']) self.connect('t3.t3',['weight.t3']) self.connect('t4.t4',['weight.t4']) self.connect('t5.t5',['weight.t5']) self.connect('b_htail.b_htail',['weight.b_htail']) self.connect('C_r_t.C_r_t',['weight.C_r_t']) self.connect('dist_LG.dist_LG',['weight.dist_LG','obj.dist_LG']) self.connect('boom_len.boom_len',['weight.boom_len','obj.boom_len']) self.connect('camber.camber', ['obj.camber']) self.connect('max_camb_pos.max_camb_pos',['obj.max_camb_pos']) self.connect('thickness.thickness', ['obj.thickness']) self.connect('max_thick_pos.max_thick_pos', ['obj.max_thick_pos']) # Connections weight Module self.connect('weight.mass', 'obj.mass') self.connect('weight.Iyy', 'obj.Iyy') self.connect('weight.Sref_wing' , 'obj.Sref_wing') self.connect('weight.Sref_tail' , 'obj.Sref_tail') self.connect('weight.MAC', 'obj.MAC') self.connect('weight.x_cg', ['obj.x_cg', 'Plot.x_cg']) self.connect('weight.Xle', 'Plot.Xle') self.connect('weight.Yle', 'Plot.Yle') self.connect('weight.C', 'Plot.C') self.connect('weight.Xle_t', 'Plot.Xle_t') self.connect('weight.Yle_t', 'Plot.Yle_t') self.connect('weight.C_t', 'Plot.C_t') self.connect('weight.test_class', 'obj.test_class') # Connections obj Module self.connect('obj.NP', 'Plot.NP') self.connect('obj.score','Plot.score')
def test(input, frames, doPrint): print 'Optimal', optimal.optimal(input[:], frames, doPrint) print 'FIFO', fifo.fifo(input, frames, doPrint) print 'LRU', lru.lru(input,frames, doPrint) print 'LFU', lfu.lfu(input, frames, doPrint) print 'Weighted', weight.weight(input, frames, 4, 1, doPrint)
print 'Weighted', weight.weight(input, frames, 4, 1, doPrint) # Run algorithms for 3 and 4 frames on a basic input and print the results. doPrint = True # Whether or not to print results to the console. input = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5] # List that the algorithms will run on. frames = 3 # Number of frames for the pages list. while frames < 5: print 'Page faults: {}\n'.format(optimal.optimal(input, frames, doPrint)) print 'Page faults: {}\n'.format(fifo.fifo(input, frames, doPrint)) print 'Page faults: {}\n'.format(lru.lru(input,frames, doPrint)) print 'Page faults: {}\n'.format(lfu.lfu(input, frames, doPrint)) # Run Weighted with increasing frequency multipliers. i = 1 # Loop variable, and frequency multiplier for Weighted. while i < 10: print 'Page faults: {}\n'.format(weight.weight(input, frames, i, 1, doPrint)) i += 1 frames += 1 # Get input data. input = [] # Reset input. with open('project_input.txt', 'r') as file: lines = file.read().strip().split('\n') for line in lines: input.append(int(line)) # Run algorithms for 3, 4, 5, 6, and 7 frames and store the results.