in web_tool/ModelSessionPyTorchExample.py [0:0]
def run_model_on_tile(self, tile, batch_size=32):
height = tile.shape[0]
width = tile.shape[1]
output = np.zeros((height, width, self.output_channels), dtype=np.float32)
output_features = np.zeros((height, width, self.output_features), dtype=np.float32)
counts = np.zeros((height, width), dtype=np.float32) + 0.000000001
kernel = np.ones((self.input_size, self.input_size), dtype=np.float32) * 0.1
kernel[10:-10, 10:-10] = 1
kernel[self.down_weight_padding:self.down_weight_padding+self.stride_y,
self.down_weight_padding:self.down_weight_padding+self.stride_x] = 5
batch = []
batch_indices = []
batch_count = 0
for y_index in (list(range(0, height - self.input_size, self.stride_y)) + [height - self.input_size,]):
for x_index in (list(range(0, width - self.input_size, self.stride_x)) + [width - self.input_size,]):
naip_im = tile[y_index:y_index+self.input_size, x_index:x_index+self.input_size, :]
batch.append(naip_im)
batch_indices.append((y_index, x_index))
batch_count+=1
batch = np.array(batch)
model_output = []
model_feature_output = []
for i in range(0, len(batch), batch_size):
t_batch = batch[i:i+batch_size]
t_batch = np.rollaxis(t_batch, 3, 1)
t_batch = torch.from_numpy(t_batch).to(self.device)
with torch.no_grad():
predictions, features = self.model.forward_features(t_batch)
predictions = F.softmax(predictions)
predictions = predictions.cpu().numpy()
features = features.cpu().numpy()
predictions = np.rollaxis(predictions, 1, 4)
features = np.rollaxis(features, 1, 4)
model_output.append(predictions)
model_feature_output.append(features)
model_output = np.concatenate(model_output, axis=0)
model_feature_output = np.concatenate(model_feature_output, axis=0)
for i, (y, x) in enumerate(batch_indices):
output[y:y+self.input_size, x:x+self.input_size] += model_output[i] * kernel[..., np.newaxis]
output_features[y:y+self.input_size, x:x+self.input_size] += model_feature_output[i] * kernel[..., np.newaxis]
counts[y:y+self.input_size, x:x+self.input_size] += kernel
output = output / counts[..., np.newaxis]
output_features = output_features / counts[..., np.newaxis]
return output, output_features