Git Product home page Git Product logo

pkmital / cadl Goto Github PK

View Code? Open in Web Editor NEW
1.5K 117.0 733.0 322.7 MB

ARCHIVED: Contains historical course materials/Homework materials for the FREE MOOC course on "Creative Applications of Deep Learning w/ Tensorflow" #CADL

Home Page: https://www.kadenze.com/courses/creative-applications-of-deep-learning-with-tensorflow/info

License: Apache License 2.0

Jupyter Notebook 98.77% Python 1.23% Shell 0.01%
jupyter-notebook neural-network tensorflow deep-learning mooc dockerfile machine-learning tutorial workshop

cadl's Introduction

Build Status Slack Channel

This repository contains lecture transcripts and homework assignments as Jupyter Notebooks for the first of three Kadenze Academy courses on Creative Applications of Deep Learning w/ Tensorflow. It also contains a python package containing all the code developed during all three courses.

COURSE 1: Creative Applications of Deep Learning with TensorFlow I
Session 1: Introduction to TensorFlow
Session 2: Training A Network W/ TensorFlow
Session 3: Unsupervised And Supervised Learning
Session 4: Visualizing And Hallucinating Representations
Session 5: Generative Models

COURSE 2: Creative Applications of Deep Learning with TensorFlow II
Session 1: Cloud Computing, GPUs, Deploying
Session 2: Mixture Density Networks
Session 3: Modeling Attention with RNNs, DRAW
Session 4: Image-to-Image Translation with GANs

COURSE 3: Creative Applications of Deep Learning with TensorFlow III
Session 1: Modeling Music and Art: Google Brain’s Magenta Lab
Session 2: Modeling Language: Natural Language Processing
Session 3: Autoregressive Image Modeling w/ PixelCNN
Session 4: Modeling Audio w/ Wavenet and NSynth

Github Contents Overview

Session Description Transcript Homework
Python Package pycadl Python package required for courses 2 and 3 N/A N/A
Installation Installation Setting up Python/Notebook and necessary libraries. N/A N/A
Preliminaries Preliminaries with Python Basics of working with Python and images. N/A N/A
1 Computing with Tensorflow Working with a small dataset of images. Dataset preprocessing. Tensorflow basics. Sorting/organizing a dataset. lecture-1.ipynb Colab session-1.ipynb
2 Basics of Neural Networks Learn how to create a Neural Network. Learn to use a neural network to paint an image. Apply creative thinking to the inputs, outputs, and definition of a network. lecture-2.ipynb session-2.ipynb
3 Unsupervised and Supervised Learning Build an autoencoder. Extend it with convolution, denoising, and variational layers. Build a deep classification network. Apply softmax and onehot encodings to classify audio using a Deep Convolutional Network. lecture-3.ipynb session-3.ipynb
4 Visualizing Representations Visualize backpropped gradients, use them to create Deep Dream, extend Deep Dream w/ regularization. Stylize images or synthesize new images with painterly or hallucinated aesthetics of another image. lecture-4.ipynb session-4.ipynb
5 Generative Models Build a Generative Adversarial Network and extend it with a Variational Autoencoder. Use the latent space of this network to perform latent arithmetic. Build a character level Recurrent Neural Network using LSTMs. Understand different ways of inferring with Recurrent Networks. lecture-5.ipynb session-5-part-1.ipynb, session-5-part-2.ipynb

Installation Preliminaries

The first course makes heavy usage of Jupyter Notebook. This will be necessary for submitting the homeworks and interacting with the guided session notebooks I will provide for each assignment. Follow along this guide and we'll see how to obtain all of the necessary libraries that we'll be using. By the end of this, you'll have installed Jupyter Notebook, NumPy, SciPy, and Matplotlib. While many of these libraries aren't necessary for performing the Deep Learning which we'll get to in later lectures, they are incredibly useful for manipulating data on your computer, preparing data for learning, and exploring results.

Quickstart Guide

Please skip this section and read the rest of this readme if you are unfamiliar w/ Jupyter Notebook or installing Python libraries. This section is only for advanced users who want to get started quickly.

There are two ways to get started. You can use a native pip installation or use Docker. There is a quickstart guide for both methods below. If you have trouble with these, then please skip to the more in depth guides below these sections.

Method 1: pip Install

For those of you that are proficient w/ Python programming, you'll need Python 3.4+ and the latest TensorFlow which you can install via pip, e.g.:

$ pip install tensorflow

or w/ CUDA as:

$ pip install tensorflow-gpu

Method 2: Docker Installation

If you want a controlled environment w/ all dependencies installed for you, and are proficient w/ Docker and Jupyter, you can get started w/ this repo like so:

$ cd
$ git clone --recursive https://github.com/pkmital/CADL.git
$ cd CADL
$ docker build -t cadl .
$ docker run -it -p 8888:8888 -p 6006:6006 -v /$(pwd)/session-1:/notebooks --name tf cadl /bin/bash

Note that you can skip the build step and download from docker hub instead like so:

$ docker run -it -p 8888:8888 -p 6006:6006 -v /$(pwd)/session-1:/notebooks --name tf pkmital/cadl /bin/bash

Be sure to replace "session-1" with whichever session you are working on, e.g. "session-2", "session-3"... This will give you a bash prompt with the files for each session:

root@39c4441bcde8:/notebooks# ls
README.md  lecture-1.ipynb  libs  session-1.ipynb  tests

Which you can use to launch jupyter like so:

root@39c4441bcde8:/notebooks# jupyter notebook --allow-root
[I 01:45:27.712 NotebookApp] [nb_conda_kernels] enabled, 2 kernels found
[I 01:45:27.715 NotebookApp] Writing notebook server cookie secret to /root/.local/share/jupyter/runtime/notebook_cookie_secret
[W 01:45:27.729 NotebookApp] WARNING: The notebook server is listening on all IP addresses and not using encryption. This is not recommended.
[I 01:45:27.799 NotebookApp] [nb_anacondacloud] enabled
[I 01:45:27.802 NotebookApp] [nb_conda] enabled
[I 01:45:27.856 NotebookApp] ✓ nbpresent HTML export ENABLED
[W 01:45:27.856 NotebookApp] ✗ nbpresent PDF export DISABLED: No module named 'nbbrowserpdf'
[I 01:45:27.858 NotebookApp] Serving notebooks from local directory: /notebooks
[I 01:45:27.858 NotebookApp] 0 active kernels
[I 01:45:27.858 NotebookApp] The Jupyter Notebook is running at: http://[all ip addresses on your system]:8888/?token=dd68eeffd8f227dd789327c981d16b24631866e909bd6469
[I 01:45:27.858 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

Jupyter should then be running if you navigate Google Chrome (suggested!) to "http://localhost:8888". If you navigate to the session-1.ipynb file, you will see the homework, or to "lecture-1.ipynb", to find the lecture transcripts. The same goes for every other session.

If you need to relaunch the docker image again, you can write:

$ cd
$ cd CADL
$ docker start -i tf

If you want to use a GPU version, and have a Linux machine, and have an NVIDIA GPU, you can use nvidia-docker (this only works for Linux machines! for non-Linux machines that want to use GPU, please follow the expanded directions below, or the quickstart pip installation above):

$ wget -P /tmp https://github.com/NVIDIA/nvidia-docker/releases/download/v1.0.0-rc.3/nvidia-docker_1.0.0.rc.3-1_amd64.deb
$ sudo dpkg -i /tmp/nvidia-docker*.deb && rm /tmp/nvidia-docker*.deb
$ nvidia-docker build -t cadl-gpu -f Dockerfile-gpu .
$ nvidia-docker run -it -p 8888:8888 -p 6006:6006 -v /$(pwd)/session-1:/notebooks --name tf cadl-gpu /bin/bash 
$ nvidia-docker start -i tf

If you had any trouble w/ this setup then please go through the rest of this document which provides much more in depth details.

What is Notebook?

Jupyter Notebook, previously called "iPython Notebook" prior to version 4.0, is a way of interacting with Python code using a web browser. It is a very useful instructional tool that we will be using for all of our homework assignments. Notebooks have the file extensions "ipynb" which are abbreviations of "iPython Notebook". Some websites such as nbviewer.ipython.org or www.github.com can view .ipynb files directly as rendered HTML. However, these are not interactive versions of the notebook, meaning, they are not running the python kernel which evaluates/interacts with the code. So the notebook is just a static version of the code contained inside of it.

In order to interact with notebook and start coding, you will need to launch Terminal (for Mac and Linux users). For Windows users, or for anyone having any problems with the Linux/Mac instructions, please follow the next section on Docker Toolbox very closely! If you are not a Windows user, please first try skipping over the next section and use the installation instructions in Jupyter Notebook before trying Docker as this solution will be much faster than running Docker.

Docker Toolbox

Currently, Windows users can only install Tensorflow via pip using a 64-bit Python 3.5 environment or using Docker, as outlined below.

The easiest way to get up an running on any type of system is to use Docker. Docker is a way of managing a "virtual" Linux machine on your computer which will aid the creation a machine capable of running Tensorflow. First, please download and install the Docker Toolbox:

https://www.docker.com/products/docker-toolbox

Linux users can install docker using their favorite package manager.

For OSX and Windows users, you'll then need to run the "Docker Quickstart Terminal" which will launch a Terminal environment running on a virtual Linux machine on your computer. A virtual machine is basically an emulation of another machine. This is important because we'll use this machine to run Linux and install all of the necessary libraries for running Tensorflow.

Note for Windows users, if you have trouble launching the Docker Quickstart Terminal because you have "Hyper-V", please instead try using https://docs.docker.com/docker-for-windows/. Then launch the newly installed "Docker CLI" program.

Once the Terminal is launched, either via Docker CLI or Docker Quickstart Terminal, run the following command (ignoring the $ sign at the beginning of each line, which just denote that each line is a terminal command that you should type out exactly and then hit ENTER afterwards):

$ cd
$ docker-machine ip

If you are using Docker Toolbox, you should see your virtual machine's IP address as a result of the last command. This is the location of your virtual machine. NOTE THIS IP ADDRESS, as we'll need it in a second. If you are using "Docker for Windows" instead, then you won't need this IP as we'll just use "localhost".

This next command will move to your "home" directory. We'll then "clone" the github repo. This will download everything for the course using "git". If you have trouble w/ this step, make sure you have installed git.

$ cd
$ git clone --recursive https://github.com/pkmital/CADL.git

We'll now print out what the full path to that directory is. PLEASE NOTE DOWN THIS DIRECTORY. This is where everything will happen, and I'll explain that in a minute.

$ echo /$(pwd)/CADL

Now run the following command, which will download everything we need to run tensorflow, python, and jupyter notebook (again, ignore the "$" at the beginning of the line only)!

$ docker run -it -p 8888:8888 -p 6006:6006 -v /$(pwd)/CADL:/notebooks --name tf pkmital/cadl

What this is doing is: * Running the docker image pkmital/cadl * --name is giving it a shorthand name of "tf" * -v is mirroring the directory "/$(pwd)/CADL" to the virtual machine's directory of "/notebooks" * -p is forwarding ports from the virtual machine to your local machine so that you can access the virtual machine's port * -it is running it as an interactive process

You will want to put files inside the "/notebooks" directory only. If you place files on the virtual machine outside of the "/notebooks" directory, which is the SAME as the "CADL" directory on your local machine, they will not be saved. We are using Docker to mirror the "CADL" directory on a virtual machine which has everything necessary for us to code in Python and Tensorflow. Whatever is in that directory will be mirrored on the virtual machine's directory under /notebooks.

You can also try running the docker run command with any other directory. For instance:

$ docker run -it -p 8888:8888 -p 6006:6006 -v /Users/YOURUSERNAME/Desktop:/notebooks --name tf pkmital/cadl

Which would mean that your Desktop is where you can move files around so that on the virtual machine, you can interact with them under the /notebooksdirectory.

For OSX users, if you are installing Docker because you had installation problems using Anaconda and pip, you would instead write the following command (note the missing slash):

$ docker run -it -p 8888:8888 -p 6006:6006 -v $(pwd)/CADL:/notebooks --name tf pkmital/cadl

When you want to start this machine, you will launch the Docker Quickstart Terminal and then write:

$ cd
$ docker start -i tf

Notice that the command prompt will now be # instead of $. You should have a new folder "tensorflow" inside your Home directory. This directory will be empty to begin with. Please make sure you do everything inside this directory only or else any files you make on your virtual machine WILL BE ERASED once it is shutdown! When you clone the CADL repository, or expand the zip file downloads contents inside this directory via your Windows machine (it will be in your Home directory under a folder "cadl"), then you will be able to access it via your Docker instance.

For instance, after running the docker start -i tf command, try going into the directory /notebooks:

# cd /notebooks

Jupyter Notebook

OSX/Linux

Note: Windows/Docker users should scroll past this section to "Windows/Docker". For OSX/Linux users, the easiest way to ensure you have Python 3.4 or higher and Jupter Notebook is to install Anaconda for Python 3.5 located here:

OSX or Linux

Make sure you restart your Terminal after you install Anaconda as there are some PATH variables that have to be set.

Then run the following:

$ curl https://bootstrap.pypa.io/ez_setup.py -o - | python

If you already have conda, but only have Python 2, you can very easily add a new environment w/ Python 3 and switch back and forth as needed. Or if you do not have Anaconda, but have a system based install, I'd really recommend either using Anaconda or pyenv to help you manage both python installations.

With Anaconda installed, you will have python and the package "ipython[notebook]", along with a ton of other very useful packages such as numpy, matplotlib, scikit-learn, scikit-image, and many others.

With everything installed, restart your Terminal application (on OSX, you can use Spotlight to find the Terminal application), and then navigate to the directory containing the "ipynb", or "iPython Notebook" file, by "cd'ing" (pronounced, see-dee-ing), into that directory. This involves typing the command: "cd some_directory". Once inside the directory of the notebook file, you will then type: "jupyter notebook". If this command does not work, it means you do not have notebook installed! Try installed anaconda as above, restart your Terminal application, or manually install notebook like so (ignore the "$" signs which just denote that this is a Terminal command that you should type out exactly and then hit ENTER!):

$ pip3 install ipython[notebook]
$ jupyter notebook

If you run into issues that say something such as:

[W 20:37:40.543 NotebookApp] Kernel not found: None

Then please try first running:

$ ipython3 kernel install
### Windows/Docker Containers

For users running firewalls, you must make sure you have an exception as per Jupyter Notebooks Firewall Instructions otherwise you may not be able to interact with the notebook. Namely, you will need to allow connections from 127.0.0.1 (localhost) on ports from 49152 to 65535. Once inside your Docker container as outlined above, you can now launch notebook like so:

$ cd /notebooks
$ jupyter notebook &

Note on Virtual versus Windows Directories:

This is tricky to grasp, mostly because I didn't explain it. Docker is "virtual" computer running inside your computer. It has its own filesystem and its own directories. So you can't reference your Windows machine's directories inside this machine. When you first ran docker (e.g. $ docker run -it -p 8888:8888 -p 6006:6006 -v /$(pwd)/tensorflow:/notebooks --name tf pkmital/cadl) it included as part of its command: -v /$(pwd)/tensorflow:/notebooks. What that was doing is "mirroring" a directory on your Windows machine inside your Virtual machine. So whatever was in your Windows machine under the directory /$(pwd)/tensorflow would appear in the Virtual machine under /notebooks. That Windows directory is likely /Users/<YOURUSERNAME>/tensorflow. So ONLY inside that directory, create it if it doesn't exist, should you put files in order to access it on the Virtual machine.

So let's say your Username was "pkmital". Then your home directory would be /Users/pkmital, and you would have mirrored /Users/pkmital/tensorflow on your Windows Machine to the Virtual machine under /notebook. Now let's say I create a directory /Users/pkmital/tensorflow/images on my Windows Machine, and then put a bunch of png files in there. I will then see them in my Virtual machine under /notebook/images. If I put the CADL repository inside /Users/pkmital/tensorflow, then I should have /Users/pkmital/tensorflow/CADL/session-1/session-1.ipynb and on the Virtual machine, it will be in /notebooks/CADL/session-1/session-1.ipynb - From this notebook, running on the virtual machine, accessed with Jupyter Notebook, I would access my images like so:

import os
os.listdir('../../images')

Navigating to Notebook

After running "jupyter notebook &", you should see a message similar to:

root@182bd64f27d2:~# jupyter notebook &
[I 21:15:33.647 NotebookApp] Writing notebook server cookie secret to /root/.local/share/jupyter/runtime/notebook_cookie_secret
[W 21:15:33.712 NotebookApp] WARNING: The notebook server is listening on all IP addresses and not using encryption. This is not recommended.
[W 21:15:33.713 NotebookApp] WARNING: The notebook server is listening on all IP addresses and not using authentication. This is highly insecure and not recommended.
[I 21:15:33.720 NotebookApp] Serving notebooks from local directory: /root
[I 21:15:33.721 NotebookApp] 0 active kernels
[I 21:15:33.721 NotebookApp] The IPython Notebook is running at: http://[all ip addresses on your system]:8888/
[I 21:15:33.721 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

Don't worry if the IP address or command prompt look different. Note where it says: The IPython Notebook is running at. If you are running Docker (Windows users), this is where we need that IP address. For OSX/Linux users, we'll use "localhost" so don't worry about this. Now open up Chrome/Safari/Firefox whatever browser you like, and then navigate to:

http://localhost:8888

or for Windows users:

http://ADDRESS:8888

where ADDRESS is the ip address you should have noted down before. For instance, on my machine, I would visit the website:

http://192.168.99.100:8888

This will launch the Jupyter Notebook where you will be able to interact with the homework assignments!

Installing Python Packages

Packages are libraries or useful extensions to the standard python libraries. In this course, we'll be using a few including Tensorflow, NumPy, MatPlotLib, SciPy, SciKit-Image, and SciKit-Learn. Windows users will already have these libraries since the Docker container includes these. However, if you needed to, you can install these using "pip", which is the python package manager. OSX/Linux users should follow these steps just to be sure they have the latest versions of these packages. In Python 3.4 and higher, pip comes with any standard python installation. In order to use pip, first make sure you are using the correct version. One way to do this is check which pip you are running:

$ which pip
$ which pip3

Use which pip points to the install path that makes the most sense (e.g. Anaconda for OSX users for some reason does not symlink pip3 to the python3 pip, and instead points to the system version of python3).

Then you'll write:

$ pip3 install -U pip setuptools

To make sure you have an up to date pip, then:

$ pip3 install some_package

To get the necessary libraries:

$ pip3 install "scikit-image>=0.11.3" "numpy>=1.11.0" "matplotlib>=1.5.1" "scikit-learn>=0.17"

This should get you all of the libraries we need for the course, EXCEPT for tensorflow. Tensorflow is a special case, but can be pip installed in much the same way by pointing pip to the github repo corresponding to your OS like so.

Ubuntu/Linux 64-bit for Python 3.4

$ pip3 install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0rc1-cp34-cp34m-linux_x86_64.whl

Ubuntu/Linux 64-bit for Python 3.5

$ pip3 install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0rc1-cp35-cp35m-linux_x86_64.whl

OSX for Python 3.4 or Python 3.5

$ pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.11.0rc1-py3-none-any.whl

Other Linux/OSX varieties

You can pip install Tensorflow for most OSX/Linux setups including those that are making use of NVIDIA GPUs and CUDA using one the packages listed on this link: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#pip-installation

If you are having trouble with pip installation, try looking here first: Common Installation Problems. Failing that, reach out to us on the forums, or else you may want to instead run a Docker instance as outlined in the Windows instructions above: Setting up a Docker Container.

CUDA/GPU instructions

Note that I have not provided instructions on getting setup w/ CUDA as it is beyond the scope of this course! If you are interested in using GPU acceleration, I highly recommend using Ubuntu Linux and setting up a machine on Nimbix or Amazon EC2 using the instructions here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#optional-install-cuda-gpus-on-linux. If you're using Nimbix, you can skip the install process as there is already a machine pre-installed w/ Tensorflow. Similarly, for Amazon EC2, there are many existing "images" of machines that have Tensorflow already installed.

Testing it

To confirm it worked, try running:

$ python3 -c 'import tensorflow as tf; print(tf.__version__)'

You should see 1.0.0 printed, depending on which version you have installed.

CUDA/GPU instructions for MacOS

When your Mac is equipped with a NVidia graphics card, you can use the GPU for computing with Tensorflow. GPU enabled computing is not supported for Macs with ATI or Intel graphics cards.

If you have a previous cpu installation of tensorflow, uninstall it first:

$ pip3 uninstall tensorflow

Using homebrew, install the following packages:

$ brew install coreutils
$ brew tap caskroom/cask
$ brew cask install cuda

Once you have the CUDA Toolkit installed you will need to setup the required environment variables by adding the following to your ~/.profile:

export CUDA_HOME=/usr/local/cuda
export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$CUDA_HOME/lib"
export PATH="$CUDA_HOME/bin:$PATH"

Tensorflow needs the library libcuda.1.dylib, so we have to create an additional symbolic link:

sudo ln -sf /usr/local/cuda/lib/libcuda.dylib /usr/local/cuda/lib/libcuda.1.dylib

Finally, you will also want to install the CUDA Deep Neural Network (cuDNN v5) library which currently requires an Accelerated Computing Developer Program account. Once you have it downloaded locally, you can unzip and move the header and libraries to your local CUDA Toolkit folder:

$ sudo mv include/cudnn.h /Developer/NVIDIA/CUDA-8.0/include/
$ sudo mv lib/libcudnn* /Developer/NVIDIA/CUDA-8.0/lib
$ sudo ln -s /Developer/NVIDIA/CUDA-8.0/lib/libcudnn* /usr/local/cuda/lib/

Then, finally, install tensorflow with GPU support with:

$ pip3 install --ignore-installed --upgrade tensorflow-gpu

According to the instructions of the TensorFlow website, this should work. However, on MacOS 10.11 (El Capitan) and above, the environment variable DYLD_LIBRARY_PATH is ignored, resulting in an error in the interactive python console and JetBrains PyCharm IDE. The dynamic library libcudart.8.0.dylib fails to load. This is due to a new protection meganism in MacOS 10.11 and higher. El Capitan ships with a new OS X feature: System Integrity Protection (SIP), also known as “rootless” mode. This reduces the attack surface for malware that relies on modifying system files by preventing any user, whether with system administrator (“root”) privileges or not from modifying a number of operating system directories and files.

Warning: The point of SIP is to prevent malware and other unwanted modifications into system files. Consider whether or not you want to dispense with this protection. Follow these steps to disable SIP:

  • Restart your Mac.
  • Before OS X starts up, hold down Command-R and keep it held down until you see an Apple icon and a progress bar. Release. This boots you into Recovery.
  • From the Utilities menu, select Terminal.
  • At the prompt type exactly the following and then press Return: csrutil disable
  • Terminal should display a message that SIP was disabled.
  • From the  menu, select Restart.

You can re-enable SIP by following the above steps, but using csrutil enable instead.

Troubleshooting

ImportError: No module named 'tensorflow'

You may have different versions of Python installed. You can troubleshoot this by looking at the output of:

$ which python3
$ which pip3
$ python3 --version
$ pip3 --version
$ which python
$ which pip
$ python --version
$ pip --version

You may simply need to install tensorflow using pip instead of pip3 and/or use python instead of python3, assuming they point to a version of python which is Python 3 or higher.

AttributeError: module 'tensorflow' has no attribute '__version__'

You could be running python inside a directory that contains the folder "tensorflow". Try running python inside a different directory.

GPU-related issues

If you encounter the following when trying to run a TensorFlow program:

ImportError: libcudart.so.7.0: cannot open shared object file: No such file or directory

Make sure you followed the GPU installation instructions. If you built from source, and you left the Cuda or cuDNN version empty, try specifying them explicitly.

Protobuf library related issues

TensorFlow pip package depends on protobuf pip package version 3.0.0b2. Protobuf's pip package downloaded from PyPI (when running pip install protobuf) is a Python only library, that has Python implementations of proto serialization/deserialization which can be 10x-50x slower than the C++ implementation. Protobuf also supports a binary extension for the Python package that contains fast C++ based proto parsing. This extension is not available in the standard Python only PIP package. We have created a custom binary pip package for protobuf that contains the binary extension. Follow these instructions to install the custom binary protobuf pip package :

# Ubuntu/Linux 64-bit:
$ pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/protobuf-3.0.0b2.post2-cp27-none-linux_x86_64.whl

# Mac OS X:
$ pip install --upgrade https://storage.googleapis.com/tensorflow/mac/protobuf-3.0.0b2.post2-cp27-none-any.whl

and for Python 3 :

# Ubuntu/Linux 64-bit:
$ pip3 install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/protobuf-3.0.0b2.post2-cp34-none-linux_x86_64.whl

# Mac OS X:
$ pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/protobuf-3.0.0b2.post2-cp35-none-any.whl

Install the above package after you have installed TensorFlow via pip, as the standard pip install tensorflow would install the python only pip package. The above pip package will over-write the existing protobuf package. Note that the binary pip package already has support for protobuf larger than 64MB, that should fix errors such as these :

[libprotobuf ERROR google/protobuf/src/google/protobuf/io/coded_stream.cc:207] A
protocol message was rejected because it was too big (more than 67108864 bytes).
To increase the limit (or to disable these warnings), see
CodedInputStream::SetTotalBytesLimit() in google/protobuf/io/coded_stream.h.

Cannot import name 'descriptor'

ImportError: Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/core/framework/graph_pb2.py", line 6, in <module>
    from google.protobuf import descriptor as _descriptor
ImportError: cannot import name 'descriptor'

If you the above error when upgrading to a newer version of TensorFlow, try uninstalling both TensorFlow and protobuf (if installed) and re-installing TensorFlow (which will also install the correct protobuf dependency).

Can't find setup.py

If, during pip install, you encounter an error like:

...
IOError: [Errno 2] No such file or directory: '/tmp/pip-o6Tpui-build/setup.py'

Solution: upgrade your version of pip:

pip install --upgrade pip

This may require sudo, depending on how pip is installed.

SSLError: SSL_VERIFY_FAILED

If, during pip install from a URL, you encounter an error like:

...
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

Solution: Download the wheel manually via curl or wget, and pip install locally.

Jupyter Notebook Kernel is always busy (Windows)

If your have installed Docker Toolbox on Windows but your jupyter notebook doesn't run properly (the notebook kernel keeps busy all the time when you open any file) then you might need to try different browsers (One guy tried Edge and it solved his problem after struggling for long time on Chrome/Firefox).

And you should also enable port forwarding by:

  1. Open VirtualBox
  2. Click on your default docker image.
  3. Click Settings.
  4. Click Network.
  5. Click forward port.
  6. Add a new rule named jupyter with host ip=127.0.0.1 and host/guess port=8888
  7. Now you should be able to browse your notebook app via localhost:8888 (instead of having to browse 192.168.xx.xx:8888)

Something Else!

Post on the Forums or check on the Tensorflow README

cadl's People

Contributors

adattudos avatar alvaroingold avatar chonigman avatar davidstutz avatar gilbertfrancois avatar iashris avatar indraastra avatar is3d-1 avatar itamaro avatar jorinvo avatar kjeanclaude avatar martin-martin avatar mimoralea avatar nok avatar offchan42 avatar pkmital avatar randomm avatar rmeertens avatar shivam-kotwalia avatar smarques avatar sunsided avatar vichug avatar williemaddox avatar wrannaman avatar xuv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cadl's Issues

Denoising VAE implementation broken

In the code for the VAE function (lines 97-102 as per bcdb019) appears to be a bug that prevents the usage of corrupted inputs:

    if denoising:
        current_input = utils.corrupt(x) * corrupt_prob + x * (1 - corrupt_prob)

    # 2d -> 4d if convolution
    x_tensor = utils.to_tensor(x) if convolutional else x
    current_input = x_tensor

Here, the current_input tensor is directly overwritten by x_tensor. It appears to be the case for all sessions.

Session 5; provided pre-trained model incompatible (and not loaded)

On Session 5, part 2, the check

    if os.path.exists(ckpt_name):
        saver.restore(sess, ckpt_name)
        print("Model restored.")

... does not match the provided checkpoint file name exactly trump.ckpt.data-00000-of-00001 so the load is not attempted.
Therefore, the model is untrained for the example and the predictions are all non-deterministic random strings,

!!--sssjjj44www???ggvvvwwwx??ggggvaaa577777t777t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t77t777t​
??ffd88l:ttttt?efiiiii8880cc99v666444sszssxrpp/mmmxxxxr!//33gggggkgggkmmmeeiiiiiiii888ccc8994444sszszsírpp/mmmxxxxr!//33gggggkgggkmmmeeiiiiiiii888ccc8994444sszszsírpp/mmmxxxxr!//33gggggkgggkmmmeeiiiiiiii888ccc8994444sszszsírpp/mmmxxxxr!//33gggggkgggkmmmeeiiiiiiii888ccc8994444sszszsírpp/mmmxxxxr!//33gggggkgggkmmmeeiiiiiiii888ccc8994444sszszsírpp/mmmxxxxr!//33gggggkgggkmmmeeiiiiiiii888ccc8994444sszszsírpp/mmmxxxxr!//33gggggkgggkmmmeeiiiiiiii888ccc8994444sszszsírpp/mmmxxxxr!//33gggggkgggkmmmeeiiiii​

etc.

If the check is removed, then the saver does pick up the provided model, but then cannot load it.
It blows up with the error below. I've also noticed, while chasing this, that the encoder and decoder used for this part of the exercise are actually initialized with a different text -- the one from Part 4 - Character-Level Language Model; I guess that's fine as the sets are probably equivalent in this case, but wouldn't it be better to add a cell just to regenerate these for the latter section?

I'm running TF 1.1.0 wit GPU support on a Debian 4.9.18-1 laptop.

INFO:tensorflow:Restoring parameters from ./trump.ckpt
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
~/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1038     try:
-> 1039       return fn(*args)
   1040     except errors.OpError as e:

~/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1020                                  feed_dict, fetch_list, target_list,
-> 1021                                  status, run_metadata)
   1022 

~/anaconda3/envs/potrero/lib/python3.6/contextlib.py in __exit__(self, type, value, traceback)
     88             try:
---> 89                 next(self.gen)
     90             except StopIteration:

~/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

InvalidArgumentError: Assign requires shapes of both tensors to match. lhs shape= [2048] rhs shape= [800]
	 [[Node: save/Assign_17 = Assign[T=DT_FLOAT, _class=["loc:@rnn/rnn/multi_rnn_cell/cell_1/basic_lstm_cell/biases"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/gpu:0"](rnn/rnn/multi_rnn_cell/cell_1/basic_lstm_cell/biases, save/RestoreV2_17/_49)]]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-8-999cfb8483be> in <module>()
     11     saver = tf.train.Saver()
     12     # if os.path.exists(ckpt_name):
---> 13     saver.restore(sess, ckpt_name)
     14     # print("Model restored.")
     15 

~/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/training/saver.py in restore(self, sess, save_path)
   1455     logging.info("Restoring parameters from %s", save_path)
   1456     sess.run(self.saver_def.restore_op_name,
-> 1457              {self.saver_def.filename_tensor_name: save_path})
   1458 
   1459   @staticmethod

~/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    980     if final_fetches or final_targets:
    981       results = self._do_run(handle, final_targets, final_fetches,
--> 982                              feed_dict_string, options, run_metadata)
    983     else:
    984       results = []

~/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1030     if handle is None:
   1031       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1032                            target_list, options, run_metadata)
   1033     else:
   1034       return self._do_call(_prun_fn, self._session, handle, feed_dict,

~/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1050         except KeyError:
   1051           pass
-> 1052       raise type(e)(node_def, op, message)
   1053 
   1054   def _extend_graph(self):

InvalidArgumentError: Assign requires shapes of both tensors to match. lhs shape= [2048] rhs shape= [800]
	 [[Node: save/Assign_17 = Assign[T=DT_FLOAT, _class=["loc:@rnn/rnn/multi_rnn_cell/cell_1/basic_lstm_cell/biases"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/gpu:0"](rnn/rnn/multi_rnn_cell/cell_1/basic_lstm_cell/biases, save/RestoreV2_17/_49)]]

Caused by op 'save/Assign_17', defined at:
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2698, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2802, in run_ast_nodes
    if self.run_code(code, result):
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-8-999cfb8483be>", line 11, in <module>
    saver = tf.train.Saver()
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1056, in __init__
    self.build()
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1086, in build
    restore_sequentially=self._restore_sequentially)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 691, in build
    restore_sequentially, reshape)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 419, in _AddRestoreOps
    assign_ops.append(saveable.restore(tensors, shapes))
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 155, in restore
    self.op.get_shape().is_fully_defined())
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/ops/state_ops.py", line 270, in assign
    validate_shape=validate_shape)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/ops/gen_state_ops.py", line 47, in assign
    use_locking=use_locking, name=name)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/gabriel/anaconda3/envs/potrero/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Assign requires shapes of both tensors to match. lhs shape= [2048] rhs shape= [800]
	 [[Node: save/Assign_17 = Assign[T=DT_FLOAT, _class=["loc:@rnn/rnn/multi_rnn_cell/cell_1/basic_lstm_cell/biases"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/gpu:0"](rnn/rnn/multi_rnn_cell/cell_1/basic_lstm_cell/biases, save/RestoreV2_17/_49)]]

Lecture 5: ValueError: Only call `sparse_softmax_cross_entropy_with_logits` with named arguments (labels=..., logits=..., ...)

In lecture 5
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits, Y_true_flat)
raises ValueError while
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = logits, labels = Y_true_flat)
seems to work
see https://www.kadenze.com/forums/creative-applications-of-deep-learning-with-tensorflow-sessions-session-5-generative-models/threads/valueerror-only-call-sparse_softmax_cross_entropy_with_logits-with-named-arguments-labels-logits

Docker-gpu dockerfile build issue

Hey @pkmital,

Awesome work!! I am really excited to dig into what you have going on. I really appreciate how well you document tf and offer docker builds with and without gpu.

I am having a problem building the gpu docker file. Of course it has to do with cuDNN. I am not sure why they make it so difficult to get a hold of that. Anyways, here is my last few lines of my docker build output:

sha256sum: WARNING: 1 computed checksum did NOT match
The command '/bin/sh -c CUDNN_DOWNLOAD_SUM=a87cb2df2e5e7cc0a05e266734e679ee1a2fadad6f06af82a76ed81a23b102c8 &&     curl -fsSL http://developer.download.nvidia.com/compute/redist/cudnn/v5.1/cudnn-8.0-linux-x64-v5.1.tgz -O &&     echo "$CUDNN_DOWNLOAD_SUM  cudnn-8.0-linux-x64-v5.1.tgz" | sha256sum -c --strict - &&     tar -xzf cudnn-8.0-linux-x64-v5.1.tgz -C /usr/local --wildcards 'cuda/lib64/libcudnn.so.*' &&     rm cudnn-8.0-linux-x64-v5.1.tgz &&     ldconfig &&     ln -s /usr/local/cuda/lib64/libcudnn.so.5 /usr/local/cuda/lib64/libcudnn.so' returned a non-zero code: 1

Maybe you want to use the caffe:0.15 base image (#71) to avoid the problem? I think they are different between ubuntu 14 and 16.

(very minnor) in session 0 : code updated, but not the comment

..a the 'Image manipulation > Croping images' paragraph, in the def of the imcrop_tosquare function : the comment says

The first branch says, if the rows of img are greater than the columns, then set the variable extra to their difference and divide by 2.

...whereas the variable extra is in fact not divided by 2 right away in the code. It's minnor but for a beginner (such as myself) it might be very brain freezing for a moment.
That's all :)

TypeError: Cannot cast ufunc multiply output from dtype('float64') to dtype('int64') with casting rule 'same_kind'

I get a type error when trying to generate image from random noise in the ipython notebook. Numpy seems to have a problem with upcasting the datatypes.

TypeError                                 Traceback (most recent call last)
<ipython-input-48-b06014ec4265> in <module>()
      1 # Create some noise, centered at gray
      2 img_noise = inception.preprocess(
----> 3     (np.random.randint(100, 150, size=(224, 224, 3))))[np.newaxis]
      4 print(img_noise.min(), img_noise.max())

/home/clu/Python/CADL-master/session-4/libs/inception.py in preprocess(img, crop, resize, dsize)
     81 def preprocess(img, crop=True, resize=True, dsize=(299, 299)):
     82     if img.dtype != np.uint8:
---> 83         img *= 255
     84 
     85     if crop:
```
`

Problem with Python 3 in Session 4 Part 5

Session 4

Part 5

There is this code snippet:

# Grab the tensor defining the input to the network
x = g.get_tensor_by_name(names[0] + ":0")

# And grab the tensor defining the softmax layer of the network
softmax = g.get_tensor_by_name(names[-2] + ":0")

for img in [content_img, style_img]:
    with tf.Session(graph=g) as sess, g.device('/cpu:0'):
        # Remember from the lecture that we have to set the dropout
        # "keep probability" to 1.0.
        res = softmax.eval(feed_dict={x: img,
                    'net/dropout_1/random_uniform:0': np.ones(
                        g.get_tensor_by_name(
                            'net/dropout_1/random_uniform:0'
                        ).get_shape().as_list()),
                    'net/dropout/random_uniform:0': np.ones(
                        g.get_tensor_by_name(
                            'net/dropout/random_uniform:0'
                        ).get_shape().as_list())})[0]
        print([(res[idx], net['labels'][idx])
               for idx in res.argsort()[-5:][::-1]])

The problem is that when you get the size as:

np.ones( g.get_tensor_by_name( 'net/dropout_1/random_uniform:0' ).get_shape().as_list()

The result is [None, 4096]

When this list is fed into np.ones, there is an error.

Instead, I suggest the following code (or similar):

# Grab the tensor defining the input to the network
x = g.get_tensor_by_name(names[0] + ":0")

# And grab the tensor defining the softmax layer of the network
softmax = g.get_tensor_by_name(names[-2] + ":0")

for img in [content_img, style_img]:
    with tf.Session(graph=g) as sess, g.device('/cpu:0'):
        # Remember from the lecture that we have to set the dropout
        # "keep probability" to 1.0.
        d_0 = g.get_tensor_by_name('net/dropout/random_uniform:0')
        d_0_list = d_0.get_shape().as_list()
        d_0_ones = np.ones([1 if x == None else x for x in d_0_list])
        print(d_0_ones.shape)
        
        d_1 = g.get_tensor_by_name('net/dropout_1/random_uniform:0')
        d_1_list = d_1.get_shape().as_list()
        d_1_ones = np.ones([1 if x == None else x for x in d_1_list])
        print(d_1_ones.shape)
        
        res_obj = softmax.eval(feed_dict={x: img,
                    'net/dropout_1/random_uniform:0': d_1_ones,
                    'net/dropout/random_uniform:0': d_0_ones})
        
        res = res_obj[0]
        
        print([(res[idx], net['labels'][idx])
               for idx in res.argsort()[-5:][::-1]])

Previous code

It's worth mentioning that in the lecture notes, you don't use np.ones, but instead, you explicitly just use [[1]*4096], which creates the same outcome.

Looking forward to hearing your thoughts - Thank you.

Normal (Gaussian Curve) formula breaks with Tensorflow 1.01

Hi, I was trying out the tutorials on windows and I found that the gaussian formula wasn't working. Something to do with the dtypes not converting correctly. None the less, there is a solution in the form of the Normal Distribution contribution in the update. I dunno if you want to re-record that bit though. I'll see if I can figure out how it works later and mention it in the Kadenze forum.

Checkpoint restoration for VAEGAN needs to account for global step

The VAEGAN training code saves checkpoints using the value of the global training step, which results in checkpoints with names like 'vaegan.ckpt-800.index', for example. Any code that looks for an existing checkpoint also needs to account for this naming scheme, but the existence check used doesn't quite work with this scheme:

if os.path.exists(ckpt_name + '.index') or os.path.exists(ckpt_name):

I would suggest changing the check to something like this:

    latest_checkpoint = tf.train.latest_checkpoint(os.path.dirname(ckpt_name))
    if latest_checkpoint:
        saver.restore(sess, latest_checkpoint)
        print("Model restored from checkpoint {}.".format(latest_checkpoint))
    else:
        print("Model checkpoint not found.")

(This won't quite work if checkpoints from multiple models are created in the same directory, since it relies on the presence of a file named 'checkpoint'.)

Issue evaluating VGG16 model

When calling test_vgg() from vgg16.py output is:
ValueError: Cannot feed value of shape (1, 1) for Tensor 'vgg/dropout_1/random_uniform:0', which has shape '(?, 4096)'

When trying to change shape to
res = np.squeeze(softmax.eval(feed_dict={ x: img, 'vgg/dropout_1/random_uniform:0': [[1.0]*4096], 'vgg/dropout/random_uniform:0': [[1.0]*4096]}))

Output is:
InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 115200 values, but the requested shape requires a multiple of 25088 [[Node: vgg/Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](vgg/pool5, vgg/Reshape/shape)]]

This output was received on OSX, running Python3 and Tensorflow 1.7

Environment Setup: "docker: invalid reference format: repository name must be lowercase."

If the path contains spaces, then
docker run -it -p 8888:8888 -p 6006:6006 -v /$(pwd)/session-1:/notebooks --name tf cadl /bin/bash
might throw the error
docker: invalid reference format: repository name must be lowercase.
or behave unexpectedly.

Wrapping in quotation marks solves this:
docker run -it -p 8888:8888 -p 6006:6006 -v "/$(pwd)/session-1":/notebooks --name tf cadl /bin/bash

Just to respect 2.7

I know you started the course with py3.0
Some people like using 2.7 (like me). Not complaining, just if I may, I'd like to include the changes I'd make in code accordingly for 2.7.

Like the one in session - 0 notebook, urllib's request module doesn't exist for 2.7, so
basically two places you have change
from urllib import request
becomes
import urllib
And
urllib.request.urlretrieve(....
becomes
urllib.urlretrieve(....
Also
print (url, end=..)
will not work. So may be we can just write
print (url)

Typo in CADL/lecture-1.ipynb

The text reads:

"By default, this will just return the first 1000 images because loading the entire dataset is a bit cumbersome"

The utils function only loads 100 images, not 1000.

Cost function minimization

I think the cost function minimization example in lecture 2 (input 4) has a bug. Following the initialization values given in the example, one should get to the local minimum just in a few steps. Below is the notebook code:
%matplotlib inline
import os
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
plt.style.use('ggplot')

def myMin(values):
import operator
min_index, min_value = min(enumerate(values),
key=operator.itemgetter(1))
return min_index, min_value

Define placeholders

hz = tf.placeholder(tf.float32, name='hz')

hz = 10

ksize = tf.placeholder(tf.int32, name='ksize')

ksize = 200

lr = tf.placeholder(tf.float32, name='learning_rate')

learning_rate = 1.0

init_p = tf.placeholder(tf.int32, name = 'init_p')

init_p = 120

x = tf.linspace(-1.0, 1.0, ksize)

Define model

x_cropped = x[init_p : init_p+2]
cost = tf.multiply(tf.sin(hzx_cropped),tf.exp(-x_cropped))
costFull = tf.multiply(tf.sin(hz
x),tf.exp(-x))
grad = cost[1:] - cost[:-1]
x_out = tf.multiply(lr,grad)

Initialize and run

init_op = tf.global_variables_initializer()
init_ps = 120 #int(120/2)
nr_iterations = 15
with tf.Session() as sess:
sess.run(init_op)
xs, cost_s = sess.run([x,costFull],{hz:10,ksize:200})
x_in = xs[init_ps]
x_ser = []
cost_ser = []
for i in range(nr_iterations):
x_ser.append(xs[init_ps])
x2, cost2 = sess.run([x_out,cost],
{hz:10,init_p:init_ps,x:xs,lr:1})
x2 = xs[init_ps] - x2
dx = np.abs(xs - x2)
init_ps, _ = myMin(dx)
cost_ser.append(cost2[0].flatten())

Prepare for plotting

x_ser = np.array(x_ser).flatten()
cost_ser = np.array(cost_ser).flatten()
cmap = plt.get_cmap('coolwarm')
c_norm = colors.Normalize(vmin=0, vmax=nr_iterations)
scalar_map = cmx.ScalarMappable(norm=c_norm, cmap=cmap)

Plot results

fig, axF = plt.subplots(2, figsize=(10, 8))
ax = axF[0]
ax.plot(xs, cost_s)
for i in range(nr_iterations):
ax.plot(x_ser[i], cost_ser[i],'ro',
color=scalar_map.to_rgba(i))
ax.set_ylabel('Cost')
ax.set_xlabel('x')

ax = axF[1]
for i in range(nr_iterations-1):
ax.plot(i, x_ser[i+1] - x_ser[i],'o',color=scalar_map.to_rgba(i))
ax.set_xlabel('Iteration')

lecture2_in4.ipynb.tar.gz

Session 2 typo: intializer => initializer

For session 2 the line of instruction that says: (the tf.random_normal_intializer you should create)

the world 'intializer' is misspelled, it should be initializer

Thanks!

Alonso

Index Error in Session 3 at Reorganize a grid.

Code:
examples_sorted = []
for i in indexes[1]:
examples_sorted.append(examples[i])
plt.figure(figsize=(15, 15))
img = utils.montage(np.array(examples_sorted)).astype(np.uint8)
plt.imshow(img,
interpolation='nearest')
plt.imsave(arr=img, fname='sorted.png')

Errror:
IndexError: index 3479 is out of bounds for axis 0 with size 100.

Number of epochs unused in dataset_utils.create_input_pipeline

The n_epochs variable goes unused in dataset_utils.create_input_pipeline(), so the line

    producer = tf.train.string_input_producer(
        files, capacity=len(files))

should probably be

    producer = tf.train.string_input_producer(
        files, num_epochs=n_epochs, capacity=len(files))

However, I also had to add a call to sess.run(tf.local_variables_initializer()) after making that change.

tensorflow 1.4 with cuda8 or 9 !

Hi mital,
I am trying to work on session-1. And started getting errors as below :

ImportError: Could not find 'cudart64_80.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Download and install CUDA 8.0 from this URL: https://developer.nvidia.com/cuda-toolkit

I am using windows 10 machine and also installed CUDA8 from nvidia site. Still dont see this issue going away. Also tried latest CUDA9, but with no luck. Later in web i saw tf1.4 does not support cuda9 for windows 10.
Can you please help with above error.

Regards
Vinay

Session3 vae.VAE decoding layers don't use transposed W from encoding layers

Session3 vae.VAE code for decoding layers is

shapes.reverse()
n_filters.reverse()
Ws.reverse()

n_filters += [input_shape[-1]]

# %%
# Decoding layers
for layer_i, n_output in enumerate(n_filters[1:]):
    with tf.variable_scope('decoder/{}'.format(layer_i)):
        shape = shapes[layer_i + 1]
        if convolutional:
            h, W = utils.deconv2d(x=current_input,
                                  n_output_h=shape[1],
                                  n_output_w=shape[2],
                                  n_output_ch=shape[3],
                                  n_input_ch=shapes[layer_i][3],
                                  k_h=filter_sizes[layer_i],
                                  k_w=filter_sizes[layer_i])
        else:
            h, W = utils.linear(x=current_input,
                                n_output=n_output)
        h = activation(batch_norm(h, phase_train, 'dec/bn' + str(layer_i)))
        if dropout:
            h = tf.nn.dropout(h, keep_prob)
        current_input = h

y = current_input
x_flat = utils.flatten(x)
y_flat = utils.flatten(y)

# l2 loss
loss_x = tf.reduce_sum(tf.squared_difference(x_flat, y_flat), 1)

This code seems to create new variables in utils.deconv2d and utils.linear

def linear(x, n_output, name=None, activation=None, reuse=None):
	"""Fully connected layer.

	Parameters
	----------
	x : tf.Tensor
		Input tensor to connect
	n_output : int
		Number of output neurons
	name : None, optional
		Scope to apply

	Returns
	-------
	h, W : tf.Tensor, tf.Tensor
		Output of fully connected layer and the weight matrix
	"""
	if len(x.get_shape()) != 2:
		x = flatten(x, reuse=reuse)

	n_input = x.get_shape().as_list()[1]

	with tf.variable_scope(name or "fc", reuse=reuse):
		W = tf.get_variable(
			name='W',
			shape=[n_input, n_output],
			dtype=tf.float32,
			initializer=tf.contrib.layers.xavier_initializer())

		b = tf.get_variable(
			name='b',
			shape=[n_output],
			dtype=tf.float32,
			initializer=tf.constant_initializer(0.0))

		h = tf.nn.bias_add(
			name='h',
			value=tf.matmul(x, W),
			bias=b)

		if activation:
			h = activation(h)

		return h, W

rather than using transposed Ws from encoding layers such as in session 3 lecture

for layer_i, n_output in enumerate(dimensions):
	# we'll use a variable scope again to help encapsulate our variables
	# This will simply prefix all the variables made in this scope
	# with the name we give it.
	with tf.variable_scope("decoder/layer/{}".format(layer_i)):

		# Now we'll grab the weight matrix we created before and transpose it
		# So a 3072 x 784 matrix would become 784 x 3072
		# or a 256 x 64 matrix, would become 64 x 256
		W = tf.transpose(Ws[layer_i])

		b = tf.get_variable(
			name='b',
			shape=[n_output],
			dtype=tf.float32,
			initializer=tf.constant_initializer(0.0))
    
		# Now we'll multiply our input by our transposed W matrix
		# and add the bias
		h = tf.nn.bias_add(
			name='h',
			value=tf.matmul(current_input, W),
			bias=b)

		# And then use a relu activation function on its output
		current_input = tf.nn.relu(h)

		# We'll also replace n_input with the current n_output, so that on the
		# next iteration, our new number inputs will be correct.
		n_input = n_output

Why? I am a rookie and don't understand. Please explain.

Conversion missing in session-3.ipynb

In the file "session-3.ipynb", the line

recon = utils.montage(clipped)

should be replaced with

recon = utils.montage(clipped).astype(np.uint8)

Otherwise the generated pictures will not display correctly.

Small potential error

Hello,

I see in your ipython notebook about VAEGANs, this in your variational step:

z_mu = tf.nn.tanh(utils.linear(h, n_code, name='mu')[0])
z_log_sigma = 0.5 * tf.nn.tanh(utils.linear(h, n_code, name='log_sigma')[0])

Why are you applying the tanh activation here?

Windows 10 Path issues

Hi,
I'm trialing the first course in audit mode before signing up for the full paid course.

I'm familiar with Docker, or at least I thought I was, but running into an issue getting the notebook started.

echo $(pwd) returns

E:\Source Control\AI\cadl

so then if I run the recommended command:

E:\Source Control\AI\cadl> docker run -it -p 8888:8888 -p 6006:6006 -v /$(pwd)/session-1:/notebooks --name tf cadl /bin/bash

I get an error:

C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error response from daemon: Mount denied:
The source path "/E:\Source Control\AI\cadl/session-0"
is not a valid Windows path.

Note:
I can get jupyter running aok by removing the $(pwd) [ie: docker run -it -p 8888:8888 -p 6006:6006 -v /session-1:/notebooks --name tf cadl /bin/bash ]
but
root@39c4441bcde8:/notebooks# ls
shows nothing as it's not in the correct subdirectory.
It does not show "README.md lecture-1.ipynb libs session-1.ipynb tests" but just an empty directory.
However, I can load the notebooks manually, but not sure how the subfolder content paths will be handled.

Any clues?

MacOS without docker

Hei!
I'm working on a Mac and (think) I don't really need to use docker, since I have all the libraries (including tensorflow) installed and also jupyter notebooks running.

I was thinking that you could add instructions about working with such a setup - or is there a specific reason to discourage this?

Thanks : )

Two typos in CADL/session-2/lecture-2.ipynb

When constructing the first bias, the comment says to use a constant value of 0 but the code initializes the value to 1

# For bias variables, we usually start with a constant value of 0.
B = tf.Variable(tf.constant([1], dtype=tf.float32), name='bias')

In the section where you reconstruct the astronaut image, the markdown says that you're going to redraw the image every 10 iterations, but the code actually uses 20 iterations:

"Every 10 iterations, we're going to draw the predicted image by evaluating the predicted image tensor, Y_pred, and giving it every location in the image to predict, the xs array."

if (it_i + 1) % 20 == 0:

Docker build failing

Running docker build -t cadl . fails during the tensorflow install with
"
Could not find a version that satisfies the requirement tensorflow==1.5.0 (from -r /requirements.txt (line 16)) (from versions: )
No matching distribution found for tensorflow==1.5.0 (from -r /requirements.txt (line 16))
"

lecture 4 : isn't there an issue with h,w ; in cell 31 ?

Cell 31 of the lecture notebook shows :

def total_variation_loss(x):
    h, w = x.get_shape().as_list()[1], x.get_shape().as_list()[1]

Shouldn't it be :

def total_variation_loss(x):
    h, w = x.get_shape().as_list()[1], x.get_shape().as_list()[2]

?

2 out of tree test failed from CADL-master\session-3\libs\vae.py

ERROR: Train an autoencoder on Celeb Net.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\Anaconda3\lib\site-packages\nose\case.py", line 198, in runTest
    self.test(*self.arg)
  File "D:\IDM\CADL-master\session-3\libs\vae.py", line 499, in test_celeb
    ckpt_name='./celeb.ckpt')
  File "D:\IDM\CADL-master\session-3\libs\vae.py", line 303, in train_vae
    shape=input_shape)
  File "D:\IDM\CADL-master\session-3\libs\dataset_utils.py", line 49, in create_input_pipeline
    files, capacity=len(files))
TypeError: object of type 'NoneType' has no len()
-------------------- >> begin captured stdout << ---------------------
Could not find celeb dataset under ./img_align_celeba/.
Try downloading the dataset from the "Aligned and Cropped" link located here (imgs/img_align_celeba.zip [1.34 GB]): http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html

--------------------- >> end captured stdout << ----------------------

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.