Package weka.core

Examples of weka.core.Instance


   * @throws Exception if classification can't be done successfully
   */
  public double classifyInstance(Instance instance) throws Exception {

    // Transform the input instance
    Instance transformedInstance = instance;
    if (!m_checksTurnedOff) {
      m_TransformFilter.input(transformedInstance);
      m_TransformFilter.batchFinished();
      transformedInstance = m_TransformFilter.output();
      m_MissingFilter.input(transformedInstance);
View Full Code Here


    if (numAttributes > 0) {
      independent = new Matrix(m_TransformedData.numInstances(),
             numAttributes);
      dependent = new Matrix(m_TransformedData.numInstances(), 1);
      for (int i = 0; i < m_TransformedData.numInstances(); i ++) {
  Instance inst = m_TransformedData.instance(i);
  int column = 0;
  for (int j = 0; j < m_TransformedData.numAttributes(); j++) {
    if (j == m_ClassIndex) {
      dependent.setElement(i, 0, inst.classValue());
    } else {
      if (selectedAttributes[j]) {
        double value = inst.value(j) - m_Means[j];
       
        // We only need to do this if we want to
        // scale the input
        if (!m_checksTurnedOff) {
    value /= m_StdDevs[j];
View Full Code Here

    return result.toString();
  }

  protected Instance applyFilters(Instance source,
      boolean incrementArtificialTime, boolean setAnyPeriodic) throws Exception {
    Instance result = source;

    /*
     * if (m_extraneousAttributeRemover != null) {
     * m_extraneousAttributeRemover.input(result); result =
     * m_extraneousAttributeRemover.output(); }
View Full Code Here

        newVals[j] = Utils.missingValue();
      }

      // copy over any overlay fields and time (if present in overlay data)
      if (overlay != null) {
        Instance overlayI = overlay.instance(i);
        for (String field : m_lagMaker.getOverlayFields()) {
          int index = m_originalHeader.attribute(field).index();
          newVals[index] = overlayI.value(index);
        }

        // non missing time stamp?
        if (!m_lagMaker.isUsingAnArtificialTimeIndex()
            && m_lagMaker.getAdjustForTrends()
            && m_lagMaker.getTimeStampField() != null
            && m_lagMaker.getTimeStampField().length() > 0) {

          int timeStampIndex = m_originalHeader.attribute(
              m_lagMaker.getTimeStampField()).index();
          if (!overlayI.isMissing(timeStampIndex)) {
            newVals[timeStampIndex] = overlayI.value(timeStampIndex);

            // want to store, rather than increment, time value since
            // we've read a time value from the overlay data
            incrementTime = false;
          }
        }
      }

      // create the test instance (original format)
      Instance origTest = new DenseInstance(1.0, newVals);
      origTest.setDataset(m_originalHeader);

      // System.err.println("Original with periodic set " + origTest);

      Instance transformedWithDate = origTest;

      // do all the filters
      // System.err.println("--- " + transformedWithDate);

      // transformedWithDate = applyFilters(transformedWithDate, true, true);
      transformedWithDate = m_lagMaker.processInstancePreview(
          transformedWithDate, incrementTime, setPeriodics);

      // the date time stamp (if exists) has now been remapped, so we can remove
      // the original
      m_dateRemover.input(transformedWithDate);
      Instance transformed = m_dateRemover.output();

      // System.err.println(transformedWithDate.dataset());
      // System.err.println(transformedWithDate);

      // System.err.println("Transformed: " + transformed);
View Full Code Here

                      .instance(i));

                  // output this instance immediately (make sure that we include
                  // any attributes for confidence intervals - these will be
                  // necessarily missing for historical instances)
                  Instance outgoing = convertToOutputFormat(m_overlayData
                      .instance(i));
                  InstanceEvent ie = new InstanceEvent(this, outgoing,
                      InstanceEvent.INSTANCE_AVAILABLE);
                  // notify listeners here
                  notifyInstanceListeners(ie);
                } catch (Exception e) {
                  e.printStackTrace();
                  statusError();
                  logError("problem occurred during priming.", e);
                  stop();
                  return;
                }

              } else {
                // transfer to the priming buffer
                m_bufferedPrimeData.add(m_overlayData.instance(i));
              }
            }

            // clear out the overlay data
            m_overlayData = new Instances(m_header, 0);
          } else {
            // not all missing and overlay buffer is empty then it's a priming
            // instance

            // either buffer it or send it directly to the forecaster (if
            // incrementally
            // primeable
            if (!m_rebuildForecaster) {
              try {
                m_forecaster.primeForecasterIncremental(toProcess);

                // output this instance immediately (make sure that we include
                // any attributes for confidence intervals - these will be
                // necessarily missing for historical instances)
                Instance outgoing = convertToOutputFormat(toProcess);
                InstanceEvent ie = new InstanceEvent(this, outgoing,
                    InstanceEvent.INSTANCE_AVAILABLE);
                // tell listeners
                notifyInstanceListeners(ie);
              } catch (Exception ex) {
                ex.printStackTrace();
                statusError();
                logError("problem occurred during priming.", ex);
                stop();
                return;
              }
            } else {
              // buffer
              m_bufferedPrimeData.add(toProcess);
            }
          }

        }
      } else {
        // not using overlay data
        if (!m_rebuildForecaster) {
          try {
            m_forecaster.primeForecasterIncremental(toProcess);

            // output this instance immediately (make sure that we include
            // any attributes for confidence intervals - these will be
            // necessarily missing for historical instances)
            Instance outgoing = convertToOutputFormat(toProcess);
            InstanceEvent ie = new InstanceEvent(this, outgoing,
                InstanceEvent.INSTANCE_AVAILABLE);
            notifyInstanceListeners(ie);
          } catch (Exception ex) {
            ex.printStackTrace();
View Full Code Here

    }

    statusMessage("Generating forecast...");
    logMessage("Generating forecast.");
    for (int i = 0; i < numSteps; i++) {
      Instance outputI = null;
      double[] outVals = new double[m_outgoingStructure.numAttributes()];
      for (int j = 0; j < outVals.length; j++) {
        if (overlay) {
          outVals[j] = m_overlayData.instance(i).value(j);
        } else {
          outVals[j] = Utils.missingValue();
        }
      }
      List<NumericPrediction> predsForStep = forecast.get(i);

      if (timeStampIndex != -1) {
        // set time value
        time = m_modelLagMaker.advanceSuppliedTimeValue(time);
        outVals[timeStampIndex] = time;
      }

      for (int j = 0; j < m_fieldsToForecast.size(); j++) {
        String target = m_fieldsToForecast.get(j);
        int targetI = m_outgoingStructure.attribute(target).index();
        NumericPrediction predForTargetAtStep = predsForStep.get(j);
        double y = predForTargetAtStep.predicted();
        double yHigh = y;
        double yLow = y;
        double[][] conf = predForTargetAtStep.predictionIntervals();
        if (!Utils.isMissingValue(y)) {
          outVals[targetI] = y;
        }

        // any confidence bounds?
        if (conf.length > 0) {
          yLow = conf[0][0];
          yHigh = conf[0][1];
          int indexOfLow = m_outgoingStructure
              .attribute(target + "_lowerBound").index();
          int indexOfHigh = m_outgoingStructure.attribute(
              target + "_upperBound").index();
          outVals[indexOfLow] = yLow;
          outVals[indexOfHigh] = yHigh;
        }
      }
      outputI = new DenseInstance(1.0, outVals);
      outputI.setDataset(m_outgoingStructure);

      // notify listeners of output instance
      InstanceEvent ie = new InstanceEvent(this, outputI,
          InstanceEvent.INSTANCE_AVAILABLE);
View Full Code Here

            .joinOptions(m_forecaster.getOptions()) + "|" : "");
  }

  private Instance convertToOutputFormat(Instance incoming) {

    Instance output = (Instance) incoming.copy();
    if (m_forecaster.isProducingConfidenceIntervals()) {
      double[] values = new double[incoming.numAttributes()
          + (m_fieldsToForecast.size() * 2)];
      for (int i = 0; i < incoming.numAttributes(); i++) {
        values[i] = incoming.value(i);
      }

      // set all bounds to missing (initially)
      for (int i = incoming.numAttributes(); i < incoming.numAttributes()
          + (m_fieldsToForecast.size() * 2); i++) {
        values[i] = Utils.missingValue();
      }

      output = new DenseInstance(1.0, values);
    }
    output.setDataset(m_outgoingStructure);

    return output;
  }
View Full Code Here

     * @return
     * @throws Exception if an error occurs
     */
    public Instance remapDateTimeStamp(Instance inst, Instance previous,
        String timeStampName) throws Exception {
      Instance result = inst;

      if (!isDateBased()) {
        throw new Exception("This periodicity is not date timestamp-based");
      }

      int origIndex = result.dataset().attribute(timeStampName).index();
      Calendar c = new GregorianCalendar();

      boolean applyTrainingSkipAdjust = true;
      long localSkipAdjust = 0;

      if (!result.isMissing(origIndex)) {

        Date d = new Date((long) result.value(origIndex));
        double origValue = result.value(origIndex);
        if (m_skipList != null && m_skipList.size() > 0 && previous != null) {
          // check this instance's date time stamp against the skip list -
          // our fundamental assumption (for the training data) is that these
          // dates
          // are not actually
          // present in the data (i.e. sat and sun for stock market data). If
          // they
          // are in the data (but with missing targets) then the missing value
          // interpolation routine will have filled them in, which is the wrong
          // thing to do if they are supposed to be skipped over
          if (dateInSkipList(d)) {
            throw new Exception(
                "This instance contains a date time stamp that is "
                    + "a member of the skip list - skip list entries are not time "
                    + "units with respect to the model and should not be present : "
                    + inst.toString());
          }

          if (!previous.isMissing(origIndex)) {
            if (result.value(origIndex) >= previous.value(origIndex)) {
              // compared to the previous date are we more than one time unit
              // ahead?
              double start = previous.value(origIndex);
              double end = origValue;
              while (start < end) {
                start = weka.classifiers.timeseries.core.Utils
                    .advanceSuppliedTimeValue(start, this);
                if (start < end) {
                  if (dateInSkipList(new Date((long) start))) {
                    m_trainingRemapSkipAdjust--;
                  } else {
                    // oh oh the difference between the current and previous
                    // instance
                    // is more than one time step but the intervening step(s)
                    // are
                    // not in the skip list!
                    throw new Exception("There is an increment of more than "
                        + "one time step between\n" + previous.toString()
                        + "\nand\n" + inst.toString() + "\n but none of the "
                        + "intervening time steps are in the " + "skip list.");
                  }
                }
              }
            } else {
              // we have a problem here - data is not sorted in ascending order
              // of the date time stamp!
              throw new Exception(
                  "The data does not seem to be sorted in ascending order "
                      + "of the date time stamp!");
            }
          }
        }

        if (m_skipList != null && m_skipList.size() > 0 && previous == null) {
          // this case indicates that we are being invoked in a
          // priming/forecasting context

          // check that this instance does not occur before the first training
          // instance!!
          if (origValue < m_dateTimeStampInitialVal) {
            throw new Exception(
                "The timestamp for this instance occurs before the "
                    + "timestamp of the first training instance!");
          }
          // can't prime/forecast for values that occurred before the training
          // data.

          double end = result.value(origIndex);
          // first advance end until it is not in the skip list (this won't
          // be needed for priming instances that are within the training
          // date range), but might occur for closed-loop forecasting when
          // the date is advanced one time unit for each step
          while (dateInSkipList(new Date((long) end))) {
            end = weka.classifiers.timeseries.core.Utils
                .advanceSuppliedTimeValue(end, this);
          }

          double start = 0;
          if (end < m_dateTimeStampFinalVal) {
            // priming/forecasting within the range of the training data -
            // will have to recompute all skips from the initial training
            // time stamp up to this instance and not apply the pre-computed
            // skip total for the full training period
            applyTrainingSkipAdjust = false;
            start = m_dateTimeStampInitialVal;
          } else {
            // priming/forecasting beyond the last training date time stamp seen
            start = m_dateTimeStampFinalVal;
          }

          // now compute local skip adjust from start up to end
          while (start < end) {
            start = weka.classifiers.timeseries.core.Utils
                .advanceSuppliedTimeValue(start, this);
            if (start < end) {
              if (dateInSkipList(new Date((long) start))) {
                localSkipAdjust--;
              }
            }
          }
          // set end as the current value
          d = new Date((long) end);
          origValue = end;
        }

        if (m_handlerPeriodicity == Periodicity.MONTHLY
            || m_handlerPeriodicity == Periodicity.WEEKLY
            || m_handlerPeriodicity == Periodicity.QUARTERLY) {
          c.setTime(d);
          long year = c.get(Calendar.YEAR);
          long month = c.get(Calendar.MONTH);
          long week = c.get(Calendar.WEEK_OF_YEAR);
          long remapped = 0;
          if (m_handlerPeriodicity == Periodicity.MONTHLY) {
            remapped = ((year - m_dateTimeStampBaseVal) * 12) + month;
          } else if (m_handlerPeriodicity == Periodicity.WEEKLY) {
            remapped = ((year - m_dateTimeStampBaseVal) * 52) + week;

            // adjust for the case where week 1 of the year actually starts
            // in the last week of December
            if (month == Calendar.DECEMBER && week == 1) {
              remapped += 52;
            }
          } else if (m_handlerPeriodicity == Periodicity.QUARTERLY) {
            remapped = ((year - m_dateTimeStampBaseVal) * 4)
                + ((month / 3L) + 1L);
          }

          if (m_skipList != null && m_skipList.size() > 0) {
            remapped += (applyTrainingSkipAdjust) ? m_trainingRemapSkipAdjust
                : 0;
            remapped += localSkipAdjust;
          }

          result.setValue(result.numAttributes() - 1, remapped);
        } else {
          double remapped = origValue - m_dateTimeStampInitialVal;
          remapped /= deltaTime();// m_deltaTime;

          // it might (or might not) make sense to take the floor here. For
          // daily data
          // I have the feeling that data arithmetic (adding 1 to day of the
          // year)
          // may actually add slightly more than
          // a day at certain times (to account for) leap seconds/years
          // remapped = Math.floor(remapped);
          if (m_skipList != null && m_skipList.size() > 0) {
            remapped += (applyTrainingSkipAdjust) ? m_trainingRemapSkipAdjust
                : 0;
            remapped += localSkipAdjust;
          }
          result.setValue(result.numAttributes() - 1, remapped);
        }
      }
      return result;
    }
View Full Code Here

       
        double lastNonMissing = Utils.missingValue();
        boolean ok = true;
        boolean hasMissing = false;
        for (int i = 0; i < m_instances.numInstances(); i++) {
          Instance current = m_instances.instance(i);
         
          if (Utils.isMissingValue(lastNonMissing)) {
            if (!current.isMissing(timeStampAtt)) {
              lastNonMissing = current.value(timeStampAtt);
            } else {
              hasMissing = true;
            }
          } else {
            if (!current.isMissing(timeStampAtt)) {
              if (current.value(timeStampAtt) - lastNonMissing < 0) {
                ok = false;
                break;
              }
             
              lastNonMissing = current.value(timeStampAtt);
            } else {
              hasMissing = true;
            }
          }
        }
View Full Code Here

    str += "\nshowdown5Model " + showdown5Model.toString().length(); // (showdown5Model == null?"NULL":"OK");
    return str;
  }
 
  public Pair<Double, Double> getCheckBetProbabilities(PlayerId actor, Propositionalizer props) {
    Instance instance;
    if ("preflop".equals(props.getRound())) {
      instance = getPreCheckBetInstance(actor, props);
    } else {
      instance = getPostCheckBetInstance(actor, props);
    }
    try {
      double prediction;
      if ("preflop".equals(props.getRound())) {
        prediction = preBetModel.classifyInstance(instance);
      } else {
        prediction = postBetModel.classifyInstance(instance);
      }
      double prob = Math.min(1, Math.max(0, prediction));

      if (Double.isNaN(prob) || Double.isInfinite(prob)) {
        throw new IllegalStateException("Bad probability: " + prob);
      }
      Pair<Double, Double> result = new Pair<Double, Double>(1 - prob, prob);
      if (logger.isTraceEnabled()) {
        logger.trace(instance + ": " + result);
      }
      return result;
    } catch (Exception e) {
      throw new IllegalStateException(e.toString() + "\n" + actor + " " + props.getRound() + ": " + instance.toString(), e);
    }
  }
View Full Code Here

TOP

Related Classes of weka.core.Instance

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.