class NeuralNetwork: def __init__(self, shape, random_value): self.layers = [] self.shape = shape self.time = 0 self.input_layer = InputLayer(shape[0]) self.middle_layer = Layer(shape[1], self.input_layer.neurons) self.input_layer.listeners.append(self.middle_layer) self.output_layer = Layer(shape[2], self.middle_layer.neurons) self.middle_layer.listeners.append(self.output_layer) self.random_layer = RandomLayer(shape[2], self.output_layer.neurons, random_value) self.output_layer.listeners.append(self.random_layer) self.layers.append(self.input_layer) self.layers.append(self.middle_layer) self.layers.append(self.output_layer) self.layers.append(self.random_layer) def __len__(self): return len(self.shape) def __getitem__(self, i): return self.layers[i] def calculate(self, x): """ calculate vector x, if random value is set, add to result vector value (random()*2-1)*random_value :param x: input vector :param random_value: random range added to result vector :return: result of network calculation """ self.input_layer.calculate(x) self.input_layer.notify_listeners() return self.random_layer.get_output_values() def teach_considering_random(self, stimulation_value): """ teach network with learn_rate = abs(stimulation_value). calculate with random value should be used before using this method. if stimulation_value > 0 then network teaches like usual by example, which is equals previous calculation result if stimulation_value < 0: then example vector is opposite previous calculation result. For correct teaching, method recalculate input values=self.input_layer.input_values, without random. :param stimulation_value: """ answer_with_random = self.random_layer.get_output_values() if stimulation_value < 0: answer_with_random = [-x for x in answer_with_random] stimulation_value = -stimulation_value self.output_layer.teach_output_layer_by_sample(stimulation_value, answer_with_random) # teach middle layers self.middle_layer.teach_middle_layer(stimulation_value) for layer in self: layer.commit_teach()
def redraw(self, update_types=set()): if len(update_types) == 0: r = RendererObjectManager(0, None) self.refresh_sources(set([r.update_type.Reset])) else: Layer.redraw( self, self.point_sources, self.line_sources, self.text_sources, self.image_sources, update_types )
def __init__(self, in_size=3, out_size=3, weights=None): """ :param in_size: :param out_size: :param weights: :return: """ Layer.__init__(self, in_size, out_size, weights)
def __init__(self, boolean): """ Constructor """ Layer.__init__(self) self.closure = None self.should_update = boolean self.text_sources = [] self.image_sources = [] self.point_sources = [] self.line_sources = [] self.astro_sources = []
def __init__(self): # Init LCD self.lcdString = [[' ' for col in range(Layer.WIDTH)] for row in range(Layer.HEIGHT)] # Init layer self.canvas = Layer() self.runner = Layer() self.barrier = Layer() # Init pixelSet self.pixelSet = [list(Layer.EMPTY) for i in range(8)] # Init LCD self.lcd = Adafruit_CharLCDPlate() self.lcd.begin(16, 2) self.lcd.backlight(Adafruit_CharLCDPlate.ON) # Init Game self.game = Game(self.lcd)
def run(self): while True: self.game.tick() if self.game.state == Game.STATE_RUNNING: self.drawBarriers() self.drawRunner() self.mergeLayers() self.updateLcdString() self.game.gameOver(self.barrier.bitmap[1][1], self.runner.bitmap[1][1]) self.draw() self.canvas = Layer() self.runner = Layer() self.barrier = Layer() sleep(.03)
def __init__(self): print "GenericANN: Constructor called" self.__layers = [] self.__links = [] self.__exec_order = [] print "GenericANN: Begin read from script" io = ann_io() __ann_data = io.read() # TODO read training data print "GenericANN: ", len(__ann_data.get_layers()) random.seed() print "GenericANN: Initializing GenericANN" for ann_layer in __ann_data.get_layers(): layer = Layer(ann_layer) self.__layers.append(layer) print "GenericANN: Added layer:" print "------------------------" layer.printout() print "------------------------" for ann_link in __ann_data.get_links(): # Adding layers to links link = Link(ann_link, self.get_layers()) self.__links.append(link) # Adding links to layers for layer in self.get_layers(): if link.getPostLayer().get_name() == layer.get_name(): layer.add_link_in(link) elif link.getPreLayer().get_name() == layer.get_name(): layer.add_link_out(link) print "GenericANN: Adding link from: " + link.getPreLayer().get_name() + " to: " + \ link.getPostLayer().get_name() if (ann_link.get_link_learn_rule() == RULE.OJA): link.setLearningRule(OjaLearning(ann_link.get_link_learn_rate())) elif (ann_link.get_link_learn_rule() == RULE.GENERAL): link.setLearningRule(GeneralHebbLearning(ann_link.get_link_learn_rate(), ann_link.get_link_learn_param())) elif (ann_link.get_link_learn_rule() == RULE.CLASSICAL): link.setLearningRule(ClassicalHebbLearning(ann_link.get_link_learn_rate())) link.connect() self.__exec_order = __ann_data.get_exec_order()
def __init__(self, shape): self.layers = [] self.shape = shape self.time = 0 self.input_layer = InputLayer(shape[0]) self.middle_layer = Layer(shape[1], self.input_layer.neurons) self.input_layer.listeners.append(self.middle_layer) self.output_layer = Layer(shape[2], self.middle_layer.neurons) self.middle_layer.listeners.append(self.output_layer) self.layers.append(self.input_layer) self.layers.append(self.middle_layer) self.layers.append(self.output_layer) self._reset_layers_states()
def forward(self, _units): self._units, self._pooled_inds = self.maxPool(_units) self._outputs = self.activate(self._units) if (not self._child == None): if self._child.type() == 'convolutional': next_units = Layer.convConvForward(self._weights, self._outputs, self._child.getUnits().shape) self._child.forward(next_units) elif self._child.type() == 'fullyconnected': self._child.forward(np.dot(self._outputs.flatten(), self._weights) + self._bias)
def __init__(self, director, pausedScene, title='Warning!', message='Message', tooltip='Press here to continue'): Scene.__init__(self, director) self.bluredBackground = None self.b = 1 self.pausedScene = pausedScene layer = Layer(director) backgroundImage = Resources.load_image("message_box.png") buttonImage = Resources.load_image("message_box_button.png") buttonWidth = 372 style = MessageBox.createMessageBoxStyle( backgroundImage, buttonImage, buttonWidth) self.messageBox = MessageBox.MessageBox( self.director, (SCREEN_W / 2 - style['bg'].get_width() / 2, SCREEN_H / 2 - style['bg'].get_height() / 2), style, True) self.messageBox.button.onMouseDown = lambda: self.popScene() self.messageBox.title = title self.messageBox.message = message self.messageBox.tooltip = tooltip layer.append(self.messageBox) self.layers.append(layer)
def __init__(self, shape, random_value): self.layers = [] self.shape = shape self.time = 0 self.input_layer = InputLayer(shape[0]) self.middle_layer = Layer(shape[1], self.input_layer.neurons) self.input_layer.listeners.append(self.middle_layer) self.output_layer = Layer(shape[2], self.middle_layer.neurons) self.middle_layer.listeners.append(self.output_layer) self.random_layer = RandomLayer(shape[2], self.output_layer.neurons, random_value) self.output_layer.listeners.append(self.random_layer) self.layers.append(self.input_layer) self.layers.append(self.middle_layer) self.layers.append(self.output_layer) self.layers.append(self.random_layer)
def forward(self, _units): self._units = _units self._outputs = self.activate(self._units) if (not self._child == None): if self._child.type() == 'convolutional': next_units = Layer.convConvForward(self._weights, self._units, self._child.getUnits().shape) self._child.forward(next_units) elif self._child.type() == 'pooling': self._child.forward(self._units)
def addPOIGroupAndLayer(self): if self.mode == 'r': raise ValueError("Can't add POI layer in read-only mode") if self._poigroup == None: # Create POI config file self.poicfg = ConfigParserUpper() self._cfg.set("POI","POI_CONFIG", self.mapnumstr + "poi.cfg") # Create POI group poigroup = POIGroup(self) poigroup.open('w') self._poigroup = poigroup # Create POI Layer layer=Layer(self, "poi", "poi", layertype=LayerTypePOI, fileidentifier=0xc0f0) layer.open('w') self._poiconfig.addLayer(layer, layerstyle=POILayerStyle())
def __init__(self, director, player): Scene.__init__(self, director) self.player = player self.enemyGroup = EntityGroup([]) self.bulletGroup = EntityGroup([]) self.groups = [] self.groups.append(self.enemyGroup) self.groups.append(self.bulletGroup) self.bg = None self.collisionBg = None self.camera = Camera() self.HUD = HUD(self.director, (0, 467), True, player) hudLayer = Layer(self.director) hudLayer.append(self.HUD) self.layers.append(hudLayer) self.mouseHoveringHUD = False self.danger = False self.dangerLevel = 0 self.gameOver = False
class NeuralNetwork: def __init__(self, shape): self.layers = [] self.shape = shape self.time = 0 self.input_layer = InputLayer(shape[0]) self.layers.append(self.input_layer) prev_layer = self.input_layer for i in range(1, len(shape)-1): cur_layer = Layer(shape[i], prev_layer.neurons) prev_layer.listeners.append(cur_layer) self.layers.append(cur_layer) prev_layer = cur_layer self.output_layer = Layer(shape[-1], prev_layer.neurons) prev_layer.listeners.append(self.output_layer) self.layers.append(self.output_layer) self._reset_layers_states() def __len__(self): return len(self.shape) def __getitem__(self, i): return self.layers[i] def calculate(self, x): """ :param x: list of input values :return: list of values which is result of network calculation """ self.input_layer.input_values = x done = False while not done: done = True for layer in self: if layer.ready_to_calculate == Readiness.READY: layer.calculate() done = False self._reset_layers_states() return self.output_layer.get_output_values() def _reset_layers_states(self): for layer in self: layer.reset_state()
def __init__(self, shape): self.layers = [] self.shape = shape self.time = 0 self.input_layer = InputLayer(shape[0]) self.layers.append(self.input_layer) prev_layer = self.input_layer for i in range(1, len(shape)-1): cur_layer = Layer(shape[i], prev_layer.neurons) prev_layer.listeners.append(cur_layer) self.layers.append(cur_layer) prev_layer = cur_layer self.output_layer = Layer(shape[-1], prev_layer.neurons) prev_layer.listeners.append(self.output_layer) self.layers.append(self.output_layer) self._reset_layers_states()
class NeuralNetwork: def __init__(self, shape): self.layers = [] self.shape = shape self.time = 0 self.input_layer = InputLayer(shape[0]) self.middle_layer = Layer(shape[1], self.input_layer.neurons) self.input_layer.listeners.append(self.middle_layer) self.output_layer = Layer(shape[2], self.middle_layer.neurons) self.middle_layer.listeners.append(self.output_layer) self.layers.append(self.input_layer) self.layers.append(self.middle_layer) self.layers.append(self.output_layer) self._reset_layers_states() def __len__(self): return len(self.shape) def __getitem__(self, i): return self.layers[i] def calculate(self, x): """ calculate vector x, if random value is set, add to result vector value (random()*2-1)*random_value :param x: input vector :param random_value: random range added to result vector :return: result of network calculation """ self.input_layer.input_values = x done = False while not done: done = True for layer in self: if layer.ready_to_calculate == Readiness.READY: layer.calculate() done = False self._reset_layers_states() return self.output_layer.get_output_values() def _reset_layers_states(self): for layer in self: layer.reset_state() def teach_by_sample(self, database, teach_value=0.5): err = 0 for inp, out in database: net_out = self.calculate(inp) self.output_layer.teach_output_layer_by_sample(teach_value, out) # teach middle layers self.middle_layer.teach_middle_layer(teach_value) for layer in self: layer.commit_teach() err += sum([abs(no-o) for no, o in zip(net_out, out)]) return err / len(database)
class DesignDict: """ Wraps objects in DXF design into a single logical item. Handles everything from ingestion to running rules against the ingested design. """ ## Layer indexes METAL = RuleConfig.METAL SU81 = RuleConfig.SU81 SU82 = RuleConfig.SU82 SU83 = RuleConfig.SU83 POST = RuleConfig.POST PORTS = RuleConfig.PORTS BORDER = RuleConfig.BORDER ALIGNMENT = RuleConfig.ALIGNMENT LAYERS = RuleConfig.LAYERS ## Layer Growth Factor LAYERGROWTH = RuleConfig.LAYERGROWTH def __init__(self): ## Layers indexed so I can see what previous and next layers are ## trivially self.dimm = None self.objects = {} self.ports = Layer("Ports", DesignDict.PORTS) self.alignments = {} self.layers = [] self.layers.append(Layer("Metal", DesignDict.METAL)) self.layers.append(Layer("SU8_1", DesignDict.SU81)) self.layers.append(Layer("SU8_2", DesignDict.SU82)) self.layers.append(Layer("SU8_3", DesignDict.SU83)) self.layers.append(Layer("POST", DesignDict.POST)) self.layers.append(self.ports) self.border = False ## Violations are gonna be lists of lists. self.violations = ViolationSummary() def __str__(self): objCount = "Design with " + str(Object.count) + " objects" vioCount = " and " + str(self.violationCount()) + " violations" return objCount + vioCount def addToLayer(self, obj, layer): """ Adds a designObject (obj) to the specified layer (integer) of the design dictionary. """ ## Filter objects inside ports if layer != DesignDict.METAL: possibleHits = self.ports.index.intersection(obj.shape.bounds) for objind in possibleHits: port = self.ports.objs[objind] if port.shape.contains(obj.shape): return if layer not in DesignDict.LAYERS: raise Exception("Supplied layer", layer, "not in range.") else: self.layers[layer].add(obj) self.objects[obj.id] = obj def getLayer(self, id): """ Accesses a layer of the device contained in the design dictionary. """ return self.layers[id] def addPort(self, port): """ Adds a port to the port layer. """ if port.id in self.ports.objs or port.id in self.objects: raise Exception("Object collision on id", port.id) self.ports.add(port) self.objects[port.id] = port def getPorts(self): """ Return the collection of ports from the port layer. Note that this doesn't give you the port layer itself. You need getLayer for that. """ return self.ports.objs def populateSize(self, runJson): """ Compute the device's size using information from the border layer. """ if self.border: dimms = self.border.bounds logger.debug("Setting border from " + str(dimms)) (minx, miny, maxx, maxy) = self.border.shape.bounds ## Do some rounding on X dx = roundedSub(maxx, minx) sxHalfCM = ceil(dx / 5000) # Now we do the same rounding on Y dy = roundedSub(maxy, miny) syHalfCM = ceil(dy / 5000) sx = sxHalfCM / 2 sy = syHalfCM / 2 sizeString = "%.1f x %.1f cm" % (sx, sy) self.dimm = (sx, sy) else: logger.error('Invalid border defined.') sizeString = "InvalidBorder!" runJson["size"] = sizeString def addAlignment(self, align): """ Adds an alignment mark to the alignment mark layer. """ if align.id in self.alignments or align.id in self.objects: raise Exception("Object collision on id", align.id) self.addToLayer(align, DesignDict.METAL) self.addToLayer(align, DesignDict.SU81) self.alignments[align.id] = align self.objects[align.id] = align def addPost(self, post): """ Adds a support post to the support post layer. """ possibleHits = self.ports.index.intersection(post.shape.bounds) for objind in possibleHits: port = self.ports.objs[objind] if port.shape.contains(post.shape): return self.objects[post.id] = post self.layers[DesignDict.POST].add(post) def getAlignments(self): """ Return a dictionary of alignment marks present in the design """ return self.alignments def violationCount(self): """ Compute and return the number of violations associated with the design dictionary. If you ask for this number before checking the rules, you'll get the number 0 back, despite the design potentially containing errors. """ return len(self.violations.violations) def getPortIndex(self): """ Returns a spatial index for the ports in the design. """ ## Already there if (hasattr(self, 'portIndex')): return self.portIndex ## Not made yet, make the port index else: self.portIndex = index.Index() portDict = self.getPorts() for key, port in portDict.items(): self.portIndex.insert(key, port.shape.bounds) return self.portIndex def setBorder(self, b): """ Set the border object (b) for the design dictionary """ self.border = Border(b) def check(self, rid): """ Check the design in the dictionary for compliance against the rule associated with the index (rid) """ rule = Rule.dict[rid] rule.check(self) def checkAllThreaded(self): """ Check the design in the dictionary for complaince with all rules described in the rule dictionary (Rule.dict). This implementaton is singled threaded. """ threads = [] for rid, rule in Rule.dict.items(): logger.info("Spawning thread for rule " + str(rule)) t = CheckThread(rid, rule, self) threads.append(t) t.start() for t in threads: t.join() def checkAllSingleThread(self): """ Check the design in the dictionary for complaince with all rules described in the rule dictionary (Rule.dict). This implementaton uses a thread for each rule. """ ind = 0 length = len(Rule.dict) for rid, rule in Rule.dict.items(): ind += 1 logger.info("Checking " + str(ind) + " of " + str(length)) logger.info("Checking " + str(rule)) rule.check(self) logger.info("Done Checking " + str(rule)) ## here's where we would update the TANK interface by posting that ind is done print "Checking rule", ind, "of", length, "Rule", rid def checkAll(self): """ Wrapper around one of checkAllThreaded or checkAllSingleThread. """ logger.info("Checking " + str(len(Rule.dict)) + " rules") self.checkAllSingleThread() def getViolationCounts(self): """ Counts violations in the violation dictionary associated with the design dictionary. Returns a tuple of hard violations and soft violations. If you run this before checking the rules, you'll get (0,0) back, despite there potentially being violations in the design dictionary. """ return (self.violations.hardCount, self.violations.softCount) def getObjCounts(self): """ Returns a dictionary mapping Layer Names to Number of Objects in that layer. """ ret = {} for layer in self.layers: ret[layer.name] = layer.objCount return ret
np.random.seed(100) with open('train.txt') as file: numOfInputs,numOfHiddenLayers,numOfOutputs = [int(x) for x in file.readline().split()] numOfExamples=int(file.readline()) temp = [] for line in file: temp.append(list(map(float, line.split()))) data=np.array(temp) X=data[:,0:numOfInputs] X= X/np.max(X,axis=0) y=data[:,numOfInputs:numOfInputs+numOfOutputs] y= y/np.max(y,axis=0) nn = NeuralNetwork() nn.addLayer(Layer(numOfInputs,numOfInputs+1)) for i in range(numOfHiddenLayers-1): nn.addLayer(Layer(numOfInputs+1,numOfInputs+1)) nn.addLayer(Layer(numOfInputs+1,numOfOutputs)) # Train the neural network errors = nn.train(X, y, 0.5, 1000) # Plot changes in mse plt.plot(errors) plt.title('Changes in MSE') plt.xlabel('Epoch (every 10th)') plt.ylabel('MSE') plt.show()
def __init__(self, config): Layer.__init__(self, config)
data_non_human = np.delete(ones_non_human, 0, 0) feature_set = np.vstack((data_human, data_non_human)) label_ones = np.ones((data_human.shape[0], 1)) label_zeros = np.zeros((data_non_human.shape[0], 1)) targets = np.vstack((label_ones, label_zeros)) X_train, X_test, Y_train, Y_test = train_test_split(feature_set, targets, test_size=0.2) # create the network nn_model = NN(X_train, Y_train) nn_model.add_layer(Layer(24, activation='relu')) nn_model.add_layer(Layer(12, activation='sigmoid')) #fit the network nn_model.fit(iteration=100, learning_rate=0.1) # plot cost function Y_train_pred = nn_model.predict(X_train) Y_test_pred = nn_model.predict(X_test) accuracy_train = np.sum(Y_train_pred == Y_train) / len(Y_train) * 100 accuracy = np.sum(Y_test_pred == Y_test) / len(Y_test) * 100 print("Train accuracy: " + str(accuracy_train) + "%") print("Test accuracy: " + str(accuracy) + "%")
def __init__(self, para): Layer.__init__(self, para) self.lastMiniBatch = True
def main(): nnfs.init() X, y = spiral_data(samples=1000, classes=3) dense1 = Layer(2, 512, weight_regularizer_l2=5e-4, bias_regularizer_l2=5e-4) activation1 = ReLU() dense2 = Layer(512, 3) cost_act = Soft_Ce() optimizer = Adam(learning_rate=0.02, decay=5e-7) for epoch in range(10001): dense1.forwardProp(X) activation1.forwardProp(dense1.output) dense2.forwardProp(activation1.output) data_cost = cost_act.forwardProp(dense2.output, y) regularization_cost = \ cost_act.cost.regularization_cost(dense1) + \ cost_act.cost.regularization_cost(dense2) cost = data_cost + regularization_cost predictions = np.argmax(cost_act.output, axis=1) if len(y.shape) == 2: y = np.argmax(y, axis=1) accuracy = np.mean(predictions == y) if not epoch % 100: print(f'epoch: {epoch}, ' + f'acc: {accuracy:.3f}, ' + f'cost: {cost:.3f}, (' + f'data_cost: {data_cost:.3f}, ' + f'reg_cost: {regularization_cost:.3f}), ' + f'lr: {optimizer.curr_learning_rate}') cost_act.backProp(cost_act.output, y) dense2.backProp(cost_act.dinputs) activation1.backProp(dense2.dinputs) dense1.backProp(activation1.dinputs) optimizer.pre_update_params() optimizer.update_params(dense1) optimizer.update_params(dense2) optimizer.post_update_params() X_test, y_test = spiral_data(samples=100, classes=3) dense1.forwardProp(X_test) activation1.forwardProp(dense1.output) dense2.forwardProp(activation1.output) cost = cost_act.forwardProp(dense2.output, y_test) predictions = np.argmax(cost_act.output, axis=1) if len(y.shape) == 2: y_test = np.argmax(y_test, axis=1) accuracy = np.mean(predictions == y_test) print(f'validation, acc: {accuracy:.3f}, cost: {cost:.3f}')
def __init__(self, name, orig=None): Layer.__init__(self, name, orig) self.seed_gui = SeedingGUI() if orig == None else orig.seed_gui self.range_gui = RangeGUI() if orig == None else orig.range_gui
def new_layer(self, name): return Layer(self.width, self.height, name)
def __init__(self,resolution_meter,parent_widget): Layer.__init__(self,'Grid Layer',parent_widget) self._resolution_meters = resolution_meter self._lock = threading.Lock()
def __init__(self, resolution_meter, parent_widget): Layer.__init__(self, 'Submarine Layer', parent_widget) self._resolution_meters = resolution_meter self.subModel = loader(parent_widget) stl_file = os.path.join(rospkg.RosPack().get_path('rqt_navigation_map'), 'resource', 'sub.stl') self.subModel.load_binary_stl(stl_file)
def __init__(self, shape): Layer.__init__(self, [shape]) self.__shape = shape self.params = []
i+=1 if i>2000: break filename = 'shape/romania/roads.shp' ds = ogr.Open(filename) layer = ds.GetLayerByIndex(0) map = Map(MapDirectory(), maptype=MapTypeImage) map.open("w") extent = layer.GetExtent() map.bbox = ((extent[0], extent[2]), (extent[1], extent[3])) ## Add streets layer streets = Layer(map, name="00_Streets", filename="00str", layertype=LayerTypePolyline) streets.open(mode='w') streetstyle = DetailMapLayerStyle() streetstyle.style = 'US_STREET_LINE' map.addLayer(streets, layerstyle = streetstyle) map.getGroupByName('00_Roads').addLayer(streets) importLayer(map, streets, map.getGroupByName('00_Roads'), layer, nameattribute='LABEL') map.close() map.writeImage('romania.imi')
def __init__(self,resolution_meter,parent_widget): Layer.__init__(self,'Path Layer', parent_widget) self._resolution_meter = resolution_meter self._path_queue = deque( maxlen=60) self._last_pos = (0,0,0)
from __future__ import print_function from Grids import Grids from Layer import Layer from run import * # set parameters ly1 = Layer(z0=-1, z1=0, mu_a=0, mu_s=0, g=1, n=1, clear=True, ambient=True) ly2 = Layer(z0=0, z1=np.inf, mu_a=0.1, mu_s=100, g=0.9, n=1.37, clear=False, ambient=False) ly3 = Layer(z0=np.inf, z1=np.inf, mu_a=0, mu_s=0, g=1, n=1, clear=True, ambient=True) ly_ls = [ly1, ly2, ly3] n_photon = 1000 w_thresh = 0.0001 m = 10 n_r = 500 # number of grid pixels along r n_z = 200 # number of grid pixels along z delta_r = 0.005 delta_z = 0.005
# coding=utf-8 import subprocess from Layer import Layer from DataBase import DataBase import os rootDir = os.path.abspath("") + "/" wmsUrlTrainSource = "http://localhost:8080/geoserver/sf/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fjpeg&STYLES&LAYERS=sf%3Aflowcount_geometry&tilesOrigin=-180%2C-90&WIDTH=256&HEIGHT=256&SRS=EPSG%3A900913&BBOX=" wmsUrlTrainTarget = "http://localhost:8080/geoserver/sf/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fjpeg&STYLES&LAYERS=sf%3AlandPolygon5&tilesOrigin=-180%2C-90&WIDTH=256&HEIGHT=256&SRS=EPSG%3A900913&BBOX=" wmsUrlRoot = "http://123.56.66.184:9092/geoserver/ceshi/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fjpeg&&styles=line&LAYERS=ceshi%3Aflowcount_geometry&tilesOrigin=-180%2C-90&WIDTH=256&HEIGHT=256&SRS=EPSG%3A900913&BBOX=" layer = Layer(16, rootDir, wmsUrlRoot, wmsUrlTrainSource, wmsUrlTrainTarget) dataBase = DataBase() def run(cmd): sub = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) sub.wait() #将原始轨迹导入到flowcount_geometry def updateToGeometry(): print "UpdateToGeometry开始" dataBase.deleteAllByIdIsGreaterThan() dataBase.updateToGeometry() print "UpdateToGeometry结束" # 创建训练数据图片
def __init__(self, config): Layer.__init__(self, config) if self.settings['min_points_number'] < 0: raise ValueError( "GenerateHintsLayer: min_points_number must not be less than zero" )
from Layer import Layer import numpy as np hidden_layer = Layer([[0.5, 0.5], [0.5, 0.5], [0.5, 0.7]], [0, 1, 0]) output_layer = Layer([[0.5, 0.4, 0.2], [0.7, 0.1, 0.5]], [0, 1]) x_1 = 0.7 x_2 = 0.2 input = np.array([x_1, x_2]) for i in range(100): hidden_layer_output = hidden_layer.feed_forward(input) output = output_layer.feed_forward(hidden_layer_output) print(output) expected = [1, 0] output_layer.feed_backwards(expected) hidden_layer.feed_backwards(expected, output_layer) hidden_layer.push() output_layer.push()
class Display(): BARRIER = [ [[0b00000, # Frame 0 0b00000, 0b00000, 0b00100, 0b01110, 0b01110, 0b11111, 0b11111], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b00000, # Frame 1 in 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b01000, 0b11100, 0b11100, 0b11110, 0b11110]], [[0b00000, # Frame 1 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00001, 0b00001], [0b00000, 0b00000, 0b00000, 0b10000, 0b11000, 0b11000, 0b11100, 0b11100]], [[0b00000, # Frame 2 in 0b00000, 0b00000, 0b00000, 0b00001, 0b00001, 0b00011, 0b00011], [0b00000, 0b00000, 0b00000, 0b00000, 0b10000, 0b10000, 0b11000, 0b11000]], [[0b00000, # Frame 2 0b00000, 0b00000, 0b00001, 0b00011, 0b00011, 0b00111, 0b00111], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b10000, 0b10000]], [[0b00000, # Frame 3 0b00000, 0b00000, 0b00010, 0b00111, 0b00111, 0b01111, 0b01111], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]]] RUNNER = [ [[0b00000, # Frame 0 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b01110, 0b11111, 0b10101, 0b11111, 0b01110]], [[0b00000, # Frame 1 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b01110, 0b11111, 0b10101, 0b11111, 0b01110]], [[0b00000, # Frame 2 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000], [0b00100, 0b01110, 0b11111, 0b10101, 0b11111, 0b01110, 0b01110, 0b00000]], [[0b00000, # Frame 3 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01110], [0b11111, 0b10101, 0b11111, 0b01110, 0b00100, 0b00000, 0b00000, 0b00000]], [[0b00000, # Frame 4 0b00000, 0b00000, 0b00000, 0b00000, 0b01110, 0b01110, 0b10101], [0b11111, 0b01110, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b00000, # Frame 5 0b00000, 0b00000, 0b00000, 0b01110, 0b11111, 0b10101, 0b11111], [0b01110, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b00000, # Frame 6 0b00000, 0b01110, 0b11111, 0b10101, 0b11111, 0b01110, 0b01110], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b00000, # Frame 7 0b01110, 0b10101, 0b11111, 0b01110, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b01110, # Frame 8 0b10101, 0b11111, 0b01110, 0b00000, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b11111, # Frame 9 0b10101, 0b01110, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]]] def __init__(self): # Init LCD self.lcdString = [[' ' for col in range(Layer.WIDTH)] for row in range(Layer.HEIGHT)] # Init layer self.canvas = Layer() self.runner = Layer() self.barrier = Layer() # Init pixelSet self.pixelSet = [list(Layer.EMPTY) for i in range(8)] # Init LCD self.lcd = Adafruit_CharLCDPlate() self.lcd.begin(16, 2) self.lcd.backlight(Adafruit_CharLCDPlate.ON) # Init Game self.game = Game(self.lcd) def mergeLayers(self): # Merge layer to canvas #self.canvas.mergeLayer(self.runner).mergeLayer(self.barrier) self.canvas.mergeLayer(self.barrier) self.canvas.mergeLayer(self.runner) def updateLcdString(self): # Update game screen count = 0 for row in range(Layer.HEIGHT): for col in range(Layer.WIDTH): if self.canvas.bitmap[row][col] == Layer.EMPTY: self.lcdString[row][col] = ' ' else: index = self.findInPixelSet(self.canvas.bitmap[row][col], count) #print '[', str(row), '][', str(col), ']: ' + str(index) #print self.canvas.bitmap[row][col] if index == -1: self.pixelSet[count] = list(self.canvas.bitmap[row][col]) self.lcdString[row][col] = chr(count) count += 1 else: self.lcdString[row][col] = chr(index) # Update score board score = str(self.game.score) index = 0 for i in range(Layer.WIDTH - len(score), Layer.WIDTH): self.lcdString[0][i] = score[index] index += 1 def loadCharset(self): for i, item in enumerate(self.pixelSet): self.lcd.createChar(i, item) def findInPixelSet(self, pixel, count): for i in range(count): if self.pixelSet[i] == pixel: return i return -1 def draw(self): if self.game.state == Game.STATE_START: self.lcd.message('Press SELECT to\n START GAME ') elif self.game.state == Game.STATE_END: self.lcd.message(' SCORE ' + str(self.game.score) + '\n GAME OVER ') else: line_1 = ''.join(self.lcdString[0]) line_2 = ''.join(self.lcdString[1]) self.lcd.message(line_1 + '\n' + line_2) self.loadCharset() def drawBarriers(self): for barrier in self.game.barriers: self.barrier.drawPointX(barrier[1], barrier[0], self.game.frame, self.BARRIER[self.game.frame]) def drawRunner(self): self.runner.drawPointY(1, 0, self.RUNNER[self.game.runner]) def run(self): while True: self.game.tick() if self.game.state == Game.STATE_RUNNING: self.drawBarriers() self.drawRunner() self.mergeLayers() self.updateLcdString() self.game.gameOver(self.barrier.bitmap[1][1], self.runner.bitmap[1][1]) self.draw() self.canvas = Layer() self.runner = Layer() self.barrier = Layer() sleep(.03)
def define_classes_mapping(self): if self.settings['classes_mapping'] != "default": self.cls_mapping = self.settings['classes_mapping'] else: Layer.define_classes_mapping(self)
def __init__(self,parent_widget): Layer.__init__(self, 'Target Layer', parent_widget) self._cross = None
filename = 'shape/romania/roads.shp' ds = ogr.Open(filename) layer = ds.GetLayerByIndex(0) map = Map(MapDirectory(), maptype=MapTypeImage) map.open("w") extent = layer.GetExtent() map.bbox = ((extent[0], extent[2]), (extent[1], extent[3])) ## Add streets layer streets = Layer(map, name="00_Streets", filename="00str", layertype=LayerTypePolyline) streets.open(mode='w') streetstyle = DetailMapLayerStyle() streetstyle.style = 'US_STREET_LINE' map.addLayer(streets, layerstyle=streetstyle) map.getGroupByName('00_Roads').addLayer(streets) importLayer(map, streets, map.getGroupByName('00_Roads'), layer, nameattribute='LABEL') map.close()
def __init__(self,parent_widget): Layer.__init__(self,'Coordinate Layer',parent_widget)
def detectFire(path_res, info): b_1s = np.load(path_res + r'\Landsat_' + info + '_B1.npy') b_2s = np.load(path_res + r'\Landsat_' + info + '_B2.npy') b_3s = np.load(path_res + r'\Landsat_' + info + '_B3.npy') b_4s = np.load(path_res + r'\Landsat_' + info + '_B4.npy') shape = b_1s.shape L1 = Layer(b_1s) L2 = Layer(b_2s) L3 = Layer(b_3s) L4 = Layer(b_4s) nw2 = L3 >> L2 | L1 >> L2 & L2 >> L3 & L3 >> L4 L3.arr = None L3 = None L2.arr = None L2 = None gc.collect() b_5s = np.load(path_res + r'\Landsat_' + info + '_B5.npy') b_6s = np.load(path_res + r'\Landsat_' + info + '_B6.npy') b_7s = np.load(path_res + r'\Landsat_' + info + '_B7.npy') L5 = Layer(b_5s) L6 = Layer(b_6s) L7 = Layer(b_7s) Sub_1_7 = L1 - L7 nw1 = L4 >> L5 & L5 >> L6 & L6 >> L7 & Sub_1_7 << 0.2 L4.arr = None L4 = None Sub_1_7.arr = None Sub_1_7 = None gc.collect() z1 = nw1 & nw2 not_water = ~z1 # logical not # z1.arr = None # z1 = None # gc.collect() result = np.zeros(shape, dtype=np.uint8) Div_7_6 = L7 / L6 Div_7_5 = L7 / L5 Sub_7_5 = L7 - L5 # R75 > 1.8 && ρ7−ρ5 > 0.17 test3 = np.zeros(shape, dtype=np.uint8) np.putmask(test3, (Div_7_5 >> 1.8 & Sub_7_5 >> 0.17 & Div_7_6 >> 1.6).arr, 3) Div_7_6.arr = None Div_7_6 = None gc.collect() print("pre-test 3 done") # R75 > 2.5 && ρ7−ρ5 > 0.3 && ρ7 > 0.5 np.putmask(result, (Div_7_5 >> 2.5 & Sub_7_5 >> 0.3 & L7 >> 0.5).arr, 1) Div_7_5.arr = None Div_7_5 = None Sub_7_5.arr = None Sub_7_5 = None gc.collect() print("test 1 done") # =================================== # ρ6 > 0.8 && ρ1 < 0.2 && ( ρ5 > 0.4 || p7 < 0.1 ) np.putmask(result, (L6 >> 0.8 & L1 << 0.2 & (L5 >> 0.4 | L7 << 0.1)).arr, 2) L1.arr = None L1 = None L6.arr = None L6 = None gc.collect() print("test 2 done") # ==================================== for i in range(shape[0]): for j in range(shape[1]): if test3[i][j] == 3: b_5_61 = b_5s[i - 30:i + 31, j - 30:j + 31] b_7_61 = b_7s[i - 30:i + 31, j - 30:j + 31] not_water61 = not_water[i - 30:i + 31, j - 30:j + 31] test3_61 = test3[i - 30:i + 31, j - 30:j + 31] shape61 = b_5_61.shape arr_7 = [] arr_5 = [] for x in range(shape61[0]): for y in range(shape61[1]): if b_7_61[x][y] > 0 and not_water61[x][y] and test3_61[ x][y] == 0: arr_7.append(b_7_61[x][y]) arr_5.append(b_5_61[x][y]) arr_7 = np.array(arr_7) arr_5 = np.array(arr_5) Div_7_5 = arr_7 / arr_5 # print(R75) Sr_7 = np.mean(arr_7) Sr_5 = np.mean(arr_5) Div_Sr7_Sr5 = Sr_7 / Sr_5 STD_7 = np.std(arr_7) STD_75 = np.std(Div_7_5) if (L7[i][j] > Sr_7 + max(3 * STD_7, 0.08)) and ( L7[i][j] / L5[i][j] > Div_Sr7_Sr5 + max(3 * STD_75, 0.8)): result[i][j] = 3 #=============================================================================== np.save(path_res + r'\fire_mask_' + info, result) mask = np.zeros(shape, dtype=np.uint8) np.putmask(mask, result != 0, 1) k = np.sum(mask) print(k, 'Points') for i in range(mask.shape[0]): for j in range(mask.shape[1]): if mask[i][j] == 1: mask[i - 50:i + 51, j - 50:j + 51] = 10 imageio.imwrite(path_res + r'\mask_' + info + '.jpg', mask) plt.title("result") plt.imshow(mask, cmap='gray') return k