The 102 Category Flower Dataset has photographs of 102 kinds of flowers. We take ten photographs of each kind, train on five of them and test on the other five.
ResNet-18 is a convolutional network with 18 layers, trained on the 1.2 million labelled images of ImageNet, in 1000 classes. Flowers are not among them. We download the trained network, cut off its last layer, and use the 512 numbers that the layer before it computes as the features of each image.
resnet = torchvision.models.resnet18(weights=weights)resnet.fc = torch.nn.Identity()resnet.eval()with torch.no_grad(): F_train = torch.cat([resnet(x) for x in X_train.split(64)]).numpy() F_test = torch.cat([resnet(x) for x in X_test.split(64)]).numpy()print(F_train.shape)
1
The architecture and the parameters fitted on ImageNet. prep above resizes and normalizes each image the way this network expects.
2
The last layer, a dense layer from 512 features to the 1000 ImageNet classes, is replaced by the identity, so the network returns the 512 features.
3
Evaluation mode, which matters for its batch normalization layers.
4
In batches of 64 images, to keep the memory small.
(510, 512)
On these features we fit a multinomial logistic regression, as in week 7.
from sklearn.linear_model import LogisticRegressionclf = LogisticRegression(max_iter=2000).fit(F_train, y_train)print(f"test accuracy with transferred features: {clf.score(F_test, y_test):.3f}")
test accuracy with transferred features: 0.769
With the same 510 training images the accuracy goes from about 0.2 to about 0.77. None of the 11 million parameters of ResNet-18 were fitted to the flowers. Only the \(102 \cdot 513\) parameters of the logistic regression were.