⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 supportvectorminingmodel.java

📁 一个数据挖掘软件ALPHAMINERR的整个过程的JAVA版源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        svmm.setLinearKernelType(lkt);
        break;
      case SupportVectorSettings.KERNEL_POLY:
        PolynomialKernelType pkt = new PolynomialKernelType();
        pkt.setCoef0(Double.toString(coef0));
        pkt.setDegree(Double.toString(degree));
        pkt.setGamma(Double.toString(gamma));
        pkt.setDescription("Polynomial kernel type");
        svmm.setPolynomialKernelType(pkt);
        break;
      case SupportVectorSettings.KERNEL_RBF:
        RadialBasisKernelType rbkt = new RadialBasisKernelType();
        rbkt.setGamma(Double.toString(gamma));
        rbkt.setDescription("Radial basis kernel type");
        svmm.setRadialBasisKernelType(rbkt);
        break;
      case SupportVectorSettings.KERNEL_SIGMOID:
        SigmoidKernelType skt = new SigmoidKernelType();
        skt.setCoef0(Double.toString(coef0));
        skt.setGamma(Double.toString(gamma));
        skt.setDescription("Sigmoid kernel type");
        svmm.setSigmoidKernelType(skt);
        break;
      default: throw new MiningException("unknown kernel type");
    }

    // Add Support Vectors from global list:
    SupportVectors xsvs = new SupportVectors();
    int nSupp = 0;
    if (supportVectors != null) nSupp = supportVectors.length;
    xsvs.setNumberOfSupportVectors( Integer.toString(nSupp) );
    MiningDataSpecification metaData = miningSettings.getDataSpecification();
    xsvs.setNumberOfAttributes( Integer.toString( metaData.getAttributesNumber() ) );
    for (int i = 0; i < nSupp; i++)
    {
      MiningVector mv = supportVectors[i];
      String mvId     = null;
      Enumeration gsv = globalSupportVectors.keys();
      while ( gsv.hasMoreElements() ) {
        String mvId2     = (String) gsv.nextElement();
        MiningVector mv2 = (MiningVector) globalSupportVectors.get(mvId2);
        if (mv == mv2) {
          mvId = mvId2;
          break;
        };
      };
      if (mvId == null)
        throw new MiningException("cannot find SV in global list");
      SupportVector xsv = new SupportVector();
      xsv.setVectorId(mvId);
      xsvs.addSupportVector(xsv);
    };
    svmm.setSupportVectors(xsvs);

    // Add coefficients:
    Coefficients xcs = new Coefficients();
    xcs.setNumberOfSupportVectors( Integer.toString(nSupp) );
    xcs.setAbsoluteValue( Double.toString(absoluteCoefficient) );
    for(int i = 0; i < coefficients.length; i++)
    {
      Coefficient xc = new Coefficient();
      xc.setValue( Double.toString(coefficients[i]) );
      xcs.addCoefficient(xc);
    };
    svmm.setCoefficients(xcs);

    return svmm;
  }

  /**
   * Reads PMML document of SVM model.
   * PMMLs SupportVectorMachineModel is used.
   *
   * @param reader reader for PMML model
   * @exception MiningException could not read PMML model
   * @see com.prudsys.pdm.Adapters.PmmlVersion20.SupportVectorMachineModel
   */
  public void readPmml(Reader reader) throws MiningException
  {
//    com.borland.xml.toolkit.XmlUtil.setEncoding( "UTF-8" );
    PMML pmml = PMML.unmarshal( reader );
    if( pmml.getSupportVectorMachineModelCount() == 0 )
      throw new MiningException("no SVM model found");

    // Read data dictionary:
    DataDictionary dictionary = pmml.getDataDictionary();
    MiningDataSpecification newMetaData = new MiningDataSpecification();
    newMetaData.parsePmmlObject( dictionary );

    // Read transformation dictionary:
    TransformationDictionary transDict = pmml.getTransformationDictionary();
    if (transDict != null) {
          MiningTransformationActivity mta = new MiningTransformationActivity();
          mta.parsePmmlObject(transDict);
          MiningDataSpecification tmds = mta.transform(newMetaData);
          tmds.setPretransformedMetaData(newMetaData);
          newMetaData = tmds;
          newMetaData.setMiningTransformationActivity( mta );
          newMetaData.setTransformed(true);
    };

    // Read global support vector dictionary:
    VectorDictionary vdic = pmml.getVectorDictionary();
    if (vdic != null) {
      VectorInstance[] vis = vdic.getVectorInstance();
      int nVecDict = 0;
      if (vis != null) nVecDict = vis.length;
      globalSupportVectors = new Hashtable();
      for (int i = 0; i < nVecDict; i++) {
        AttributeInstance[] ais = vis[i].getAttributeInstance();
        double[] values = new double[ais.length];
        for (int j = 0; j < ais.length; j++) {
          MiningAttribute ma = newMetaData.getMiningAttribute(ais[j].getName());
          values[newMetaData.getAttributeIndex(ma)] = Double.parseDouble(ais[j].
              getValue());
        };
        MiningVector supportVector = new MiningVector(values);
        supportVector.setMetaData(newMetaData);
        String supportVectorID = vis[i].getId();
        globalSupportVectors.put(supportVectorID, supportVector);
      };
      System.out.println("#support vectors:" + globalSupportVectors.size());
    };

    // Init settings:
    SupportVectorSettings svmSettings = new SupportVectorSettings();
    svmSettings.setDataSpecification( newMetaData );
    setMiningSettings( svmSettings );

    // Read SVM model:
    SupportVectorMachineModel[] svmModel = pmml.getSupportVectorMachineModel();
    parsePmmlObject(svmModel[0]);
  }

  /**
   * Reads PMML SupportVectorMachineModel element.
   *
   * @param pmml object of SupportVectorMachineModel
   * @exception MiningException could not parse PMML model
   * @see com.prudsys.pdm.Adapters.PmmlVersion20.SupportVectorMachineModel
   */
  public void parsePmmlObject(Object pmml) throws MiningException
  {
    SupportVectorMachineModel svmm = (SupportVectorMachineModel) pmml;

    // Get mining schema:
    MiningSchema schema = svmm.getMiningSchema();

    // Create input specification, get target attribute and inner trafo from schema:
    inputSpec = new ApplicationInputSpecification();
    inputSpec.parsePmmlObject( schema );
    target          = inputSpec.getTargetApplicationAttribute();
    miningTransform = inputSpec.createInnerTrafoFromInputSpec( miningSettings.getDataSpecification() );

    // Add target attribute to mining settings:
    SupportVectorSettings svs = (SupportVectorSettings) miningSettings;
    String classificationAttributeName = target.getName();
    svs.setPredictedAttributeName( classificationAttributeName );
    MiningAttribute targetAtt = svs.getDataSpecification().getMiningAttribute( classificationAttributeName );
    svs.setTarget( targetAtt );

    // Get SVM type:
    String xsvm = svmm.getSvmType();
    if(xsvm.equals("C_SVC")) svmType = SupportVectorSettings.SVM_C_SVC;
    else if(xsvm.equals("EPSILON_SVR")) svmType = SupportVectorSettings.SVM_EPSILON_SVR;
    else if(xsvm.equals("NU_SVC")) svmType = SupportVectorSettings.SVM_NU_SVC;
    else if(xsvm.equals("NU_SVR")) svmType = SupportVectorSettings.SVM_NU_SVR;
    else if(xsvm.equals("ONE_CLASS_SVM")) svmType = SupportVectorSettings.SVM_ONE_CLASS;
    else throw new MiningException("unknown svm type");

    // Get kernel:
    LinearKernelType lkt = svmm.getLinearKernelType();
    PolynomialKernelType pkt = svmm.getPolynomialKernelType();
    RadialBasisKernelType rbkt = svmm.getRadialBasisKernelType();
    SigmoidKernelType skt = svmm.getSigmoidKernelType();
    try {
      if(lkt != null)
      {
        kernelType = SupportVectorSettings.KERNEL_LINEAR ;
      }
      else if(pkt != null)
      {
        coef0 = Double.parseDouble(pkt.getCoef0());
        gamma = Double.parseDouble(pkt.getGamma());
        degree = Double.parseDouble(pkt.getDegree());
        kernelType = SupportVectorSettings.KERNEL_POLY;
      }
      else if(rbkt != null)
      {
        gamma = Double.parseDouble(rbkt.getGamma());
        kernelType = SupportVectorSettings.KERNEL_RBF;
      }
      else if(skt != null)
      {
        coef0 = Double.parseDouble(skt.getCoef0());
        gamma = Double.parseDouble(skt.getGamma());
        kernelType = SupportVectorSettings.KERNEL_SIGMOID;
      }
    } catch(NumberFormatException ex) {
      throw new MiningException("not a number in one of the fields of the kernel type");
    };

    // Get SVs and copy them from global into local SV list:
    SupportVectors xsvs = svmm.getSupportVectors();
    int nSV = Integer.parseInt( xsvs.getNumberOfSupportVectors() );
    SupportVector[] suppVec = xsvs.getSupportVector();
    int nSuppVec = suppVec.length;
    if (nSuppVec != nSuppVec)
      System.out.println("Warning: Number of SVs does not match SV array length");

    supportVectors = new MiningVector[nSuppVec];
    for (int i = 0; i < nSuppVec; i++) {
      String supportVectorId     = suppVec[i].getVectorId();
      MiningVector supportVector = (MiningVector) globalSupportVectors.get(supportVectorId);
      if (supportVector == null)
        throw new MiningException("cannot find SV in global SV list");
     supportVectors[i] = supportVector;
    };
    System.out.println("#local SVs = " + nSuppVec);

    // Get coefficients:
    Coefficient[] coefs = svmm.getCoefficients().getCoefficient();
    double[] newCoefficients = new double[coefs.length];
    for(int i = 0; i < coefs.length; i++)
      newCoefficients[i] = Double.parseDouble(coefs[i].getValue());
    coefficients = newCoefficients;
    absoluteCoefficient = Double.parseDouble(svmm.getCoefficients().getAbsoluteValue());

    // Create classifier object:
    SupportVectorClassifier svc = new SupportVectorClassifier();
    MiningDataSpecification svcMetaData = svs.getDataSpecification();
    if (miningTransform != null)  // reduce meta data to mining schema
      svcMetaData = miningTransform.transform(svs.getDataSpecification());
    svc.setMetaData( svcMetaData );
    svc.classIndex          = svcMetaData.getAttributeIndex(targetAtt);
    svc.svmType             = svmType;
    svc.kernelType          = kernelType;
    svc.degree              = degree;
    svc.gamma               = gamma;
    svc.coef0               = coef0;
    svc.supportVectors      = supportVectors;
    svc.coefficients        = coefficients;
    svc.absoluteCoefficient = absoluteCoefficient;

    if (miningTransform != null) { // reduce support vectors to mining schema
      svc.supportVectors = new MiningVector[ supportVectors.length ];
      for (int i = 0; i < supportVectors.length; i++)
        svc.supportVectors[i] = miningTransform.transform(supportVectors[i]);
    };

    setClassifier( svc );
  }

  // -----------------------------------------------------------------------
  //  Other export methods
  // -----------------------------------------------------------------------
  /**
   * Writes SVM model as plain text. Currently not supported.
   *
   * @param ps print stream for plain text model
   * @exception MiningException could not write plain text
   */
  public void writePlainText(PrintStream ps) throws MiningException
  {
    ps.println("Not implemented");
  }

  /**
   * Returns support vector machine model as HTML string.
   *
   * @return model as HTML string
   */
  public String toHtmlString()
  {
    StringBuffer sb = new StringBuffer();
    sb.append("<br>");
    sb.append("<P>Kernel type: ");
    switch(kernelType)
    {
      case SupportVectorSettings.KERNEL_LINEAR: sb.append("linear"); break;
      case SupportVectorSettings.KERNEL_POLY: sb.append("polinomial"); break;
      case SupportVectorSettings.KERNEL_RBF: sb.append("radial basis"); break;
      case SupportVectorSettings.KERNEL_SIGMOID: sb.append("sigmoid"); break;
      default: sb.append(" unknown"); break;
    }
    sb.append("<br>SVM type: ");
    switch(svmType)
    {
      case SupportVectorSettings.SVM_C_SVC: sb.append("C_SVC"); break;
      case SupportVectorSettings.SVM_NU_SVC: sb.append("NU_SVC"); break;
      case SupportVectorSettings.SVM_ONE_CLASS: sb.append("ONE CLASS"); break;
      case SupportVectorSettings.SVM_EPSILON_SVR: sb.append("EPSILON_SVR"); break;
      case SupportVectorSettings.SVM_NU_SVR: sb.append("NU_SVR"); break;
    }
    sb.append("<br>Support vectors:<br><table width=50% border=1 cellspacing=0 cellpadding=0><tr><th>#</th>");
    MiningDataSpecification mds = miningSettings.getDataSpecification();
    int n = mds.getAttributesNumber();
    for(int i=0;i<n;i++)
    {
      sb.append("<th>"+mds.getMiningAttribute(i).getName()+"</th>");
    }
    sb.append("</tr>");
    for(int i=0;i<supportVectors.length;i++)
    {
      sb.append("<tr><td>"+Integer.toString(i)+"</td>");
      double[] vs = supportVectors[i].getValues();
      for(int j=0;j<vs.length;j++)
      {
        sb.append("<td>");
        String sv = null;
        MiningAttribute ma = mds.getMiningAttribute(j);
        if(ma instanceof CategoricalAttribute)
          sv = ((CategoricalAttribute)ma).getCategory(vs[j]).getDisplayValue();
        else
          sv = Double.toString(vs[j]);
        sb.append(sv+"</td>");
      }
      sb.append("</tr>");
    }
    sb.append("</table><P>Coefficients:</P><br><table width=50% border=1 cellspacing=0 cellpadding=0><tr><th>#</th><th>Coefficient</th></tr>");
    for(int i=0;i<coefficients.length;i++)
      sb.append("<tr><td>"+Integer.toString(i)+"</td><td>"+Double.toString(coefficients[i])+"</td></tr>");
    sb.append("</table><br><P>Absolute coefficient: "+Double.toString(absoluteCoefficient)+"</P>");
    return sb.toString();
  }

  /**
   * Returns string representation (just few words).
   *
   * @return string representation
   */
  public String toString()
  {
    return "Support vector mining model";
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -