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

📄 bifreader.java

📁 代码是一个分类器的实现,其中使用了部分weka的源代码。可以将项目导入eclipse运行
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. *  * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the * GNU General Public License for more details. *  * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *//* * BIFReader.java * Copyright (C) 2003 Remco Bouckaert *  */package weka.classifiers.bayes.net;import weka.classifiers.bayes.BayesNet;import weka.classifiers.bayes.net.estimate.DiscreteEstimatorBayes;import weka.core.FastVector;import weka.core.Instances;import weka.core.TechnicalInformation;import weka.core.TechnicalInformation.Type;import weka.core.TechnicalInformation.Field;import weka.core.TechnicalInformationHandler;import weka.estimators.Estimator;import java.io.File;import java.util.StringTokenizer;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.CharacterData;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;/** <!-- globalinfo-start --> * Builds a description of a Bayes Net classifier stored in XML BIF 0.3 format.<br/> * <br/> * For more details on XML BIF see:<br/> * <br/> * Fabio Cozman, Marek Druzdzel, Daniel Garcia (1998). XML BIF version 0.3. URL http://www-2.cs.cmu.edu/~fgcozman/Research/InterchangeFormat/. * <p/> <!-- globalinfo-end --> *  <!-- technical-bibtex-start --> * BibTeX: * <pre> * &#64;misc{Cozman1998, *    author = {Fabio Cozman and Marek Druzdzel and Daniel Garcia}, *    title = {XML BIF version 0.3}, *    year = {1998}, *    URL = {http://www-2.cs.cmu.edu/~fgcozman/Research/InterchangeFormat/} * } * </pre> * <p/> <!-- technical-bibtex-end --> * <!-- options-start --> * Valid options are: <p/> *  * <pre> -D *  Do not use ADTree data structure * </pre> *  * <pre> -B &lt;BIF file&gt; *  BIF file to compare with * </pre> *  * <pre> -Q weka.classifiers.bayes.net.search.SearchAlgorithm *  Search algorithm * </pre> *  * <pre> -E weka.classifiers.bayes.net.estimate.SimpleEstimator *  Estimator algorithm * </pre> *  <!-- options-end --> * * @author Remco Bouckaert (rrb@xm.co.nz) * @version $Revision: 1.10 $ */public class BIFReader     extends BayesNet    implements TechnicalInformationHandler {      private int [] m_nPositionX;    private int [] m_nPositionY;    private int [] m_order;        /** for serialization */    static final long serialVersionUID = -8358864680379881429L;    /**     * This will return a string describing the classifier.     * @return The string.     */    public String globalInfo() {        return             "Builds a description of a Bayes Net classifier stored in XML "        + "BIF 0.3 format.\n\n"        + "For more details on XML BIF see:\n\n"        + getTechnicalInformation().toString();    }	/** processFile reads a BIFXML file and initializes a Bayes Net	 * @param sFile name of the file to parse	 * @return the BIFReader	 * @throws Exception if processing fails	 */	public BIFReader processFile(String sFile) throws Exception {		m_sFile = sFile;        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        factory.setValidating(true);        Document doc = factory.newDocumentBuilder().parse(new File(sFile));        doc.normalize();        buildInstances(doc, sFile);        buildStructure(doc);        return this;	} // processFile	/** the current filename */	String m_sFile;		/**	 * returns the current filename	 * 	 * @return the current filename	 */	public String getFileName() {	  return m_sFile;	}			/**	 * Returns an instance of a TechnicalInformation object, containing 	 * detailed information about the technical background of this class,	 * e.g., paper reference or book this class is based on.	 * 	 * @return the technical information about this class	 */	public TechnicalInformation getTechnicalInformation() {	  TechnicalInformation 	result;	  	  result = new TechnicalInformation(Type.MISC);	  result.setValue(Field.AUTHOR, "Fabio Cozman and Marek Druzdzel and Daniel Garcia");	  result.setValue(Field.YEAR, "1998");	  result.setValue(Field.TITLE, "XML BIF version 0.3");	  result.setValue(Field.URL, "http://www-2.cs.cmu.edu/~fgcozman/Research/InterchangeFormat/");	  	  return result;	}		/** buildStructure parses the BIF document in the DOM tree contained	 * in the doc parameter and specifies the the network structure and 	 * probability tables.	 * It assumes that buildInstances has been called before	 * @param doc DOM document containing BIF document in DOM tree	 * @throws Exception if building of structure fails	 */    void buildStructure(Document doc)  throws Exception {        // Get the name of the network		// initialize conditional distribution tables		m_Distributions = new Estimator[m_Instances.numAttributes()][];        for (int iNode = 0; iNode < m_Instances.numAttributes(); iNode++) {        	// find definition that goes with this node        	String sName = m_Instances.attribute(iNode).name();			Element definition = getDefinition(doc, sName);/*	        if (nodelist.getLength() == 0) {	        	throw new Exception("No definition found for node " + sName);	        }	        if (nodelist.getLength() > 1) {	        	System.err.println("More than one definition found for node " + sName + ". Using first definition.");	        }	        Element definition = (Element) nodelist.item(0);*/	        	        	        // get the parents for this node	        // resolve structure	        FastVector nodelist = getParentNodes(definition);	        for (int iParent = 0; iParent < nodelist.size(); iParent++) {	        	Node parentName = ((Node) nodelist.elementAt(iParent)).getFirstChild();	        	String sParentName = ((CharacterData) (parentName)).getData();	        	int nParent = getNode(sParentName);	        	m_ParentSets[iNode].addParent(nParent, m_Instances);	        }	        // resolve conditional probability table		        int nCardinality = m_ParentSets[iNode].getCardinalityOfParents();	        int nValues = m_Instances.attribute(iNode).numValues();	        m_Distributions[iNode] = new Estimator[nCardinality];			for (int i = 0; i < nCardinality; i++) {				m_Distributions[iNode][i] = new DiscreteEstimatorBayes(nValues, 0.0f);			}/*	        StringBuffer sTable = new StringBuffer();	        for (int iText = 0; iText < nodelist.getLength(); iText++) {	        	sTable.append(((CharacterData) (nodelist.item(iText))).getData());	        	sTable.append(' ');	        }	        StringTokenizer st = new StringTokenizer(sTable.toString());*/	        String sTable = getTable(definition);			StringTokenizer st = new StringTokenizer(sTable.toString());	        	        			for (int i = 0; i < nCardinality; i++) {				DiscreteEstimatorBayes d = (DiscreteEstimatorBayes) m_Distributions[iNode][i];				for (int iValue = 0; iValue < nValues; iValue++) {					String sWeight = st.nextToken();					d.addValue(iValue, new Double(sWeight).doubleValue());				}			}         }    } // buildStructure    /** synchronizes the node ordering of this Bayes network with     * those in the other network (if possible).     * @param other Bayes network to synchronize with     * @throws Exception if nr of attributes differs or not all of the variables have the same name.     */    public void Sync(BayesNet other) throws Exception {    	int nAtts = m_Instances.numAttributes();    	if (nAtts != other.m_Instances.numAttributes()) {    		throw new Exception ("Cannot synchronize networks: different number of attributes.");    	}        m_order = new int[nAtts];        for (int iNode = 0; iNode < nAtts; iNode++) {        	String sName = other.getNodeName(iNode);        	m_order[getNode(sName)] = iNode;        }    } // Sync	/** getNode finds the index of the node with name sNodeName	 * and throws an exception if no such node can be found.	 * @param sNodeName name of the node to get the index from	 * @return index of the node with name sNodeName	 * @throws Exception if node cannot be found	 */    public int getNode(String sNodeName) throws Exception {    	int iNode = 0;    	while (iNode < m_Instances.numAttributes()) {    		if (m_Instances.attribute(iNode).name().equals(sNodeName)) {    			return iNode;    		}	    	iNode++;     	}    	throw new Exception("Could not find node [[" + sNodeName + "]]");    } // getNode    /**     * Returns all TEXT children of the given node in one string. Between     * the node values new lines are inserted.     *      * @param node the node to return the content for     * @return the content of the node     */    public String getContent(Element node) {      NodeList       list;      Node           item;      int            i;      String         result;            result = "";      list   = node.getChildNodes();            for (i = 0; i < list.getLength(); i++) {         item = list.item(i);         if (item.getNodeType() == Node.TEXT_NODE)            result += "\n" + item.getNodeValue();      }               return result;    }	/** buildInstances parses the BIF document and creates a Bayes Net with its 	 * nodes specified, but leaves the network structure and probability tables empty.	 * @param doc DOM document containing BIF document in DOM tree	 * @param sName default name to give to the Bayes Net. Will be overridden if specified in the BIF document.	 * @throws Exception if building fails	 */	void buildInstances(Document doc, String sName) throws Exception {		NodeList nodelist;        // Get the name of the network        nodelist = selectAllNames(doc);        if (nodelist.getLength() > 0) {        	sName = ((CharacterData) (nodelist.item(0).getFirstChild())).getData();        }        // Process variables        nodelist = selectAllVariables(doc);		int nNodes = nodelist.getLength();		// initialize structure		FastVector attInfo = new FastVector(nNodes);        // Initialize        m_nPositionX = new int[nodelist.getLength()];        m_nPositionY = new int[nodelist.getLength()];

⌨️ 快捷键说明

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