{
  "source_file": "0930",
  "source_platform": "Hashnode",
  "author": "Muhammad Fahad Bashir",
  "title_listed": "Decision Tree Algorithm Explained: Simple Guide with Example and Gradio App",
  "keywords": "",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://ml-diaries-by-fahd.hashnode.dev/decision-tree-algorithm-explained-simple-guide-with-example-and-gradio-app",
  "publish_date": "2025-10-02",
  "corpus_stage": "",
  "notes": "",
  "id": "e5f9611d268f",
  "collected_at": "2026-10-02T14:10:55",
  "title": "Decision Tree Algorithm Explained: Simple Guide with Example and Gradio App",
  "body_markdown": "Decision Tree Algorithm Explained: Simple Guide with Example and Gradio App\nPublished\nOctober 2, 2025\n•\n5\nmin read\n•\nView as Markdown\nM\nMuhammad Fahad Bashir\nMachine Learning, Artificial Intelligence\nPart of series\nSupervise Learning\nIn our supervised learning series, we’ve explored the basics of classification algorithms and covered the\nconcept of logistic regression\n. Now, let’s move to another popular algorithm:\nDecision Trees\n.\nDecision Trees are widely used in machine learning because they are simple, interpretable, and effective for both\nclassification\nand\nregression\ntasks. The beauty of decision trees is that they break complex problems into smaller, more understandable steps — just like following a flowchart.\nWhat is a Decision Tree?\nA\nDecision Tree\nis a hierarchical structure that helps make predictions based on conditions.\nRoot Node\n→ The starting point (first split).\nInternal Nodes\n→ Tests based on feature values.\nBranches\n→ Outcomes of the test.\nLeaf Nodes\n→ Final decision or prediction.\nThink of it like a series of\nYes/No\nquestions that lead you to an answer.\nHow Does a Decision Tree Work?\nThe algorithm builds the tree by repeatedly splitting the dataset into groups:\nSelect the best feature\nusing a rule (Attribute Selection Measure, ASM).\nCommon ASMs:\nInformation Gain, Gain Ratio, Gini Index\n.\nSplit the dataset\nbased on that feature.\nCreate decision nodes\nfor splits, and\nleaf nodes\nfor final decisions.\nRepeat until:\nAll records in a branch belong to the same class.\nNo features are left.\nThe dataset can’t be split further.\nThe goal is to create “pure” groups where each group mostly contains samples from one class.\nAttribute Selection: Choosing the Best Split\nA big question is:\nHow does the algorithm decide which feature to split on?\nIt uses\nAttribute Selection Measures (ASMs)\nlike\nInformation Gain\n,\nGain Ratio, Gini Index\n. For detail math, you can visit\nhere\n.\nThese methods measure how well a feature divides the dataset into clear groups. The feature with the\nbest score\nbecomes the node for splitting.\nDecision Trees for Classification vs Regression\nDecision Trees can be used in\ntwo ways\n:\nClassification\n→ The tree predicts a\nclass label\n(e.g., Setosa, Versicolor, Virginica in the Iris dataset). It splits data into pure groups until each branch mainly belongs to one class.\nRegression\n→ Instead of predicting a class, the tree predicts a\ncontinuous value\n(e.g., predicting house prices). At each split, it tries to minimize the difference between predicted and actual values (using metrics like Mean Squared Error).\n👉 In short, classification trees answer\n“Which category does this belong to?”\n, while regression trees answer\n“What is the value?”\n.\nPractical Example with the Iris Dataset\nLet’s use the\nIris dataset\n, which has:\n4 features\n→ Sepal length, Sepal width, Petal length, Petal width.\nTarget\n→ Type of Iris flower (Setosa, Versicolor, Virginica).\nStep 1: Root Node\nThe algorithm looks at all features. It finds that\nPetal length\nseparates Setosa from the others very well.\nPetal length ≤ 2.45 → Setosa\nPetal length > 2.45 → Needs more splitting\nStep 2: Split Further\nFor samples where\nPetal length > 2.45\n, we still have two species mixed (Versicolor & Virginica). The algorithm checks the remaining features and finds\nPetal width\nis the best split:\nPetal width ≤ 1.75 → Versicolor\nPetal width > 1.75 → Virginica\nStep 3: Stop at Pure Nodes\nNow each branch contains only one species. The tree looks like this:\nPetal length ≤ 2.45 →\nSetosa\nPetal length > 2.45 & Petal width ≤ 1.75 →\nVersicolor\nPetal length > 2.45 & Petal width > 1.75 →\nVirginica\nThat’s it —how it works!\nThe\nIris dataset\nis one of the most common beginner datasets. It contains measurements of iris flowers (like sepal length, sepal width, petal length, petal width) and the goal is to predict the species (Setosa, Versicolor, Virginica).\nWe’ll use a\nDecision Tree Classifier\nfrom\nsklearn\nto solve this problem.\nfrom\nsklearn.datasets\nimport\nload_iris\nfrom\nsklearn.tree\nimport\nDecisionTreeClassifier\nfrom\nsklearn.model_selection\nimport\ntrain_test_split\nfrom\nsklearn.metrics\nimport\naccuracy_score\n# Step 1: Load the Iris dataset\nX, y = load_iris(return_X_y=\nTrue\n)\n# Step 2: Split data into training (80%) and testing (20%)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=\n0.2\n, random_state=\n42\n)\n# Step 3: Initialize Decision Tree Classifier\nclf = DecisionTreeClassifier(random_state=\n42\n)\n# Step 4: Train the model\nclf.fit(X_train, y_train)\n# Step 5: Predict and evaluate\ny_pred = clf.predict(X_test)\nacc = accuracy_score(y_test, y_pred) *\n100\nprint(\nf\"Decision Tree model accuracy:\n{acc:\n.2\nf}\n%\"\n)\nWrapping with a Simple UI using Gradio 🎨\nWe can make our model interactive so that anyone can test predictions without writing code. Let’s build a\nGradio interface\nwhere users input flower measurements and see the predicted species.We can perform the\nSave the trained model\nLoad the iris tables\nDefine prediction function\nBuild Gradio UI\nimport\ngradio\nas\ngr\nimport\njoblib\n# Save the trained model\njoblib.dump(clf,\n\"decision_tree_iris.pkl\"\n)\n# Load iris dataset labels\niris = load_iris()\ntarget_names = iris.target_names\n# Define prediction function\ndef\npredict_species\n(\nsepal_length, sepal_width, petal_length, petal_width\n):\nmodel = joblib.load(\n\"decision_tree_iris.pkl\"\n)\n    features = [[sepal_length, sepal_width, petal_length, petal_width]]\n    prediction = model.predict(features)[\n0\n]\nreturn\nf\"Predicted Species:\n{target_names[prediction]}\n\"\n# Build Gradio UI\ninterface = gr.Interface(\n    fn=predict_species,\n    inputs=[\n        gr.Number(label=\n\"Sepal Length\"\n),\n        gr.Number(label=\n\"Sepal Width\"\n),\n        gr.Number(label=\n\"Petal Length\"\n),\n        gr.Number(label=\n\"Petal Width\"\n)\n    ],\n    outputs=\n\"text\"\n,\n    title=\n\"Decision Tree Classifier - Iris Dataset 🌸\"\n,\n    description=\n\"Enter flower measurements and let the Decision Tree predict the species.\"\n)\n\ninterface.launch()\nConclusion\nDecision Trees work by asking the most important “Yes/No” questions about features until they can classify data into groups. In the Iris dataset, just two questions about petal length and width were enough to classify flowers into three species.\nIn real-world scenarios, decision trees can grow much larger, but the concept remains the same. They’re simple, interpretable, and a great starting point before moving on to advanced ensemble methods like\nRandom Forests\nand\nGradient Boosting\n.\nStay tuned — in the next articles, we’ll explore how decision trees form the foundation for these advanced models. 🚀\n#\ndecisiontree\n#\ngradio\n#\nsupervised-learning\n#\nmachine-learning\n#\nalgorithms\n22\nviews",
  "metadata": {
    "title": "Decision Tree Algorithm Explained: Simple Guide with Example and Gradio App",
    "description": "Learn how Decision Trees work, their components, and build a Gradio app using the Iris dataset for classification tasks with this comprehensive guide",
    "keywords": null,
    "author": null,
    "og:title": "Decision Tree Algorithm Explained: Simple Guide with Example and Gradio App",
    "og:description": "Learn how Decision Trees work, their components, and build a Gradio app using the Iris dataset for classification tasks with this comprehensive guide",
    "og:url": "https://ml-diaries-by-fahd.hashnode.dev/decision-tree-algorithm-explained-simple-guide-with-example-and-gradio-app",
    "og:site_name": "ML Diaries by Fahd",
    "og:image": "https://cdn.hashnode.com/res/hashnode/image/upload/v1759413668577/4676b913-c2a1-4865-a457-7b94119ac5e5.png",
    "og:image:width": "1200",
    "og:image:height": "630",
    "og:type": "article",
    "twitter:card": "summary_large_image",
    "twitter:title": "Decision Tree Algorithm Explained: Simple Guide with Example and Gradio App",
    "twitter:description": "Learn how Decision Trees work, their components, and build a Gradio app using the Iris dataset for classification tasks with this comprehensive guide",
    "twitter:image": "https://cdn.hashnode.com/res/hashnode/image/upload/v1759413668577/4676b913-c2a1-4865-a457-7b94119ac5e5.png",
    "article:published_time": "2025-10-02T14:02:26.068Z",
    "article:author": "https://ml-diaries-by-fahd.hashnode.dev/@mfahadbashir"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "file": "attachments/e5f9611d268f/code/body-000.txt",
      "chars": 701,
      "language": "text"
    },
    {
      "file": "attachments/e5f9611d268f/code/body-001.txt",
      "chars": 952,
      "language": "text"
    }
  ],
  "images": [
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1759413668577/4676b913-c2a1-4865-a457-7b94119ac5e5.png",
      "bytes": 769384,
      "reused": true,
      "local_path": "attachments/e5f9611d268f/images/002.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1759413668577/4676b913-c2a1-4865-a457-7b94119ac5e5.png",
      "alt": "Decision Tree Algorithm Explained: Simple Guide with Example and Gradio App",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://dataaspirant.com/wp-content/uploads/2017/01/B03905_05_01-compressor.png",
      "bytes": 94186,
      "reused": true,
      "local_path": "attachments/e5f9611d268f/images/004.png",
      "src": "https://dataaspirant.com/wp-content/uploads/2017/01/B03905_05_01-compressor.png",
      "alt": "How Decision Tree Algorithm works",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://images.datacamp.com/image/upload/f_auto,q_auto:best/v1545934190/2_btay8n.png",
      "bytes": 132898,
      "reused": true,
      "local_path": "attachments/e5f9611d268f/images/005.png",
      "src": "https://images.datacamp.com/image/upload/f_auto,q_auto:best/v1545934190/2_btay8n.png",
      "alt": "How does the Decision Tree Algorithm Work?",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1759413485945/03b7e185-5444-46c6-a3e9-5590724e5087.png",
      "bytes": 34981,
      "reused": true,
      "local_path": "attachments/e5f9611d268f/images/006.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1759413485945/03b7e185-5444-46c6-a3e9-5590724e5087.png",
      "alt": "",
      "downloaded": true
    }
  ],
  "audio": [],
  "videos": [],
  "links": [
    {
      "href": "https://ml-diaries-by-fahd.hashnode.dev/decision-tree-algorithm-explained-simple-guide-with-example-and-gradio-app.md",
      "label": "View as Markdown",
      "type": "a"
    },
    {
      "href": "https://hashnode.com/@mfahadbashir",
      "label": "M",
      "type": "a"
    },
    {
      "href": "https://www.linkedin.com/in/muhammad-fahad-bashir-09568216a/",
      "label": "",
      "type": "a"
    },
    {
      "href": "https://ml-diaries-by-fahd.hashnode.dev/series/supervised-learning",
      "label": "Part of series Supervise Learning",
      "type": "a"
    },
    {
      "href": "https://ml-diaries-by-fahd.hashnode.dev/a-simple-guide-to-logistic-regression-with-concepts-workflow-and-real-world-use-case",
      "label": "concept of logistic regression",
      "type": "a"
    },
    {
      "href": "https://www.datacamp.com/tutorial/decision-tree-classification-python",
      "label": "",
      "type": "a"
    },
    {
      "href": "https://www.geeksforgeeks.org/machine-learning/decision-tree-introduction-example/",
      "label": "here",
      "type": "a"
    },
    {
      "href": "https://ml-diaries-by-fahd.hashnode.dev/tag/decisiontree",
      "label": "# decisiontree",
      "type": "a"
    },
    {
      "href": "https://ml-diaries-by-fahd.hashnode.dev/tag/gradio",
      "label": "# gradio",
      "type": "a"
    },
    {
      "href": "https://ml-diaries-by-fahd.hashnode.dev/tag/supervised-learning",
      "label": "# supervised-learning",
      "type": "a"
    },
    {
      "href": "https://ml-diaries-by-fahd.hashnode.dev/tag/machine-learning",
      "label": "# machine-learning",
      "type": "a"
    },
    {
      "href": "https://ml-diaries-by-fahd.hashnode.dev/tag/algorithms",
      "label": "# algorithms",
      "type": "a"
    }
  ],
  "retry_at": "2026-10-03T08:07:35",
  "repair_version": 2,
  "repaired_at": "2026-10-14T10:50:42Z",
  "source_url": "https://ml-diaries-by-fahd.hashnode.dev/decision-tree-algorithm-explained-simple-guide-with-example-and-gradio-app",
  "papers": [],
  "actual_video_files": [],
  "body_chars": 6654,
  "expected_body_images": 4,
  "discovery_status": "ok",
  "delivery_status": "ok",
  "missing_reason": "",
  "raw_html": "attachments/e5f9611d268f/pages/source.html",
  "local_html": "attachments/e5f9611d268f/pages/article.html",
  "body_base_path": "attachments/e5f9611d268f/pages/",
  "body_markdown_path": "attachments/e5f9611d268f/pages/article.md"
}