{"record":{"id":"afbe940d35a9af08","repo":"ultralytics/ultralytics","slug":"nc-not-specified-must-specify-nc-in-model-yaml-or","errorCode":null,"errorMessage":"nc not specified. Must specify nc in model.yaml or function arguments.","messagePattern":"nc not specified\\. Must specify nc in model\\.yaml or function arguments\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"ultralytics/nn/tasks.py","lineNumber":851,"sourceCode":"\n    def _from_yaml(self, cfg, ch, nc, verbose):\n        \"\"\"Set Ultralytics YOLO model configurations and define the model architecture.\n\n        Args:\n            cfg (str | dict): Model configuration file path or dictionary.\n            ch (int): Number of input channels.\n            nc (int, optional): Number of classes.\n            verbose (bool): Whether to display model information.\n        \"\"\"\n        self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg)  # cfg dict\n\n        # Define model\n        ch = self.yaml[\"channels\"] = self.yaml.get(\"channels\", ch)  # input channels\n        if nc and nc != self.yaml[\"nc\"]:\n            LOGGER.info(f\"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}\")\n            self.yaml[\"nc\"] = nc  # override YAML value\n        elif not nc and not self.yaml.get(\"nc\", None):\n            raise ValueError(\"nc not specified. Must specify nc in model.yaml or function arguments.\")\n        self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose)  # model, savelist\n        self.stride = torch.Tensor([1])  # no stride constraints\n        self.names = {i: f\"{i}\" for i in range(self.yaml[\"nc\"])}  # default names dict\n        self.info()\n\n    @staticmethod\n    def reshape_outputs(model, nc):\n        \"\"\"Update a TorchVision classification model to class count 'nc' if required.\n\n        Args:\n            model (torch.nn.Module): Model to update.\n            nc (int): New number of classes.\n        \"\"\"\n        name, m = list((model.model if hasattr(model, \"model\") else model).named_children())[-1]  # last module\n        if isinstance(m, Classify):  # YOLO Classify() head\n            if m.linear.out_features != nc:\n                m.linear = torch.nn.Linear(m.linear.in_features, nc)\n        elif isinstance(m, torch.nn.Linear):  # ResNet, EfficientNet","sourceCodeStart":833,"sourceCodeEnd":869,"githubUrl":"https://github.com/ultralytics/ultralytics/blob/0449ea011cfd6c9a0d50a0bf1043aca5190cd476/ultralytics/nn/tasks.py#L833-L869","documentation":"When building a ClassificationModel from YAML, the constructor requires a class count: either nc explicitly passed (e.g. YOLO('yolov8n-cls.yaml', nc=10)) or nc present in the YAML. If neither is set, there is no way to size the final classification head, so ValueError is raised before parse_model runs. Note the printed error message is generic even though this constructor is the classification path (stride=1, numeric default names, reshape_outputs helper below it).","triggerScenarios":"Instantiating a classification model from a YAML that omits nc and not passing nc to the constructor or YOLO() call; creating ClassificationModel('my-cls.yaml') with only channels defined; custom YAML copied from another model with the nc line deleted.","commonSituations":"Authoring a new classification YAML and forgetting the nc: key; trimming a template YAML down for a minimal test config; porting a config from another framework where class count is inferred from data.","solutions":["Add nc: <N> to the model YAML (top level, next to channels/scales)","Or pass nc explicitly: YOLO('my-cls.yaml', nc=10)","Or start from an official template like yolov8n-cls.yaml which defines nc, and edit from there"],"exampleFix":"# before\nmodel = YOLO('my-cls.yaml')  # YAML has no nc\n\n# after\nmodel = YOLO('my-cls.yaml', nc=10)\n# or in my-cls.yaml add: nc: 10","handlingStrategy":"validation","validationCode":"from ultralytics.utils import yaml_model_load\ncfg = yaml_model_load('my-cls.yaml')\nnc = cfg.get('nc') or passed_nc\nif not nc:\n    raise ValueError('set nc in yaml or pass nc=')","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Template every new model YAML from an official one that already defines nc","Pass nc explicitly when constructing from YAML for a dataset with a known class count","Validate yaml keys (nc, channels) in config CI before model builds"],"tags":["config","yaml","classification","nc","model-build"],"backgroundTag":null,"analyzedSha":"0449ea011cfd6c9a0d50a0bf1043aca5190cd476","analyzedAt":"2026-08-15T02:34:13.413Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}