Implementation:LaurentMazare Tch rs Resnet18 No Final Layer
| Knowledge Sources | |
|---|---|
| Domains | Computer_Vision, Transfer_Learning |
| Last Updated | 2026-02-08 14:00 GMT |
Overview
Concrete tool for instantiating a ResNet-18 model without the final classification layer, for use as a frozen feature extractor, provided by the tch vision module.
Description
resnet::resnet18_no_final_layer creates a ResNet-18 model that outputs a 512-dimensional feature vector instead of class logits. It passes None for num_classes to the internal resnet constructor, which omits the final fc layer and instead applies adaptive_avg_pool2d followed by flat_view. Pretrained weights can still be loaded with VarStore::load — the missing fc weights are silently skipped.
Usage
Use for transfer learning when you need a frozen feature extractor. After loading pretrained weights, wrap feature computation in tch::no_grad for efficiency.
Code Reference
Source Location
- Repository: tch-rs
- File: src/vision/resnet.rs
- Lines: 82-84
Signature
pub fn resnet18_no_final_layer(p: &nn::Path) -> FuncT<'static>
Import
use tch::vision::resnet;
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| p | &nn::Path | Yes | VarStore path for parameter registration |
Outputs
| Name | Type | Description |
|---|---|---|
| FuncT<'static> | impl ModuleT | ResNet-18 backbone outputting [batch, 512] feature vectors |
Usage Examples
use tch::{nn, nn::ModuleT, vision::resnet, Device};
let mut vs = nn::VarStore::new(Device::Cpu);
let backbone = resnet::resnet18_no_final_layer(&vs.root());
vs.load("resnet18.ot")?; // fc weights ignored
// Pre-compute features
let features = tch::no_grad(|| {
dataset.train_images.apply_t(&backbone, false)
});
println!("{:?}", features.size()); // [N, 512]