I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part2-Plotting_Methods_Overview.ipynb".
The first task is:
Exercise 2.1:
Now let's try combining bar and fill_between to make a nice prediction of what will happen as this class progresses:
Can you reproduce the figure below?
<img src="images/exercise_2.1-bar_and_fill_between.png">
Can you write Python code for it?

%load exercises/2.1-bar_and_fill_between.py

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)

# Generate data...
y_raw = np.random.randn(1000).cumsum() + 15
x_raw = np.linspace(0, 24, y_raw.size)

# Get averages of every 100 samples...
x_pos = x_raw.reshape(-1, 100).min(axis=1)
y_avg = y_raw.reshape(-1, 100).mean(axis=1)
y_err = y_raw.reshape(-1, 100).ptp(axis=1)

bar_width = x_pos[1] - x_pos[0]

# Make a made up future prediction with a fake confidence
x_pred = np.linspace(0, 30)
y_max_pred = y_avg[0] + y_err[0] + 2.3 * x_pred
y_min_pred = y_avg[0] - y_err[0] + 1.2 * x_pred

# Just so you don't have to guess at the colors...
barcolor, linecolor, fillcolor = 'wheat', 'salmon', 'lightblue'

# Now you're on your own!


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part2-Plotting_Methods_Overview.ipynb".
The first task is:
In this case, we'd really like the white in the colormap to correspond to 0.  A quick way to do this is to make the vmin equal to the negative of the vmax.
Can you write Python code for it?

fig, ax = plt.subplots()
im = ax.imshow(data, cmap='seismic', interpolation='nearest',
               vmin=-2, vmax=2)
fig.colorbar(im)
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part2-Plotting_Methods_Overview.ipynb".
The first task is:
Input Data: 2D Arrays or Images
There are several options for plotting 2D datasets.  imshow, pcolor, and pcolormesh have a lot of overlap, at first glance.  (The example image below is meant to clarify that somewhat.)

In short, imshow can interpolate and display large arrays very quickly, while pcolormesh and pcolor are much slower, but can handle flexible (i.e. more than just rectangular) arrangements of cells.
We won't dwell too much on the differences and overlaps here.  They have overlapping capabilities, but different default behavior because their primary use-cases are a bit different (there's also matshow, which is imshow with different defaults).
Instead we'll focus on what they have in common.
imshow, pcolor, pcolormesh, scatter, and any other matplotlib plotting methods that map a range of data values onto a colormap will return artists that are instances of ScalarMappable.  In practice, what that means is a) you can display a colorbar for them, and b) they share several keyword arguments.
Colorbars
Let's add a colorbar to the figure to display what colors correspond to values of data we've plotted.
Can you write Python code for it?

from matplotlib.cbook import get_sample_data
data = np.load(get_sample_data('axes_grid/bivariate_normal.npy'))

fig, ax = plt.subplots()
im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im)
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part2-Plotting_Methods_Overview.ipynb".
The first task is:
Keep in mind that any plotting method in matplotlib returns the artists that are plotted. We'll use it again, particularly when we get to adding colorbars to images.
Filled Regions: ax.fill(x, y), fill_between(...), etc
<img src="images/fill_example.png">
Of these functions, ax.fill_between(...) is probably the one you'll use the most often.  In its most basic form, it fills between the given y-values and 0:
Can you write Python code for it?

np.random.seed(1)
y = np.random.randn(100).cumsum()
x = np.linspace(0, 10, 100)

fig, ax = plt.subplots()
ax.fill_between(x, y, color='lightblue')
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part2-Plotting_Methods_Overview.ipynb".
The first task is:
One note: In the last module in this tutorial, we'll briefly cover axes_grid, which is very useful for aligning colorbars and/or other axes with images displayed with imshow.
### Shared parameters for imshow, pcolormesh, contour, scatter, etc
As we mentioned earlier, any plotting method that creates a ScalarMappable will have some common kwargs.  The ones you'll use the most frequently are:

cmap : The colormap (or name of the colormap) used to display the input.  (We'll go over the different colormaps in the next section.)
vmin : The minimum data value that will correspond to the "bottom" of the colormap (defaults to the minimum of your input data).
vmax : The maximum data value that will correspond to the "top" of the colormap (defaults to the maximum of your input data).
norm : A Normalize instance to control how the data values are mapped to the colormap. By default, this will be a linear scaling between vmin and vmax, but other norms are available (e.g. LogNorm, PowerNorm, etc).

vmin and vmax are particularly useful.  Quite often, you'll want the colors to be mapped to a set range of data values, which aren't the min/max of your input data. For example, you might want a symmetric ranges of values around 0.
As an example of that, let's use a divergent colormap with the data we showed earlier. We'll also use interpolation="nearest" to "turn off" interpolation of the cells in the input dataset:
Can you write Python code for it?

from matplotlib.cbook import get_sample_data
data = np.load(get_sample_data('axes_grid/bivariate_normal.npy'))

fig, ax = plt.subplots()
im = ax.imshow(data, cmap='seismic', interpolation='nearest')
fig.colorbar(im)
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part2-Plotting_Methods_Overview.ipynb".
The first task is:
vmin and vmax are also very useful when we want multiple plots to share one colorbar, as our next exercise will do.
Exercise 2.2:
Can you reproduce the figure below?
<img src="images/exercise_2.2-vmin_vmax_imshow_and_colorbars.png">
Can you write Python code for it?

%load exercises/2.2-vmin_vmax_imshow_and_colorbars.py

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)

# Generate random data with different ranges...
data1 = np.random.random((10, 10))
data2 = 2 * np.random.random((10, 10))
data3 = 3 * np.random.random((10, 10))

# Set up our figure and axes...
fig, axes = plt.subplots(ncols=3, figsize=plt.figaspect(0.5))
fig.tight_layout() # Make the subplots fill up the figure a bit more...
cax = fig.add_axes([0.25, 0.1, 0.55, 0.03]) # Add an axes for the colorbar

# Now you're on your own!


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part3-HowToSpeakMPL.ipynb".
The first task is:
Annotations and Arrows
There are two ways one can place arbitrary text anywhere they want on a plot. The first is a simple text().  Then there is the fancier annotate() function that can help "point out" what you want to annotate.
Can you write Python code for it?

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
             arrowprops=dict(facecolor='black', shrink=0.05))

plt.ylim(-2, 2)
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part3-HowToSpeakMPL.ipynb".
The first task is:
Colormaps
Another very important property of many figures is the colormap. The job of a colormap is to relate a scalar value to a color. In addition to the regular portion of the colormap, an "over", "under" and "bad" color can be optionally defined as well. NaNs will trigger the "bad" part of the colormap.
As we all know, we create figures in order to convey information visually to our readers. There is much care and consideration that have gone into the design of these colormaps. Your choice in which colormap to use depends on what you are displaying. In mpl, the "jet" colormap has historically been used by default, but it will often not be the colormap you would want to use. Much discussion has taken place on the mailing lists with regards to what colormap should be default. The upcoming v2.0 release of matplotlib will take on a new default colormap along with some other stylistic changes to the defaults. The defaults will be discussed this week during SciPy 2015.
I want to acknowedge Nicolas Rougier and Tony Yu for putting significant effort in educating users in proper colormap selections. Here is the full gallery of all the pre-defined colormaps, organized by the types of data they are usually used for.
Can you write Python code for it?

%load http://matplotlib.org/mpl_examples/color/colormaps_reference.py  # For those with v1.2 or higher

"""
Reference for colormaps included with Matplotlib.

This reference example shows all colormaps included with Matplotlib. Note that
any colormap listed here can be reversed by appending "_r" (e.g., "pink_r").
These colormaps are divided into the following categories:

Sequential:
    These colormaps are approximately monochromatic colormaps varying smoothly
    between two color tones---usually from low saturation (e.g. white) to high
    saturation (e.g. a bright blue). Sequential colormaps are ideal for
    representing most scientific data since they show a clear progression from
    low-to-high values.

Diverging:
    These colormaps have a median value (usually light in color) and vary
    smoothly to two different color tones at high and low values. Diverging
    colormaps are ideal when your data has a median value that is significant
    (e.g.  0, such that positive and negative values are represented by
    different colors of the colormap).

Qualitative:
    These colormaps vary rapidly in color. Qualitative colormaps are useful for
    choosing a set of discrete colors. For example::

        color_list = plt.cm.Set3(np.linspace(0, 1, 12))

    gives a list of RGB colors that are good for plotting a series of lines on
    a dark background.

Miscellaneous:
    Colormaps that don't fit into the categories above.

"""
import numpy as np
import matplotlib.pyplot as plt

cmaps = [('Sequential',     ['binary', 'Blues', 'BuGn', 'BuPu', 'gist_yarg',
                             'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd',
                             'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu',
                             'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']),
         ('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool', 'copper',
                             'gist_gray', 'gist_heat', 'gray', 'hot', 'pink',
                             'spring', 'summer', 'winter']),
        ...


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part3-HowToSpeakMPL.ipynb".
The first task is:
Exercise 3.2
Try out some different markers and colors
Can you write Python code for it?

%load exercises/3.2-markers.py

t = np.arange(0.0, 5.0, 0.2)
plt.plot(t, t, , t, t**2, , t, t**3, )
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part3-HowToSpeakMPL.ipynb".
The first task is:
Hatches
A Patch object can have a hatching defined for it.

/   - diagonal hatching
\   - back diagonal
|   - vertical
-   - horizontal
+   - crossed
x   - crossed diagonal
o   - small circle
O   - large circle (upper-case 'o')
.   - dots
*   - stars

Letters can be combined, in which case all the specified
hatchings are done.  If same letter repeats, it increases the
density of hatching of that pattern.
Ugly tie contest!
Can you write Python code for it?

bars = plt.bar([1, 2, 3, 4], [10, 12, 15, 17])
plt.setp(bars[0], hatch='x', facecolor='w')
plt.setp(bars[1], hatch='xx-', facecolor='orange')
plt.setp(bars[2], hatch='+O.', facecolor='c')
plt.setp(bars[3], hatch='*', facecolor='y')
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part3-HowToSpeakMPL.ipynb".
The first task is:
It is a bit confusing, but the line styles mentioned above are only valid for lines. Whenever you are dealing with the linestyles of the edges of "Patch" objects, you will need to use words instead of the symbols. So "solid" instead of "-", and "dashdot" instead of "-.". This issue will be fixed for the v2.1 release and allow these specifications to be used interchangably.
Can you write Python code for it?


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part3-HowToSpeakMPL.ipynb".
The first task is:
Linestyles
Line styles are about as commonly used as colors. There are a few predefined linestyles available to use. Note that there are some advanced techniques to specify some custom line styles. Here is an example of a custom dash pattern.
linestyle          | description
-------------------|------------------------------
'-'                | solid
'--'               | dashed
'-.'               | dashdot
':'                | dotted
'None'             | draw nothing
' '                | draw nothing
''                 | draw nothing
Also, don't mix up ".-" (line with dot markers) and "-." (dash-dot line) when using the plot function!
Can you write Python code for it?


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part3-HowToSpeakMPL.ipynb".
The first task is:
Plot attributes
With just about any plot you can make, there are many attributes that can be modified to make the lines and markers suit your needs. Note that for many plotting functions, matplotlib will cycle the colors for each dataset you plot. However, you are free to explicitly state which colors you want used for which plots. For the plt.plot() and plt.scatter() functions, you can mix the specification for the colors, linestyles, and markers in a single string.
Can you write Python code for it?

t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part3-HowToSpeakMPL.ipynb".
The first task is:
Transforms
The topic of transforms in matplotlib, that is the ability to map the coordinates specified by your data to the coordinates of your figure, is very advanced and will not be covered in this tutorial. For those who are interested in learning about them, see the transformation tutorial. For those who are really daring, there are the developer guides to transforms and scales. While most users will never, ever need to understand matplotlib transforms to the level described in those links, it is important to be aware of them, and their critical role in figure-making.
In a figure, there are four coordinate systems: display, figure, axes, and data. Transforms are used to convert coordinates in one system into another system for various uses. This is how matplotlib knows exactly where to place the ticks and ticklabels, even when you change the axis limits. The ticker says that the tick and label "1.5", for example, are to go at data x-coordinate 1.5. The transform says that location is at 0.4 in axes x-coordinate space. Meanwhile, the xlabel of "Distance" is placed at axes x-coordinate space of 0.5 (half-way). Meanwhile, a legend might be placed at a location relative to the figure coordinates.
Furthermore, the transform system is what is used to allow various scales to work, such as log scales. The transform system is what is used to make the polar plots work seamlessly. Whether you realize it or not, you use the transforms system in matplotlib all the time. Everything drawn in matplotlib has a transform associated with it. Most of the time, you will never notice this, and will happily operate within the data coordinate system. But when you want to do some more advanced plots, with some eye-catching visual tricks, the transform system will be there for you.
Managing the unmanagable -- Introducing matplotlibrc
Matplotlib's greatest strength is its ability to give you complete control over every single aspect of your plots and figures. Matplotlib's second greatest strength is its ability to take as much...
Can you write Python code for it?


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part3-HowToSpeakMPL.ipynb".
The first task is:
When colormaps are created in mpl, they get "registered" with a name. This allows one to specify a colormap to use by name.
Can you write Python code for it?

fig, (ax1, ax2) = plt.subplots(1, 2)
z = np.random.random((10, 10))
ax1.imshow(z, interpolation='none', cmap='gray')
ax2.imshow(z, interpolation='none', cmap='coolwarm')
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part3-HowToSpeakMPL.ipynb".
The first task is:
| Property               | Value Type
|------------------------|-------------------------------------------------
|alpha                   | float
|color or c              | any matplotlib color
|dash_capstyle           | ['butt', 'round' 'projecting']
|dash_joinstyle          | ['miter' 'round' 'bevel']
|dashes                  | sequence of on/off ink in points
|drawstyle               | [ ‘default’ ‘steps’ ‘steps-pre’
|                        |   ‘steps-mid’ ‘steps-post’ ]
|linestyle or ls         | [ '-' '--' '-.' ':' 'None' ' ' '']
|                        | and any drawstyle in combination with a
|                        | linestyle, e.g. 'steps--'.
|linewidth or lw         | float value in points
|marker                  | [ 0 1 2 3 4 5 6 7 'o' 'd' 'D' 'h' 'H'
|                        |  '' 'None' ' ' None '8' 'p' ','
|                        |  '+' 'x' '.' 's' '*' '_' '|'
|                        |  '1' '2' '3' '4' 'v' '<' '>' '^' ]
|markeredgecolor or mec  | any matplotlib color
|markeredgewidth or mew  | float value in points
|markerfacecolor or mfc  | any matplotlib color
|markersize or ms        | float
|solid_capstyle          | ['butt' 'round' 'projecting']
|solid_joinstyle         | ['miter' 'round' 'bevel']
|visible                 | [True False]
|zorder                  | any number
Exercise 3.3
Make a plot that has a dotted red line, with large yellow diamond markers that have a green edge
Can you write Python code for it?

%load exercises/3.3-properties.py

t = np.arange(0.0, 5.0, 0.1)
a = np.exp(-t) * np.cos(2*np.pi*t)
plt.plot(t, a, )
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part4-Limits_Legends_and_Layouts.ipynb".
The first task is:
A common "gotcha" is that the labels are not automatically adjusted to avoid overlapping those of another subplot. Matplotlib does not currently have any sort of robust layout engine, as it is a design decision to minimize the amount of "magic" that matplotlib performs. We intend to let users have complete, 100% control over their plots. LaTeX users would be quite familiar with the amount of frustration that can occur with placement of figures in their documents.
That said, there have been some efforts to develop tools that users can use to help address the most common compaints. The "Tight Layout" feature, when invoked, will attempt to resize margins, and subplots so that nothing overlaps.
If you have multiple subplots, and want to avoid overlapping titles/axis labels/etc, fig.tight_layout is a great way to do so:
Can you write Python code for it?

def example_plot(ax):
    ax.plot([1, 2])
    ax.set_xlabel('x-label', fontsize=16)
    ax.set_ylabel('y-label', fontsize=8)
    ax.set_title('Title', fontsize=24)

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)

# Try enabling fig.tight_layout to compare...
#fig.tight_layout()

plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part4-Limits_Legends_and_Layouts.ipynb".
The first task is:
A commonly-asked question is "How do I plot non-numerical categories?"
The easiest way to do this is to "fake" the x-values and then change the tick labels to reflect the category.
For example:
Can you write Python code for it?

data = [('apples', 2), ('oranges', 3), ('peaches', 1)]
fruit, value = zip(*data)

fig, ax = plt.subplots()
x = np.arange(len(fruit))
ax.bar(x, value, align='center', color='gray')
ax.set(xticks=x, xticklabels=fruit)
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part4-Limits_Legends_and_Layouts.ipynb".
The first task is:
Axis Spines
Spines are the axis lines for a plot. Each plot can have four spines: "top", "bottom", "left" and "right". By default, they are set so that they frame the plot, but they can be individually positioned and configured via the set_position() method of the spine. Here are some different configurations.
Can you write Python code for it?

fig, ax = plt.subplots()
ax.plot([-2, 2, 3, 4], [-10, 20, 25, 5])
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')  # no ticklines at the top
ax.spines['right'].set_visible(False)
ax.yaxis.set_ticks_position('left')  # no ticklines on the right

# "outward"
# Move the two remaining spines "out" away from the plot by 10 points
ax.spines['bottom'].set_position(('outward', 10))
ax.spines['left'].set_position(('outward', 10))

# "data"
# Have the spines stay intersected at (0,0)
#ax.spines['bottom'].set_position(('data', 0))
#ax.spines['left'].set_position(('data', 0))

# "axes"
# Have the two remaining spines placed at a fraction of the axes
#ax.spines['bottom'].set_position(('axes', 0.75))
#ax.spines['left'].set_position(('axes', 0.25))

plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part4-Limits_Legends_and_Layouts.ipynb".
The first task is:
Dealing with the boundaries: Layout, ticks, spines, etc
One key thing we haven't talked about yet is all of the annotation on the outside of the axes, the borders of the axes, and how to adjust the amount of space around the axes.  We won't go over every detail, but this next section should give you a reasonable working knowledge of how to configure what happens around the edges of your axes.
Ticks, Tick Lines, Tick Labels and Tickers
This is a constant source of confusion:

A Tick is the location of a Tick Label.
A Tick Line is the line that denotes the location of the tick.
A Tick Label is the text that is displayed at that tick.
A Ticker automatically determines the ticks for an Axis and formats the tick labels.

tick_params() is often used to help configure your tickers.
Can you write Python code for it?

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 25, 30])

# Manually set ticks and tick labels *on the x-axis* (note ax.xaxis.set, not ax.set!)
ax.xaxis.set(ticks=range(1, 5), ticklabels=[3, 100, -12, "foo"])

# Make the y-ticks a bit longer and go both in and out...
ax.tick_params(axis='y', direction='inout', length=10)

plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part4-Limits_Legends_and_Layouts.ipynb".
The first task is:
Exercise 4.1
Once again, let's use a bit of what we've learned.  Try to reproduce the following figure:
<img src="images/exercise_4-1.png">
Hint: You'll need to combine ax.axis(...) and ax.margins(...).  Here's the data and some code to get you started:
Can you write Python code for it?

%load exercises/4.1-legends_and_scaling.py

import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 2 * np.pi, 150)
x1, y1 = np.cos(t), np.sin(t)
x2, y2 = 2 * x1, 2 * y1

colors = ['darkred', 'darkgreen']

# Try to plot the two circles, scale the axes as shown and add a legend
# Hint: it's easiest to combine `ax.axis(...)` and `ax.margins(...)` to scale the axes


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part4-Limits_Legends_and_Layouts.ipynb".
The first task is:
GridSpec
Under the hood, matplotlib utilizes GridSpec to lay out the subplots. While plt.subplots() is fine for simple cases, sometimes you will need more advanced subplot layouts. In such cases, you should use GridSpec directly. GridSpec is outside the scope of this tutorial, but it is handy to know that it exists. Here is a guide on how to use it.
Sharing axes
There will be times when you want to have the x axis and/or the y axis of your subplots to be "shared". Sharing an axis means that the axis in one or more subplots will be tied together such that any change in one of the axis changes all of the other shared axes. This works very nicely with autoscaling arbitrary datasets that may have overlapping domains. Furthermore, when interacting with the plots (panning and zooming), all of the shared axes will pan and zoom automatically.
Can you write Python code for it?


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part4-Limits_Legends_and_Layouts.ipynb".
The first task is:
Limits, Legends, and Layouts
In this section, we'll focus on what happens around the edges of the axes:  Ticks, ticklabels, limits, layouts, and legends.
Limits and autoscaling
By default, matplotlib will attempt to determine limits for you that encompasses all the data you have plotted.  This is the "autoscale" feature. For line and image plots, the limits are not padded, while plots such as scatter plots and bar plots are given some padding.
Can you write Python code for it?


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part4-Limits_Legends_and_Layouts.ipynb".
The first task is:
Manually setting only one limit
Another trick with limits is to specify only half of a limit. When done after a plot is made, this has the effect of allowing the user to anchor a limit while letting matplotlib autoscale the rest of it.
Can you write Python code for it?


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part4-Limits_Legends_and_Layouts.ipynb".
The first task is:
Subplot Spacing
The spacing between the subplots can be adjusted using fig.subplots_adjust(). Play around with the example below to see how the different arguments affect the spacing.
Can you write Python code for it?

fig, axes = plt.subplots(2, 2, figsize=(9, 9))
fig.subplots_adjust(wspace=0.5, hspace=0.3,
                    left=0.125, right=0.9,
                    top=0.9,    bottom=0.1)
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part4-Limits_Legends_and_Layouts.ipynb".
The first task is:
ax.axis(...)
The ax.axis(...) method is a convienent way of controlling the axes limits and enabling/disabling autoscaling.
If you ever need to get all of the current plot limits, calling ax.axis() with no arguments will return the xmin/max/etc:
xmin, xmax, ymin, ymax = ax.axis()

If you'd like to manually set all of the x/y limits at once, you can use ax.axis for this, as well (note that we're calling it with a single argument that's a sequence, not 4 individual arguments):
ax.axis([xmin, xmax, ymin, ymax])

However, you'll probably use axis mostly with either the "tight" or "equal" options. There are other options as well; see the documentation for full details.  In a nutshell, though:

tight: Set axes limits to the exact range of the data
equal: Set axes scales such that one cm/inch in the y-direction is the same as one cm/inch in the x-direction. (In matplotlib terms, this sets the aspect ratio of the plot to 1.  That doesn't mean that the axes "box" will be square, though!)

And as an example:
Can you write Python code for it?

fig, axes = plt.subplots(nrows=3)

for ax in axes:
    ax.plot([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1])

axes[0].set_title('Normal Autoscaling', y=0.7, x=0.8)

axes[1].set_title('ax.axis("tight")', y=0.7, x=0.8)
axes[1].axis('tight')

axes[2].set_title('ax.axis("equal")', y=0.7, x=0.8)
axes[2].axis('equal')

plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part4-Limits_Legends_and_Layouts.ipynb".
The first task is:
ax.margins(...)
If you'd like to add a bit of "padding" to a plot, ax.margins(<some_small_fraction>) is a very handy way to do so.  Instead of choosing "even-ish" numbers as min/max ranges for each axis, margins will make matplotlib calculate the min/max of each axis by taking the range of the data and adding on a fractional amount of padding.
As an example: (Note that the ranges for the scatter example actually shrink slightly in this case)
Can you write Python code for it?


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part5-Artists.ipynb".
The first task is:
Collections
In addition to the Figure and Axes containers, there is another special type of container called a Collection. A Collection usually contains a list of primitives of the same kind that should all be treated similiarly. For example, a CircleCollection would have a list of Circle objects all with the same color, size, and edge width. Individual values for artists in the collection can also be set.
Can you write Python code for it?

from matplotlib.collections import LineCollection
fig, ax = plt.subplots(1, 1)
lc = LineCollection([[(4, 10), (16, 10)],
                     [(2, 2), (10, 15), (6, 7)],
                     [(14, 3), (1, 1), (3, 5)]])
lc.set_color('r')
lc.set_linewidth(5)
ax.add_collection(lc)
ax.set_xlim(0, 18)
ax.set_ylim(0, 18)
plt.show()

# Now show how to set individual properties in a collection
fig, ax = plt.subplots(1, 1)
lc = LineCollection([[(4, 10), (16, 10)],
                     [(2, 2), (10, 15), (6, 7)],
                     [(14, 3), (1, 1), (3, 5)]])
lc.set_color(['r', 'blue', (0.2, 0.9, 0.3)])
lc.set_linewidth([4, 3, 6])
ax.add_collection(lc)
ax.set_xlim(0, 18)
ax.set_ylim(0, 18)
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part5-Artists.ipynb".
The first task is:
Containers are objects like Figure and Axes. Containers are given primitives to draw. The plotting functions we discussed back in Parts 1 & 2 are convenience functions that generate these primitives and places them into the appropriate containers. In fact, most of those functions will return artist objects (or a list of artist objects) as well as store them into the appropriate axes container.
As discussed in Part 3, there is a wide range of properties that can be defined for your plots.  These properties are processed and passed down to the primitives, for your convenience. Ultimately, you can override anything you want just by directly setting a property to the object itself.
Can you write Python code for it?


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part5-Artists.ipynb".
The first task is:
Exercise 5.1
Give yourselves 4 gold stars!
Hint: StarPolygonCollection
Can you write Python code for it?

%load exercises/5.1-goldstar.py

from matplotlib.collections import StarPolygonCollection

fig, ax = plt.subplots(1, 1)

collection = StarPolygonCollection(5,
                                   offsets=[(0.5, 0.5)],
                                   transOffset=ax.transData)
ax.add_collection(collection)
plt.show()


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part5-Artists.ipynb".
The first task is:
To see what properties are set for an artist, use getp()
Can you write Python code for it?

fig = plt.figure()
print(plt.getp(fig.patch))


I am working on the file "MatplotLib Pynotebooks/AnatomyOfMatplotlib-Part6-mpl_toolkits.ipynb".
The first task is:
axes_grid1
This module was originally intended as a collection of helper classes to ease the displaying of (possibly multiple) images with matplotlib. Some of the functionality has come to be useful for non-image plotting as well. Some classes deals with the sizing and positioning of multiple Axes relative to each other (ImageGrid, RGB Axes, and AxesDivider). The ParasiteAxes allow for the plotting of multiple datasets in the same axes, but with each their own x or y scale. Also, there is the AnchoredArtist that can be used to anchor particular artist objects in place.
One can get a sense of the neat things that can be done with this toolkit by browsing through its user guide linked above. There is one particular feature that is an absolute must-have for me -- automatic allocation of space for colorbars.
Can you write Python code for it?

from mpl_toolkits.axes_grid1 import AxesGrid
fig = plt.figure()
grid = AxesGrid(fig, 111, # similar to subplot(111)
                nrows_ncols = (2, 2),
                axes_pad = 0.2,
                share_all=True,
                label_mode = "L",  # similar to "label_outer"
                cbar_location = "right",
                cbar_mode="single",
               )

extent = (-3,4,-4,3)
for i in range(4):
    im = grid[i].imshow(Z, extent=extent, interpolation="nearest")

grid.cbar_axes[0].colorbar(im)
plt.show()


I am working on the file "Matplotlib e Seaborn/Modulo 2 - Scatter Plot + Text.ipynb".
The first task is:
Adicionando mais um dataset
Can you write Python code for it?

plt.figure(figsize=(12, 8))

plt.scatter(d1.x, d1.y, c="darkorange", s=100, marker="s", label="golden squares")
plt.scatter(d2.x, d2.y, c="purple", s=200, marker="*", label="purple stars")

plt.legend()  # captura os nomes das series em 'label'

plt.show()


I am working on the file "Matplotlib e Seaborn/Modulo 2 - Scatter Plot + Text.ipynb".
The first task is:
Aplicando 'fontdict' em outros textos
Can you write Python code for it?

plt.figure(figsize=(12,8))

plt.xlim(-10, 10)
plt.ylim(-10, 10)

font = {
    'family': 'serif',
    'color':  'darkred',
    'weight': 'bold',
    'size': 26,
}

plt.text(x=-5, y=-2, s="Texto a ser mostrado", fontdict=font)

plt.xlabel("X Axis", fontdict=font)
plt.ylabel("Y Axis", fontdict=font)

plt.show()


I am working on the file "Matplotlib e Seaborn/Modulo 2 - Scatter Plot + Text.ipynb".
The first task is:
Desafio
Objetivo:
Visualizar dados de um problema de classificação de produtos de e-commerce projetados em 2D.
Dataset:
Can you write Python code for it?

""" Tamanho do Dataset """
df = pd.read_csv(
    os.path.join("data", "produtos_ecommerce.csv"),
    sep=";",
    encoding="utf-8"
)
df[["coord_x", "coord_y"]] = df[["coord_x", "coord_y"]].astype(float)
df.head()

""" Tamanho da tabela """
df.shape

""" Contagem de Produtos por Categoria"""
df.label.value_counts()


I am working on the file "Matplotlib e Seaborn/Modulo 2 - Scatter Plot + Text.ipynb".
The first task is:
Facilidades no Pandas
Can you write Python code for it?

""" inicialização como antes """
plt.figure(figsize=(12, 8))

""" plt.gca() retorna a janela mais recente """
d1.plot(
    ax=plt.gca(),
    kind="scatter",
    x="x", y="y",
    c="k",
    s=100,
    marker="o",
    label="black circles"
)

d2.plot(
    ax=plt.gca(),
    kind="scatter",
    x="x", y="y",
    c="cyan",
    s=200,
    marker="v",
    label="cyan triangles"
)

""" visualizar com legenda """
plt.legend()
plt.show()


I am working on the file "Matplotlib e Seaborn/Modulo 2 - Scatter Plot + Text.ipynb".
The first task is:
Scatter Plot
Variáveis
Can you write Python code for it?

""" Dataset com Distribuição Normal 2D """
d1 = pd.DataFrame(
    columns=["x", "y"],
    data=np.random.randn(20, 2) + np.array([5, 5])
)

d2 = pd.DataFrame(
    columns=["x", "y"],
    data=np.random.randn(30, 2) + np.array([1, 2])
)


I am working on the file "Matplotlib e Seaborn/Modulo 2 - Scatter Plot + Text.ipynb".
The first task is:
Text Plot
Posicionando Texto na Visualização
Can you write Python code for it?

""" Plot Simples """
plt.figure(figsize=(12,8))

plt.text(x=0.5, y=0.5, s="Texto a ser mostrado")

plt.show()

""" Plot Simples """
plt.figure(figsize=(12,8))

plt.text(x=1, y=1, s="Texto a ser mostrado")

plt.show()


I am working on the file "Matplotlib e Seaborn/Modulo 2 - Scatter Plot + Text.ipynb".
The first task is:
Visualização com Pandas + Matplotlib
Can you write Python code for it?

""" Visualização por Scatter Plot """
pd.plotting.scatter_matrix(df, s=400, color="red", figsize=(13,13))
plt.show()


I am working on the file "Matplotlib e Seaborn/Modulo 2 - Scatter Plot + Text.ipynb".
The first task is:
Visualização com Pandas + Seaborn
Can you write Python code for it?

""" Visualização por Scatter Plot """
sns.pairplot(df)
plt.show()


I am working on the file "Matplotlib e Seaborn/Modulo 2 - Scatter Plot + Text.ipynb".
The first task is:
[ B ]: Visualizar uma amostra com o texto
Plotar duas categorias, apenas 10 produtos de cada, usando o campo product para plotar também o texto.
A figura deve manter a legenda mostrando apenas as duas categorias e suas cores.
Can you write Python code for it?


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
Box Plot
Matplotlib Puro
Uma Série
Can you write Python code for it?

""" default: vertical """
plt.figure(figsize=(15,10))

plt.boxplot(df.S1)

plt.show()

""" horizontal pra variar """

plt.figure(figsize=(15,10))

plt.boxplot(df.S1, vert=False)

plt.show()


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
Dataset
Can you write Python code for it?

""" DataFrame contendo 5 Séries com Distribuições Normais distintas """
df = pd.DataFrame(
    columns=["S1", "S2", "S3", "S4", "S5"],
    data=(
        np.random.randn(100, 5) * np.array([10, 15, 50, 100, 200]) + np.array([0, 5, 30, 30, 50])
    )
)


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
Desafio
Objetivo:
Visualizar uma Distribuição Normal usando Histogramas e Box Plot
Dataset:
Can you write Python code for it?

serie_original = pd.Series(np.random.randn(900)) * 32 + 230
outliers = pd.Series(np.random.randn(100)) * 320 + 230


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
Histogram Plot
Matplotlib Puro
Can you write Python code for it?

""" Histograma sem Normalização """
plt.figure(figsize=(12,8))

plt.hist(df.S1, bins=10)

plt.show()

""" Histograma com Normalização """
plt.figure(figsize=(12,8))

plt.hist(df.S1, bins=10, normed=True)

plt.show()
df.S1.describe()

""" Histograma de duas Séries """
plt.figure(figsize=(12,8))

plt.hist(df[["S1", "S2"]], bins=10, normed=True)

plt.show()
df[["S1", "S2"]].describe()

""" Histograma de mais de duas Séries """
plt.figure(figsize=(12,8))

plt.hist(df, bins=10, normed=True)

plt.show()
df.describe()


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
Mais Séries
Can you write Python code for it?

plt.figure(figsize=(15,10))

plt.boxplot(df.T)

plt.show()


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
Observação:
A visualização do histograma de várias séries é muito confusa usando o matplotlib sozinho. Às vezes é preferível usar uma visualização em uma janela só, como mostrada abaixo:
Can you write Python code for it?

plt.figure(figsize=(15,10))

plt.hist(df.S1, bins=10, normed=True, color="blue", alpha=0.5, label="S1")
plt.hist(df.S2, bins=10, normed=True, color="red", alpha=0.5, label="S2")
plt.legend()
plt.show()


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
Outliers!!!
Can you write Python code for it?

tmp1 = df.copy()
tmp2 = df[["S5", "S5", "S5", "S5", "S5"]]
tmp2.columns = tmp1.columns  # append com colunas iguais não cria NaNs

tmp = tmp1.append(tmp2)

plt.figure(figsize=(15,10))

tmp.plot(kind="box", figsize=(15,10))

plt.show()
tmp.describe(percentiles=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])


tmp1 = df[["S1", "S2"]]
tmp2 = df[["S3", "S3"]]
tmp2.columns = tmp1.columns  # append com colunas iguais não cria NaNs

tmp = tmp1.append(tmp2)

plt.figure(figsize=(15,10))

plt.boxplot(tmp.T)

plt.show()
tmp.describe(percentiles=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
Pandas for the Go!
Todos Juntos e com Labels!
Can you write Python code for it?


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
Parte 2
Juntar a Série Original com os Outliers para criar uma Série Contaminada. Visualizar a nova série.
Depois, propor cortes na série para eliminar os outliers sem perder muitos dados de dentro da distribuição.
Em cada corte executado, visualizar a distribuição e as medidas de constrole da distribuição.
Can you write Python code for it?


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
Usando Pandas
Can you write Python code for it?

""" Uma Série """
df.S1.hist(bins=10, normed=True, figsize=(12,8))

plt.show()

""" Histograma de duas Séries """
df[["S1", "S2"]].hist(bins=10, normed=True, figsize=(12,8))

plt.show()
df[["S1", "S2"]].describe()

""" Histograma de mais de duas Séries """
df.hist(bins=10, figsize=(12,8))

plt.show()
df.describe()


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
Usando Seaborn
Can you write Python code for it?

""" Uma Série """
plt.figure( figsize=(12,8))

sns.distplot(df.S1)

plt.show()


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
[ A ] Exploração
Parte 1
Usar Histograma e Box Plot para visualizar:
* a Série Original
* os Outliers
* a Série Original e os Outliers na mesma janela
Can you write Python code for it?


I am working on the file "Matplotlib e Seaborn/Modulo 3 - Histogramas + Box Plot.ipynb".
The first task is:
[ B ]
Criar um plot de duas janelas empilhadas na vertical, onde:
* A janela de cima é um Box Plot horizontal
* A Janela de baixo é um histograma
As duas janelas devem compartilhar o eixo horixontal, de forma que os atributos da distribuição estejam alinhados.
Can you write Python code for it?


I am working on the file "Matplotlib--osy_mrizka.ipynb".
The first task is:
Logaritmická osa
Can you write Python code for it?

plot([23, 456, 676, 89, 906, 34, 2345])
yscale('log')
grid(b=True, which='major', color='b', linestyle='-')
grid(b=True, which='minor', color='r', linestyle='--')


I am working on the file "Matplotlib--osy_mrizka.ipynb".
The first task is:
Výce grafů v jednom obrázku

http://matplotlib.org/examples/pylab_examples/subplots_demo.html
http://matplotlib.org/users/gridspec.html
http://matplotlib.org/examples/pylab_examples/subplots_adjust.html
Can you write Python code for it?

fig=figure()

ax1=subplot(221)
title('abc')
grid()
hist(rand(1000),50)

ax2=subplot(222)
title('abc')
grid()

ax3=subplot(223)
title('abc')
grid()

# zvětším prostor mezi grafy
tight_layout()

# pokud chci mít větší kontrolu použiji
# subplots_adjust(bottom=-1, right=0.8, top=0.9)

ax=subplot(111)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

plot(X, C, color="blue", linewidth=2.5, linestyle="-",label='cosinus')
plot(X, S, color="red", linewidth=2.5, linestyle="-", label='sinus')

#ax = gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

xlim(X.min()*1.1, X.max()*1.1)
xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
       [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

ylim(C.min()*1.1,C.max()*1.1)
yticks([-1, 0, +1],
       [r'$-1$', r'$0$', r'$+1$'])

# savefig("../figures/exercice_7.png",dpi=72)
#show()
grid()
legend(loc='upper left')

subplot(111)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plot(X, S, color="red", linewidth=2.5, linestyle="-",  label="sine")

ax = gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

xlim(X.min()*1.1, X.max()*1.1)
xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
       [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

ylim(C.min()*1.1,C.max()*1.1)
yticks([-1, +1],
       [r'$-1$', r'$+1$'])

legend(loc='upper left')

t = 2*np.pi/3
plot([t,t],[0,np.cos(t)],
     color ='blue',  linewidth=1.5, linestyle="--")
scatter([t,],[np.cos(t),], 50, color ='blue')
annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', xy=(t, np.sin(t)),  xycoords='data',
      ...


I am working on the file "Matplotlib--popisky,znacky.ipynb".
The first task is:
Graf v grafu
Can you write Python code for it?

import numpy as np
from matplotlib import pyplot as plt
from scipy import randn, convolve

#data
t = np.arange(0.0, 20.0, 0.001)
r = np.exp(-t[:1000]/0.05)
x = randn(len(t))
s = convolve(x,r)[:len(x)]*0.001
theta = 2 * np.pi * t
#
fig = plt.figure(figsize=(7, 6))
#main
plt.plot(t, s)
plt.axis([0, 1, np.amin(s), 2.5*np.amax(s)])
plt.xlabel('xlabel')
plt.ylabel('ylabel')
#polar
ax = fig.add_axes([0.2, 0.47, 0.30, 0.40], polar=True, axisbg='yellow')
ax.plot(theta, t, color='blue', lw=3)
ax.set_rmax(1.0)
plt.grid(True)

plt.show()


I am working on the file "Matplotlib--popisky,znacky.ipynb".
The first task is:
Ja na text, šipky, popisky

boxstyle (když chci text do rámečku): http://matplotlib.org/api/artist_api.html?highlight=boxstyle#matplotlib.patches.BoxStyle
FancyArroPatch: http://matplotlib.org/api/artist_api.html?highlight=fancyarrowpatch#matplotlib.patches.FancyArrowPatch
Can you write Python code for it?

import matplotlib.patches as mpp

ax=subplot(111)
axis([0,300, 0,400])
grid(True,'both')

# linestyle or ls 	[‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’]
c = mpp.FancyArrowPatch((50,300), (150,200), arrowstyle='<|-|>',
                        lw=2, linestyle='dotted', mutation_scale=20,
                        color='green', label='popisek', alpha=0.5)
ax.add_patch(c)
legend()
text(90,240,'BB',size=32)

# i anntate použíévá class matplotlib.patches.FancyArrowPatch

annotate('Ahoj', xy=(200,150),size=20, xytext=(250,200),
          arrowprops=dict(arrowstyle="->",
                          connectionstyle="arc3,rad=0.2",
                          fc="w")
         )

annotate('Q', xy=(100,100),size=20, xytext=(150,100),
          arrowprops=dict(arrowstyle="->",connectionstyle="arc3,rad=0", ),
         )
annotate('B', xy=(200,100),size=20, xytext=(150,100),
          arrowprops=dict(arrowstyle="->",connectionstyle='bar') ,
          horizontalalignment='right', verticalalignment='top'
         )

####################
# Bubliny
bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="cyan", ec="b", lw=2)
t = ax.text(150,300, "Direction", ha="center", va="center", rotation=45,
            size=15,
            bbox=bbox_props)

bbox_props = dict(boxstyle="round,pad=0.3", fc=".9", ec="b", lw=2)
t=annotate(u'Carsonův odhad', xy=(150,120),size=16, xytext=(40,20),bbox=bbox_props,
          arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=-1.5", fc="w")
         )

ax=subplot(111)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plot(X, S, color="red", linewidth=2.5, linestyle="-",  label="sine")

#############Přesnun popisků na "klasické" místo
#ax = gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

############# Popisky...


I am working on the file "Matplotlib--popisky,znacky.ipynb".
The first task is:
Různé styly šipek

Použitelná je IMHO FancyArroPatch: http://matplotlib.org/api/artist_api.html?highlight=fancyarrowpatch#matplotlib.patches.FancyArrowPatch
Can you write Python code for it?

import matplotlib.pyplot as plt
import matplotlib.patches as mpp
fig = plt.figure(figsize=(7,4))
ax=fig.add_subplot(111)
ax.axis([520,580, 0,0.2])
a = plt.arrow(550,0.06,15,0.1, width=0.01, head_length=1.)
ax.add_patch(a)
b = mpp.YAArrow(fig, (555,0.16), (540,0.06), width=0.01, headwidth=0.03)
ax.add_patch(b)
c = mpp.FancyArrowPatch((530,0.06), (545,0.16), arrowstyle='<|-|>', lw=2, mutation_scale=50, color='k')
ax.add_patch(c)
plt.show()


I am working on the file "Matplotlib--zakladni_myslenky_postupy.ipynb".
The first task is:
Fungují samozřejmě běžné matematické funkce:

sin
cos
tan
log -- přirozený logaritmus
log10 -- dekadický logaritmus
exp -- exponencíální funkce

Kreslení
Pokud mám řadu hodnot na ose x a řadu hodnot na ose y, můžu je vinést do souřadnicového systému.
K tomuto účelu slouží funkce plot().
Can you write Python code for it?


I am working on the file "Matplotlib--zakladni_myslenky_postupy.ipynb".
The first task is:
Nejen výřezy
S datovým typpem numpy.array lze pracovat jako
s klasickým python senzamem,
ale je možné provádět i mnohem
pokročilejší operace.
Can you write Python code for it?

t=linspace(0,10,11)
print t

print t[1:5]

print t[-1]
print t[-2]
print t[-3]

print t[5:-3]


I am working on the file "Matplotlib--zakladni_myslenky_postupy.ipynb".
The first task is:
Ve výřezech lze prvky i přeskakovat:
Can you write Python code for it?

t=arange(0,100,1)
print t

print t[0:20:3]

print t[::9]


I am working on the file "Matplotlib--zakladni_myslenky_postupy.ipynb".
The first task is:
Výřez je možné použít i k přiřazení:
Can you write Python code for it?


I am working on the file "Matplotlib--zakladni_myslenky_postupy.ipynb".
The first task is:
linspace
vytvoří řadu čísel tak, aby jich byl požadovaný počet:
Can you write Python code for it?

linspace(2,5,9)

linspace(0,5,4)

linspace(0,1,20)


I am working on the file "Matplotlib--zaklady_pro_tvorbu_grafu.ipynb".
The first task is:
... a poté pro osu y:...
Can you write Python code for it?


I am working on the file "Matplotlib--zaklady_pro_tvorbu_grafu.ipynb".
The first task is:
... a proudu:
Can you write Python code for it?


I am working on the file "Matplotlib--zaklady_pro_tvorbu_grafu.ipynb".
The first task is:
... a vyneseme do grafu:
Can you write Python code for it?


I am working on the file "Matplotlib--zaklady_pro_tvorbu_grafu.ipynb".
The first task is:
Funkci plot můžeme předat další parametr, který určuje:

styl čáry: - -- -. :
barvu: b g r c m y k w
styl vykreslení bodu: . , o v ^ < > s p h H * d D _ | + x
chci vědět víc
Can you write Python code for it?

plot(x,y,'g<')

plot(x,y,'b+:')

plot(x,y,'r*', markersize=15)
plot(x,y,'y--')


I am working on the file "Matplotlib--zaklady_pro_tvorbu_grafu.ipynb".
The first task is:
Příklad s funkcí sinus, f=50 Hz
Nejpve si vytvoříme časovou osu:..
Can you write Python code for it?


I am working on the file "Matplotlib--zaklady_pro_tvorbu_grafu.ipynb".
The first task is:
Vypočítáme výkon:..
Can you write Python code for it?


I am working on the file "Matplotlib.ipynb".
The first task is:
Apelul functiei  matplotlib.pyplot.plot se realizeaza fie transmitandu-i doar argumente obligatorii, fie argumente si cuvinte cheie carora li s-au atribuit valori.
Atunci cand am prezentat sintaxa unei functii in Python am precizat  doar ca o functie poate avea un numar
de parametri,
fara a intra in detalii relativ la natura argumentelor ce se transmit la apelul functiei.
Functia plt.plot este un exemplu de functie care ilustreaza concret diferitele posibilitati.
O functie in Python poate fi apelata, cu urmatoarele tipuri de argumente:

argumente obligatorii in numar fix sau variabil

argumente cuvinte cheie

Argumentele obligatorii sunt transmise unei functii in pozitie si ordine precisa.
De exemplu pentru functia plt.plot listele (sau array-urile 1D) x, y,  de aceeasi lungime $n$,  continand respectiv abscisele si ordonatele unor puncte, sunt argumente ce se transmit in aceasta ordine  pentru a trasa graficul unei functii $y=f(x)$ sau pentru a marca punctele de coordonate $(x_i, y_i)$, $i=0, 1,\ldots, n-1$.
In locul primelor doua argumente, se poate transmite insa doar singur  un argument pentru plt.plot si anume o lista (sau un array 1D), y. In acest caz lista absciselor este implicita, ea fiind lista indicilor, $0,1,2, \ldots, len(y)-1$, a elementelor din y:
Can you write Python code for it?


I am working on the file "Matplotlib.ipynb".
The first task is:
Apoi se importa modulul astfel:
Can you write Python code for it?


I am working on the file "Matplotlib.ipynb".
The first task is:
Cuvintele cheie se pot plasa in orice pozitie dupa argumentele obligatorii.
In modulul matplotlib.pyplot sunt definite si functii care manipuleaza imagini.
Array-urile 2D pot fi afisate  ca imagini. Functiile de baza destinate imaginilor sunt:
plt.imread() incarca o imagine intr-un array
plt.imsave() salveaza un array intr-o imagine
plt.imshow() afiseaza imaginea
Can you write Python code for it?

import matplotlib
X=np.random.random((16,16))# genereaza o matrice de tip 16x16 de elemente
                           #aleator generate in intervalul [0,1)
img=plt.imshow(X,cmap=matplotlib.cm.spectral, interpolation='nearest')#afiseaza matricea ca o
#imagine care rezulta realizand o corespondenta intre numerele din intervalul [0,1] si
#un colormap(paleta de culori)

X=plt.imread('Imag/Iony.png')
print 'Imaginea este de tip', X.shape
plt.imshow(X)


I am working on the file "Matplotlib.ipynb".
The first task is:
Daca copiati liniile de cod din celula precedenta si le salvati intr-un fisier spirala.py si comentati linia
plt.show() veti vedea ca la rulare nu este afisat nici un mesaj de eroare, dar figura nu este vizualizata.
Decomentand plt.show() va apare figura de mai sus.
Can you write Python code for it?

from IPython.core.display import HTML
def  css_styling():
    styles = open("./custom.css", "r").read()
    return HTML(styles)
css_styling()


I am working on the file "Matplotlib.ipynb".
The first task is:
O alta solutie este  sa divizam intervalul $[a,b]$ precizand pasul de diviziune, h,  nu numarul de puncte de diviziune:
Can you write Python code for it?

a=-5
b=7
h=0.01
X=np.arange(a,b, h)
Y=-2*X*X+X+1
plt.plot(X,Y, 'g')
plt.title('Un arc de parabola')


I am working on the file "Matplotlib.ipynb".
The first task is:
Pentru a trasa un segment intre doua puncte de coordonate $(2,4)$, $(6,-1)$, constituim lista absciselor,
x=[2,6], si respectiv a ordonatelor celor doua puncte, y=[4,-1]:
Can you write Python code for it?


I am working on the file "Matplotlib.ipynb".
The first task is:
Un alt argument al functiei plt.plot este culoarea de trasare sau marcare a punctelor.
Implicit culoarea este setata pe blue (a se vedea segmentul de dreapta de mai sus).
Culoarea de trasare/marcare se poate transmite in mai multe moduri:

precizand un caracter care este codul culorii:

'b',    blue;
'g',    green;
'r',    red;
'c',    cyan;
'm',    magenta;
'y',    yellow;
'k',    black;
'w',    white.

folosind cuvantul cheie color setat cu un tuple, color=(r, g, b) sau color=(r,g,b,alpha). Elementele celor 2 tuple-uri sunt subunitare
 si r,g,b indica cantitatea de red, green si blue din care este sintetizata culoarea.
alpha indica transparenta culorii. Pentru alpha mai apropiat de 1, culoarea este mai opaca, iar mai apropiat de zero, mai transparenta.

folosind cuvantul cheie color setat cu un string ce reprezinta  codul html al unei culori,
color='#33FF99'
Can you write Python code for it?


I am working on the file "Matplotlib.ipynb".
The first task is:
matplotlib contine numeroase alte module care vor fi prezentate pe masura ce vor fi folosite.
Un script Python NumeScript.py care se ruleaza din linia de comanda sau in Spyder si apeleaza functii din matplotlib.pyplot va afisa figura generata doar daca la sfarsitul script-ului  se insereaza functia
plt.show(). Altfel figura desi generata, nu este afisata.
Un exemplu de astfel de script este urmatorul:
Can you write Python code for it?

import numpy as np
import matplotlib.pyplot as plt
t=np.arange(0,4, 0.01)
x=np.exp(-t)*np.cos(2*np.pi*t)
y=np.exp(-t)*np.sin(2*np.pi*t)
plt.plot(x,y,'r')
plt.axis('equal')
plt.xlabel('x(t)')
plt.ylabel('y(t)')
plt.show()


I am working on the file "Matplotlib/.ipynb_checkpoints/MatplotlibEx02-checkpoint.ipynb".
The first task is:
Exoplanet properties
Over the past few decades, astronomers have discovered thousands of extrasolar planets. The following paper describes the properties of some of these planets.
http://iopscience.iop.org/1402-4896/2008/T130/014001
Your job is to reproduce Figures 2 and 4 from this paper using an up-to-date dataset of extrasolar planets found on this GitHub repo:
https://github.com/OpenExoplanetCatalogue/open_exoplanet_catalogue
A text version of the dataset has already been put into this directory. The top of the file has documentation about each column of data:
Can you write Python code for it?

!head -n 30 open_exoplanet_catalogue.txt


I am working on the file "Matplotlib/.ipynb_checkpoints/MatplotlibEx02-checkpoint.ipynb".
The first task is:
Use np.genfromtxt with a delimiter of ',' to read the data into a NumPy array called data:
Can you write Python code for it?

data = np.genfromtxt('open_exoplanet_catalogue.txt',delimiter=',')

assert data.shape==(1993,24)


I am working on the file "Matplotlib/Matplotlib.ipynb".
The first task is:
Box and grid
You can enable a grid or disable the box. Notice that the ticks and tick labels remain.
Can you write Python code for it?

plt.plot(np.random.rand(100), 'b-')
plt.grid(True)
plt.box(False)


I am working on the file "Matplotlib/Matplotlib.ipynb".
The first task is:
Here is a list of the single character color strings:
b: blue
    g: green
    r: red
    c: cyan
    m: magenta
    y: yellow
    k: black
    w: white
The following will show all of the line and marker styles:
Can you write Python code for it?

from matplotlib import lines
lines.lineStyles.keys()

from matplotlib import markers
markers.MarkerStyle.markers.keys()


I am working on the file "Matplotlib/Matplotlib.ipynb".
The first task is:
Multiple series
Multiple calls to a plotting function will all target the current Axes:
Can you write Python code for it?

plt.plot(t, np.sin(t), label='sin(t)')
plt.plot(t, np.cos(t), label='cos(t)')
plt.xlabel('t')
plt.ylabel('Signal(t)')
plt.ylim(-1.5, 1.5)
plt.xlim(right=12.0)
plt.legend()


I am working on the file "Matplotlib/Matplotlib.ipynb".
The first task is:
Overview
The following conceptual organization is simplified and adapted from Benjamin Root's AnatomyOfMatplotlib tutorial.
Figures and Axes

In Matplotlib a single visualization is a Figure.
A Figure can have multiple areas, called subplots. Each subplot is an Axes.
If you don't create a Figure and Axes yourself, Matplotlib will automatically create one for you.
All plotting commands apply to the current Figure and Axes.

The following functions can be used to create and manage Figure and Axes objects.
Function          | Description
:-----------------|:----------------------------------------------------------
figure          | Creates a new Figure
gca             | Get the current Axes instance
savefig         | Save the current Figure to a file
sca             | Set the current Axes instance
subplot         | Create a new subplot Axes for the current Figure
subplots        | Create a new Figure and a grid of subplots Axes
Plotting Functions
Once you have created a Figure and one or more Axes objects, you can use the following function to put data onto that Axes.
Function          | Description
:-----------------|:--------------------------------------------
bar             | Make a bar plot
barh            | Make a horizontal bar plot
boxplot         | Make a box and whisker plot
contour         | Plot contours
contourf        | Plot filled contours
hist            | Plot a histogram
hist2d          | Make a 2D histogram plot
imshow          | Display an image on the axes
matshow         | Display an array as a matrix
pcolor          | Create a pseudocolor plot of a 2-D array
pcolormesh      | Plot a quadrilateral mesh
plot            | Plot lines and/or markers
plot_date       | Plot with data with dates
polar           | Make a polar plot
scatter         | Make a scatter plot of x vs y
Plot modifiers
You can then use the following functions to modify your visualization.
Function          |...
Can you write Python code for it?

t = np.linspace(0, 10.0, 100)
plt.plot(t, np.sin(t))
plt.xlabel('Time')
plt.ylabel('Signal')
plt.title('My Plot'); # supress text output


I am working on the file "Matplotlib/Matplotlib.ipynb".
The first task is:
Subplots
Subplots allow you to create a grid of plots in a single figure. There will be an Axes associated with each subplot and only one Axes can be active at a time.
The first way you can create subplots is to use the subplot function, which creates and activates a new Axes for the active Figure:
Can you write Python code for it?

plt.subplot(2,1,1) # 2 rows x 1 col, plot 1
plt.plot(t, np.exp(0.1*t))
plt.ylabel('Exponential')

plt.subplot(2,1,2) # 2 rows x 1 col, plot 2
plt.plot(t, t**2)
plt.ylabel('Quadratic')
plt.xlabel('x')

plt.tight_layout()


I am working on the file "Matplotlib/Matplotlib.ipynb".
The first task is:
The subplots function also makes it easy to pass arguments to Figure and to share axes:
Can you write Python code for it?

f, ax = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(6,6))

for i in range(2):
    for j in range(2):
        plt.sca(ax[i,j])
        plt.plot(np.random.rand(20))
        if i==1:
            plt.xlabel('x')
        if j==0:
            plt.ylabel('y')

plt.tight_layout()


I am working on the file "Matplotlib/Matplotlib.ipynb".
The first task is:
You can change the ticks along a given axis by using xticks, yticks and tick_params:
Can you write Python code for it?

plt.plot(t, np.sin(t)*np.exp(-0.1*t),'bo')
plt.xlim(0.0, 10.0)
plt.ylim(-1.0, 1.0)
plt.xticks([0,5,10], ['zero','five','10'])
plt.tick_params(axis='y', direction='inout', length=10)


I am working on the file "Matplotlib/MatplotlibEx01.ipynb".
The first task is:
Describe the choices you have made in building this visualization and how they make it effective.
First I gave the visualization a title and labeled the axis in the standard location. I removed the top and right spine because they were unecessary and hurt my data to ink ratio. I changed the aspect ratio of the plot so that it was easier to see the trend.
Now make 4 subplots, one for each century in the data set. This approach works well for this dataset as it allows you to maintain mild slopes while limiting the overall width of the visualization. Perform similar customizations as above:

Customize your plot to follow Tufte's principles of visualizations.
Adjust the aspect ratio/size so that the steepest slope in your plot is approximately 1.
Customize the box, grid, spines and ticks to match the requirements of this data.
Can you write Python code for it?

fig, (ax1,ax2,ax3,ax4) = plt.subplots(4,1,figsize=(10,15),sharey=True)

ax1.plot(year[0:100], ssc[0:100])
ax2.plot(year[100:200], ssc[100:200])
ax3.plot(year[200:300], ssc[200:300])
ax4.plot(year[300:315], ssc[300:315])

ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.yaxis.set_ticks_position('left')
ax1.xaxis.set_ticks_position('bottom')

ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.yaxis.set_ticks_position('left')
ax2.xaxis.set_ticks_position('bottom')

ax3.spines['right'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax3.yaxis.set_ticks_position('left')
ax3.xaxis.set_ticks_position('bottom')

ax4.spines['right'].set_visible(False)
ax4.spines['top'].set_visible(False)
ax4.yaxis.set_ticks_position('left')
ax4.xaxis.set_ticks_position('bottom')

plt.xlim(2001,2014);

plt.sca(ax1)
plt.xlabel('Year')
plt.ylabel('Number of Recorded Sunspots')
plt.title('18th Century: Recorded Sunspots vs Year')

plt.sca(ax2)
plt.xlabel('Year')
plt.ylabel('Number of Recorded Sunspots')
plt.title('19th Century: Recorded Sunspots vs Year')

plt.sca(ax3)
plt.xlabel('Year')
plt.ylabel('Number of Recorded Sunspots')
plt.title('20th Century: Recorded Sunspots vs Year')

plt.sca(ax4)
plt.xlabel('Year')
plt.ylabel('Number of Recorded Sunspots')
plt.title('21st Century: Recorded Sunspots vs Year')

plt.tight_layout()


I am working on the file "Matplotlib/MatplotlibEx01.ipynb".
The first task is:
Line plot of sunspot data
Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the SILSO website. Upload the file to the same directory as this notebook.
Can you write Python code for it?

import os
assert os.path.isfile('yearssn.dat')


I am working on the file "Matplotlib/MatplotlibEx01.ipynb".
The first task is:
Use np.loadtxt to read the data into a NumPy array called data. Then create two new 1d NumPy arrays named years and ssc that have the sequence of year and sunspot counts.
Can you write Python code for it?

data = np.loadtxt('yearssn.dat')
year,ssc = np.split(data,2,1)

assert len(year)==315
assert year.dtype==np.dtype(float)
assert len(ssc)==315
assert ssc.dtype==np.dtype(float)


I am working on the file "Matplotlib/MatplotlibEx02.ipynb".
The first task is:
Exoplanet properties
Over the past few decades, astronomers have discovered thousands of extrasolar planets. The following paper describes the properties of some of these planets.
http://iopscience.iop.org/1402-4896/2008/T130/014001
Your job is to reproduce Figures 2 and 4 from this paper using an up-to-date dataset of extrasolar planets found on this GitHub repo:
https://github.com/OpenExoplanetCatalogue/open_exoplanet_catalogue
A text version of the dataset has already been put into this directory. The top of the file has documentation about each column of data:
Can you write Python code for it?


I am working on the file "Matplotlib/MatplotlibEx02.ipynb".
The first task is:
Make a scatter plot of the orbital eccentricity (y) versus the semimajor axis. This will reproduce Figure 4 of the original paper. Use a log scale on the x axis.

Customize your plot to follow Tufte's principles of visualizations.
Customize the box, grid, spines and ticks to match the requirements of this data.
Can you write Python code for it?

OE = data[:,6]
SMA = data[:,5]
fig, ax = plt.subplots(figsize=(9,6));
ax.scatter(SMA,OE)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plt.semilogx()
plt.xlim(.01,100);
plt.ylim(-0.05,1);
plt.xlabel('Semimajor Axis');
plt.ylabel('Orbital Eccentricity');
plt.title('Semimajor Axis vs Orbital Eccentricity')

assert True # leave for grading


I am working on the file "Matplotlib/MatplotlibEx02.ipynb".
The first task is:
Use np.genfromtxt with a delimiter of ',' to read the data into a NumPy array called data:
Can you write Python code for it?


I am working on the file "Matplotlib/MatplotlibEx03.ipynb".
The first task is:
Next make a visualization using one of the pcolor functions:
Can you write Python code for it?

plt.figure(figsize=(9,6))
plt.pcolormesh(XX,YY,well2d(XX, YY, nx, ny, L),cmap=('spectral'))
plt.colorbar(shrink=.8)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Contour plot of two dimensional wave function in an infinite well')
plt.xlabel('x')
plt.ylabel('y')
plt.tick_params(axis='x',top='off',direction='out')
plt.tick_params(axis='y',right='off',direction='out')

assert True # use this cell for grading the pcolor plot


I am working on the file "Matplotlib/MatplotlibEx03.ipynb".
The first task is:
The contour, contourf, pcolor and pcolormesh functions of Matplotlib can be used for effective visualizations of 2d scalar fields. Use the Matplotlib documentation to learn how to use these functions along with the numpy.meshgrid function to visualize the above wavefunction:

Use $n_x=3$, $n_y=2$ and $L=0$.
Use the limits $[0,1]$ for the x and y axis.
Customize your plot to make it effective and beautiful.
Use a non-default colormap.
Add a colorbar to you visualization.

First make a plot using one of the contour functions:
Can you write Python code for it?

nx = 3
ny = 2
L = 1
x = np.linspace(0,L,1000)
y = np.linspace(0,L,1000)
XX,YY = np.meshgrid(x,y)
plt.figure(figsize=(9,6))
f = plt.contourf(x,y,well2d(XX, YY, nx, ny, L),cmap=('seismic'))
plt.xlabel('x')
plt.ylabel('y')
plt.title('Contour plot of two dimensional wave function in an infinite well')
plt.tick_params(axis='x',top='off',direction='out')
plt.tick_params(axis='y',right='off',direction='out')
plt.colorbar(shrink=.8)

XX

YY

assert True # use this cell for grading the contour plot


I am working on the file "Matplotlib/MatplotlibExercises.ipynb".
The first task is:
Scatter plots
Learn how to use Matplotlib's plt.scatter function to make a 2d scatter plot.

Generate random data using np.random.randn.
Style the markers (color, size, shape, alpha) appropriately.
Include an x and y label and title.
Can you write Python code for it?

fig, ax = plt.subplots(figsize=(9,6))
ax.scatter(np.random.randn(20), np.random.randn(20))
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plt.xlabel('Random y');
plt.ylabel('Random x');
plt.title('Plot of a Random (x,y)');


I am working on the file "Matplotlib_tutorial.ipynb".
The first task is:
Or try a scatter plot
Can you write Python code for it?

plt.scatter(x,y, label="one")
plt.scatter(x2,y2, color='r', label="two")
plt.legend()


I am working on the file "Matplotlib_tutorial.ipynb".
The first task is:
Reading from CSV file using NumPy
Say we create a csv file name test.csv. We can use numpy to load the file and use matplotlib to plot it!
Can you write Python code for it?

import numpy as np # load numpy

x,y = np.loadtxt('test.csv',
                unpack=True,  # unpack the values into x and y ...
                delimiter=',') # these values are separated by a ','
                               # else unpacks the whole dataset into a
                               # single value (list of lists...)

print x

plt.plot(x,y)


I am working on the file "Matrices/Matrices.ipynb".
The first task is:
For $3\times 3$ or more matrices
$M = \left(\begin{array}{cc}
1 & -1 & 3 \2 & -1 & 4\ 2 & 2 & 1
\end{array}\right)$
To find $M^{-1}$:
First, find the Determinant:
For each element in the matrix, remove the row and column its in so you're left with a 2x2 matrix
if $M^{0,0}$ is choosen
$\left(\begin{array}{cc}
T & - & - \- & -1 & 4\ - & 2 & 1
\end{array}\right)$
with T as $M^{0,0}$
Returns
$\left(\begin{array}{cc}
-1 & 4\2 & 1
\end{array}\right)$
or if $M^{1,2}$ is choosen
$\left(\begin{array}{cc}
1 & -1 & - \- & - & T\ 2 & 2 & -
\end{array}\right)$
with T as $M^{0,0}$
Returns
$\left(\begin{array}{cc}
1 & -1\2 & 2
\end{array}\right)$
Now find the determinant of this submatrix using $ad-bc$
det$\left(\begin{array}{cc}
-1 & 4\2 & 1
\end{array}\right)$ = $(-1\times 1) - (4\times 2$) =  $-9$
Since this submatrix was choosen from point $M^{0,0}$, in our matrix of minors, $M^{0,0} = -9$
if we do this for every point:
Matrix of Minors $= \left(\begin{array}{cc}
-9 & -6 & 6 \-7 & -5 & 4\ -1 & -2 & 1
\end{array}\right)$
Now we need to find the cofactors of the original matrix
We do this by multiplying each element by $-1^{i+j}$
for $M^{0,0}$, i and j = 0 so:
$-9\times -1^{0+0} = -9\times 1 = -9$
or for $M^{2,1}$, i = 2 and j = 1 so:
$-2\times -1^{2+1} = -2\times -1 = 2$
it can also be visualised as an array with alternating positive and negatives while always starting with a positive like:
$\left(\begin{array}{cc}
+ & - & + \- & + & -\ + & - & +
\end{array}\right)$
This gives us:
Matrix of Cofactors
$= \left(\begin{array}{cc}
-9 & 6 & 6 \7 & -5 & -4\ -1 & 2 & 1
\end{array}\right)$
Now find the determinant of the original matrix
Do this by multiplying each individual determinant on one row from our matrix of cofactors by the corresponding original value. It doesnt matter what row you choose, it will always be the same as the calculation endsup using all the elements in the original matrix
$|M| = (-9\times 1) + (6\times -1) + (6\times 3) = 3$
Now find the adjugate (or known as adjoint)
All we do is transpose the...
Can you write Python code for it?

# The same example but in 1 line of python

print(np.linalg.inv(np.array([[1,-1,3],[2,-1,4],[2,2,1]])))


I am working on the file "Matrices/Matrices.ipynb".
The first task is:
In this Example,
the element $C_{i,j}$ will be
$\sum A[i,:] \cdot B[:,j]$
Another Example
Can you write Python code for it?

A = np.linspace(1,6,6).reshape(2,3)
B = np.linspace(2,12,6).reshape(3,2)
C = np.matmul(A, B)
print('A =')
print(A)
print('B =')
print(B)
print('\nWith A x B = C \nC =')
print(C)


I am working on the file "Matrices/Matrices.ipynb".
The first task is:
Simple Matrix Operations
Addition/Subtraction
$(A+B)_{i,j}$
$(A-B)_{i,j}$
Can you write Python code for it?

# They can be added if they are the same size/shape
# they are added by adding the equivilent value in the other array
A = np.arange(9).reshape([3,3])
B = np.eye(3,3)

add = np.add(A,B)
sub = np.subtract(A,B)
print('A + B =\n', add)
print('A - B =\n', sub)


I am working on the file "Matrices/Matrices.ipynb".
The first task is:
Transposition
This is where each row and column is swapped with its corresponding row or column.
$A^T$
Can you write Python code for it?

B = np.linspace(0.5,12,24).reshape(3,8)
print('B =')
print(B)
print('\nB^T =')
print( np.transpose(B))


I am working on the file "Matrices/Matrices.ipynb".
The first task is:
Zero Matrices
These are Matrices full of only 0's
Noted as: $O$
Inverse Matrices
If $A\cdot B = C$, then $A = \frac{C}{B}$
But we cant divide matrices so we use
$A = B^{-1}C$
$B^{-1}$ is the inverse of B
Also
$B\cdot B^{-1} = I$
with I as an identity matrix
For $2\times 2$ matrices
$\left(\begin{array}{cc}
a & b \c & d
\end{array}\right)^{-1} = \frac{1}{ad-bc}\left(\begin{array}{cc}
d & -b \-c & a
\end{array}\right)$
Matrices with inverses are called nonsingulars or invertables
A Matrix with no inverse, where $ad-bc=0$, is called a singular
The Determinant
$ad-bc$ is the determinant from above.
Noted as:
$det(M)$ or $|M|$
with M as the Matrix
Can you write Python code for it?

A = np.arange(4).reshape(2,2)
print('A =')
print(A)
print('\nA^-1 =')
print(np.linalg.inv(A))


I am working on the file "Matrix Factorization.ipynb".
The first task is:
Experiments
Can you write Python code for it?

R = [
     [5,3,0,1],
     [4,0,0,1],
     [1,1,0,5],
     [1,0,0,4],
     [0,1,5,4],
    ]

R = numpy.array(R)

N = len(R)
M = len(R[0])

# number of dimension about factor vector
K = 2

P = numpy.random.rand(N,K)
Q = numpy.random.rand(M,K)

nP, nQ = matrix_factorization(R, P, Q, K)
nR = numpy.dot(nP, nQ.T)

print(nR)


I am working on the file "Matrix Factorization.ipynb".
The first task is:
error
scalar indicates the difference between $$R \ and \  \hat{R}$$
regularization term
scalar $$ \lambda ( \sum_{i}^{} \|x_i\| ^2 + \sum_{j}^{} \|y_j\| ^2 ) $$
Can you write Python code for it?

def error(P, Q, i, j):
    return R[i][j] - numpy.dot(P[i,:],Q[:,j])

def regular(beta, P, Q, i, k, j):
    return (beta/2) * (pow(P[i][k], 2) + pow(Q[k][j], 2))

def matrix_factorization(R, P, Q, K, steps=5000, alpha=0.0002, beta=0.02):
    Q = Q.T
    for step in range(steps):
        for i in range(len(R)):
            for j in range(len(R[i])):
                if R[i][j] > 0:
                    for k in range(K):
                        P[i][k] = P[i][k] + alpha * (2 * error(P, Q, i, j)
                                                     * Q[k][j] - beta * P[i][k])
                        Q[k][j] = Q[k][j] + alpha * (2 * error(P, Q, i, j)
                                                     * P[i][k] - beta * Q[k][j])

        eR = numpy.dot(P,Q)
        e = 0
        for i in range(len(R)):
            for j in range(len(R[i])):
                if R[i][j] > 0:
                    e = e + error(P, Q, i, j) ** 2
                    for k in range(K):
                        e = e + regular(beta, P, Q, i, k, j)
        if e < 0.001:
            break
    return P, Q.T


I am working on the file "Max/Evaluating-using-Dreams-from-the-orbm.ipynb".
The first task is:
Lets take a quick look at the images if instead of combining they had just done their own thing
Can you write Python code for it?


I am working on the file "Max/Evaluating-using-Dreams-from-the-orbm.ipynb".
The first task is:
Now we need to compare the ORBM and RBM at reconstructing
Can you write Python code for it?

help(orbm_sampler.v_to_v)

# prepare the ORBM sampler
# UGh! passing a starting hidden pattern should be optional!
rand_h_a = np.random.randint(0,2,size=( two_rbm.num_hid()))
rand_h_b = np.random.randint(0,2,size=( three_rbm.num_hid()))

orbm_sampler = ContinuousApproxSampler(two_rbm.weights, three_rbm.weights, two_rbm.hidden_bias, three_rbm.hidden_bias)
orbm_two_recon, orbm_three_recon = orbm_sampler.v_to_v(rand_h_a,rand_h_b, composite_dream, num_gibbs=100)

# we can reuse the continous vanilla samplers from before
rbm_two_recon = two_sampler.reconstruction_given_visible(composite_dream)
rbm_three_recon = three_sampler.reconstruction_given_visible(composite_dream)

plt.suptitle("ORBM Two Reconstruction")
pp.image(orbm_two_recon.reshape(28,28))
plt.suptitle("ORBM Three Reconstruction")
pp.image(orbm_three_recon.reshape(28,28))

plt.suptitle("RBM Two Reconstruction")
pp.image(rbm_two_recon.reshape(28,28))
plt.suptitle("RBM Three Reconstruction")
pp.image(rbm_three_recon.reshape(28,28))


I am working on the file "Max/MNIST-Model-Generation.ipynb".
The first task is:
for d in ds[1:]:
    trainerer(a,d[:10], 1000,l_r = 0.006, batches= 5 )
trainerer(a,ds_three[:200], 1000,l_r = 0.002, batches= 1 )
Can you write Python code for it?

# !say "Finished"
eval_complex_model(a)

save_model(a, "attempt_two/zero_models")


I am working on the file "Max/MNIST-Model-Generation.ipynb".
The first task is:
with open("models/bar_models", "rb") as f:
    a = pickle.load(f)
Can you write Python code for it?

trainerer(a,ds_twos[:100], 10,l_r = 0.002, batches = 5)

vs = ContinuousSampler(a)
ds_twos[0].shape
pp.image(vs.reconstruction_given_visible(ds_twos[0].reshape(784)).reshape(28,28))

ds_all = np.vstack((ds))

from sklearn.neural_network import BernoulliRBM
model = BernoulliRBM(n_components=100, n_iter=40)
model.fit(rbmpy.datasets.flatten_data_set(ds_all))

eval_complex_model(rbmpy.rbm.create_from_sklearn_rbm(model, 784, ds_nine.shape[0]))

model


I am working on the file "Max/MNIST-ORBM-Inference.ipynb".
The first task is:
In the cell below
I have calculated in the previous cell the loglikelyhood score of the partitioned sampling and vanilla sampling technique image-wise. So I have a score for each image. I have done this for all the MNIST digits that have been 'corrupted' by the bar images. That is RBM's trained models 1 - 9 and an RBM trained on 2's and 3's
The wins for a given model are where the partitioned scored better than the vanilla sampling technique
Conversly, losses are images where the vanilla score better.
Intuitively, ties is where they scored the same, which could only really occur when the correction would be zero, or ultimately cancelled out.
Can you write Python code for it?

for key in results:
    logging.info("Plotting, win, lose and tie images for the {}".format(key))
    results[key].plot_various_images()


I am working on the file "Max/MNIST-ORBM-Inference.ipynb".
The first task is:
Thoughts
So on a dataset of size 50, with 100 gibbs alterations we see in all cases that for the digit model, 1,2,3,..,9 that the partitioned sampling technique does either better or the same more often than the vanilla does. Let's try some different configurations.
Can you write Python code for it?

results.update(results_for_models(models, corruption_model_name, 400, 500))


I am working on the file "Max/MNIST-ORBM-Inference.ipynb".
The first task is:
results.update(results_for_models(models, corruption_model_name, 10, 1))
Can you write Python code for it?

results

# with open('results_dict', 'wb') as f3le:
#     pickle.dump(results,f3le, protocol = None)
with open('results_dict', 'rb') as f4le:
    results = pickle.load(f4le)

# for key in results:
#     if key.startswith('400'):
#         logging.info("Results for hiddens")
#         r = results[key].stored_hiddens
#         for i in range(len(r)):
#             print(results[key].imagewise_score())


I am working on the file "Max/ORBM-Inference-XOR.ipynb".
The first task is:
Below
In this cell below I check the code still holds together given more hidden nodes. Than visibles. It does.
Can you write Python code for it?

training_set = np.eye(2)
dot = RBM(3,2,1)
s = VanillaSampler(dot)
t = VanillaTrainier(dot, s)
t.train(10000, training_set)
h_a = np.array([1,0,0])
h_b = np.array([0,1,0])
v = np.array([1,1])
plot_avg_results_for_hidden_pattern(h_a, h_b,np.array([1,1]) , ApproximatedSampler(dot.weights,dot.weights,0,0))
plot_avg_results_for_hidden_pattern(h_a, h_b,np.array([1,0]) , ApproximatedSampler(dot.weights,dot.weights,0,0))
plot_avg_results_for_hidden_pattern(h_a, h_b,np.array([0,1]) , ApproximatedSampler(dot.weights,dot.weights,0,0))
plot_avg_results_for_hidden_pattern(h_a, h_b,np.array([0,0]) , ApproximatedSampler(dot.weights,dot.weights,0,0))

training_set = np.eye(3)

dot = RBM(2,3,1)
s = VanillaSampler(dot)
t = VanillaTrainier(dot, s)
t.train(10000, training_set)

plot_avg_results_for_visible_pattern(np.array([1,1]), a)
plot_avg_results_for_visible_pattern(np.array([1,1]), WrappedVanillaSampler(dot))


I am working on the file "Max/ORBM-Inference-XOR.ipynb".
The first task is:
Yussssssssss
This is perfect, over all cases for the visible pattern it can separate it. Creating excellent reconstructions the majority of the time. We already know the vanilla RBM will fail to do this. Still i graphed the output of on of the visible reconstructions of the vanilla.
Can you write Python code for it?

plot_avg_results_for_visible_pattern(np.array([1,0]), a)
plot_avg_results_for_visible_pattern(np.array([0,1]), a)

plot_avg_results_for_visible_pattern(np.array([1,0]), WrappedVanillaSampler(dot))
plot_avg_results_for_visible_pattern(np.array([0,1]), WrappedVanillaSampler(dot))


I am working on the file "Max/ORBM-XOR-X-Bits.ipynb".
The first task is:
4 bits #
Lets try 4 hiddens and 4 visibles
- Excellent it works really well. See graphs below
Can you write Python code for it?

four_bit = build_and_eval(4,4)

vs = [np.array([1,1,0,0]),np.array([0,1,0,1]),np.array([1,0,0,1])]
for v in vs:
    eval_partitioned(four_bit,v)


I am working on the file "Max/ORBM-XOR-X-Bits.ipynb".
The first task is:
Lets try and make a really, really good model
I'm going to do the pathological number of hidden units, that is $2n$ for $n$ visibles. Can I train a perfect (likely super overfit model) and examine the partitioning affect.
Can you write Python code for it?

model = build_and_eval(n_hid= 4, n_vis= 2,epochs=1000)


I am working on the file "Max/ORBM-XOR-X-Bits.ipynb".
The first task is:
Not bad. It separates quite well.
Can you write Python code for it?

class PlottingSampler(ApproximatedSampler):
    """Wrapper for the sampler allow us to observe the calculation"""
    def approx_correction(self, h_a, h_b, w_a, w_b,v):
        c_a, c_b = super().approx_correction(h_a,h_b,w_a, w_b,v) # wrap those delicious corrections up
#         print("C_A{}\nC_B{}".format(c_a, c_b))
        self.plot_all(self.plot_ready_shape(h_a),self.plot_ready_shape(h_b),c_a,c_b)
        plt.show()
        return c_a, c_b

    def plot_ready_shape(self, h):
        return h.reshape(1,h.shape[0])

    def plot_all(self,h_a,h_b,c_a, c_b):
        plt.subplot(141)
        self.plot_hid('h_a',h_a)
        plt.subplot(142)
        self.plot_hid('h_b',h_b)
        plt.subplot(143)
        self.plot_correction('c_a',self.reshape_for_plot(c_a.sum(1)))
        plt.subplot(144)
        self.plot_correction('c_b',self.reshape_for_plot(c_b.sum(1)))
        plt.colorbar(ticks=[-1,0,1])

    def reshape_for_plot(self, c):
        return c.reshape(1,c.shape[0])

    def plot_correction(self,title, c):
        plt.title(title)
        plt.axis('off')
        plt.imshow(c, cmap='seismic', interpolation ='nearest')

    def plot_hid(self,title,h):
        plt.title(title)
        plt.axis('off')
        plt.imshow(h, cmap='copper', interpolation ='nearest')


I am working on the file "Max/ORBM-XOR-X-Bits.ipynb".
The first task is:
That is a really strong model
I would expect 50% of the patterns to be [1,0] and visa versa [0,1]
It took a few tries to get here though
Can you write Python code for it?


I am working on the file "Max/ORBM-XOR-X-Bits.ipynb".
The first task is:
Updating the Hidden States Layerwise V Alternatives
So we know that we should possibly (but hopefully not) actually let a given update to the hiddens mutilple times, because the $h^A$ and $h^A$ are depedant on each other. Actaully each unit of each hidden layer is depedant on each other. So the full version would be to update a given $h^A_j$ for all $j$ and do the same for $h^B_k $ - Realistically do this I would probably swap to a Java implementation, two reasons:
- Efficiency, for $1,..,n $ hidden units I would have $n$ iterations for each $j$ plus the eqiuvalent $k$ for the the other layer.. :(
- Indices, personally a lot easier to keep track of in Java. Would want typechecking and explicit for loops.
Hopefully it won't come to that, hence what i'm doing below
Up until this point I update the hidden states (for both layers) all at once. I calculate $h^A$ and $h^B$ all at once given a $v$. But it's worth looking into how this affects the reconstructions. So I will compare the current technique to:
- Update $h^A | v$ to get $h'^A$, where the correction is calculated using $h^B$
- Update $h^B | v$ to get $h'^B$, where the correction is now calculated using $h'^A$
- Update $h^A | v$ to get $h'^A$, where the correction is calculated using $h'^A$
- Finally do an update given $h'^A$ and $h'^A$
Or in words: Update the left layer, then update the right based on the update to the left. Then update the left based on the new right and the current left. And then update both the left and right based on these values. Hopefully this won't perform drasitcally better, especially because I am only Markov Chaining(?Is this what I am doing?)
Can you write Python code for it?

## Separation with 2 hids and 2 vis
model = build_and_eval(2,2)
n_hid = model.num_hid()
h_a = np.random.randint(2,size=(n_hid,))
h_b = np.random.randint(2,size=(n_hid,))
v=np.array([1,1])
s = ApproximatedSampler(model.weights, model.weights,model.hidden_bias, model.hidden_bias)
plotter.plot_dict(perform(h_a, h_b, v, s, 1000, 400), title="v'| {}".format(v), size = "")

# Compare that to the separation of the layerwise h_a updater
s = LayerWiseApproxSampler(model.weights, model.weights,model.hidden_bias, model.hidden_bias)
plotter.plot_dict(perform(h_a, h_b, v, s, 1000, 400), title="v'| {}".format(v), size = "")


I am working on the file "Max/RBM-ORBM-Single-Models.ipynb".
The first task is:
Make a composite training set
Can you write Python code for it?

def gen_composite_training(sq_shape, img_size, static_xy):
    training = []
    for x in range(img_size[0]-1):
        for y in range(img_size[1]-1):
            training.append(np.maximum(gen_square((x,y), sq_shape, img_size),gen_square(static_xy, sq_shape, img_size)))
    return np.array(training)

comp = gen_composite_training((2,2),(5,5),(1,1))
pp.images(comp)

rand_h = np.random.randint(0,2,35)
approx= ApproximatedSampler(model.weights, model.weights, model.hidden_bias, model.hidden_bias)

for current_img in comp:
    reconstruction = approx.v_to_v(rand_h,rand_h,current_img.reshape(25),num_gibbs=1000)
    pp.images(np.array([current_img,reconstruction[0].reshape(5,5), reconstruction[1].reshape(5,5), s.reconstruction_given_visible(current_img.reshape(25)).reshape(5,5)]))


I am working on the file "Max/RBM-ORBM-Single-Models.ipynb".
The first task is:
Make the sampler and random Composite
Can you write Python code for it?

help(s.dream)

s = VanillaSampler(model)
dream1 = s.dream(model, num_gibbs = 500)
dream2 = s.dream(model, num_gibbs = 500)

phi_1 = np.dot(s.visible_to_hidden(dream1), model.weights)
phi_2 = np.dot(s.visible_to_hidden(dream2), model.weights)
pp.image(expit(phi_1).reshape(5,5))
pp.image(expit(phi_2).reshape(5,5))
# pp.image((expit(phi_1) + expit(phi_2)).reshape(5,5))
comp = expit(phi_1 + phi_2)
pp.image(comp.reshape(5,5))

orbm_sampler = ApproximatedSampler(model.weights,model.weights,model.hidden_bias, model.hidden_bias)

rand_h = np.random.randint(0,2,size=( model.num_hid()))

left, right =  orbm_sampler.v_to_v(rand_h,rand_h, comp)
plt.suptitle("ORBM")
pp.image(left.reshape(5,5))
pp.image(right.reshape(5,5))
rbm_sampler = VanillaSampler(model)
plt.suptitle("RBM")
pp.image(rbm_sampler.reconstruction_given_visible(comp).reshape(5,5))

a = ApproximatedMulDimSampler(model.weights,model.weights, model.hidden_bias,model.hidden_bias)
data = model.visible.copy()
np.random.shuffle(data)
item_one = inflate_images(data)[0]
item_two = inflate_images(data)[1]
composite_v = np.maximum(item_one,item_two )
pp.image(item_one+ item_two,cmap='Paired',show_colorbar=False)

rand_h = np.random.randint(0,2,10)
approx= ApproximatedSampler(model.weights, model.weights, model.hidden_bias, model.hidden_bias)
reconstruction = approx.v_to_v(rand_h,rand_h, composite_v.reshape(25),num_gibbs=500)
pp.image(reconstruction[0].reshape(5,5),show_colorbar=False, title="V'_a")
pp.image(reconstruction[1].reshape(5,5), show_colorbar=False, title = "V'_b" )
pp.image(reconstruction[0].reshape(5,5) + reconstruction[1].reshape(5,5),title="Composite Recon" ,cmap ='Paired',show_colorbar=False)
pp.image(s.reconstruction_given_visible(composite_v.reshape(25)).reshape(5,5),show_colorbar=False)


I am working on the file "May2015/vowpal_wabbit.ipynb".
The first task is:
Convert to VOWPAL WABBIT format
Can you write Python code for it?

import csv
import re
i = 0
def clean(s):
  return " ".join(re.findall(r'\w+', s,flags = re.UNICODE | re.LOCALE)).lower()
with open("train_titanic.csv", "r") as infile, open("train_titanic.vw", "wb") as outfile:
  reader = csv.reader(infile)
  for line in reader:
    i+= 1
    if i > 1:
      vw_line = ""
      if str(line[1]) == "1":
        vw_line += "1 '"
      else:
        vw_line += "-1 '"

      vw_line += str(line[0]) + " |f "

      vw_line += "passenger_class_" + str(line[2]) + " "
      vw_line += "sex_"             + str(line[3]) + " "
      vw_line += "age:"             + str(line[4]) + " "
      vw_line += "sibsp:"           + str(line[5]) + " "
      vw_line += "parch:"           + str(line[6]) + " "
      vw_line += "fare:"            + str(line[7]) + " "
      vw_line += "embarked_"        + str(line[8]) + " "
      vw_line += "last_name_"       + str(line[9]) + " "
      vw_line += "title_"           + str(line[10]) + " "
      vw_line += "fare2_"           + str(line[11]) + " "
      vw_line += "familysize:"      + str(line[12]) + " "
      vw_line += "farepp:"          + str(line[13]) + " "
      vw_line += "deck_"            + str(line[14]) + " "
      vw_line += "side_"            + str(line[15]) + " "

      outfile.write(vw_line[:-1] + "\n")
i = 0
with open("test_titanic.csv", "r") as infile, open("test_titanic.vw", "wb") as outfile:
  reader = csv.reader(infile)
  for line in reader:
    i+= 1
    if i > 1:
      vw_line = ""
      vw_line += "1 '"
      vw_line += str(line[0]) + " |f "

      vw_line += "passenger_class_" + str(line[1]) + " "
      vw_line += "sex_"             + str(line[2]) + " "
      vw_line += "age:"             + str(line[3]) + " "
      vw_line += "sibsp:"           + str(line[4]) + " "
      vw_line += "parch:"           + str(line[5]) + " "
      vw_line += "fare:"            + str(line[6]) + " "
      vw_line += "embarked_"        + str(line[7]) + " "
      vw_line += "last_name_"       + str(line[8]) + " "
      vw_line += "title_"         ...


I am working on the file "May2015/vowpal_wabbit.ipynb".
The first task is:
Create a model
vw train_titanic.vw -f model.vw --binary --passes 20 -c -q ff --adaptive --normalized --l1 0.00000001 --l2 0.0000001 -b 24
Predict
vw -d test_titanic.vw -t -i model.vw -p preds_titanic.txt
Create kaggle submission file
Can you write Python code for it?

import csv
with open("preds_titanic.txt", "r") as infile, open("submission_vw.csv", "wb") as outfile:
  outfile.write("PassengerId,Survived\n")
  for line in infile.readlines():
    kaggle_line = str(line.split(" ")[1]).replace("\n","")
    if str(int(float(line.split(" ")[0]))) == "1":
      kaggle_line += ",1\n"
    else:
      kaggle_line += ",0\n"
    outfile.write(kaggle_line)

i=0
with open("preds_titanic.txt", "r") as infile:
    for line in infile.readlines():
        print str(line.split(" ")[1]).replace("\n","")
        print str(float(line.split(" ")[0]))
        print str(int(float(line.split(" ")[0])))

        print
        i+=1
        if i>5: break


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
And to create the model:
Can you write Python code for it?

style_extractor = vgg_layers(style_layers)
style_outputs = style_extractor(style_image*255)

#Look at the statistics of each layer's output
for name, output in zip(style_layers, style_outputs):
  print(name)
  print("  shape: ", output.numpy().shape)
  print("  min: ", output.numpy().min())
  print("  max: ", output.numpy().max())
  print("  mean: ", output.numpy().mean())
  print()


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
Choose intermediate layers from the network to represent the style and content of the image:
Can you write Python code for it?

# Content layer where will pull our feature maps
content_layers = ['block5_conv2']

# Style layer of interest
style_layers = ['block1_conv1',
                'block2_conv1',
                'block3_conv1',
                'block4_conv1',
                'block5_conv1']

num_content_layers = len(content_layers)
num_style_layers = len(style_layers)


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
Create a simple function to display an image:
Can you write Python code for it?

def imshow(image, title=None):
  if len(image.shape) > 3:
    image = tf.squeeze(image, axis=0)

  plt.imshow(image)
  if title:
    plt.title(title)

content_image = load_img(content_path)
style_image = load_img(style_path)

plt.subplot(1, 2, 1)
imshow(content_image, 'Content Image')

plt.subplot(1, 2, 2)
imshow(style_image, 'Style Image')


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
Create an optimizer. The paper recommends LBFGS, but Adam works okay, too:
Can you write Python code for it?

opt = tf.optimizers.Adam(learning_rate=0.02, beta_1=0.99, epsilon=1e-1)


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
Define a tf.Variable to contain the image to optimize. To make this quick, initialize it with the content image (the tf.Variable must be the same shape as the content image):
Can you write Python code for it?


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
Define content and style representations
Use the intermediate layers of the model to get the content and style representations of the image. Starting from the network's input layer, the first few layer activations represent low-level features like edges and textures. As you step through the network, the final few layers represent higher-level features—object parts like wheels or eyes. In this case, you are using the VGG19 network architecture, a pretrained image classification network. These intermediate layers are necessary to define the representation of content and style from the images. For an input image, try to match the corresponding style and content target representations at these intermediate layers.
Load a VGG19 and test run it on our image to ensure it's used correctly:
Can you write Python code for it?

x = tf.keras.applications.vgg19.preprocess_input(content_image*255)
x = tf.image.resize(x, (224, 224))
vgg = tf.keras.applications.VGG19(include_top=True, weights='imagenet')
prediction_probabilities = vgg(x)
prediction_probabilities.shape

predicted_top_5 = tf.keras.applications.vgg19.decode_predictions(prediction_probabilities.numpy())[0]
[(class_name, prob) for (number, class_name, prob) in predicted_top_5]


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
Finally, save the result:
Can you write Python code for it?

file_name = 'stylized-image.png'
tensor_to_image(image).save(file_name)

try:
  from google.colab import files
except ImportError:
   pass
else:
  files.download(file_name)


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
Neural style transfer

    View on TensorFlow.org

    Run in Google Colab

    View source on GitHub

    Download notebook

This tutorial uses deep learning to compose one image in the style of another image (ever wish you could paint like Picasso or Van Gogh?). This is known as neural style transfer and the technique is outlined in A Neural Algorithm of Artistic Style (Gatys et al.).
Note: This tutorial demonstrates the original style-transfer algorithm. It optimizes the image content to a particular style. Modern approaches train a model to generate the stylized image directly (similar to cyclegan). This approach is much faster (up to 1000x). A pretrained Arbitrary Image Stylization module is available in TensorFlow Hub, and for TensorFlow Lite.
Neural style transfer is an optimization technique used to take two images—a content image and a style reference image (such as an artwork by a famous painter)—and blend them together so the output image looks like the content image, but “painted” in the style of the style reference image.
This is implemented by optimizing the output image to match...
Can you write Python code for it?

from __future__ import absolute_import, division, print_function, unicode_literals

try:
  # %tensorflow_version only exists in Colab.
  %tensorflow_version 2.x
except Exception:
  pass
import tensorflow as tf

import IPython.display as display

import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (12,12)
mpl.rcParams['axes.grid'] = False

import numpy as np
import PIL.Image
import time
import functools

def tensor_to_image(tensor):
  tensor = tensor*255
  tensor = np.array(tensor, dtype=np.uint8)
  if np.ndim(tensor)>3:
    assert tensor.shape[0] == 1
    tensor = tensor[0]
  return PIL.Image.fromarray(tensor)


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
Now include it in the train_step function:
Can you write Python code for it?

@tf.function()
def train_step(image):
  with tf.GradientTape() as tape:
    outputs = extractor(image)
    loss = style_content_loss(outputs)
    loss += total_variation_weight*tf.image.total_variation(image)

  grad = tape.gradient(loss, image)
  opt.apply_gradients([(grad, image)])
  image.assign(clip_0_1(image))


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
Now load a VGG19 without the classification head, and list the layer names
Can you write Python code for it?

vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet')

print()
for layer in vgg.layers:
  print(layer.name)


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
Now run a few steps to test:
Can you write Python code for it?

train_step(image)
train_step(image)
train_step(image)
tensor_to_image(image)


I am working on the file "Mayreck_style_transfer.ipynb".
The first task is:
Re-run the optimization
Choose a weight for the total_variation_loss:
Can you write Python code for it?