PyTorch Implementation of Fully Convolutional Networks. (Training code to reproduce the original result is available.)

Overview

pytorch-fcn

PyPI Version Python Versions GitHub Actions

PyTorch implementation of Fully Convolutional Networks.

Requirements

Installation

git clone https://github.com/wkentaro/pytorch-fcn.git
cd pytorch-fcn
pip install .

# or

pip install torchfcn

Training

See VOC example.

Accuracy

At 10fdec9.

Model Implementation epoch iteration Mean IU Pretrained Model
FCN32s Original - - 63.63 Download
FCN32s Ours 11 96000 62.84
FCN16s Original - - 65.01 Download
FCN16s Ours 11 96000 64.91
FCN8s Original - - 65.51 Download
FCN8s Ours 7 60000 65.49
FCN8sAtOnce Original - - 65.40
FCN8sAtOnce Ours 11 96000 64.74

Visualization of validation result of FCN8s.

Cite This Project

If you use this project in your research or wish to refer to the baseline results published in the README, please use the following BibTeX entry.

@misc{pytorch-fcn2017,
  author =       {Ketaro Wada},
  title =        {{pytorch-fcn: PyTorch Implementation of Fully Convolutional Networks}},
  howpublished = {\url{https://github.com/wkentaro/pytorch-fcn}},
  year =         {2017}
}
Comments
  • resume error

    resume error

    hi, when i using resume to load parameters, it is crash saying ''unexpected key "module.features.0.weight" in state_dict''. I don't know what wrong with this, Thanks a lot!

    bug 
    opened by apchenstu 10
  • out of memory

    out of memory

    Hi,

    I want to test on the example cases, so I just run python example/voc/train_fcn8s.py -g 1 on a DGX station, with Tesla V100 16GB memory. After loading the model, it immediately reports out of memory in the first forward pass. Has anyone encountered this situation?

    environment: Pytorch: v0.4.1 CUDA: 9.0 cuDNN: 7.1.4

    Kaicheng

    question 
    opened by kcyu2014 9
  • Upsampling the output from self.upscore

    Upsampling the output from self.upscore

    Hello, I am new to this community and I have doubt regarding the fcn32.py. It's getting hard for me to understand that the output of self.upscore is [batch_size,21,64,64], then how it doesn't generate any error while calculating the loss with the ground-truth. According to me, the output should be [batch_size,21,64,64] and then it should be rescaled to size [batch_size,21,224,224] If your input image is of 224x224x3 size. Am I right over here ? How is this upsampling taking place ? how does our self.upscore output size matches with ground-truth size ?

    help wanted question 
    opened by keyurparalkar 8
  • Incorrect result when testing on a single image

    Incorrect result when testing on a single image

    The image is correctly segmented when I run FCN in caffe. I recently decided to switch to pytorch, and installed pytorch FCN. Here's the self-contained code:

    import torch
    import sys, os, path
    # this sets the same order as in nvidia-smi
    os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
    os.environ['CUDA_VISIBLE_DEVICES'] = '1'
    import numpy as np
    import skimage.data
    from PIL import Image
    import matplotlib.pyplot as plt
    import torch
    from torch import unsqueeze
    from torch.autograd import Variable
    from torch.utils.data import Dataset, DataLoader, TensorDataset
    from torch.utils.data.dataset import Subset
    from torchvision.datasets import ImageFolder
    from torchvision.transforms import Compose, RandomResizedCrop, RandomVerticalFlip, RandomHorizontalFlip
    from torchvision.transforms import ColorJitter, ToTensor, Normalize, ToPILImage, Resize
    from torchvision.utils import save_image
    # torch for FCN
    import torchfcn
    ##########################################
    #
    # Compose: combine a number of image transforms
    #
    ########################################## 
    
    
    img = "000000559099.png"
    device = "cuda"
    
    def preprocess (img):
        im = Image.open(img)
        norm = Normalize(mean = [0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225])
        transf = Compose ([Resize((300,300)), ToTensor(), norm])
        im = transf(im)  
        im = im.unsqueeze(0) 
        return im
    
    im = preprocess(img)
    
    print 'img', im.shape
    print torch.cuda.get_device_name(0)
    print torch.cuda.get_device_capability(0)
    # set to Tesla K40m
    torch.cuda.device(1)
    print 'CURRENT',  torch.cuda.current_device()
    model = torchfcn.models.FCN8s(n_class=21)
    model = model.cuda()
    im = im.cuda()
    im = Variable(im, requires_grad = False)
    weights = torch.load('/home/ICTDOMAIN/453615/data/models/pytorch/fcn8s_from_caffe.pth')
    model.load_state_dict(weights)
    print (model)
    score = model(im)	
    output= score.data.cpu().numpy()
    print output.shape
    plt.imshow(output[0].argmax(0))
    plt.show()
    

    Every pixel is classified as background. What is wrong with the code?

    question 
    opened by AlexTS1980 7
  • Error when run command

    Error when run command"pip install torchfcn"

    when i run the command: pip install torchfcn i got the error like this. I have tried re-install torch, but the bug is still here.

    Log: Installing collected packages: torchfcn Running setup.py install for torchfcn ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-install-EVS88p/torchfcn/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-record-W87s66/install-record.txt --single-version-externally-managed --compile: running install

     error: can't copy 'torchfcn/ext/fcn.berkeleyvision.org': doesn't exist or not a regular file
        
        ----------------------------------------
    Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-EVS88p/torchfcn/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-W87s66/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-EVS88p/torchfcn/
    chao@user-Server:~/chao/action/segmentation/pytorch-fcn$ sudo pip uninstall torchfcn
    
    question 
    opened by CLAPoo 7
  • question about learning_curve.py

    question about learning_curve.py

    Hi, thank you for sharing the code. I trained FCN32s on VOC12 and got the correct results when using view_log. However, when I tried to draw the learning curves, my log couldn't work with the code. After rolling_mean , all the data in df_train became NaN. Is there something wrong with my log? There are some pics about this problem. step4 step5 Do you know how to fix it? Thank you very much. @wkentaro

    bug 
    opened by haomengchao 7
  • Hi,I have a problem?

    Hi,I have a problem?

    When I test the trained model use the test data or the train data ,the output is only zero.Anyone can help me to solve this?Thanks! the output like this: [[0 0 0 ..., 0 0 0] [0 0 0 ..., 0 0 0] [0 0 0 ..., 0 0 0] ..., [0 0 0 ..., 0 0 0] [0 0 0 ..., 0 0 0] [0 0 0 ..., 0 0 0]]

    question 
    opened by BCWang93 6
  • view_log error:can't multiply sequence by non-int of type 'float'

    view_log error:can't multiply sequence by non-int of type 'float'

    When I follow the voc examples, I got problems of visualizing the logs in command ./view_log logs/XXX/log.csv with error

    can't multiply sequence by non-int of type 'float'

    bug 
    opened by WangLanxiao 6
  • A little bug in trainer.py

    A little bug in trainer.py

    Hello, wkentaro. Do you find that the training loss will suddenly become larger when a new epoch starts? I've noticed that and think it is because of the incorrect use of the training and evaluating mode of the model. In train_epoch(), line 171, when you finish validation, I think you should change the model back into training mode.

    bug 
    opened by WeiQijie 6
  • About VGG16 pretrained model

    About VGG16 pretrained model

    Hi @wkentaro , I see that you use the vgg16 pretrained model from caffe. I wonder that why you do not use a pretrained one provided by torchvision. Is the pretrained one from caffe better?

    Thanks.

    question 
    opened by zijundeng 6
  • Inconsistent Tensor Size

    Inconsistent Tensor Size

    When I implement the VOC2012 Dataset based your code, it occurs an error "incosistent tensor size". The code about dataset is same with yours. But I add some test code as below:

    if __name__ == '__main__':
        dst = VOCDataSet("./data", is_transform=True)
        trainloader = data.DataLoader(dst, batch_size=4)
        for i, data in enumerate(trainloader):
            imgs, labels = data
            print(imgs[0].type())
    

    Did you encounter this problem?

    question 
    opened by ycszen 6
  • Gradient explosion occurs after modifying the weight initialization method

    Gradient explosion occurs after modifying the weight initialization method

    I wanted to change the initialization method of the convolution from 0 to a positive-terrestrial distribution, but this led to a gradient explosion after a few iters.Why does this happen?

    opened by eadstry 0
  • 这是怎么处理的?

    这是怎么处理的?

    Traceback (most recent call last): File "demo.py", line 59, in demo(args) File "demo.py", line 45, in demo model = get_model(args.model, local_rank=args.local_rank, pretrained=True, root=args.save_folder).to(device) File "E:\Python_Projects\awesome-semantic-segmentation-pytorch-master\core\models\model_zoo.py", line 83, in get_model net = _modelsname File "E:\Python_Projects\awesome-semantic-segmentation-pytorch-master\core\models\fcn.py", line 219, in get_fcn32s_vgg16_voc return get_fcn32s('pascal_voc', 'vgg16', **kwargs) File "E:\Python_Projects\awesome-semantic-segmentation-pytorch-master\core\models\fcn.py", line 172, in get_fcn32s model.load_state_dict(torch.load("E:\fcn32s_vgg16_pascal_voc.pth",map_location="cpu")) File "D:\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 1483, in load_state_dict self.class.name, "\n\t".join(error_msgs))) RuntimeError: Error(s) in loading state_dict for FCN32s: Missing key(s) in state_dict: "pretrained.0.weight", "pretrained.0.bias", "pretrained.2.weight", "pretrained.2.bias", "pretrained.5.weight", "pretrained.5.bias", "pretrained.7.weight", "pretrained.7.bias", "pretrained.10.weight", "pretrained.10.bias", "pretrained.12.weight", "pretrained.12.bias", "pretrained.14.weight", "pretrained.14.bias", "pretrained.17.weight", "pretrained.17.bias", "pretrained.19.weight", "pretrained.19.bias", "pretrained.21.weight", "pretrained.21.bias", "pretrained.24.weight", "pretrained.24.bias", "pretrained.26.weight", "pretrained.26.bias", "pretrained.28.weight", "pretrained.28.bias", "head.block.0.weight", "head.block.1.weight", "head.block.1.bias", "head.block.1.running_mean", "head.block.1.running_var", "head.block.4.weight", "head.block.4.bias". Unexpected key(s) in state_dict: "features.0.weight", "features.0.bias", "features.2.weight", "features.2.bias", "features.5.weight", "features.5.bias", "features.7.weight", "features.7.bias", "features.10.weight", "features.10.bias", "features.12.weight", "features.12.bias", "features.14.weight", "features.14.bias", "features.17.weight", "features.17.bias", "features.19.weight", "features.19.bias", "features.21.weight", "features.21.bias", "features.24.weight", "features.24.bias", "features.26.weight", "features.26.bias", "features.28.weight", "features.28.bias", "classifier.0.weight", "classifier.0.bias", "classifier.3.weight", "classifier.3.bias", "classifier.6.weight", "classifier.6.bias".

    opened by Shajiu 0
  • Why the padding of first conv layer in FCN32s is 100?

    Why the padding of first conv layer in FCN32s is 100?

    I wonder why the padding of first conv layer in FCN32s is 100? FCN32s( (conv1_1): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(100, 100)) I am a newcomer in ML.Can you give me some answer? Thank you for advance

    opened by msy1412 3
  • requests.exceptions.ConnectionError

    requests.exceptions.ConnectionError

    When I ran ./train_fcn32s.py -g 0,I got this error Traceback (most recent call last): File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/urllib3/connection.py", line 160, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/urllib3/util/connection.py", line 84, in create_connection raise err File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/urllib3/util/connection.py", line 74, in create_connection sock.connect(sa) OSError: [Errno 101] Network is unreachable

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last): File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/urllib3/connectionpool.py", line 677, in urlopen chunked=chunked, File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/urllib3/connectionpool.py", line 392, in _make_request conn.request(method, url, **httplib_request_kw) File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/http/client.py", line 1262, in request self._send_request(method, url, body, headers, encode_chunked) File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/http/client.py", line 1308, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/http/client.py", line 1257, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/http/client.py", line 1036, in _send_output self.send(msg) File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/http/client.py", line 974, in send self.connect() File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/urllib3/connection.py", line 187, in connect conn = self._new_conn() File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/urllib3/connection.py", line 172, in _new_conn self, "Failed to establish a new connection: %s" % e urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7f1ef9d08588>: Failed to establish a new connection: [Errno 101] Network is unreachable

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last): File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/requests/adapters.py", line 449, in send timeout=timeout File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/urllib3/connectionpool.py", line 725, in urlopen method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2] File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/urllib3/util/retry.py", line 439, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='drive.google.com', port=80): Max retries exceeded with url: /uc?id=0B9P1L--7Wd2vLTJZMXpIRkVVRFk (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1ef9d08588>: Failed to establish a new connection: [Errno 101] Network is unreachable',))

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last): File "./train_fcn32s.py", line 151, in main() File "./train_fcn32s.py", line 116, in main vgg16 = torchfcn.models.VGG16(pretrained=True) File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/torchfcn/models/vgg.py", line 13, in VGG16 model_file = _get_vgg16_pretrained_model() File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/torchfcn/models/vgg.py", line 23, in _get_vgg16_pretrained_model md5='aa75b158f4181e7f6230029eb96c1b13', File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/fcn/data.py", line 32, in cached_download gdown.download(url, path, quiet=quiet) File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/gdown/download.py", line 110, in download res = sess.get(url, stream=True) File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/requests/sessions.py", line 543, in get return self.request('GET', url, **kwargs) File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/requests/sessions.py", line 530, in request resp = self.send(prep, **send_kwargs) File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/requests/sessions.py", line 643, in send r = adapter.send(request, **kwargs) File "/home/jbwen/anaconda3/envs/py36/lib/python3.6/site-packages/requests/adapters.py", line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='drive.google.com', port=80): Max retries exceeded with url: /uc?id=0B9P1L--7Wd2vLTJZMXpIRkVVRFk (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1ef9d08588>: Failed to establish a new connection: [Errno 101] Network is unreachable',))

    opened by Wenenen 5
Owner
Kentaro Wada
I'm a final-year PhD student at Imperial College London working on computer vision and robotics.
Kentaro Wada
C++ Implementation of PyTorch Tutorials for Everyone

C++ Implementation of PyTorch Tutorials for Everyone OS (Compiler)\LibTorch 1.9.0 macOS (clang 10.0, 11.0, 12.0) Linux (gcc 8, 9, 10, 11) Windows (msv

Omkar Prabhu 1.5k Jan 4, 2023
PyTorch tutorials.

PyTorch Tutorials All the tutorials are now presented as sphinx style documentation at: https://pytorch.org/tutorials Contributing We use sphinx-galle

null 6.6k Jan 2, 2023
A set of examples around pytorch in Vision, Text, Reinforcement Learning, etc.

PyTorch Examples WARNING: if you fork this repo, github actions will run daily on it. To disable this, go to /examples/settings/actions and Disable Ac

null 19.4k Jan 1, 2023
Deep Learning (with PyTorch)

Deep Learning (with PyTorch) This notebook repository now has a companion website, where all the course material can be found in video and textual for

Alfredo Canziani 6.2k Jan 2, 2023
Open source guides/codes for mastering deep learning to deploying deep learning in production in PyTorch, Python, C++ and more.

Deep Learning Materials by Deep Learning Wizard Start Learning Now Please head to www.deeplearningwizard.com to start learning! It is mobile/tablet fr

Ritchie Ng 572 Dec 28, 2022
Simple examples to introduce PyTorch

This repository introduces the fundamental concepts of PyTorch through self-contained examples. At its core, PyTorch provides two main features: An n-

Justin Johnson 4.4k Jan 7, 2023
Minimal tutorials for PyTorch

Minimal tutorials for PyTorch adapted from Alec Radford's Theano tutorials. Tensor multiplication Linear Regression Logistic Regression Neural Network

Vinh Khuc 321 Oct 25, 2022
PyTorch Tutorial for Deep Learning Researchers

This repository provides tutorial code for deep learning researchers to learn PyTorch. In the tutorial, most of the models were implemented with less

Yunjey Choi 25.4k Jan 5, 2023
Simple PyTorch Tutorials Zero to ALL!

PyTorchZeroToAll Quick 3~4 day lecture materials for HKUST students. Video Lectures: (RNN TBA) Youtube Bilibili Slides Lecture Slides @GoogleDrive If

Sung Kim 3.7k Dec 30, 2022
Pytorch implementations of various Deep NLP models in cs-224n(Stanford Univ)

DeepNLP-models-Pytorch Pytorch implementations of various Deep NLP models in cs-224n(Stanford Univ: NLP with Deep Learning) This is not for Pytorch be

Kim SungDong 2.9k Dec 24, 2022
PyTorch tutorials and best practices.

Effective PyTorch Table of Contents Part I: PyTorch Fundamentals PyTorch basics Encapsulate your model with Modules Broadcasting the good and the ugly

Vahid Kazemi 1.5k Jan 4, 2023
A scalable template for PyTorch projects, with examples in Image Segmentation, Object classification, GANs and Reinforcement Learning.

PyTorch Project Template is being sponsored by the following tool; please help to support us by taking a look and signing up to a free trial PyTorch P

Mo'men AbdelRazek 740 Dec 23, 2022
Some example scripts on pytorch

pytorch-practice Some example scripts on pytorch CONLL 2000 Chunking task Uses BiLSTM CRF loss with char CNN embeddings. To run use: cd data/conll2000

Shubhanshu Mishra 180 Dec 22, 2022
Example of network fine-tuning in pytorch for the kaggle competition Dogs vs. Cats Redux: Kernels Edition

Example of network fine-tuning in pytorch for the kaggle competition Dogs vs. Cats Redux: Kernels Edition Currently

bobby 70 Sep 22, 2022
simple generative adversarial network (GAN) using PyTorch

Generative Adversarial Networks (GANs) in PyTorch Running Run the sample code by typing: ./gan_pytorch.py ...and you'll train two nets to battle it o

vanguard_space 32 Jun 14, 2020
Torch Containers simplified in PyTorch

pytorch-containers This repository aims to help former Torchies more seamlessly transition to the "Containerless" world of PyTorch by providing a list

Max deGroot 88 Apr 25, 2022
The Hitchiker's Guide to PyTorch

The Hitchiker's Guide to PyTorch

Kai Arulkumaran 1k Dec 20, 2022
Interactive deep learning book with multi-framework code, math, and discussions. Adopted at 200 universities.

D2L.ai: Interactive Deep Learning Book with Multi-Framework Code, Math, and Discussions Book website | STAT 157 Course at UC Berkeley | Latest version

Dive into Deep Learning (D2L.ai) 16k Jan 3, 2023
PyTorch Implementation of Fully Convolutional Networks. (Training code to reproduce the original result is available.)

pytorch-fcn PyTorch implementation of Fully Convolutional Networks. Requirements pytorch >= 0.2.0 torchvision >= 0.1.8 fcn >= 6.1.5 Pillow scipy tqdm

Kentaro Wada 1.6k Jan 4, 2023
Script that receives an Image (original) and a set of images to be used as "pixels" in reconstruction of the Original image using the set of images as "pixels"

picinpics Script that receives an Image (original) and a set of images to be used as "pixels" in reconstruction of the Original image using the set of

RodrigoCMoraes 1 Oct 24, 2021