diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..5dd8d38eb71c1b0e08994211f53bdc3a2f8e8b29
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2019 Máté Kisantal
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
index 83e2bb8fc4249bf43f9524ebffb7896e583dd681..4d220bbfaccab93a2107a9e00d85c8947b60aca7 100644
--- a/README.md
+++ b/README.md
@@ -1,92 +1,52 @@
 # backboned-unet
+U-Nets for image segmentation with pre-trained backbones in PyTorch.
 
+## Why another U-Net implementation?
+I was looking for an U-Net PyTorch implementation that can use pre-trained
+torchvision models as backbones in the encoder path. There is a great
+[repo](https://github.com/qubvel/segmentation_models)
+for this in Keras, but I didn't find a good PyTorch implementation that works
+with multiple torchvision models. So I decided to create one.
 
+### WIP
 
-## Getting started
+So far VGG, ResNet and DenseNet backbones have been implemented.
 
-To make it easy for you to get started with GitLab, here's a list of recommended next steps.
+### Setup
 
-Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
+Installing package:
 
-## Add your files
+    git clone https://github.com/mkisantal/backboned-unet.git
+    cd backboned-unet
+    pip install .
 
-- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
-- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
+### Simple usage example
+The U-net model can be imported just like any other torchvision model. The user can specify
+a backbone architecture, choose upsampling operation (transposed convolution or bilinear upsampling
+followed by convolution), specify the number of filters in the different decoder stages, etc.
 
-```
-cd existing_repo
-git remote add origin https://lab.compute.dtu.dk/manli/backboned-unet.git
-git branch -M main
-git push -uf origin main
-```
+    from backboned_unet import Unet
+    net = Unet(backbone_name='densenet121', classes=21)
+    
+The module loads the backbone torchvision model, and builds a decoder on top of it using specified
+internal features of the backbone.
 
-## Integrate with your tools
 
-- [ ] [Set up project integrations](https://lab.compute.dtu.dk/manli/backboned-unet/-/settings/integrations)
+### Results on Pascal VOC
 
-## Collaborate with your team
+The figure below illustrates the training results for U-Nets with different ImageNet pretrained backbones.
 
-- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
-- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
-- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
-- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
-- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
+![pascal training](images/model_ious.png?raw=true "Pascal VOC training results")
 
-## Test and Deploy
+Setup:
 
-Use the built-in continuous integration in GitLab.
+    network = Unet(backbone_name=model_name, classes=21, decoder_filters=(512, 256, 128, 64, 32)
+    criterion = torch.nn.CrossEntropyLoss(ignore_index=255)
+    optimizer = torch.optim.Adam([{'params': network.get_pretrained_parameters(), 'lr':1e-5},
+                                  {'params': network.get_random_initialized_parameters()}], lr=1e-4)
+    
+Images were resized to 224x224. Batch size 32. No dataset augmentation. IoU is calculated with the background ignored.
 
-- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
-- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
-- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
-- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
-- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
+Example segmentation results:
 
-***
-
-# Editing this README
-
-When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
-
-## Suggestions for a good README
-Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
-
-## Name
-Choose a self-explaining name for your project.
-
-## Description
-Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
-
-## Badges
-On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
-
-## Visuals
-Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
-
-## Installation
-Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
-
-## Usage
-Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
-
-## Support
-Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
-
-## Roadmap
-If you have ideas for releases in the future, it is a good idea to list them in the README.
-
-## Contributing
-State if you are open to contributions and what your requirements are for accepting them.
-
-For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
-
-You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
-
-## Authors and acknowledgment
-Show your appreciation to those who have contributed to the project.
-
-## License
-For open source projects, say how it is licensed.
-
-## Project status
-If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
+![pascal results](images/examples.png?raw=true "Example segmentations from Pascal")
diff --git a/backboned-unet b/backboned-unet
deleted file mode 160000
index 8e60ce62481c56eacf4a1441c376bb580da41bc5..0000000000000000000000000000000000000000
--- a/backboned-unet
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 8e60ce62481c56eacf4a1441c376bb580da41bc5
diff --git a/backboned_unet/__init__.py b/backboned_unet/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6bd9ec1a1caf1b209b9f1590d3c959cc3103b324
--- /dev/null
+++ b/backboned_unet/__init__.py
@@ -0,0 +1,2 @@
+from .unet import Unet
+from .utils import iou, soft_iou, dice_score, DiceLoss
\ No newline at end of file
diff --git a/backboned_unet/unet.py b/backboned_unet/unet.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e6ab2f67ae2d00e56f554ee3d37a1929ac0746b
--- /dev/null
+++ b/backboned_unet/unet.py
@@ -0,0 +1,252 @@
+import torch
+import torch.nn as nn
+from torchvision import models, datasets, transforms
+from torch.nn import functional as F
+
+
+def get_backbone(name, pretrained=True):
+
+    """ Loading backbone, defining names for skip-connections and encoder output. """
+
+    # TODO: More backbones
+
+    # loading backbone model
+    if name == 'resnet18':
+        backbone = models.resnet18(pretrained=pretrained)
+    elif name == 'resnet34':
+        backbone = models.resnet34(pretrained=pretrained)
+    elif name == 'resnet50':
+        backbone = models.resnet50(pretrained=pretrained)
+    elif name == 'resnet101':
+        backbone = models.resnet101(pretrained=pretrained)
+    elif name == 'resnet152':
+        backbone = models.resnet152(pretrained=pretrained)
+    elif name == 'vgg16':
+        backbone = models.vgg16_bn(pretrained=pretrained).features
+    elif name == 'vgg19':
+        backbone = models.vgg19_bn(pretrained=pretrained).features
+    # elif name == 'inception_v3':
+    #     backbone = models.inception_v3(pretrained=pretrained, aux_logits=False)
+    elif name == 'densenet121':
+        backbone = models.densenet121(pretrained=True).features
+    elif name == 'densenet161':
+        backbone = models.densenet161(pretrained=True).features
+    elif name == 'densenet169':
+        backbone = models.densenet169(pretrained=True).features
+    elif name == 'densenet201':
+        backbone = models.densenet201(pretrained=True).features
+    elif name == 'unet_encoder':
+        from unet_backbone import UnetEncoder
+        backbone = UnetEncoder(3)
+    else:
+        raise NotImplemented('{} backbone model is not implemented so far.'.format(name))
+
+    # specifying skip feature and output names
+    if name.startswith('resnet'):
+        feature_names = [None, 'relu', 'layer1', 'layer2', 'layer3']
+        backbone_output = 'layer4'
+    elif name == 'vgg16':
+        # TODO: consider using a 'bridge' for VGG models, there is just a MaxPool between last skip and backbone output
+        feature_names = ['5', '12', '22', '32', '42']
+        backbone_output = '43'
+    elif name == 'vgg19':
+        feature_names = ['5', '12', '25', '38', '51']
+        backbone_output = '52'
+    # elif name == 'inception_v3':
+    #     feature_names = [None, 'Mixed_5d', 'Mixed_6e']
+    #     backbone_output = 'Mixed_7c'
+    elif name.startswith('densenet'):
+        feature_names = [None, 'relu0', 'denseblock1', 'denseblock2', 'denseblock3']
+        backbone_output = 'denseblock4'
+    elif name == 'unet_encoder':
+        feature_names = ['module1', 'module2', 'module3', 'module4']
+        backbone_output = 'module5'
+    else:
+        raise NotImplemented('{} backbone model is not implemented so far.'.format(name))
+
+    return backbone, feature_names, backbone_output
+
+
+class UpsampleBlock(nn.Module):
+
+    # TODO: separate parametric and non-parametric classes?
+    # TODO: skip connection concatenated OR added
+
+    def __init__(self, ch_in, ch_out=None, skip_in=0, use_bn=True, parametric=False):
+        super(UpsampleBlock, self).__init__()
+
+        self.parametric = parametric
+        ch_out = ch_in/2 if ch_out is None else ch_out
+
+        # first convolution: either transposed conv, or conv following the skip connection
+        if parametric:
+            # versions: kernel=4 padding=1, kernel=2 padding=0
+            self.up = nn.ConvTranspose2d(in_channels=ch_in, out_channels=ch_out, kernel_size=(4, 4),
+                                         stride=2, padding=1, output_padding=0, bias=(not use_bn))
+            self.bn1 = nn.BatchNorm2d(ch_out) if use_bn else None
+        else:
+            self.up = None
+            ch_in = ch_in + skip_in
+            self.conv1 = nn.Conv2d(in_channels=ch_in, out_channels=ch_out, kernel_size=(3, 3),
+                                   stride=1, padding=1, bias=(not use_bn))
+            self.bn1 = nn.BatchNorm2d(ch_out) if use_bn else None
+
+        self.relu = nn.ReLU(inplace=True)
+
+        # second convolution
+        conv2_in = ch_out if not parametric else ch_out + skip_in
+        self.conv2 = nn.Conv2d(in_channels=conv2_in, out_channels=ch_out, kernel_size=(3, 3),
+                               stride=1, padding=1, bias=(not use_bn))
+        self.bn2 = nn.BatchNorm2d(ch_out) if use_bn else None
+
+    def forward(self, x, skip_connection=None):
+
+        x = self.up(x) if self.parametric else F.interpolate(x, size=None, scale_factor=2, mode='bilinear',
+                                                             align_corners=None)
+        if self.parametric:
+            x = self.bn1(x) if self.bn1 is not None else x
+            x = self.relu(x)
+
+        if skip_connection is not None:
+            x = torch.cat([x, skip_connection], dim=1)
+
+        if not self.parametric:
+            x = self.conv1(x)
+            x = self.bn1(x) if self.bn1 is not None else x
+            x = self.relu(x)
+        x = self.conv2(x)
+        x = self.bn2(x) if self.bn2 is not None else x
+        x = self.relu(x)
+
+        return x
+
+
+class Unet(nn.Module):
+
+    """ U-Net (https://arxiv.org/pdf/1505.04597.pdf) implementation with pre-trained torchvision backbones."""
+
+    def __init__(self,
+                 backbone_name='resnet50',
+                 pretrained=True,
+                 encoder_freeze=False,
+                 classes=21,
+                 decoder_filters=(256, 128, 64, 32, 16),
+                 parametric_upsampling=True,
+                 shortcut_features='default',
+                 decoder_use_batchnorm=True):
+        super(Unet, self).__init__()
+
+        self.backbone_name = backbone_name
+
+        self.backbone, self.shortcut_features, self.bb_out_name = get_backbone(backbone_name, pretrained=pretrained)
+        shortcut_chs, bb_out_chs = self.infer_skip_channels()
+        if shortcut_features != 'default':
+            self.shortcut_features = shortcut_features
+
+        # build decoder part
+        self.upsample_blocks = nn.ModuleList()
+        decoder_filters = decoder_filters[:len(self.shortcut_features)]  # avoiding having more blocks than skip connections
+        decoder_filters_in = [bb_out_chs] + list(decoder_filters[:-1])
+        num_blocks = len(self.shortcut_features)
+        for i, [filters_in, filters_out] in enumerate(zip(decoder_filters_in, decoder_filters)):
+            print('upsample_blocks[{}] in: {}   out: {}'.format(i, filters_in, filters_out))
+            self.upsample_blocks.append(UpsampleBlock(filters_in, filters_out,
+                                                      skip_in=shortcut_chs[num_blocks-i-1],
+                                                      parametric=parametric_upsampling,
+                                                      use_bn=decoder_use_batchnorm))
+
+        self.final_conv = nn.Conv2d(decoder_filters[-1], classes, kernel_size=(1, 1))
+
+        if encoder_freeze:
+            self.freeze_encoder()
+
+        self.replaced_conv1 = False  # for accommodating  inputs with different number of channels later
+
+    def freeze_encoder(self):
+
+        """ Freezing encoder parameters, the newly initialized decoder parameters are remaining trainable. """
+
+        for param in self.backbone.parameters():
+            param.requires_grad = False
+
+    def forward(self, *input):
+
+        """ Forward propagation in U-Net. """
+
+        x, features = self.forward_backbone(*input)
+
+        for skip_name, upsample_block in zip(self.shortcut_features[::-1], self.upsample_blocks):
+            skip_features = features[skip_name]
+            x = upsample_block(x, skip_features)
+
+        x = self.final_conv(x)
+        return x
+
+    def forward_backbone(self, x):
+
+        """ Forward propagation in backbone encoder network.  """
+
+        features = {None: None} if None in self.shortcut_features else dict()
+        for name, child in self.backbone.named_children():
+            x = child(x)
+            if name in self.shortcut_features:
+                features[name] = x
+            if name == self.bb_out_name:
+                break
+
+        return x, features
+
+    def infer_skip_channels(self):
+
+        """ Getting the number of channels at skip connections and at the output of the encoder. """
+
+        x = torch.zeros(1, 3, 224, 224)
+        has_fullres_features = self.backbone_name.startswith('vgg') or self.backbone_name == 'unet_encoder'
+        channels = [] if has_fullres_features else [0]  # only VGG has features at full resolution
+
+        # forward run in backbone to count channels (dirty solution but works for *any* Module)
+        for name, child in self.backbone.named_children():
+            x = child(x)
+            if name in self.shortcut_features:
+                channels.append(x.shape[1])
+            if name == self.bb_out_name:
+                out_channels = x.shape[1]
+                break
+        return channels, out_channels
+
+    def get_pretrained_parameters(self):
+        for name, param in self.backbone.named_parameters():
+            if not (self.replaced_conv1 and name == 'conv1.weight'):
+                yield param
+
+    def get_random_initialized_parameters(self):
+        pretrained_param_names = set()
+        for name, param in self.backbone.named_parameters():
+            if not (self.replaced_conv1 and name == 'conv1.weight'):
+                pretrained_param_names.add('backbone.{}'.format(name))
+
+        for name, param in self.named_parameters():
+            if name not in pretrained_param_names:
+                yield param
+
+
+if __name__ == "__main__":
+
+    # simple test run
+    net = Unet(backbone_name='resnet18')
+
+    criterion = nn.MSELoss()
+    optimizer = torch.optim.Adam(net.parameters())
+    print('Network initialized. Running a test batch.')
+    for _ in range(1):
+        with torch.set_grad_enabled(True):
+            batch = torch.empty(1, 3, 224, 224).normal_()
+            targets = torch.empty(1, 21, 224, 224).normal_()
+
+            out = net(batch)
+            loss = criterion(out, targets)
+            loss.backward()
+            optimizer.step()
+        print(out.shape)
+
+    print('fasza.')
diff --git a/backboned_unet/unet_backbone.py b/backboned_unet/unet_backbone.py
new file mode 100644
index 0000000000000000000000000000000000000000..c65faa8cf962b8e3365bea83ef3d3baabad9bacd
--- /dev/null
+++ b/backboned_unet/unet_backbone.py
@@ -0,0 +1,53 @@
+from torch import nn
+
+
+class UnetDownModule(nn.Module):
+
+    """ U-Net downsampling block. """
+
+    def __init__(self, in_channels, out_channels, downsample=True):
+        super(UnetDownModule, self).__init__()
+
+        # layers: optional downsampling, 2 x (conv + bn + relu)
+        self.maxpool = nn.MaxPool2d((2,2)) if downsample else None
+        self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
+                               kernel_size=3, padding=1)
+        self.bn1 = nn.BatchNorm2d(out_channels)
+        self.conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels,
+                               kernel_size=3, padding=1)
+        self.bn2 = nn.BatchNorm2d(out_channels)
+        self.relu = nn.ReLU(inplace=True)
+
+    def forward(self, x):
+        if self.maxpool is not None:
+            x = self.maxpool(x)
+        x = self.conv1(x)
+        x = self.bn1(x)
+        x = self.relu(x)
+
+        x = self.conv2(x)
+        x = self.bn2(x)
+        x = self.relu(x)
+
+        return x
+
+
+class UnetEncoder(nn.Module):
+
+    """ U-Net encoder. https://arxiv.org/pdf/1505.04597.pdf """
+
+    def __init__(self, num_channels):
+        super(UnetEncoder, self,).__init__()
+        self.module1 = UnetDownModule(num_channels, 64, downsample=False)
+        self.module2 = UnetDownModule(64, 128)
+        self.module3 = UnetDownModule(128, 256)
+        self.module4 = UnetDownModule(256, 512)
+        self.module5 = UnetDownModule(512, 1024)
+
+    def forward(self, x):
+        x = self.module1(x)
+        x = self.module2(x)
+        x = self.module3(x)
+        x = self.module4(x)
+        x = self.module5(x)
+        return x
diff --git a/backboned_unet/utils.py b/backboned_unet/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1601e61b0dec77a282bc826e68a49ba940d03c5
--- /dev/null
+++ b/backboned_unet/utils.py
@@ -0,0 +1,161 @@
+import torch
+
+
+def iou(predictions, labels, threshold=None, average=True, device=torch.device("cpu"), classes=21,
+        ignore_index=255, ignore_background=True):
+
+    """ Calculating Intersection over Union score for semantic segmentation. """
+
+    gt = labels.long().unsqueeze(1).to(device)
+
+    # getting mask for valid pixels, then converting "void class" to background
+    valid = gt != ignore_index
+    gt[gt == ignore_index] = 0
+
+    # converting to onehot image whith class channels
+    onehot_gt_tensor = torch.LongTensor(gt.shape[0], classes, gt.shape[-2], gt.shape[-1]).zero_().to(device)
+    onehot_gt_tensor.scatter_(1, gt, 1)  # write ones along "channel" dimension
+    classes_in_image = onehot_gt_tensor.sum([2, 3]) > 0
+
+    # check if it's only background
+    if ignore_background:
+        only_bg = (classes_in_image[:, 1:].sum(dim=1) == 0).sum() > 0
+        if only_bg:
+            raise ValueError('Image only contains background. Since background is set to ' +
+                             'ignored, IoU is invalid.')
+
+    if threshold is None:
+        # taking the argmax along channels
+        pred = torch.argmax(predictions, dim=1).unsqueeze(1)
+        pred_tensor = torch.LongTensor(pred.shape[0], classes, pred.shape[-2], pred.shape[-1]).zero_().to(device)
+        pred_tensor.scatter_(1, pred, 1)
+    else:
+        # counting predictions above threshold
+        pred_tensor = (predictions > threshold).long()
+
+    onehot_gt_tensor *= valid.long()
+    pred_tensor *= valid.long().to(device)
+
+    intersection = (pred_tensor & onehot_gt_tensor).sum([2, 3]).float()
+    union = (pred_tensor | onehot_gt_tensor).sum([2, 3]).float()
+
+    iou = intersection / (union + 1e-12)
+
+    start_id = 1 if ignore_background else 0
+
+    if average:
+        average_iou = iou[:, start_id:].sum(dim=1) /\
+                      (classes_in_image[:, start_id:].sum(dim=1)).float()  # discard background IoU
+        iou = average_iou
+
+    return iou.cpu().numpy()
+
+
+def soft_iou(pred_tensor, labels, average=True, device=torch.device("cpu"), classes=21,
+             ignore_index=255, ignore_background=True):
+
+    """ Soft IoU score for semantic segmentation, based on 10.1109/ICCV.2017.372 """
+
+    gt = labels.long().unsqueeze(1).to(device)
+
+    # getting mask for valid pixels, then converting "void class" to background
+    valid = gt != ignore_index
+    gt[gt == ignore_index] = 0
+    valid = valid.float().to(device)
+
+    # converting to onehot image with class channels
+    onehot_gt_tensor = torch.LongTensor(gt.shape[0], classes, gt.shape[-2], gt.shape[-1]).zero_().to(device)
+    onehot_gt_tensor.scatter_(1, gt, 1)  # write ones along "channel" dimension
+    classes_in_image = onehot_gt_tensor.sum([2, 3]) > 0
+    onehot_gt_tensor = onehot_gt_tensor.float().to(device)
+
+    # check if it's only background
+    if ignore_background:
+        only_bg = (classes_in_image[:, 1:].sum(dim=1) == 0).sum() > 0
+        if only_bg:
+            raise ValueError('Image only contains background. Since background is set to ' +
+                             'ignored, IoU is invalid.')
+
+    onehot_gt_tensor *= valid
+    pred_tensor *= valid
+
+    # intersection = torch.max(torch.tensor(0).float(), torch.min(pred_tensor, onehot_gt_tensor).sum(dim=[2, 3]))
+    # union = torch.min(torch.tensor(1).float(), torch.max(pred_tensor, onehot_gt_tensor).sum(dim=[2, 3]))
+
+    intersection = (pred_tensor * onehot_gt_tensor).sum(dim=[2, 3])
+    union = (pred_tensor + onehot_gt_tensor).sum(dim=[2, 3]) - intersection
+
+    iou = intersection / (union + 1e-12)
+
+    start_id = 1 if ignore_background else 0
+
+    if average:
+        average_iou = iou[:, start_id:].sum(dim=1) /\
+                      (classes_in_image[:, start_id:].sum(dim=1)).float()  # discard background IoU
+        iou = average_iou
+
+    return iou.cpu().numpy()
+
+
+def dice_score(input, target, classes, ignore_index=-100):
+
+    """ Functional dice score calculation. """
+
+    target = target.long().unsqueeze(1)
+
+    # getting mask for valid pixels, then converting "void class" to background
+    valid = target != ignore_index
+    target[target == ignore_index] = 0
+    valid = valid.float()
+
+    # converting to onehot image with class channels
+    onehot_target = torch.LongTensor(target.shape[0], classes, target.shape[-2], target.shape[-1]).zero_().cuda()
+    onehot_target.scatter_(1, target, 1)  # write ones along "channel" dimension
+    # classes_in_image = onehot_gt_tensor.sum([2, 3]) > 0
+    onehot_target = onehot_target.float()
+
+    # keeping the valid pixels only
+    onehot_target = onehot_target * valid
+    input = input * valid
+
+    dice = 2 * (input * onehot_target).sum([2, 3]) / ((input**2).sum([2, 3]) + (onehot_target**2).sum([2, 3]))
+    return dice.mean(dim=1)
+
+
+class DiceLoss(torch.nn.Module):
+
+    """ Dice score implemented as a nn.Module. """
+
+    def __init__(self, classes, loss_mode='negative_log', ignore_index=255, activation=None):
+        super(DiceLoss, self).__init__()
+        self.classes = classes
+        self.ignore_index = ignore_index
+        self.loss_mode = loss_mode
+        self.activation = activation
+
+    def forward(self, input, target):
+        if self.activation is not None:
+            input = self.activation(input)
+        score = dice_score(input, target, self.classes, self.ignore_index)
+        if self.loss_mode == 'negative_log':
+            eps = 1e-12
+            return (-(score+eps).log()).mean()
+        elif self.loss_mode == 'one_minus':
+            return (1 - score).mean()
+        else:
+            raise ValueError('Loss mode unknown. Please use \'negative_log\' or \'one_minus\'!')
+
+
+if __name__ == "__main__":
+
+    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
+    predictions = torch.softmax(torch.empty(7, 21, 224, 224).normal_(), dim=1)
+    conv = torch.nn.Conv2d(21, 21, 1, 1, 0)
+    labels = (torch.empty(7, 224, 224).normal_(10, 10) % 21)
+    criterion = DiceLoss(21, activation=torch.nn.Softmax(dim=1))
+    loss = criterion(conv(predictions), labels)
+
+    loss.backward()
+    print(loss)
+
+    print('done.')
diff --git a/images/examples.png b/images/examples.png
new file mode 100644
index 0000000000000000000000000000000000000000..7741e830331458b66775f11353a9156c328199a1
Binary files /dev/null and b/images/examples.png differ
diff --git a/images/model_ious.png b/images/model_ious.png
new file mode 100644
index 0000000000000000000000000000000000000000..6e90fcb123b5459a09ac42cc44a1e43f2ffb711c
Binary files /dev/null and b/images/model_ious.png differ
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4af60c70f39dc0329ba448f2b78d43234b41a3b
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,16 @@
+from setuptools import setup
+
+setup(name='backboned_unet',
+      version='0.0.1',
+      description='U-Net built with TorchVision backbones.',
+      url='https://github.com/mkisantal/backboned-unet',
+      keywords='machine deep learning neural networks pytorch torchvision segmentation unet',
+      author='mate Kisantal',
+      author_email='kisantal.mate@gmail.com',
+      license='MIT',
+      packages=['backboned_unet'],
+      install_requires=[
+          'torch',
+          'torchvision'
+      ],
+      zip_safe=False)