id
stringlengths
36
36
text
stringlengths
1
1.25M
6c703b6b-d733-4704-9848-ba509874f805
public void removeTaskIndex(int taskIndex) { taskList.remove(taskIndex); }
5240a8e0-da5e-4bca-9a91-35ed6b105e51
public void clearTasks() { taskList.clear(); }
2915508a-d6a2-4e2e-966b-ba0f21c5d383
public Task getTask(int taskIndex) { Task chosenTask = taskList.get(taskIndex); return chosenTask; }
f43279d0-443f-4b45-8752-18b965d25e97
public int lengthOfTaskList() { int length = taskList.size(); return length; }
ffd060f6-5c45-4e7d-b02a-83492613bbc1
public TextInput() { stringScanner = new Scanner(System.in); intScanner = new Scanner(System.in); boolScanner = new Scanner(System.in); finished = false; }
96a8756d-d97a-463f-8906-28b6608ae880
public void inputName() { System.out.println("Enter the name of the task:\n"); name = stringScanner.nextLine(); }
7387f6a5-0e53-4cce-8394-e84b5ddf9d6a
public void inputTaskNum() { System.out.println("Enter the number of the task:\n"); taskNum = intScanner.nextInt(); }
481934a1-456b-4329-83ab-9906f32a0724
public void inputParentNum() { System.out.println("Enter the parent of the task, or 0 if it doesn't have one:\n"); parentNum = intScanner.nextInt(); }
0030d688-d56c-40c2-9efd-a848948cd4c7
public void inputNumOfDays() { System.out.println("Enter the number of days to complete the task:\n"); numOfDays = intScanner.nextInt(); }
23460044-7d8e-4dfc-881d-25260603ad80
public void inputFinished() { System.out.println("Have You finished? Enter true or false:\n"); finished = boolScanner.nextBoolean(); }
5473b61a-0fc4-4aea-9433-8dbac39c08b9
public String getName() { return name; }
0a056845-aba5-494d-8f15-9188b5a5fea5
public int getTaskNum() { return taskNum; }
99ccfd3d-7a63-4df0-85e4-e889f051be70
public int getParentNum() { return parentNum; }
679d6f7c-b38e-4c0a-a5ab-b9f19dea320e
public int getNumOfDays() { return numOfDays; }
a3becf1c-9b96-4137-a8f5-b9a49a0a18ca
public boolean getFinished() { return finished; }
5db563f0-a7ee-4e93-beca-9b76946cfab4
public void inputTask() { inputName(); inputTaskNum(); inputParentNum(); inputNumOfDays(); inputFinished(); }
ecf99882-15eb-4ad7-a60c-cffea9c8ff95
public TestGraphics() { super("Pert Chart"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); taskList = new ListOfTasks(); //Create the gui window JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); getContentPane().add(mainPanel); JPanel graphicsPanel = new JPanel(); //Create the graphics canvas GWindow window = new GWindow(); mainPanel.add(window.getCanvas(), BorderLayout.CENTER); //Create scene scene = new GScene(window, "scene"); double w0[] = {0.0, 1500.0, 0.0}; double w1[] = {1500.0, 1500.0, 0.0}; double w2[] = {0.0, 0.0, 0.0}; scene.setWorldExtent(w0, w1, w2); scene.shouldZoomOnResize(false); GStyle style = new GStyle(); style.setForegroundColor(Color.BLUE); style.setBackgroundColor(new Color (255, 255, 255)); style.setFont(new Font("Dialog", Font.BOLD, 10)); scene.setStyle(style); TextInput input = new TextInput(); while(input.getFinished() == false) { input.inputTaskNum(); input.inputParentNum(); input.inputFinished(); Task parentTask = null; int parentCounter = 0; double xPosition = 300; //Checks if this is the first task. If it is it's xCoordinates //get set a position of 200 rather than 500. /* if(taskList.lengthOfTaskList() == 0) { xPosition = 200; } */ for(Task task : taskList.getTaskList()) { if(task.getTaskNumber() == input.getParentNum()) { parentTask = task; //xPosition = xPosition + parentTask.getXPosition() + 200; } if(task.getParent() == parentTask) { parentCounter++; } } double yPosition = 500 + parentCounter * 300; taskList.addTask(new Task("name", input.getTaskNum(), 2, "startDate", "endDate", scene, parentTask, xPosition, yPosition)); } /* Task task1 = new Task("task1", 1, 2, "startDate", "endDate", scene, null, 200, 500); Task task2 = new Task("task2", 2, 2, "startDate", "endDate", scene, task1, 200, 500); Task task3 = new Task("task3", 3, 2, "startDate", "endDate", scene, task2, 200, 500); Task task4 = new Task("task4", 4, 2, "startDate", "endDate", scene, task2, 200, 500); */ pack(); setSize (new Dimension(500, 500)); setVisible(true); }
e2840cc9-d14a-4512-b57f-83f22f82140c
public static void main(String[] args) { new Start(); }
1380f842-1a06-49c9-a4ec-d56325f1c66d
public Start() { super("Pert Chart"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //will need to change this ********************** taskList = new ListOfTasks(); //Create the gui window JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); getContentPane().add(mainPanel); JPanel graphicsPanel = new JPanel(); //Create the graphics canvas GWindow window = new GWindow(); mainPanel.add(window.getCanvas(), BorderLayout.CENTER); //Create scene scene = new GScene(window, "scene"); double w0[] = {0.0, 1500.0, 0.0}; double w1[] = {1500.0, 1500.0, 0.0}; double w2[] = {0.0, 0.0, 0.0}; scene.setWorldExtent(w0, w1, w2); scene.shouldZoomOnResize(false); GStyle style = new GStyle(); style.setForegroundColor(Color.BLUE); style.setBackgroundColor(new Color (255, 255, 255)); style.setFont(new Font("Dialog", Font.BOLD, 10)); scene.setStyle(style); //Gets the input from the user then creates the Task objects and also //adds them to the taskList. TextInput input = new TextInput(); while(input.getFinished() == false) { input.inputTask(); Task parentTask = null; int parentCounter = 0; double xPosition = 400; //Checks to see if this is the first task. If it is xPosition is //set to 200. if(taskList.lengthOfTaskList() == 0) { xPosition = 200; } //Loops through the taskList field for(Task task : taskList.getTaskList()) { //Checks if there is a task with a task number matching the input //parent task number. If there is parentTask is set to that task. if(task.getTaskNumber() == input.getParentNum()) { parentTask = task; } //Checks to see if there is already tasks with the same parent. //If there is the parentCounter variable is incremented. if(task.getParent() == parentTask) { parentCounter++; } } //The yPosition is determined on how many children a parentTask has. //This is done using the previous parentCounter variable. double yPosition = 500 + parentCounter * 300; taskList.addTask(new Task(input.getName(), input.getTaskNum(), input.getNumOfDays(), "startDate", "endDate", scene, parentTask, xPosition, yPosition)); } //Checks if more than 3 tasks have been created, if they have it changes //the size of the scene world extent. //********* this may need to be change to reflect the y axis. if(taskList.lengthOfTaskList() > 3) { double newSize = 1500 + taskList.lengthOfTaskList() * 500; double we0[] = {0.0, newSize, 0.0}; double we1[] = {newSize, newSize, 0.0}; double we2[] = {0.0, 0.0, 0.0}; scene.setWorldExtent(we0, we1, we2); } pack(); setSize (new Dimension(500, 500)); /* * Checks if more than 3 tasks have been created, if they have it changes * the size of the scene world extent. */ setVisible(true); }
1b3ae729-897b-410e-8e5a-0bbca705f92d
public Task() { }
c1e6a930-552a-43c6-9a1e-a5cf395b4c31
public Task(String name, int taskNumber, int numberOfDays, String startDate, String endDate, GScene scene, Task parent, double xPosition, double yPosition) { this.name = name; this.taskNumber = taskNumber; this.numberOfDays = numberOfDays; this.startDate = startDate; this.endDate = endDate; this.parent = parent; this.yPosition = yPosition; xSize = 200; ySize = 200; line = new GSegment(); addSegment(line); square = new GSegment(); addSegment(square); setStyle(new GStyle()); //maybe change this and remove the scene field. if(parent == null) { scene.add(this); this.xPosition = xPosition; } else { parent.add(this); this.xPosition = parent.getXPosition() + xPosition; } updateText(); }
a3cacd4a-c848-45d3-9531-960a2aea1e7b
public String getName() { return name; }
058eb502-3d61-4f0e-b6bd-27376619b61e
public int getTaskNumber() { return taskNumber; }
41e1a511-9495-4da7-868c-916fc8e88a53
public int getNumberOfDays() { return numberOfDays; }
4640dfe1-393b-4379-bbb1-af62dadedf89
public String getStartDate() { return startDate; }
a3b15d2d-85c8-4268-b1ec-be40a4c7660a
public String getEndDate() { return endDate; }
87fec9a6-42c8-4e3d-8b8e-05910a838d64
public double getXPosition() { return xPosition; }
e12dc0bd-aa6b-43d7-b9e1-85693979328f
public double getYPosition() { return yPosition; }
186f7a28-1ddc-41d2-ac9f-9e2c0da6235c
public double getXSize() { return xSize; }
505bc8c1-9a0e-477c-9db8-a31c2e67fb19
public double getYSize() { return ySize; }
7fe50f38-3f14-4385-8cd1-85e694cf7b97
public void updateText() { GText textName = new GText(name, GPosition.TOP); Integer num; num = taskNumber; GText textTaskNum = new GText(num.toString(), GPosition.TOP); num = numberOfDays; GText textNumOfDays = new GText(num.toString(), GPosition.TOP); GText textStart = new GText(startDate, GPosition.TOP); GText textEnd = new GText(endDate, GPosition.TOP); square.addText(textName); square.addText(textTaskNum); square.addText(textNumOfDays); square.addText(textStart); square.addText(textEnd); }
250a880a-3651-458b-a01b-e1d1b607cb8e
public void draw() { if(parent != null) { line.setGeometry(parent.getXPosition() + 200, parent.getYPosition() + 100, xPosition, yPosition + 100); } square.setGeometryXy(Geometry.createRectangle(xPosition, yPosition, xSize, ySize)); }
cf8e0983-2b7e-4093-8121-f007b1597c2d
public void addInstance(String line) { if (instances == null) { instances = new ArrayList<Instance>(); } Instance instance = new Instance(); String[] splitline = line.split(DELIMITER); for(int i = 0; i < splitline.length - 1; i ++) instance.addAttribute(splitline[i]); instance.setLabel(splitline[splitline.length - 1]); instances.add(instance); }
c21c3c9f-a3f0-4435-97a6-5e001f5298e9
public void addAttribute(String i) { if (attributes == null) { attributes = new ArrayList<String>(); } attributes.add(i); }
911ad28b-f583-487a-9b7f-88af6dc72b02
public void setLabel(String _label) { label = _label; }
d2f7fad6-aec3-4179-9f41-a8874a75254f
private Category(String name, Type type) { this.name = name; this.type = type; }
97dae526-c340-42fe-9e80-c79b4bb93c46
public String toString() { return name; }
6f50830a-838a-4fa2-a33c-40b419f38ce2
public String getName() { return name; }
414e34ff-efd9-414d-be71-e98ed61ca482
public Type getType() { return type; }
970005eb-0cb5-4aea-8cc8-a3ebe46dce63
public static Attribute.Category getAttribute(int index) { return values()[index]; }
7da1d83e-8201-49d6-b09d-6626cbbdb4de
public Attribute(int index) { this.index = index; this.category = Category.getAttribute(index); }
d7245cc2-8470-4eac-921c-9a0793b8a05e
public void addValue(String value) { values.add(value); }
a3b4852f-b47b-48f5-be0c-7f2003e26be5
public static void main(String[] args) { if (args.length != 4) { System.out.println("usage: java HW2 <modeFlag> <trainFilename> " + "<tuneFilename> <testFilename>"); System.exit(-1); } /* * mode 1 : create a decision tree using the training set, then print * the tree and the prediction accuracy on the test set * 2 : create a decision tree using the training set, prune using * the tuning set, then print the tree and prediction accuracy * on the test set */ int mode = Integer.parseInt(args[0]); if (mode < 1 || mode > 2) { System.out.println("Error: modeFlag must be an integer 1 or 2"); System.exit(-1); } // Turn text into array // Only create the sets that we intend to use DataSet trainSet = null, tuneSet = null, testSet = null; trainSet = createDataSet(args[1], mode); testSet = createDataSet(args[3], mode); if(mode > 1) tuneSet = createDataSet(args[2], mode); // Create decision tree DecisionTree tree = null; if (mode == 1) { tree = new DecisionTreeImpl(trainSet); } else { if(tuneSet == null) { System.out.println("Empty tuning set"); System.exit(-1); } tree = new DecisionTreeImpl(trainSet, tuneSet); } // print the tree and calculate accuracy tree.print(); calcTestAccuracy(testSet, tree.classify(testSet)); }
3153cbce-35ec-4228-be47-60edb0e0b5ef
private static DataSet createDataSet(String file, int modeFlag) { DataSet set = new DataSet(); BufferedReader in; try { in = new BufferedReader(new FileReader(file)); while (in.ready()) { String line = in.readLine(); set.addInstance(line); } in.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } return set; }
e79793ca-7560-4888-bb9c-49a69021b877
private static void calcTestAccuracy(DataSet test, String[] results) { if(results == null) { System.out.println("Error in calculating accuracy: " + "You must implement the classify method"); System.exit(-1); } List<Instance> testInsList = test.instances; if(testInsList.size() == 0) { System.out.println("Error: Size of test set is 0"); System.exit(-1); } if(testInsList.size() > results.length) { System.out.println("Error: The number of predictions is inconsistant " + "with the number of instances in test set, please check it"); System.exit(-1); } int correct = 0, total = testInsList.size(); for(int i = 0; i < testInsList.size(); i ++) if(testInsList.get(i).label.equals(results[i])) correct ++; System.out.println("Prediction accuracy on the test set is: " + String.format("%.5f", correct * 1.0 / total)); return; }
0a655ea5-2da9-4269-8416-58b1dabb1c73
NumericalInternalDecTreeNode(String _label, Attribute _attribute, String _parentAttributeValue, List<DecTreeNode> _children, double _midpoint) { super(_label, _attribute, _parentAttributeValue, _children); this.midpoint = _midpoint; }
b645638f-e875-490d-b302-a7ff322965d9
public String classify(Instance example) { String childExampleAttributeValue = example.attributes.get(attribute.index); if(Attribute.Type.NUMERICAL.equals(attribute.category.getType())) { for (DecTreeNode childNode : children) { if("A".equals(childNode.parentAttributeValue) == (Integer.parseInt(childExampleAttributeValue) < midpoint)) { if(childNode instanceof InternalDecTreeNode) { return ((InternalDecTreeNode)childNode).classify(example); } else { return childNode.label; } } } } return label; }
e74a015e-8c5a-472b-9346-929d50e212fe
DecisionTreeImpl() { // no code necessary // this is void purposefully }
976d57d7-87d9-409a-88c7-9b0365d4d3e5
DecisionTreeImpl(DataSet train) { if (train == null || train.instances == null || train.instances.isEmpty()) { return; } List<Attribute> attributes = new ArrayList<Attribute>(); for (Instance instance : train.instances) { for (int i = 0; i < instance.attributes.size(); i++) { if (i > attributes.size() - 1) { attributes.add(new Attribute(i)); } attributes.get(i).addValue(instance.attributes.get(i)); } } root = trainTree(train.instances, attributes, train.instances, "Root"); }
0efd0a51-66a6-4db6-ae41-e60c7da52efb
DecisionTreeImpl(DataSet train, DataSet tune) { this(train); prune(tune); }
8354a960-87ee-441e-8a08-507563dd1b4b
private DecTreeNode trainTree(List<Instance> examples, List<Attribute> attributes, List<Instance> parentExamples, String parentAttributeValue) { if (examples.isEmpty()) { return new LeafDecTreeNode(plurality(parentExamples), parentAttributeValue); } else if(attributes.isEmpty() || sameLabel(examples)) { return new LeafDecTreeNode(plurality(examples), parentAttributeValue); } else { Attribute importantAttribute = importance(attributes, examples); //System.out.println("Winning Attribute: "+importantAttribute.category.getName()); List<Attribute> childAttributes = new ArrayList<Attribute>( attributes); childAttributes.remove(importantAttribute); if (Attribute.Type.NUMERICAL.equals(importantAttribute.category.getType())) { double midpoint = midpoint(examples, importantAttribute.index); List<Instance> positiveChildExamples = new ArrayList<Instance>(), negativeChildExamples = new ArrayList<Instance>(); for (Instance example : examples) { if(Integer.parseInt(example.attributes.get(importantAttribute.index)) > midpoint) { positiveChildExamples.add(example); } else { negativeChildExamples.add(example); } } List<DecTreeNode> children = new ArrayList<DecTreeNode>(); children.add(trainTree(negativeChildExamples, childAttributes, examples, "A")); children.add(trainTree(positiveChildExamples, childAttributes, examples, "B")); return new NumericalInternalDecTreeNode(plurality(examples), importantAttribute, parentAttributeValue, children, midpoint); } else { Map<String, List<Instance>> childExamples = new LinkedHashMap<String, List<Instance>>(); for (Instance example : examples) { String importantAttributeValue = example.attributes .get(importantAttribute.index); List<Instance> childExample = childExamples .get(importantAttributeValue); if (childExample == null) { childExample = new ArrayList<Instance>(); childExamples.put(importantAttributeValue, childExample); } childExample.add(example); } List<DecTreeNode> children = new ArrayList<DecTreeNode>(); for (String attribute : importantAttribute.values) { List<Instance> childExamplesForAttribute = childExamples.get(attribute); if(childExamplesForAttribute == null) { childExamplesForAttribute = new ArrayList<Instance>(); } children.add(trainTree(childExamplesForAttribute, childAttributes, examples, attribute)); } return new InternalDecTreeNode(plurality(examples), importantAttribute, parentAttributeValue, children); } } }
34a10d5e-55a2-449d-8262-a82bbb0aeeb8
private String plurality(List<Instance> examples) { Map<String, Integer> scores = new LinkedHashMap<String, Integer>(); for (Instance instance : examples) { Integer score = scores.get(instance.label); if (score == null) { score = 0; } scores.put(instance.label, score + 1); } if(scores.isEmpty()) { return "1"; } else if (scores.size() == 1) { return scores.keySet().iterator().next(); } else { int winningScore = Integer.MIN_VALUE; String winner = null; for (String label : scores.keySet()) { if (!label.equals(winner)) { int score = scores.get(label); if (winningScore == score) { if (label.compareToIgnoreCase(winner) < 0) { winner = label; } } else if (winningScore < score) { winner = label; winningScore = score; } } } return winner; } }
8dd9b644-18ca-409c-9ed2-b81332300c21
private Attribute importance(List<Attribute> attributes, List<Instance> examples) { double winningEntropy = Double.NEGATIVE_INFINITY; Attribute winningAttribute = null; // Calculate H(Credit) double givenCredit = 0; for (Instance example : examples) { if ("1".equals(example.label)) { givenCredit++; } } double creditEntropy = booleanEntropy(givenCredit / examples.size()); System.out.println("H(Credit) = " + creditEntropy); for (int i = 0; i < attributes.size(); i++) { Attribute attribute = attributes.get(i); // Use these LinkedHashMaps to add up probabilities for // attributes both given credit and without Map<String, Double> attributeScore = new LinkedHashMap<String, Double>( attribute.values.size()); Map<String, Double> attributeScoreGivenCredit = new LinkedHashMap<String, Double>( attribute.values.size()); int examplesWithCredit = 0; if (Attribute.Type.NUMERICAL.equals(attribute.category.getType())) { double midpoint = midpoint(examples, attribute.index); List<Instance> examplesGivenCredits = new ArrayList<Instance>(); for (int j = 0; j < examples.size(); j++) { Instance example = examples.get(j); if ("1".equals(example.label)) { examplesGivenCredits.add(example); } } double midpointGivenCredits = midpoint(examplesGivenCredits, attribute.index); for (int j = 0; j < examples.size(); j++) { Instance example = examples.get(j); int value = Integer.parseInt(example.attributes.get(i)); String larger = String.valueOf(value > midpoint); Double score = attributeScore.get(larger); if (score == null) { score = 0.0; } attributeScore.put(larger, score + 1); if ("1".equals(example.label)) { String largerGivenCredit = String.valueOf(value > midpointGivenCredits); Double scoreGivenCredit = attributeScoreGivenCredit .get(largerGivenCredit); if (scoreGivenCredit == null) { scoreGivenCredit = 0.0; } attributeScoreGivenCredit.put(largerGivenCredit, scoreGivenCredit + 1); examplesWithCredit++; } } } else { for (int j = 0; j < examples.size(); j++) { Instance example = examples.get(j); String value = example.attributes.get(i); Double score = attributeScore.get(value); if (score == null) { score = 0.0; } attributeScore.put(value, score + 1); if ("1".equals(example.label)) { Double scoreGivenCredit = attributeScoreGivenCredit .get(value); if (scoreGivenCredit == null) { scoreGivenCredit = 0.0; } attributeScoreGivenCredit.put(value, scoreGivenCredit + 1); examplesWithCredit++; } } } // Calculate H(Credit|Attribute) double attributeEntropy = 0; for (String value : attributeScore.keySet()) { Double score = attributeScore.get(value); Double scoreGivenCredit = attributeScoreGivenCredit.get(value); if (score != null && scoreGivenCredit != null && score != 0 && scoreGivenCredit != 0) { attributeEntropy += (score / examples.size() * booleanEntropy(scoreGivenCredit / examplesWithCredit)); } } // Calculate I(Credit;Attribute) = H(Credit) - H(Credit|Attribute) double totalEntropy = creditEntropy - attributeEntropy; System.out.println("I(Credit;" + attribute.category.getName() + ") = " + totalEntropy); if (totalEntropy >= winningEntropy) { winningEntropy = totalEntropy; winningAttribute = attribute; } } return winningAttribute; }
b94d0c6c-d01a-40ac-9848-b7e83f1877ce
private double booleanEntropy(double q) { if (q <= 0 || q >= 1) { return 0; } return -(((q * Math.log(q)) / LOG_OF_2) + (((1 - q) * Math.log(1 - q)) / LOG_OF_2)); }
1df623f7-b7ef-477f-8657-9555c243bf63
private boolean sameLabel(List<Instance> examples) { if (examples == null || examples.isEmpty()) { return true; } boolean positive = "1".equals(examples.get(0).label); for (Instance instance : examples) { if (("2".equals(instance.label) && positive) || ("1".equals(instance.label) && !positive)) { return false; } } return true; }
d69e5b4f-6b54-4db0-a03a-f477e5d7fe3c
private double midpoint(List<Instance> examples, int attributeIndex) { if (examples == null || examples.isEmpty()) { return 0.0; } double max = Double.NEGATIVE_INFINITY, min = Double.POSITIVE_INFINITY; for (Instance instance : examples) { int attribute = Integer.parseInt(instance.attributes .get(attributeIndex)); if (attribute > max) { max = attribute; } if (attribute < min) { min = attribute; } } return 0.5 * (max + min); }
961e2a60-d4fe-4afa-9412-01c3b2070ea1
@Override /** * Evaluates the learned decision tree on a test set. * @return the label predictions for each test instance * according to the order in data set list */ public String[] classify(DataSet test) { String[] classification = new String[test.instances.size()]; for (int i = 0; i < test.instances.size(); i++) { Instance example = test.instances.get(i); if(root instanceof InternalDecTreeNode) { classification[i] = ((InternalDecTreeNode)root).classify(example); } else { classification[i] = root.label; } } return classification; }
f04c2c81-7753-4fcd-a4c9-d3b8b1c7103b
private void prune(DataSet tune) { double originalAccuracy = calcTestAccuracy(tune, classify(tune)); // System.out.println("Original Accuracy: "+originalAccuracy); // Can't really go about pruning if the root isn't internal if(root instanceof InternalDecTreeNode) { InternalDecTreeNode nodeToPrune = null, parentNodeToPrune = null; double maxAccuracy = originalAccuracy; InternalDecTreeNode savedInternalNode = (InternalDecTreeNode) root; LeafDecTreeNode prunedLeafNode = new LeafDecTreeNode(savedInternalNode.label, savedInternalNode.parentAttributeValue); // Test pruning the root node root = prunedLeafNode; // Calculate the test accuracy with this node pruned double accuracy = calcTestAccuracy(tune, classify(tune)); // System.out.println("Prune Accuracy: "+accuracy); if(accuracy >= maxAccuracy) { maxAccuracy = accuracy; nodeToPrune = (InternalDecTreeNode)savedInternalNode; } // Return tree back to original state root = savedInternalNode; // Do a BFS search to determine which node to prune Queue<InternalDecTreeNode> queue = new LinkedList<InternalDecTreeNode>(); queue.add((InternalDecTreeNode)root); while(!queue.isEmpty()) { InternalDecTreeNode internalNode = queue.remove(); for (int i = 0; i < internalNode.children.size(); i++) { DecTreeNode child = internalNode.children.get(i); if(child instanceof InternalDecTreeNode) { // Calculate the test accuracy with this node pruned savedInternalNode = (InternalDecTreeNode) child; prunedLeafNode = new LeafDecTreeNode(savedInternalNode.label, savedInternalNode.parentAttributeValue); internalNode.removeChild(child); internalNode.addChild(prunedLeafNode); accuracy = calcTestAccuracy(tune, classify(tune)); // System.out.println("Prune Accuracy: "+accuracy); if(accuracy >= maxAccuracy) { maxAccuracy = accuracy; nodeToPrune = savedInternalNode; parentNodeToPrune = internalNode; } internalNode.removeChild(prunedLeafNode); internalNode.returnChild(i, child); queue.add(savedInternalNode); } } } // Prune the node if it's better than original accuracy if(nodeToPrune != null && maxAccuracy > originalAccuracy) { if(parentNodeToPrune != null) { parentNodeToPrune.removeChild(nodeToPrune); parentNodeToPrune.addChild(new LeafDecTreeNode(nodeToPrune.label, nodeToPrune.parentAttributeValue)); // Keep pruning until we can't get better accuracy than current prune(tune); } else { root = new LeafDecTreeNode(nodeToPrune.label, nodeToPrune.parentAttributeValue); } } } }
08ecfd9b-d185-46f7-8588-1039899d47d4
private double calcTestAccuracy(DataSet test, String[] results) { List<Instance> testInsList = test.instances; int correct = 0, total = testInsList.size(); for(int i = 0; i < testInsList.size(); i ++) if(testInsList.get(i).label.equals(results[i])) correct ++; return correct * 1.0 / total; }
065e4c79-fa42-4635-9955-77a82ce55b35
@Override /** * Prints the tree in specified format. It is recommended, but not * necessary, that you use the print method of DecTreeNode. * * Example: * Root {Existing checking account?} * A11 (2) * A12 {Foreign worker?} * A71 {Credit Amount?} * A (1) * B (2) * A72 (1) * A13 (1) * A14 (1) * */ public void print() { root.print(0); }
cbc9c4ce-33ff-4642-8292-97cd65007c7e
InternalDecTreeNode(String _label, Attribute _attribute, String _parentAttributeValue, List<DecTreeNode> _children) { super(_label, _attribute.category.getName(), _parentAttributeValue, false); this.attribute = _attribute; this.children = _children; }
13464270-d0b4-4b72-ad33-45aba4296306
public void returnChild(int index, DecTreeNode child) { children.add(index, child); }
0dbf0a0a-e90b-4cb8-a1eb-816f4f82a593
public void removeChild(DecTreeNode child) { children.remove(child); }
8d1751f2-907f-4d82-b605-df0a523c277d
public String classify(Instance example) { String childExampleAttributeValue = example.attributes.get(attribute.index); for (DecTreeNode childNode : children) { if(childExampleAttributeValue.equals(childNode.parentAttributeValue)) { if(childNode instanceof InternalDecTreeNode) { return ((InternalDecTreeNode)childNode).classify(example); } else { return childNode.label; } } } return label; }
5d21ee14-2354-4898-8e9a-0f3417540314
DecTreeNode(String _label, String _attribute, String _parentAttributeValue, boolean _terminal) { label = _label; attribute = _attribute; parentAttributeValue = _parentAttributeValue; terminal = _terminal; if (_terminal) { children = null; } else { children = new ArrayList<DecTreeNode>(); } }
b38ce7fc-7411-4f67-ad81-48834da1e93f
public void addChild(DecTreeNode child) { if (children != null) { children.add(child); } }
563df8b4-d9fd-4b5a-805d-e9d3c7c1bc39
public void print(int k) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { sb.append(" "); } sb.append(parentAttributeValue); if (terminal) { sb.append(" (" + label + ")"); System.out.println(sb.toString()); } else { sb.append(" {" + attribute + "?}"); System.out.println(sb.toString()); for(DecTreeNode child: children) { child.print(k+1); } } }
9056d0f5-26fd-4c51-8b86-96d4a5dc678b
LeafDecTreeNode(String _label, String _parentAttributeValue) { super(_label, "", _parentAttributeValue, true); }
caf4d6fa-9407-481b-8ee6-cd77d1c8ae29
abstract public String[] classify(DataSet testSet);
e62244cd-327a-46e5-9d58-d00f23d2746b
abstract public void print();
8ac4f7ed-874d-47e7-8c60-1ec61c7beca5
@Override public String toString() { StringBuilder sb = new StringBuilder("\tGame State:\n"); sb.append("\t\thand: " + Arrays.toString(hand) + "\n"); if (card > 0) sb.append("\t\tcard: " + card + "\n"); sb.append("\t\thand_id: " + hand_id + "\n"); sb.append("\t\tgame_id: " + game_id + "\n"); sb.append("\t\tyour_tricks: " + your_tricks + "\n"); sb.append("\t\ttheir_tricks: " + their_tricks + "\n"); sb.append("\t\tcan_challenge: " + can_challenge + "\n"); sb.append("\t\tin_challenge: " + in_challenge + "\n"); sb.append("\t\ttotal_tricks: " + total_tricks + "\n"); sb.append("\t\tyour_points: " + your_points + "\n"); sb.append("\t\topponent_id: " + opponent_id + "\n"); sb.append("\t\ttheir_points: " + their_points + "\n"); sb.append("\t\tplayer_number: " + player_number + "\n"); return sb.toString(); }
06b43218-d6d4-48e4-a4a1-b4aa30e351b0
public Response(String type) { this.type = type; }
cd1d3134-49fb-4d35-8084-096f99be9743
public Response(String type, int card) { this.type = type; this.card = new Integer(card); }
796295e1-626e-4d9d-80e8-e47013e67f06
@Override public String toString() { StringBuilder sb = new StringBuilder("\tResponse:\n"); sb.append("\t\ttype: " + type + "\n"); return sb.toString(); }
0a0f6d1c-e9bf-4481-a0ac-b24682506119
public OfferChallengeMessage(int request_id) { super(request_id); response = new Response("offer_challenge"); }
f4a0a891-be85-4848-ad69-08bbc3fc18b2
@Override public String toString() { return "Offer Challenge\n"; }
ef120fd6-df38-4213-8524-73b2fe02dbac
@Override public String toString() { StringBuilder sb = new StringBuilder("Greeting Message:\n"); sb.append("\tteam_id: " + team_id + "\n"); sb.append("\tsark: " + sark + "\n"); return sb.toString(); }
be552a70-e489-44b4-b7c3-8ec43464375f
@Override public String toString() { StringBuilder sb = new StringBuilder("Result Message:\n"); sb.append(result.toString()); sb.append("\tyour_player_num: " + your_player_num + "\n"); return sb.toString(); }
1f1d9b99-8cb8-4efb-befd-cef99c388f00
public AcceptChallengeMessage(int request_id) { super(request_id); response = new Response("accept_challenge"); }
051db5d5-70aa-46fe-aa95-235089935ff2
@Override public String toString() { return "Accept Challenge\n"; }
a4cbdd30-5e22-4c15-af73-cafb43e074c7
public PlayCardMessage(int request_id, int card) { super(request_id); response = new Response("play_card", card); }
f2fdea95-2db6-459b-9816-efbf8f2fbcb3
@Override public String toString() { return "Play Card " + response.card + "\n"; }
b7fe5720-f8b2-44fe-87d8-48e098969149
public PlayerMessage(int request_id) { this.request_id = request_id; type = "move"; }
9b135137-f3a1-4b61-be7b-9e9a9d4ba5bc
@Override public abstract String toString();
1bece1bd-feb4-4842-aabe-d3b4191fc6d3
public RejectChallengeMessage(int request_id) { super(request_id); response = new Response("reject_challenge"); }
ca09cd44-8683-4bb4-b858-a15f604aa1f4
@Override public String toString() { return "Reject Challenge\n"; }
28656569-3ba1-4ec3-bcf9-5d25103a0a17
@Override public abstract String toString();
a7505640-a2e8-43dc-9d11-4f08195fc478
public ContestBot(String host, int port) { this.host = host; this.port = port; }
2d66032f-2e66-4bea-bb5d-b536c08434c0
void onReceiveResult(Status status, ResultMessage r){ if ( r.result.type.equals("trick_won")) { if ( r.result.by == r.your_player_num ) winTime++; else loseTime++; theirLastCard = r.result.card; totalTime++; } if ( r.result.type.equals("trick_tied")) { tiedTime++; theirLastCard = myLastCard; totalTime++; } if ( r.result.type.equals("hand_done") ) { winTime = 0; loseTime = 0; totalTime = 0; tiedTime = 0; // strategy = 0; myLastCard = -1; theirLastCard = -1; } }
43e9797c-f20d-48ea-98c1-e5632cdba883
int onReceiveRequest(Status status, MoveMessage m){ int index = -1; int hand[] = m.state.hand; int their_card = m.state.card; sort(hand); if(m.state.total_tricks==0&&m.state.in_challenge==false&&m.state.card>0 && winTime < 9){ double prob = 0.6 + ( hand[2] - 10 ) * 0.2; if ( prob > Math.random()) return 9999; //return 9999; } if(their_card<=0){ if (winTime == 1&&loseTime == 1&&tiedTime ==0){ return hand.length-1; } //in this round, I play first. if (totalTime == 0 ) { int idx=-1; for(int i=0;i<hand.length;i++){ if(hand[i]<10){ idx = i; break; } } index = 2>idx?2:idx; } else if(totalTime == 1){ index = 2; } else { index = secondBigger(hand); } if ( tiedTime == 0 ) { if ( winTime == 1 && loseTime == 2) index = 0; } else { if ( loseTime >= 1 ) index = 0; } } else{ theirLastCard = their_card; if((m.state.card>hand[hand.length-1])&&((m.state.card-hand[hand.length-1])>6)){ index = hand.length-1; } else if((findCard(hand,m.state.card)==hand.length-1|| findCard(hand,m.state.card)==hand.length-2) &&(m.state.card<=4)){ index = findCard(hand,m.state.card); } else{ index = minBigger(hand,m.state.card); } //in this round,they play first. } // if ( index < 0 || index >= hand.length ) { // System.err.println("W:" + winTime + " L:" + loseTime + " T:" + tiedTime); // System.err.println("Hand: "); // for ( int x : hand ) { // System.err.print(x + " "); // } // // System.err.println("\nIndex:" + index + "\n"); // } myLastCard = hand[index]; //return hand[0]; if ( index >= hand.length ) { System.err.println("W:" + winTime + " L:" + loseTime + " T:" + tiedTime); System.err.println("Hand: "); for ( int x : hand ) { System.err.print(x + " "); } System.err.println("\nIndex:" + index + "\n"); return 0; } return index; }
7000c5cf-19b5-43f2-9c51-d8fb62909fe5
private int findCard(int[] hand, int card){ int index = -3; for(int i=0;i<hand.length;i++){ if(hand[i]==card){ index = i; break; } } return index; }
4731fbfe-0623-4dd5-8f5d-93c34a00d146
private void run() { dm = new DecisionMaker(); status = new Status(); while (true) { // just reconnect upon any failure try { JsonSocket sock = new JsonSocket(host, port); try { sock.connect(); } catch (IOException e) { throw new Exception("Error establishing connection to server: " + e.toString()); } while (true) { Message message = sock.getMessage(); PlayerMessage response = handleMessage(message); if (response != null) { sock.sendMessage(response); } } } catch (Exception e) { System.err.println("Error: " + e.toString()); e.printStackTrace(); System.err.println("Reconnecting in " + RECONNECT_TIMEOUT + "s"); try { Thread.sleep(RECONNECT_TIMEOUT * 1000); } catch (InterruptedException ex) {} } } }
345c90ca-7f88-4824-aed9-c49bf8d8e293
public PlayerMessage handleMessage(Message message) { if (message.type.equals("request")) { MoveMessage m = (MoveMessage)message; if (game_id != m.state.game_id) { game_id = m.state.game_id; // System.out.println("new game " + game_id); if ( opponent != m.state.opponent_id) { if ( totalGames != 0 ) { double wonRatio = 1.0 * wonGames / totalGames; System.out.println(opponent + " --- " + String.format("%.2f", wonRatio) + "(W:" + wonGames + " T:" + totalGames + ")"); } totalGames = 0; wonGames = 0; opponent = m.state.opponent_id; } } // System.out.println(m.toString()); if (m.request.equals("request_card")) { boolean shouldPlay = (! m.state.can_challenge || isChanllenge(m) == false); // shouldPlay = shouldPlay || (strategy == 1 && totalTime <=1); if ( shouldPlay ) { //int i = (int)(Math.random() * m.state.hand.length); int i = dm.onReceiveRequest(status, m); ////////////// if(i==9999){ OfferChallengeMessage challenge = new OfferChallengeMessage(m.request_id); return challenge; } ////////////// int[] hand = m.state.hand; sort(hand); PlayCardMessage card = new PlayCardMessage(m.request_id,hand[i]); // System.out.println(card.toString()); return card; } else { OfferChallengeMessage challenge = new OfferChallengeMessage(m.request_id); // System.out.println(challenge.toString()); return challenge; } } else if (m.request.equals("challenge_offered")) { PlayerMessage response; if(acceptChallenge(m)){ response = new AcceptChallengeMessage(m.request_id); } else{ response = new RejectChallengeMessage(m.request_id); } // System.out.println(response.toString()); return response; } } else if (message.type.equals("result")) { ResultMessage r = (ResultMessage)message; if ( r.result.type.equals("game_won") ) { if ( r.result.by == r.your_player_num ) wonGames++; totalGames++; //System.out.println("Won ratio: " + (double)wonGames/totalGames); } // System.out.println(r.toString()); dm.onReceiveResult(status, r); } else if (message.type.equals("error")) { ErrorMessage e = (ErrorMessage)message; System.err.println("Error: " + e.message); // need to register IP address on the contest server if (e.seen_host != null) { System.exit(1); } } return null; }
8cccf6b2-b5dc-4117-9ad6-e2a59006647b
public static void main(String[] args) { if (args.length < 2) { System.err.println("Usage: java -jar ContestBot.jar <HOST> <PORT>"); System.exit(1); } String host = args[0]; Integer port = Integer.parseInt(args[1]); ContestBot cb = new ContestBot(host, port); cb.run(); }
f224a533-b0a9-4d69-aa2e-3b07e4aadccc
public boolean isChanllenge(MoveMessage m){ if(haveLostHand(m)){ return false; } if (haveWinHand(m)) { return true; } // if(isHandBig(m.state.hand)>0){ // return true; // } // else if(m.state.their_points>8){ // return true; // } return activeChallenge(m.state.hand, winTime, loseTime, m.state.their_points, m.state.your_points); // return true; }
93162f5e-3a31-4d2b-acc2-93becf954ab4
public boolean haveLostHand(MoveMessage m){ if((m.state.your_tricks<m.state.their_tricks) &&(Math.abs(m.state.their_tricks-m.state.your_tricks)>(5-m.state.total_tricks) )){ return true; } return false; }
19ceedf9-8108-4a17-af3e-e84d411fe0b4
public boolean haveWinHand(MoveMessage m){ if((m.state.your_tricks>m.state.their_tricks) &&(Math.abs(m.state.their_tricks-m.state.your_tricks)>(5-m.state.total_tricks) )){ return true; } return false; }
931a1457-cd3b-40c4-a834-df0a639d5311
public boolean acceptChallenge(MoveMessage m){ if(haveWinHand(m)){ return true; } else if(haveLostHand(m)){ return false; } return passiveChallenge(m.state.hand, winTime, loseTime, m.state.their_points, m.state.your_points); // return true; }
ba8f52c8-b458-4d0b-a104-a1f3ffcc5e33
public int myHandQuality(int[] hand,int hid){ for (int i=0;i<hand.length;i++){ if(hand[i]==13){ return 1; } } return 0; }
d31968ac-cd84-492f-95f4-fcc87a3c17fd
public int isHandBig(int[] hand){ int sum = 0; for(int i=0;i<hand.length;i++){ sum+=hand[i]; } if((sum/hand.length)>=8){ return 1; } return 0; }