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

📄 mainfrm.cpp

📁 实现决策树分类训练试验。 源自c4.5
💻 CPP
字号:
// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include "Cart.h"
#include "defns.h"
#include "types.h"
#include "MyDiag.h"
#include "MyBase.h"
#include "MainFrm.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

char Msg[200];
FILE *fLog,*fRST;
CProgressCtrl	mProgCtrl;

/*  External data, described in extern.i  */
/*  This is from C45.c  */
// 主要参数变量定义。
short		MaxAtt, MaxClass, MaxDiscrVal = 2;
ItemNo		MaxItem;
Description	*Item;
DiscrValue	*MaxAttVal;
char        * SpecialStatus, FileName[100];
String		* ClassName, * AttName, ** AttValName;
short		VERBOSITY = 0,	TRIALS    = 10;
BOOL	GAINRATIO  = true,
		SUBSET     = false,
		BATCH      = true,
		UNSEENS    = false,
		PROBTHRESH = false;

ItemNo		MINOBJS   = 2,
	    	WINDOW    = 0,
		    INCREMENT = 0;
float		CF = 0.25;
Tree		*Pruned;
Boolean		AllKnown = true;
/*  End of  This is from C45.c  */

/*  This is from C45Rule.c  */

BOOL	SIGTEST	 = false,	/* use significance test in rule pruning */
		SIMANNEAL  = false ;	/* use simulated annealing */
float	SIGTHRESH   = 0.05,
		REDUNDANCY  = 1.0;	/* factor that guesstimates the
					   amount of redundancy and
					   irrelevance in the attributes */
PR		*Rule;			/* current rules */
RuleNo	NRules = 0,		/* number of current rules */
		*RuleIndex;		/* rule index */
short		RuleSpace = 0;		/* space allocated for rules */
ClassNo		DefaultClass;		/* current default class */
RuleSet		*PRSet;			/* sets of rulesets */
float	AttTestBits,		/* bits to encode tested att */
		*BranchBits;		/* ditto attribute value */

Tree	DecisionTree;
RangeDescRec RangeDesc;
extern short MYTRACE;
/*  End of   This is from C45Rule.c  */



/////////////////////////////////////////////////////////////////////////////
// CMainFrame

IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	//{{AFX_MSG_MAP(CMainFrame)
	ON_WM_CREATE()
	ON_COMMAND(ID_CART_C45, OnCartC45)
	ON_COMMAND(ID_CART_C45RULE, OnCartC45Rule)
	ON_COMMAND(ID_CART_C45CONSULT, OnCartConsult)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // status line indicator
	ID_INDICATOR_CAPS,
	ID_INDICATOR_NUM,
	ID_INDICATOR_SCRL,
};

/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
	fLog=fopen("MyProgramLog.txt","wt");
}

CMainFrame::~CMainFrame()
{
	if(fLog!=NULL)
		fclose(fLog);
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
		| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
		!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
	{
		TRACE0("Failed to create toolbar\n");
		return -1;      // fail to create
	}

	if (!m_wndStatusBar.Create(this) ||
		!m_wndStatusBar.SetIndicators(indicators,
		  sizeof(indicators)/sizeof(UINT)))
	{
		TRACE0("Failed to create status bar\n");
		return -1;      // fail to create
	}

	// TODO: Delete these three lines if you don't want the toolbar to
	//  be dockable
	m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
	EnableDocking(CBRS_ALIGN_ANY);
	DockControlBar(&m_wndToolBar);

	return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWnd::Dump(dc);
}

#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers


void CMainFrame::OnCartC45() 
{
	/*************************************************************************/
	/*									 */
	/*	Main routine, c4.5						 */
	/*	------------------						 */
	/*									 */
	/*************************************************************************/

	// 程序变量定义:
	
	int j;
    Boolean FirstTime=true;
    short Best;
	char Buffer[100];

	C45Option pDlg;
	if(pDlg.DoModal()!=IDOK)
		return;
	if(pDlg.mD_Fname!="")
		strcpy(FileName,pDlg.mD_Fname);
	// 去掉文件扩展名。
	j=strlen(FileName);
	while (FileName[j]!='.')j--;
	FileName[j]='\0';
	BATCH = pDlg.mD_Batch;
	UNSEENS = pDlg.mD_Unseen;
	PROBTHRESH = pDlg.mD_ProbThresh;
	if(pDlg.mD_V)
		VERBOSITY = pDlg.mD_VerbLevel;
	if(pDlg.mD_T)
	{
		TRIALS = pDlg.mD_Trials;
		BATCH=false;
	}
	if(pDlg.mD_W)
	{
		WINDOW = pDlg.mD_Window;
		BATCH=false;
	}
	if(pDlg.mD_I)
	{
		INCREMENT = pDlg.mD_Increment;
		BATCH=false;
	}
	GAINRATIO = pDlg.mD_GainCrit;
	SUBSET = pDlg.mD_Subset;
	if(pDlg.mD_M)
		MINOBJS = pDlg.mD_MinObjs;
	if(pDlg.mD_C)
		CF = (float)(pDlg.mD_CF)/100;/**/

/*  Initialise  */
	strcpy(Buffer,FileName);
	strcat(Buffer,".txt");
	fRST=fopen(Buffer,"wt");

    GetNames();
	
	GetData(".data");
	fprintf(fLog,"Read %d cases (%d attributes) from %s.data",
		MaxItem+1, MaxAtt+1, FileName);
	/*  Build decision trees  */

    if ( BATCH )
    {
		TRIALS = 1;
		OneTree();
		Best = 0;
    }
    else
    {
		Best = BestTree();
    }

    /*  Soften thresholds in best tree  */

    if ( PROBTHRESH )
    {
		fprintf(fLog,"Softening thresholds");
		if ( ! BATCH ) 
			fprintf(fLog," for best tree from trial %d", Best);
		
		SoftenThresh(Pruned[Best]);
		PrintTree(Pruned[Best]);
	}

    /*  Save best tree  */

    if ( BATCH || TRIALS == 1 )
    {
		fprintf(fLog,"Tree saved! ");
    }
    else
    {
		fprintf(fLog,"Best tree from trial %d saved !", Best);
    }
    SaveTree(Pruned[Best], ".tree");


    /*  Evaluation  */

    fprintf(fLog,"Evaluation on training data (%d items):", MaxItem+1);
    //Evaluate(false, Best);
	GetData(".data");
	fprintf(fLog,"Read %d cases (%d attributes) from %s.data",
		MaxItem+1, MaxAtt+1, FileName);

	Evaluate(true, Best);

    if ( UNSEENS )
    {   
        GetData(".test");
        fprintf(fLog,"Evaluation on test data (%d items):", MaxItem+1);
        Evaluate(true, Best);
    }/***/
	MessageBox("任务完成!");
	fclose(fRST);
    return ;
	
}

void CMainFrame::OnCartC45Rule() 
{
	/*************************************************************************/
	/*									 */
	/*	Main routine, c4.5 Rule						 */
	/*	------------------						 */
	/*									 */
	/*************************************************************************/

	// 程序变量定义:
	int j;
    short Best;
	CRect pRect;
	
	C45RULEOPTION pDlg;
	if(pDlg.DoModal()!=IDOK)
		return;
	if(pDlg.mD_Fn!="")
		strcpy(FileName,pDlg.mD_Fn);
	// 去掉文件扩展名。
	j=strlen(FileName);
	while (FileName[j]!='.')j--;
	FileName[j]='\0';
	
	UNSEENS = pDlg.mD_U;
	SIMANNEAL = pDlg.mD_A;
	if(pDlg.mC_V)
		VERBOSITY = pDlg.mD_V;
	if(pDlg.mC_C)
		CF = float(pDlg.mD_CF)/100;/**/
	if(pDlg.mC_R)
		REDUNDANCY = pDlg.mD_R;
	if(pDlg.mC_S)
	{
		SIGTEST = pDlg.mC_S;
		SIGTHRESH = (float )(pDlg.mD_S) / 100;
	}

	BeginWaitCursor();
	/***
	GetWindowRect(&pRect);
	RedrawWindow();
	pRect.bottom = pRect.bottom - (pRect.bottom - pRect.top)/3;
	pRect.right = pRect.right*19/20 + pRect.left/20;
	pRect.left = pRect.right/20 + pRect.left*19/20;
	pRect.top = pRect.bottom - 20;

	mProgCtrl.Create(WS_VISIBLE|PBS_SMOOTH, pRect,this, 1);
	mProgCtrl.SetRange(0,1000);
	mProgCtrl.SetStep(1);
    /*  Initialise  */

    GetNames();

	GetData(".data");
    fprintf(fLog,"\nRead %d cases (%d attributes) from %s\n",
	   MaxItem+1, MaxAtt+1, FileName);

	GenerateLogs();

    /*  Construct rules  */

    GenerateRules();

   /*  Evaluations  */

    fprintf(fLog,"\n\nEvaluation on training data (%d items):\n", MaxItem+1);
    EvaluateRulesets(true);

    /*  Save current ruleset  */

    SaveRules();

    if ( UNSEENS )
    {
		GetData(".test");
		fprintf(fLog,"\nEvaluation on test data (%d items):\n", MaxItem+1);
		EvaluateRulesets(false);
    }
	
	EndWaitCursor();
	MessageBox("任务完成!");
	return ;
}

void CMainFrame::OnCartConsult() 
{
/*************************************************************************/
/*								  	 */
/*  Main routine for classifying items using a decision tree	  	 */
/*								  	 */
/*************************************************************************/
    int j;

    fprintf(fLog,"\n\n decision tree interpreter \n");
    
	/*  Process options  */
	ConsultOption cDlg;
	if(cDlg.DoModal()!=IDOK)
		return;
	if(cDlg.mD_Fname!="")
		strcpy(FileName,cDlg.mD_Fname);
	// 去掉文件扩展名。
	j=strlen(FileName);
	while (FileName[j]!='.')j--;
	FileName[j]='\0';

	MYTRACE = cDlg.mD_T;
	VERBOSITY = cDlg.mD_V;
	Attribute a;

    /*  Initialise  */
    GetNames();

    DecisionTree = GetTree(".tree");
    if (MYTRACE )
		PrintTree(DecisionTree);

    /*  Allocate value ranges  */

    RangeDesc = (struct ValRange *) calloc(MaxAtt+1, sizeof(struct ValRange));

    ForEach(a, 0, MaxAtt)
    {
		if ( MaxAttVal[a] )
		{
			RangeDesc[a].Probability = 
				(float *) calloc(MaxAttVal[a]+1, sizeof(float));
		}
    }

    /*  Consult  */

    Clear();
    while ( true )
    {
		InterpretTree();
    }
	
}

⌨️ 快捷键说明

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