Files
audio-driven-face-animation/project/notebooks/notebook_tricks.ipynb
T

36 KiB

Import modules from parent directory

In [1]:
# add directory above current directory to path
import sys
sys.path.insert(0, '..')
In [2]:
# now we can import modules from parent directory
import train
import pipeline_modules

Define function to print object length with commas

In [3]:
showlen = lambda data: print(f"{len(data):,}")
showlen([0 for i in range(2395940)])
2,395,940

Create quick progress bars with tqdm

In [4]:
from tqdm import tqdm
import time

for i in tqdm(range(10)):
    time.sleep(1)
100%|█████████████████████████████████████████████████████████| 10/10 [00:10<00:00,  1.00s/it]

Prettier ipywidgets version of the progress bar specifically for the notebook environment

In [5]:
from tqdm.auto import tqdm

for i in tqdm(range(10)):
    time.sleep(1)
HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=10.0), HTML(value='')))

Beyond basic for loops, you can also use it in list comprehensions

In [6]:
some_list = [x**2 for x in tqdm(10*[0])]
HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=10.0), HTML(value='')))

If you’re iterating over a generator, tqdm won’t know the length and the progress bar will be more limited but if you know or can calculate the total length you can supply that as an argument

In [7]:
# generator expressions are surrounded by parenthesis ()
generator = (x**2 for x in [1, 2, 3, 4])
# print(next(generator))

some_list = [x for x in tqdm(generator, total=4)]
HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=4.0), HTML(value='')))

Jupyter Notebook Shortcuts

  • Esc will take you into command mode where you can navigate around your notebook with arrow keys.
  • While in command mode:
    • A to insert a new cell above the current cell, B to insert a new cell below.
    • M to change the current cell to Markdown, Y to change it back to code
    • D + D (press the key twice) to delete the current cell
    • Enter will take you from command mode back into edit mode for the given cell.
  • Shift + Tab will show you the Docstring (documentation) for the the object you have just typed in a code cell – you can keep pressing this short cut to cycle through a few modes of documentation.
  • Ctrl + Shift + - will split the current cell into two from where your cursor is.
  • Esc + O Toggle cell output.
  • Select Multiple Cells:
    • Shift + J or Shift + Down selects the next sell in a downwards direction. You can also select sells in an upwards direction by using Shift + K or Shift + Up.
    • Once cells are selected, you can then delete / copy / cut / paste / run them as a batch. This is helpful when you need to move parts of a notebook.
    • You can also use Shift + M to merge multiple cells.
In [1]:
from IPython.display import IFrame, HTML, YouTubeVideo
YouTubeVideo("ZbrRrXiWBKc")
Out [1]:
In [2]:
from ipywidgets import FloatSlider, interactive, IntSlider
In [3]:
def simple_ex(amplitude=2.0, phase=0.0):
    x = np.linspace(-2*np.pi, 2*np.pi, 1000)
    y = amplitude * np.sin(x + phase)
    plt.rcParams['figure.figsize'] = 8,6
    plt.figure()
    plt.plot(x, y)
    plt.xlim(-3, 3)
    plt.ylim(-2*np.pi, 2*np.pi)

In [4]:
amplitude_slider = FloatSlider(value=2.0, min=-10, max=10.0, step=.05)
phase_slider = FloatSlider(value=0.0, min=-np.pi, max=np.pi, step=.05)

w = interactive(simple_ex,
                amplitude=amplitude_slider,
                phase=phase_slider
               )
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-2d6992e82ad5> in <module>
      1 amplitude_slider = FloatSlider(value=2.0, min=-10, max=10.0, step=.05)
----> 2 phase_slider = FloatSlider(value=0.0, min=-np.pi, max=np.pi, step=.05)
      3 
      4 w = interactive(simple_ex,
      5                 amplitude=amplitude_slider,

NameError: name 'np' is not defined
In [7]:
import pandas as  pd
data = pd.read_csv('loan_train.csv')

import pandas_profiling
report = pandas_profiling.ProfileReport(data)

report
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-7-633a1b7025a6> in <module>
      1 import pandas as  pd
----> 2 data = pd.read_csv('loan_train.csv')
      3 
      4 import pandas_profiling
      5 report = pandas_profiling.ProfileReport(data)

~\Anaconda3\envs\gdl\lib\site-packages\pandas\io\parsers.py in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision)
    686     )
    687 
--> 688     return _read(filepath_or_buffer, kwds)
    689 
    690 

~\Anaconda3\envs\gdl\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
    452 
    453     # Create the parser.
--> 454     parser = TextFileReader(fp_or_buf, **kwds)
    455 
    456     if chunksize or iterator:

~\Anaconda3\envs\gdl\lib\site-packages\pandas\io\parsers.py in __init__(self, f, engine, **kwds)
    946             self.options["has_index_names"] = kwds["has_index_names"]
    947 
--> 948         self._make_engine(self.engine)
    949 
    950     def close(self):

~\Anaconda3\envs\gdl\lib\site-packages\pandas\io\parsers.py in _make_engine(self, engine)
   1178     def _make_engine(self, engine="c"):
   1179         if engine == "c":
-> 1180             self._engine = CParserWrapper(self.f, **self.options)
   1181         else:
   1182             if engine == "python":

~\Anaconda3\envs\gdl\lib\site-packages\pandas\io\parsers.py in __init__(self, src, **kwds)
   2008         kwds["usecols"] = self.usecols
   2009 
-> 2010         self._reader = parsers.TextReader(src, **kwds)
   2011         self.unnamed_cols = self._reader.unnamed_cols
   2012 

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader.__cinit__()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._setup_parser_source()

FileNotFoundError: [Errno 2] No such file or directory: 'loan_train.csv'
In [8]:
# print many outputs in the same cell!
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
In [9]:
%history -t
from IPython.display import IFrame, HTML, YouTubeVideo
YouTubeVideo("ZbrRrXiWBKc")
from ipywidgets import FloatSlider, interactive, IntSlider
def simple_ex(amplitude=2.0, phase=0.0):
    x = np.linspace(-2*np.pi, 2*np.pi, 1000)
    y = amplitude * np.sin(x + phase)
    plt.rcParams['figure.figsize'] = 8,6
    plt.figure()
    plt.plot(x, y)
    plt.xlim(-3, 3)
    plt.ylim(-2*np.pi, 2*np.pi)
amplitude_slider = FloatSlider(value=2.0, min=-10, max=10.0, step=.05)
phase_slider = FloatSlider(value=0.0, min=-np.pi, max=np.pi, step=.05)

w = interactive(simple_ex,
                amplitude=amplitude_slider,
                phase=phase_slider
               )
import pandas as  pd
data = pd.read_csv('loan_train.csv')

import pandas_profiling
report = pandas_profiling.ProfileReport(data)

report
import pandas as  pd
data = pd.read_csv('loan_train.csv')

import pandas_profiling
report = pandas_profiling.ProfileReport(data)

report
import pandas as  pd
data = pd.read_csv('loan_train.csv')

import pandas_profiling
report = pandas_profiling.ProfileReport(data)

report
# print many outputs in the same cell!
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
get_ipython().run_line_magic('history', '-t')
In [ ]: