\n",
"
sklearn.tree._classes.DecisionTreeClassifier
def __init__(*, criterion='gini', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, class_weight=None, ccp_alpha=0.0)
/usr/local/lib/python3.10/dist-packages/sklearn/tree/_classes.pyA decision tree classifier.\n",
"\n",
"Read more in the :ref:`User Guide <tree>`.\n",
"\n",
"Parameters\n",
"----------\n",
"criterion : {"gini", "entropy", "log_loss"}, default="gini"\n",
" The function to measure the quality of a split. Supported criteria are\n",
" "gini" for the Gini impurity and "log_loss" and "entropy" both for the\n",
" Shannon information gain, see :ref:`tree_mathematical_formulation`.\n",
"\n",
"splitter : {"best", "random"}, default="best"\n",
" The strategy used to choose the split at each node. Supported\n",
" strategies are "best" to choose the best split and "random" to choose\n",
" the best random split.\n",
"\n",
"max_depth : int, default=None\n",
" The maximum depth of the tree. If None, then nodes are expanded until\n",
" all leaves are pure or until all leaves contain less than\n",
" min_samples_split samples.\n",
"\n",
"min_samples_split : int or float, default=2\n",
" The minimum number of samples required to split an internal node:\n",
"\n",
" - If int, then consider `min_samples_split` as the minimum number.\n",
" - If float, then `min_samples_split` is a fraction and\n",
" `ceil(min_samples_split * n_samples)` are the minimum\n",
" number of samples for each split.\n",
"\n",
" .. versionchanged:: 0.18\n",
" Added float values for fractions.\n",
"\n",
"min_samples_leaf : int or float, default=1\n",
" The minimum number of samples required to be at a leaf node.\n",
" A split point at any depth will only be considered if it leaves at\n",
" least ``min_samples_leaf`` training samples in each of the left and\n",
" right branches. This may have the effect of smoothing the model,\n",
" especially in regression.\n",
"\n",
" - If int, then consider `min_samples_leaf` as the minimum number.\n",
" - If float, then `min_samples_leaf` is a fraction and\n",
" `ceil(min_samples_leaf * n_samples)` are the minimum\n",
" number of samples for each node.\n",
"\n",
" .. versionchanged:: 0.18\n",
" Added float values for fractions.\n",
"\n",
"min_weight_fraction_leaf : float, default=0.0\n",
" The minimum weighted fraction of the sum total of weights (of all\n",
" the input samples) required to be at a leaf node. Samples have\n",
" equal weight when sample_weight is not provided.\n",
"\n",
"max_features : int, float or {"auto", "sqrt", "log2"}, default=None\n",
" The number of features to consider when looking for the best split:\n",
"\n",
" - If int, then consider `max_features` features at each split.\n",
" - If float, then `max_features` is a fraction and\n",
" `max(1, int(max_features * n_features_in_))` features are considered at\n",
" each split.\n",
" - If "auto", then `max_features=sqrt(n_features)`.\n",
" - If "sqrt", then `max_features=sqrt(n_features)`.\n",
" - If "log2", then `max_features=log2(n_features)`.\n",
" - If None, then `max_features=n_features`.\n",
"\n",
" .. deprecated:: 1.1\n",
" The `"auto"` option was deprecated in 1.1 and will be removed\n",
" in 1.3.\n",
"\n",
" Note: the search for a split does not stop until at least one\n",
" valid partition of the node samples is found, even if it requires to\n",
" effectively inspect more than ``max_features`` features.\n",
"\n",
"random_state : int, RandomState instance or None, default=None\n",
" Controls the randomness of the estimator. The features are always\n",
" randomly permuted at each split, even if ``splitter`` is set to\n",
" ``"best"``. When ``max_features < n_features``, the algorithm will\n",
" select ``max_features`` at random at each split before finding the best\n",
" split among them. But the best found split may vary across different\n",
" runs, even if ``max_features=n_features``. That is the case, if the\n",
" improvement of the criterion is identical for several splits and one\n",
" split has to be selected at random. To obtain a deterministic behaviour\n",
" during fitting, ``random_state`` has to be fixed to an integer.\n",
" See :term:`Glossary <random_state>` for details.\n",
"\n",
"max_leaf_nodes : int, default=None\n",
" Grow a tree with ``max_leaf_nodes`` in best-first fashion.\n",
" Best nodes are defined as relative reduction in impurity.\n",
" If None then unlimited number of leaf nodes.\n",
"\n",
"min_impurity_decrease : float, default=0.0\n",
" A node will be split if this split induces a decrease of the impurity\n",
" greater than or equal to this value.\n",
"\n",
" The weighted impurity decrease equation is the following::\n",
"\n",
" N_t / N * (impurity - N_t_R / N_t * right_impurity\n",
" - N_t_L / N_t * left_impurity)\n",
"\n",
" where ``N`` is the total number of samples, ``N_t`` is the number of\n",
" samples at the current node, ``N_t_L`` is the number of samples in the\n",
" left child, and ``N_t_R`` is the number of samples in the right child.\n",
"\n",
" ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,\n",
" if ``sample_weight`` is passed.\n",
"\n",
" .. versionadded:: 0.19\n",
"\n",
"class_weight : dict, list of dict or "balanced", default=None\n",
" Weights associated with classes in the form ``{class_label: weight}``.\n",
" If None, all classes are supposed to have weight one. For\n",
" multi-output problems, a list of dicts can be provided in the same\n",
" order as the columns of y.\n",
"\n",
" Note that for multioutput (including multilabel) weights should be\n",
" defined for each class of every column in its own dict. For example,\n",
" for four-class multilabel classification weights should be\n",
" [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of\n",
" [{1:1}, {2:5}, {3:1}, {4:1}].\n",
"\n",
" The "balanced" mode uses the values of y to automatically adjust\n",
" weights inversely proportional to class frequencies in the input data\n",
" as ``n_samples / (n_classes * np.bincount(y))``\n",
"\n",
" For multi-output, the weights of each column of y will be multiplied.\n",
"\n",
" Note that these weights will be multiplied with sample_weight (passed\n",
" through the fit method) if sample_weight is specified.\n",
"\n",
"ccp_alpha : non-negative float, default=0.0\n",
" Complexity parameter used for Minimal Cost-Complexity Pruning. The\n",
" subtree with the largest cost complexity that is smaller than\n",
" ``ccp_alpha`` will be chosen. By default, no pruning is performed. See\n",
" :ref:`minimal_cost_complexity_pruning` for details.\n",
"\n",
" .. versionadded:: 0.22\n",
"\n",
"Attributes\n",
"----------\n",
"classes_ : ndarray of shape (n_classes,) or list of ndarray\n",
" The classes labels (single output problem),\n",
" or a list of arrays of class labels (multi-output problem).\n",
"\n",
"feature_importances_ : ndarray of shape (n_features,)\n",
" The impurity-based feature importances.\n",
" The higher, the more important the feature.\n",
" The importance of a feature is computed as the (normalized)\n",
" total reduction of the criterion brought by that feature. It is also\n",
" known as the Gini importance [4]_.\n",
"\n",
" Warning: impurity-based feature importances can be misleading for\n",
" high cardinality features (many unique values). See\n",
" :func:`sklearn.inspection.permutation_importance` as an alternative.\n",
"\n",
"max_features_ : int\n",
" The inferred value of max_features.\n",
"\n",
"n_classes_ : int or list of int\n",
" The number of classes (for single output problems),\n",
" or a list containing the number of classes for each\n",
" output (for multi-output problems).\n",
"\n",
"n_features_in_ : int\n",
" Number of features seen during :term:`fit`.\n",
"\n",
" .. versionadded:: 0.24\n",
"\n",
"feature_names_in_ : ndarray of shape (`n_features_in_`,)\n",
" Names of features seen during :term:`fit`. Defined only when `X`\n",
" has feature names that are all strings.\n",
"\n",
" .. versionadded:: 1.0\n",
"\n",
"n_outputs_ : int\n",
" The number of outputs when ``fit`` is performed.\n",
"\n",
"tree_ : Tree instance\n",
" The underlying Tree object. Please refer to\n",
" ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and\n",
" :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py`\n",
" for basic usage of these attributes.\n",
"\n",
"See Also\n",
"--------\n",
"DecisionTreeRegressor : A decision tree regressor.\n",
"\n",
"Notes\n",
"-----\n",
"The default values for the parameters controlling the size of the trees\n",
"(e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and\n",
"unpruned trees which can potentially be very large on some data sets. To\n",
"reduce memory consumption, the complexity and size of the trees should be\n",
"controlled by setting those parameter values.\n",
"\n",
"The :meth:`predict` method operates using the :func:`numpy.argmax`\n",
"function on the outputs of :meth:`predict_proba`. This means that in\n",
"case the highest predicted probabilities are tied, the classifier will\n",
"predict the tied class with the lowest index in :term:`classes_`.\n",
"\n",
"References\n",
"----------\n",
"\n",
".. [1] https://en.wikipedia.org/wiki/Decision_tree_learning\n",
"\n",
".. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification\n",
" and Regression Trees", Wadsworth, Belmont, CA, 1984.\n",
"\n",
".. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical\n",
" Learning", Springer, 2009.\n",
"\n",
".. [4] L. Breiman, and A. Cutler, "Random Forests",\n",
" https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm\n",
"\n",
"Examples\n",
"--------\n",
">>> from sklearn.datasets import load_iris\n",
">>> from sklearn.model_selection import cross_val_score\n",
">>> from sklearn.tree import DecisionTreeClassifier\n",
">>> clf = DecisionTreeClassifier(random_state=0)\n",
">>> iris = load_iris()\n",
">>> cross_val_score(clf, iris.data, iris.target, cv=10)\n",
"... # doctest: +SKIP\n",
"...\n",
"array([ 1. , 0.93..., 0.86..., 0.93..., 0.93...,\n",
" 0.93..., 0.93..., 1. , 0.93..., 1. ])
\n",
" \n",
"
"
]
},
"metadata": {},
"execution_count": 49
}
],
"source": [
"type(weather_classifier)"
]
},
{
"cell_type": "markdown",
"id": "vULqmNvVF4q4",
"metadata": {
"id": "vULqmNvVF4q4"
},
"source": [
"### **5. Model Evaluation**\n",
"Evaluate the model's performance using metrics such as accuracy, precision, recall, and F1-score."
]
},
{
"cell_type": "code",
"execution_count": 50,
"id": "lYjAaucHjeij",
"metadata": {
"id": "lYjAaucHjeij"
},
"outputs": [],
"source": [
"# Make predictions\n",
"y_pred_array = weather_classifier.predict(X_test)"
]
},
{
"cell_type": "code",
"execution_count": 51,
"id": "68E1R0hGjee_",
"metadata": {
"id": "68E1R0hGjee_"
},
"outputs": [],
"source": [
"# Ensure y_test is a Pandas Series to access its index\n",
"if isinstance(y_test, np.ndarray):\n",
" y_test = pd.Series(y_test)"
]
},
{
"cell_type": "code",
"execution_count": 52,
"id": "UL0yIOXcjeYi",
"metadata": {
"id": "UL0yIOXcjeYi"
},
"outputs": [],
"source": [
"# Create DataFrame from the predictions\n",
"y_pred = pd.DataFrame(y_pred_array, columns=[\"weather\"])"
]
},
{
"cell_type": "code",
"execution_count": 53,
"id": "chg9gMVRjkH9",
"metadata": {
"id": "chg9gMVRjkH9"
},
"outputs": [],
"source": [
"# Set the index of the DataFrame to match y_test index\n",
"y_pred.index = y_test.index"
]
},
{
"cell_type": "code",
"execution_count": 54,
"id": "acb6ff0f-e48c-4184-9cd7-75281b5a5c9b",
"metadata": {
"id": "acb6ff0f-e48c-4184-9cd7-75281b5a5c9b"
},
"outputs": [],
"source": [
"# Ensure the data type is int\n",
"y_pred = y_pred.astype(int)"
]
},
{
"cell_type": "code",
"execution_count": 55,
"id": "rHo5wG80jpeR",
"metadata": {
"id": "rHo5wG80jpeR",
"outputId": "c50535fd-7b87-43ab-c6cb-d8fa9930ec92",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
" weather\n",
"571 1\n",
"1369 2\n",
"1394 2\n",
"115 2\n",
"456 2\n",
"... ...\n",
"1730 2\n",
"873 2\n",
"1083 3\n",
"1733 2\n",
"329 3\n",
"\n",
"[513 rows x 1 columns]\n"
]
}
],
"source": [
"print(y_pred)"
]
},
{
"cell_type": "code",
"execution_count": 56,
"id": "65aab513-c6cf-4489-96f9-7d750754233e",
"metadata": {
"id": "65aab513-c6cf-4489-96f9-7d750754233e"
},
"outputs": [],
"source": [
"y_test = np.array(y_test,dtype = int)"
]
},
{
"cell_type": "code",
"execution_count": 57,
"id": "05ca175a-a41b-42c3-92bc-97375c6aab73",
"metadata": {
"id": "05ca175a-a41b-42c3-92bc-97375c6aab73",
"outputId": "c1c02c65-a259-45cf-c960-3af1d0fb8cad",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"numpy.ndarray"
]
},
"metadata": {},
"execution_count": 57
}
],
"source": [
"type(y_test)"
]
},
{
"cell_type": "code",
"execution_count": 58,
"id": "c1e80c44-e162-4ca1-83a5-13f64b036b19",
"metadata": {
"id": "c1e80c44-e162-4ca1-83a5-13f64b036b19",
"outputId": "fbbd3fcd-3549-4a38-f49a-ef8cba6c7a0a",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"array([1, 2, 2, 2, 2, 2, 2, 1, 2, 1, 2, 2, 2, 1, 2, 1, 1, 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, 2, 2, 3, 2, 3, 2, 2, 2, 2, 2, 3, 2, 2, 1, 1, 3, 2, 2,\n",
" 2, 3, 2, 1, 1, 1, 1, 1, 2, 2, 2, 1, 3, 2, 2, 2, 1, 2, 1, 2, 1, 1,\n",
" 1, 1, 1, 3, 1, 2, 2, 2, 2, 2, 3, 2, 3, 2, 2, 2, 2, 3, 1, 1, 2, 2,\n",
" 2, 1, 3, 2, 2, 2, 1, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,\n",
" 2, 1, 2, 3, 1, 1, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2,\n",
" 2, 2, 3, 2, 3, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 3, 2, 1, 2,\n",
" 1, 1, 2, 1, 2, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 3, 2, 1, 2, 1, 2, 2,\n",
" 2, 3, 3, 3, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 2, 1, 2,\n",
" 1, 2, 2, 2, 3, 2, 3])"
]
},
"metadata": {},
"execution_count": 58
}
],
"source": [
"y_test"
]
},
{
"cell_type": "code",
"execution_count": 59,
"id": "42c4582e-1a9e-4ca5-9133-d4ff0bc7ca92",
"metadata": {
"id": "42c4582e-1a9e-4ca5-9133-d4ff0bc7ca92",
"outputId": "45c2cec0-dfa9-4687-dc61-84a91c222f78",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"0.9980506822612085"
]
},
"metadata": {},
"execution_count": 59
}
],
"source": [
"# Measure Accuracy\n",
"metrics.accuracy_score(y_test,y_pred)"
]
},
{
"cell_type": "code",
"execution_count": 60,
"id": "181bd3c2-6026-4092-ac0b-4a51c928d6b6",
"metadata": {
"id": "181bd3c2-6026-4092-ac0b-4a51c928d6b6",
"outputId": "a2b2a35e-f938-4e6f-cd74-1de0cc01b42b",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
" precision recall f1-score support\n",
"\n",
" 1 1.00 1.00 1.00 136\n",
" 2 1.00 1.00 1.00 311\n",
" 3 0.99 1.00 0.99 66\n",
"\n",
" accuracy 1.00 513\n",
" macro avg 1.00 1.00 1.00 513\n",
"weighted avg 1.00 1.00 1.00 513\n",
"\n"
]
}
],
"source": [
"print(metrics.classification_report(y_test, y_pred))"
]
},
{
"cell_type": "markdown",
"id": "566afdb7-c26f-46b0-9ae2-0e0ca73ef037",
"metadata": {
"id": "566afdb7-c26f-46b0-9ae2-0e0ca73ef037"
},
"source": [
"### **6. Model Deployment**\n",
"Save the trained model for future use and deploying it in real-world applications."
]
},
{
"cell_type": "code",
"execution_count": 61,
"id": "2f755dff-26ee-407e-8c0b-2a3056d0c1cb",
"metadata": {
"id": "2f755dff-26ee-407e-8c0b-2a3056d0c1cb",
"outputId": "536a7788-0967-4762-bd2e-dff2fcb60308",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"#pragma once\n",
"#include