{"record":{"id":"e25fd69f8868c869","repo":"TheAlgorithms/Python","slug":"data-set-labels-must-be-one-dimensional","errorCode":null,"errorMessage":"Data set labels must be one-dimensional","messagePattern":"Data set labels must be one-dimensional","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/decision_tree.py","lineNumber":88,"sourceCode":"            ...\n        ValueError: x and y have different lengths\n\n        4. Try to train when x & y are of the same length but different dimensions\n        >>> dt = DecisionTree()\n        >>> dt.train(np.array([1,2,3,4,5]),np.array([[1],[2],[3],[4],[5]]))\n        Traceback (most recent call last):\n            ...\n        ValueError: Data set labels must be one-dimensional\n\n        This section is to check that the inputs conform to our dimensionality\n        constraints\n        \"\"\"\n        if x.ndim != 1:\n            raise ValueError(\"Input data set must be one-dimensional\")\n        if len(x) != len(y):\n            raise ValueError(\"x and y have different lengths\")\n        if y.ndim != 1:\n            raise ValueError(\"Data set labels must be one-dimensional\")\n\n        if len(x) < 2 * self.min_leaf_size:\n            self.prediction = np.mean(y)\n            return\n\n        if self.depth == 1:\n            self.prediction = np.mean(y)\n            return\n\n        best_split = 0\n        min_error = self.mean_squared_error(x, np.mean(y)) * 2\n\n        \"\"\"\n        loop over all possible splits for the decision tree. find the best split.\n        if no split exists that is less than 2 * error for the entire array\n        then the data set is not split and the average for the entire array is used as\n        the predictor\n        \"\"\"","sourceCodeStart":70,"sourceCodeEnd":106,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/decision_tree.py#L70-L106","documentation":"Raised by DecisionTree.train when the y (labels) argument is not one-dimensional, even if lengths match. The tree computes np.mean(y) for leaf predictions and compares scalar labels against the decision boundary, which only works for shape (n,) arrays.","triggerScenarios":"Calling dt.train(np.array([1,2,3,4,5]), np.array([[1],[2],[3],[4],[5]])) exactly as in the doctest — a column-vector y with shape (n, 1) has len equal to x but ndim == 2.","commonSituations":"Labels reshaped to (n, 1) for a keras/sklearn pipeline and reused here, or labels loaded via df[['label']].values instead of df['label'].values.","solutions":["Flatten y: y = np.asarray(y).ravel().","Extract labels as a 1D Series: df['label'].values, not df[['label']].values.","Add a shared shape check (x.ndim == 1 and y.ndim == 1) in your data-prep function."],"exampleFix":"# before\ndt.train(x, y.reshape(-1, 1))\n\n# after\ndt.train(x, y.ravel())","handlingStrategy":"type-guard","validationCode":"x = np.asarray(x).ravel()\ny = np.asarray(y).ravel()\ndt.train(x, y)","typeGuard":"def is_1d_pair(x, y) -> bool:\n    return np.asarray(x).ndim == 1 and np.asarray(y).ndim == 1","tryCatchPattern":"try:\n    dt.train(x, y)\nexcept ValueError as e:\n    if \"one-dimensional\" in str(e):\n        dt.train(np.asarray(x).ravel(), np.asarray(y).ravel())\n    else:\n        raise","preventionTips":["Undo (n, 1) reshapes made for other frameworks before training.","Use .ravel() on both arrays defensively.","Keep one canonical 1D representation for labels in the pipeline."],"tags":["machine-learning","decision-tree","shape-mismatch","numpy"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}