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

📄 bifreader.java

📁 代码是一个分类器的实现,其中使用了部分weka的源代码。可以将项目导入eclipse运行
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        // Process variables        for (int iNode = 0; iNode < nodelist.getLength(); iNode++) {            // Get element			FastVector valueslist;	        // Get the name of the network    	    valueslist = selectOutCome(nodelist.item(iNode));			int nValues = valueslist.size();			// generate value strings	        FastVector nomStrings = new FastVector(nValues + 1);	        for (int iValue = 0; iValue < nValues; iValue++) {	        	Node node = ((Node) valueslist.elementAt(iValue)).getFirstChild();	        	String sValue = ((CharacterData) (node)).getData();	        	if (sValue == null) {	        		sValue = "Value" + (iValue + 1);	        	}				nomStrings.addElement(sValue);	        }			FastVector nodelist2;	        // Get the name of the network    	    nodelist2 = selectName(nodelist.item(iNode));    	    if (nodelist2.size() == 0) {    	    	throw new Exception ("No name specified for variable");    	    }    	    String sNodeName = ((CharacterData) (((Node) nodelist2.elementAt(0)).getFirstChild())).getData();			weka.core.Attribute att = new weka.core.Attribute(sNodeName, nomStrings);			attInfo.addElement(att);    	    valueslist = selectProperty(nodelist.item(iNode));			nValues = valueslist.size();			// generate value strings	        for (int iValue = 0; iValue < nValues; iValue++) {                // parsing for strings of the form "position = (73, 165)"	        	Node node = ((Node)valueslist.elementAt(iValue)).getFirstChild();	        	String sValue = ((CharacterData) (node)).getData();                if (sValue.startsWith("position")) {                    int i0 = sValue.indexOf('(');                    int i1 = sValue.indexOf(',');                    int i2 = sValue.indexOf(')');                    String sX = sValue.substring(i0 + 1, i1).trim();                    String sY = sValue.substring(i1 + 1, i2).trim();                    try {                    	m_nPositionX[iNode] = (int) Integer.parseInt(sX);                    	m_nPositionY[iNode] = (int) Integer.parseInt(sY);                    } catch (NumberFormatException e) {                    	System.err.println("Wrong number format in position :(" + sX + "," + sY +")");                   	    m_nPositionX[iNode] = 0;                   	    m_nPositionY[iNode] = 0;                    }                }            }        }         		m_Instances = new Instances(sName, attInfo, 100);		m_Instances.setClassIndex(nNodes - 1);		setUseADTree(false);		initStructure();	} // buildInstances//	/** selectNodeList selects list of nodes from document specified in XPath expression//	 * @param doc : document (or node) to query//	 * @param sXPath : XPath expression//	 * @return list of nodes conforming to XPath expression in doc//	 * @throws Exception//	 *///	private NodeList selectNodeList(Node doc, String sXPath) throws Exception {//		NodeList nodelist = org.apache.xpath.XPathAPI.selectNodeList(doc, sXPath);//		return nodelist;//	} // selectNodeList	NodeList selectAllNames(Document doc) throws Exception {		//NodeList nodelist = selectNodeList(doc, "//NAME");		NodeList nodelist = doc.getElementsByTagName("NAME");		return nodelist;	} // selectAllNames	NodeList selectAllVariables(Document doc) throws Exception {		//NodeList nodelist = selectNodeList(doc, "//VARIABLE");		NodeList nodelist = doc.getElementsByTagName("VARIABLE");		return nodelist;	} // selectAllVariables	Element getDefinition(Document doc, String sName) throws Exception {		//NodeList nodelist = selectNodeList(doc, "//DEFINITION[normalize-space(FOR/text())=\"" + sName + "\"]");		NodeList nodelist = doc.getElementsByTagName("DEFINITION");		for (int iNode = 0; iNode < nodelist.getLength(); iNode++) {			Node node = nodelist.item(iNode);			FastVector list = selectElements(node, "FOR");			if (list.size() > 0) {				Node forNode = (Node) list.elementAt(0);				if (getContent((Element) forNode).trim().equals(sName)) {					return (Element) node;				}			}		}		throw new Exception("Could not find definition for ((" + sName + "))");	} // getDefinition	FastVector getParentNodes(Node definition) throws Exception {		//NodeList nodelist = selectNodeList(definition, "GIVEN");		FastVector nodelist = selectElements(definition, "GIVEN");		return nodelist;	} // getParentNodes	String getTable(Node definition) throws Exception {		//NodeList nodelist = selectNodeList(definition, "TABLE/text()");		FastVector nodelist = selectElements(definition, "TABLE");		String sTable = getContent((Element) nodelist.elementAt(0));		sTable = sTable.replaceAll("\\n"," ");		return sTable;	} // getTable	FastVector selectOutCome(Node item) throws Exception {		//NodeList nodelist = selectNodeList(item, "OUTCOME");		FastVector nodelist = selectElements(item, "OUTCOME");		return nodelist;	} // selectOutCome	FastVector selectName(Node item) throws Exception {	   //NodeList nodelist = selectNodeList(item, "NAME");	   FastVector nodelist = selectElements(item, "NAME");	   return nodelist;   } // selectName   FastVector selectProperty(Node item) throws Exception {	  // NodeList nodelist = selectNodeList(item, "PROPERTY");	  FastVector nodelist = selectElements(item, "PROPERTY");	  return nodelist;   } // selectProperty	FastVector selectElements(Node item, String sElement) throws Exception {	  NodeList children = item.getChildNodes();	  FastVector nodelist = new FastVector();	  for (int iNode = 0; iNode < children.getLength(); iNode++) {		Node node = children.item(iNode);		if ((node.getNodeType() == Node.ELEMENT_NODE) && node.getNodeName().equals(sElement)) {			nodelist.addElement(node);		}	  }	  return nodelist;  } // selectElements	/** Count nr of arcs missing from other network compared to current network	 * Note that an arc is not 'missing' if it is reversed.	 * @param other network to compare with	 * @return nr of missing arcs	 */	public int missingArcs(BayesNet other) {		try {			Sync(other);			int nMissing = 0;			for (int iAttribute = 0; iAttribute < m_Instances.numAttributes(); iAttribute++) {				for (int iParent = 0; iParent < m_ParentSets[iAttribute].getNrOfParents(); iParent++) {					int nParent = m_ParentSets[iAttribute].getParent(iParent);					if (!other.getParentSet(m_order[iAttribute]).contains(m_order[nParent]) && !other.getParentSet(m_order[nParent]).contains(m_order[iAttribute])) {						nMissing++;					}				}			}			return nMissing;		} catch (Exception e) {			System.err.println(e.getMessage());			return 0;		}	} // missingArcs	/** Count nr of exta arcs  from other network compared to current network	 * Note that an arc is not 'extra' if it is reversed.	 * @param other network to compare with	 * @return nr of missing arcs	 */	public int extraArcs(BayesNet other) {		try {			Sync(other);			int nExtra = 0;			for (int iAttribute = 0; iAttribute < m_Instances.numAttributes(); iAttribute++) {				for (int iParent = 0; iParent < other.getParentSet(m_order[iAttribute]).getNrOfParents(); iParent++) {					int nParent = m_order[other.getParentSet(m_order[iAttribute]).getParent(iParent)];					if (!m_ParentSets[iAttribute].contains(nParent) && !m_ParentSets[nParent].contains(iAttribute)) {						nExtra++;					}				}			}			return nExtra;		} catch (Exception e) {			System.err.println(e.getMessage());			return 0;		}	} // extraArcs	/** calculates the divergence between the probability distribution	 * represented by this network and that of another, that is,	 * \sum_{x\in X} P(x)log P(x)/Q(x)	 * where X is the set of values the nodes in the network can take,	 * P(x) the probability of this network for configuration x	 * Q(x) the probability of the other network for configuration x	 * @param other network to compare with	 * @return divergence between this and other Bayes Network	 */	public double divergence(BayesNet other) {		try {			Sync(other);			// D: divergence			double D = 0.0;			int nNodes = m_Instances.numAttributes();			int [] nCard = new int[nNodes];			for (int iNode = 0; iNode < nNodes; iNode++) {				nCard[iNode] = m_Instances.attribute(iNode).numValues();			}			// x: holds current configuration of nodes			int [] x = new int[nNodes];			// simply sum over all configurations to calc divergence D			int i = 0;			while (i < nNodes) {				// update configuration				x[i]++;				while (i < nNodes && x[i] == m_Instances.attribute(i).numValues()) {					x[i] = 0;					i++;					if (i < nNodes){						x[i]++;					}				}				if (i < nNodes) {					i = 0;					// calc P(x) and Q(x)					double P = 1.0;					for (int iNode = 0; iNode < nNodes; iNode++) {						int iCPT = 0;						for (int iParent = 0; iParent < m_ParentSets[iNode].getNrOfParents(); iParent++) {					    	int nParent = m_ParentSets[iNode].getParent(iParent);						    iCPT = iCPT * nCard[nParent] + x[nParent];						} 						P = P * m_Distributions[iNode][iCPT].getProbability(x[iNode]);					}						double Q = 1.0;					for (int iNode = 0; iNode < nNodes; iNode++) {						int iCPT = 0;						for (int iParent = 0; iParent < other.getParentSet(m_order[iNode]).getNrOfParents(); iParent++) {					    	int nParent = m_order[other.getParentSet(m_order[iNode]).getParent(iParent)];						    iCPT = iCPT * nCard[nParent] + x[nParent];						} 						Q = Q * other.m_Distributions[m_order[iNode]][iCPT].getProbability(x[iNode]);					}						// update divergence if probabilities are positive					if (P > 0.0 && Q > 0.0) {						D = D + P * Math.log(Q / P);					}				}			}			return D;		} catch (Exception e) {			System.err.println(e.getMessage());			return 0;		}	} // divergence	/** Count nr of reversed arcs from other network compared to current network	 * @param other network to compare with	 * @return nr of missing arcs	 */	public int reversedArcs(BayesNet other) {		try {			Sync(other);			int nReversed = 0;		    for (int iAttribute = 0; iAttribute < m_Instances.numAttributes(); iAttribute++) {				for (int iParent = 0; iParent < m_ParentSets[iAttribute].getNrOfParents(); iParent++) {					int nParent = m_ParentSets[iAttribute].getParent(iParent);					if (!other.getParentSet(m_order[iAttribute]).contains(m_order[nParent]) && other.getParentSet(m_order[nParent]).contains(m_order[iAttribute])) {						nReversed++;					}				}			}			return nReversed;		} catch (Exception e) {			System.err.println(e.getMessage());			return 0;		}	} // reversedArcs	/**	 * the default constructor	 */	public BIFReader() {	}    /**     * Loads the file specified as first parameter and prints it to stdout.     *      * @param args the command line parameters     */    public static void main(String[] args) {        try {            BIFReader br = new BIFReader();            br.processFile(args[0]);	    System.out.println(br.toString());                }        catch (Throwable t) {            t.printStackTrace();        }    } // main} // class BIFReader

⌨️ 快捷键说明

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