def startFitModel(self):
    if not utils.checkInputRasters(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Initial or final raster is not set. Please specify input data and try again")
                         )
      return

    if not utils.checkFactors(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Factors rasters is not set. Please specify them and try again")
                         )
      return

    if not utils.checkChangeMap(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Change map raster is not set. Please create it try again")
                         )
      return

    self.settings.setValue("ui/LR/neighborhood", self.spnNeighbourhood.value())

    self.plugin.logMessage(self.tr("Init LR model"))

    model = LR(ns=self.spnNeighbourhood.value())
    self.inputs["model"] = model
    model.setMaxIter(self.spnMaxIterations.value())

    model.setState(self.inputs["initial"])
    model.setFactors(self.inputs["factors"].values())
    model.setOutput(self.inputs["changeMap"])
    model.setMode(self.inputs["samplingMode"],)
    model.setSamples(self.plugin.spnSamplesCount.value())

    self.plugin.logMessage(self.tr("Set training data"))
    model.moveToThread(self.plugin.workThread)
    self.plugin.workThread.started.connect(model.startTrain)
    self.plugin.setProgressRange("Train LR model", 0)
    model.finished.connect(self.__trainFinished)
    model.errorReport.connect(self.plugin.logErrorReport)
    model.finished.connect(self.plugin.workThread.quit)
    self.plugin.workThread.start()
  def manageGui(self):
    if not utils.checkFactors(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Factors rasters is not set. Please specify them and try again")
                         )
      return

    if not utils.checkChangeMap(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Change map raster is not set. Please create it try again")
                         )
      return

    self.tblReclass.clearContents()
    self.delegate = spinboxdelegate.SpinBoxDelegate(self.tblReclass.model(), minRange=2, maxRange=dataprovider.MAX_CATEGORIES)

    row = 0
    for k, v in self.inputs["factors"].iteritems():
      v.denormalize()   # Denormalize the factor's bands if they are normalized
      for b in xrange(1, v.getBandsCount()+1):
        if v.isCountinues(b):
          self.tblReclass.insertRow(row)
          if v.getBandsCount()>1:
            name = u"%s (band %s)" % (utils.getLayerById(k).name(), unicode(b))
          else:
            name = u"%s" % (utils.getLayerById(k).name(), )
          stat = v.getBandStat(b)
          for n, item_data in enumerate([name, (u"%f" % (stat["min"], )), (u"%f" % (stat["max"])), u"" , u"" ]):
            item = QTableWidgetItem(item_data)
            if n < 3:
              item.setFlags(item.flags() ^ Qt.ItemIsEditable)
            self.tblReclass.setItem(row, n, item)
          row += 1
    rowCount = row

    self.tblReclass.setItemDelegateForColumn(3, self.delegate)
    for row in range(rowCount):
      # Set 2 bins as default value
      self.tblReclass.setItem(row, 3, QTableWidgetItem(u'2'))

    self.tblReclass.resizeRowsToContents()
    self.tblReclass.resizeColumnsToContents()
  def trainNetwork(self):
    if not utils.checkInputRasters(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Initial or final raster is not set. Please specify input data and try again")
                         )
      return

    if not utils.checkFactors(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Factors rasters is not set. Please specify them and try again")
                         )
      return

    if not utils.checkChangeMap(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Change map raster is not set. Please create it try again")
                         )
      return

    if self.leTopology.text() == "":
      QMessageBox.warning(self.plugin,
                          self.tr("Wrong network topology"),
                          self.tr("Network topology is undefined. Please define it and try again")
                         )
      return

    self.settings.setValue("ui/ANN/neighborhood", self.spnNeigbourhood.value())
    self.settings.setValue("ui/ANN/learningRate", self.spnLearnRate.value())
    self.settings.setValue("ui/ANN/maxIterations", self.spnMaxIterations.value())
    self.settings.setValue("ui/ANN/topology", self.leTopology.text())
    self.settings.setValue("ui/ANN/momentum", self.spnMomentum.value())

    self.btnStop.setEnabled(True)
    self.btnTrainNetwork.setEnabled(False)

    self.plugin.logMessage(self.tr("Init ANN model"))

    model = MlpManager(ns=self.spnNeigbourhood.value())
    self.inputs["model"] = model
    model.createMlp(self.inputs["initial"],
                         self.inputs["factors"].values(),
                         self.inputs["changeMap"],
                         [int(n) for n in self.leTopology.text().split(" ")]
                        )

    self.plugin.logMessage(self.tr("Set training data"))
    model.setTrainingData(self.inputs["initial"],
                               self.inputs["factors"].values(),
                               self.inputs["changeMap"],
                               mode=self.inputs["samplingMode"],
                               samples=self.plugin.spnSamplesCount.value()
                              )

    model.setEpochs(self.spnMaxIterations.value())
    model.setValPercent(20)
    model.setLRate(self.spnLearnRate.value())
    model.setMomentum(self.spnMomentum.value())
    model.setContinueTrain()

    self.axes.cla()
    self.axes.grid(True)
    self.dataTrain = []
    self.dataVal = []
    self.plotTrain = self.axes.plot(self.dataTrain,
                                    linewidth=1,
                                    color="green",  marker='o'
                                   )[0]
    self.plotVal = self.axes.plot(self.dataVal,
                                  linewidth=1,
                                  color="red",
                                 )[0]
    leg = self.axes.legend(('Train', 'Validation'), 'upper right', shadow=False)
    for t in leg.get_texts():
        t.set_fontsize('small')
    model.moveToThread(self.plugin.workThread)

    self.plugin.workThread.started.connect(model.startTrain)
    self.btnStop.clicked.connect(model.stopTrain)
    model.updateGraph.connect(self.__updateGraph)
    model.updateDeltaRMS.connect(self.__updateRMS)
    model.updateMinValErr.connect(self.__updateValidationError)
    model.updateKappa.connect(self.__updateKappa)
    model.processInterrupted.connect(self.__trainInterrupted)
    model.rangeChanged.connect(self.plugin.setProgressRange)
    model.updateProgress.connect(self.plugin.showProgress)
    model.errorReport.connect(self.plugin.logErrorReport)
    model.processFinished.connect(self.__trainFinished)
    model.processFinished.connect(self.plugin.workThread.quit)

    self.plugin.logMessage(self.tr("Start trainig ANN model"))
    self.plugin.workThread.start()
Exemple #4
0
    def trainNetwork(self):
        if not utils.checkInputRasters(self.inputs):
            QMessageBox.warning(
                self.plugin, self.tr("Missed input data"),
                self.
                tr("Initial or final raster is not set. Please specify input data and try again"
                   ))
            return

        if not utils.checkFactors(self.inputs):
            QMessageBox.warning(
                self.plugin, self.tr("Missed input data"),
                self.
                tr("Factors rasters is not set. Please specify them and try again"
                   ))
            return

        if not utils.checkChangeMap(self.inputs):
            QMessageBox.warning(
                self.plugin, self.tr("Missed input data"),
                self.
                tr("Change map raster is not set. Please create it try again"))
            return

        if self.leTopology.text() == "":
            QMessageBox.warning(
                self.plugin, self.tr("Wrong network topology"),
                self.
                tr("Network topology is undefined. Please define it and try again"
                   ))
            return

        self.settings.setValue("ui/ANN/neighborhood",
                               self.spnNeigbourhood.value())
        self.settings.setValue("ui/ANN/learningRate",
                               self.spnLearnRate.value())
        self.settings.setValue("ui/ANN/maxIterations",
                               self.spnMaxIterations.value())
        self.settings.setValue("ui/ANN/topology", self.leTopology.text())
        self.settings.setValue("ui/ANN/momentum", self.spnMomentum.value())

        self.btnStop.setEnabled(True)
        self.btnTrainNetwork.setEnabled(False)

        self.plugin.logMessage(self.tr("Init ANN model"))

        model = MlpManager(ns=self.spnNeigbourhood.value())
        self.inputs["model"] = model
        model.createMlp(self.inputs["initial"],
                        self.inputs["factors"].values(),
                        self.inputs["changeMap"],
                        [int(n) for n in self.leTopology.text().split(" ")])

        self.plugin.logMessage(self.tr("Set training data"))
        model.setTrainingData(self.inputs["initial"],
                              self.inputs["factors"].values(),
                              self.inputs["changeMap"],
                              mode=self.inputs["samplingMode"],
                              samples=self.plugin.spnSamplesCount.value())

        model.setEpochs(self.spnMaxIterations.value())
        model.setValPercent(20)
        model.setLRate(self.spnLearnRate.value())
        model.setMomentum(self.spnMomentum.value())
        model.setContinueTrain()

        self.axes.cla()
        self.axes.grid(True)
        self.dataTrain = []
        self.dataVal = []
        self.plotTrain = self.axes.plot(self.dataTrain,
                                        linewidth=1,
                                        color="green",
                                        marker='o')[0]
        self.plotVal = self.axes.plot(
            self.dataVal,
            linewidth=1,
            color="red",
        )[0]
        leg = self.axes.legend(('Train', 'Validation'),
                               'upper right',
                               shadow=False)
        for t in leg.get_texts():
            t.set_fontsize('small')
        model.moveToThread(self.plugin.workThread)

        self.plugin.workThread.started.connect(model.startTrain)
        self.btnStop.clicked.connect(model.stopTrain)
        model.updateGraph.connect(self.__updateGraph)
        model.updateDeltaRMS.connect(self.__updateRMS)
        model.updateMinValErr.connect(self.__updateValidationError)
        model.updateKappa.connect(self.__updateKappa)
        model.processInterrupted.connect(self.__trainInterrupted)
        model.rangeChanged.connect(self.plugin.setProgressRange)
        model.updateProgress.connect(self.plugin.showProgress)
        model.errorReport.connect(self.plugin.logErrorReport)
        model.processFinished.connect(self.__trainFinished)
        model.processFinished.connect(self.plugin.workThread.quit)

        self.plugin.logMessage(self.tr("Start trainig ANN model"))
        self.plugin.workThread.start()