{"record":{"id":"8d2e2ff21f33214d","repo":"pola-rs/polars","slug":"label-and-features-only-apply-when-return-typ-8d2e2f","errorCode":null,"errorMessage":"`label` and `features` only apply when `return_type` is 'dataset' or 'dict'","messagePattern":"`label` and `features` only apply when `return_type` is 'dataset' or 'dict'","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/dataframe/frame.py","lineNumber":2470,"sourceCode":"        >>> housing = fetch_california_housing()  # doctest: +SKIP\n        >>> df = pl.DataFrame(\n        ...     data=housing.data,\n        ...     schema=housing.feature_names,\n        ... ).with_columns(\n        ...     Target=housing.target,\n        ... )  # doctest: +SKIP\n        >>> train = df.to_torch(\"dataset\", label=\"Target\")  # doctest: +SKIP\n        >>> loader = DataLoader(\n        ...     train,\n        ...     shuffle=True,\n        ...     batch_size=64,\n        ... )  # doctest: +SKIP\n        \"\"\"\n        if return_type not in (\"dataset\", \"dict\") and (\n            label is not None or features is not None\n        ):\n            msg = \"`label` and `features` only apply when `return_type` is 'dataset' or 'dict'\"\n            raise ValueError(msg)\n        elif return_type == \"dict\" and label is None and features is not None:\n            msg = \"`label` is required if setting `features` when `return_type='dict'\"\n            raise ValueError(msg)\n\n        torch = import_optional(\"torch\")\n\n        # Cast columns.\n        if dtype in (UInt16, UInt32, UInt64):\n            msg = f\"PyTorch does not support u16, u32, or u64 dtypes; given {dtype}\"\n            raise ValueError(msg)\n\n        to_dtype = dtype or {UInt16: Int32, UInt32: Int64, UInt64: Int64}\n\n        if label is not None:\n            label_frame = self.select(label)\n            # Avoid casting the label if it's an expression.\n            if not isinstance(label, pl.Expr):\n                label_frame = label_frame.cast(to_dtype)  # type: ignore[arg-type]","sourceCodeStart":2452,"sourceCodeEnd":2488,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/dataframe/frame.py#L2452-L2488","documentation":"Raised by DataFrame.to_torch when `label` or `features` is supplied but `return_type` is not 'dataset' or 'dict'. Label/features splitting exists only for those two exports: 'dataset' builds a PolarsDataset with labeled features and 'dict' returns {'label': tensor, 'features': tensor}. The default 'tensor' export returns one tensor of the whole frame, so there is no slot for a separate label.","triggerScenarios":"`df.to_torch('tensor', label='y')`, `df.to_torch(label='target')` (default return_type is 'tensor'), or any call with label/features and return_type='tensor'.","commonSituations":"Writing a DataLoader pipeline and forgetting to switch the first argument to 'dataset'; refactoring from to_jax('dict', ...) to to_torch and keeping label but not the return_type; tutorial code adapted with label added but default return_type left in place.","solutions":["Use return_type='dataset' for DataLoader training: `df.to_torch('dataset', label='target')`","Or 'dict' for raw tensors: `df.to_torch('dict', label='target', features=['f1'])`","Or drop label/features and export the whole frame as one tensor: `df.to_torch()`"],"exampleFix":"# before\ntrain = df.to_torch(label='target')\n\n# after\ntrain = df.to_torch('dataset', label='target')\nloader = DataLoader(train, batch_size=64)","handlingStrategy":"validation","validationCode":"if (label is not None or features is not None) and return_type not in ('dataset', 'dict'):\n    raise ValueError('to_torch: label/features require return_type \"dataset\" or \"dict\"')\nout = df.to_torch(return_type, label=label, features=features)","typeGuard":null,"tryCatchPattern":"try:\n    out = df.to_torch(return_type, label=label, features=features)\nexcept ValueError as e:\n    if 'only apply when' in str(e):\n        out = df.to_torch('dataset', label=label, features=features)\n    else:\n        raise","preventionTips":["Default to to_torch('dataset', label=...) for DataLoader workflows","Remember the default return_type is 'tensor', which forbids label/features","Validate the (return_type, label, features) triple in shared export helpers"],"tags":["torch","export","argument-mismatch","ml"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}