def classify(self, data_source: DataSource) -> [Classification]: ''' Classifies the image against the model, and closes the datasource. The datasource may not be reclassified after this operation. All returned classifications have an accuracy greater than zero. ''' if self.use_cuda: data_source.batch_tensor.to('cuda') with torch.no_grad(): result = self.model(data_source.batch_tensor) data_source.close() normalised_result = F.softmax(result[0], dim=0) return self._convert_tensor_to_classification(normalised_result)
def test_sanity_recognition_with_datasource(): ds = DataSource(golden_retriever_url) assert net.classify(ds)[0].label.name == 'golden retriever'
def classify_url(self, url: str) -> [Classification]: ''' Classifies the image stored in the URL against the model. Utility method delagating to classify with a built datasource. ''' return self.classify(DataSource(url))
def test_invalid_url(): url = "httpz://bla.xy wr" with pytest.raises(ValueError) as value_error: DataSource(url) assert str(value_error.value).startswith( f"Failed to read URL of data source.\nURL in question: {url}")
def test_batch_shape(): ds = DataSource(valid_image_url) assert ds.batch_tensor.shape == ds.tensor.unsqueeze(0).shape ds.close()
def test_tensor_is_not_none(): ds = DataSource(valid_image_url) assert ds.tensor is not None ds.close()
def test_non_image_url(): url = "http://google.com" with pytest.raises(ValueError) as value_error: DataSource(url) assert str(value_error.value).startswith( f"Failed to read data into Pillow image. URL in question: {url}")
from classification.datasource import DataSource from classification.net import Network from classification.word_hierarchy import Hierarchy data = [ # 3 retrievers { 'description': "golden retriever puppy", 'ds': DataSource( "https://i.pinimg.com/originals/99/f9/ed/99f9ede31328c8484e9e252d08811535.jpg" ) }, { 'description': "golden retriever adult", 'ds': DataSource( "https://www.prestigeanimalhospital.com/sites/default/files/styles/large/adaptive-image/public/golden-retriever-dog-breed-info.jpg?itok=scGfz-nI" ) }, { 'description': "golden retriever head", 'ds': DataSource( "https://previews.123rf.com/images/osborn/osborn1105/osborn110500001/9481470-golden-retriever-head-shoulders.jpg" ) },