Skip to content

Commit

Permalink
Merge pull request #2 from mbrukman/update-python-from-notebook
Browse files Browse the repository at this point in the history
Re-generate Python code from IPython notebooks
  • Loading branch information
rasbt committed Jan 24, 2022
2 parents 8e5c2d2 + 6aade64 commit d1caac3
Show file tree
Hide file tree
Showing 14 changed files with 111 additions and 35 deletions.
2 changes: 1 addition & 1 deletion ch03/ch03.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ def loss_0(z):

plt.ylim(0.0, 5.1)
plt.xlim([0, 1])
plt.xlabel('$\sigma$(z)')
plt.xlabel('$\sigma(z)$')
plt.ylabel('L(w, b)')
plt.legend(loc='best')
plt.tight_layout()
Expand Down
1 change: 1 addition & 0 deletions ch04/ch04.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,7 @@




LogisticRegression(penalty='l1')


Expand Down
5 changes: 5 additions & 0 deletions ch07/ch07.py
Original file line number Diff line number Diff line change
Expand Up @@ -890,3 +890,8 @@ def get_params(self, deep=True):








2 changes: 1 addition & 1 deletion ch08/ch08.py
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ def get_minibatch(doc_stream, size):


n_top_words = 5
feature_names = count.get_feature_names()
feature_names = count.get_feature_names_out()

for topic_idx, topic in enumerate(lda.components_):
print(f'Topic {(topic_idx + 1)}:')
Expand Down
5 changes: 5 additions & 0 deletions ch09/ch09.py
Original file line number Diff line number Diff line change
Expand Up @@ -877,3 +877,8 @@ def mean_absolute_deviation(data):








5 changes: 5 additions & 0 deletions ch13/ch13_part1.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,3 +579,8 @@ def predict(self, x):








2 changes: 1 addition & 1 deletion ch13/ch13_part3_lightning.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@


class MultiLayerPerceptron(pl.LightningModule):
def __init__(self,image_shape=(1, 28, 28), hidden_units=(32, 16)):
def __init__(self, image_shape=(1, 28, 28), hidden_units=(32, 16)):
super().__init__()

# new PL attributes:
Expand Down
33 changes: 33 additions & 0 deletions ch13/ch13_part4_ignite.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# coding: utf-8


import sys
from python_environment_check import check_packages
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
Expand All @@ -11,6 +13,37 @@
from ignite.handlers import Checkpoint, DiskSaver
from ignite.contrib.handlers import TensorboardLogger, global_step_from_engine






# # Machine Learning with PyTorch and Scikit-Learn
# # -- Code Examples

# ## Package version checks

# Add folder to path in order to load from the check_packages.py script:



sys.path.insert(0, '..')


# Check recommended package versions:





d = {
'numpy': '1.21.2',
'matplotlib': '3.4.3',
'sklearn': '1.0',
}
check_packages(d)


# # Chapter 13: Going Deeper -- the Mechanics of PyTorch

# **Big thanks and credit to Victor Fomin for creating and helping with the original draft of this section!**
Expand Down
5 changes: 0 additions & 5 deletions ch15/ch15_part2.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,8 +410,3 @@ def forward(self, text, lengths):








7 changes: 1 addition & 6 deletions ch15/ch15_part3.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def __getitem__(self, idx):

class RNN(nn.Module):
def __init__(self, vocab_size, embed_dim, rnn_hidden_size):
super(RNN, self).__init__()
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.rnn_hidden_size = rnn_hidden_size
self.rnn = nn.LSTM(embed_dim, rnn_hidden_size,
Expand Down Expand Up @@ -365,8 +365,3 @@ def sample(model, starting_str,








9 changes: 7 additions & 2 deletions ch17/ch17_part1.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ def create_samples(g_model, input_z):
ax.set_xlabel('Iteration', size=15)
ax.set_ylabel('Discriminator output', size=15)

#plt.savefig('images/ch17-gan-learning-curve.pdf')
#plt.savefig('figures/ch17-gan-learning-curve.pdf')
plt.show()


Expand All @@ -467,7 +467,7 @@ def create_samples(g_model, input_z):
image = epoch_samples[e-1][j]
ax.imshow(image, cmap='gray_r')

#plt.savefig('images/ch17-vanila-gan-samples.pdf')
#plt.savefig('figures/ch17-vanila-gan-samples.pdf')
plt.show()


Expand Down Expand Up @@ -546,3 +546,8 @@ def compute_score(fake, real , k=1, sigma=1, sqrt=True):








53 changes: 39 additions & 14 deletions ch17/ch17_part2.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# coding: utf-8


import sys
from python_environment_check import check_packages
#from google.colab import drive
import torch
import torch.nn as nn
Expand All @@ -11,11 +13,33 @@
from torch.utils.data import DataLoader
from torch.autograd import grad as torch_grad

# *Python Machine Learning, PyTorch Edition* by [Sebastian Raschka](https://sebastianraschka.com), [Yuxi (Hayden) Liu](https://www.mlexample.com/) & [Vahid Mirjalili](http://vahidmirjalili.com), Packt Publishing Ltd. 2021
#
# Code Repository:
#
# Code License: [MIT License]()
# # Machine Learning with PyTorch and Scikit-Learn
# # -- Code Examples

# ## Package version checks

# Add folder to path in order to load from the check_packages.py script:



sys.path.insert(0, '..')


# Check recommended package versions:





d = {
'torch': '1.8.0',
'torchvision': '0.9.0',
'numpy': '1.21.2',
'matplotlib': '3.4.3',
}

check_packages(d)


# # Chapter 17 - Generative Adversarial Networks for Synthesizing New Data (Part 2/2)

Expand Down Expand Up @@ -80,6 +104,8 @@





print(torch.__version__)
print("GPU Available:", torch.cuda.is_available())

Expand All @@ -93,10 +119,13 @@




# ## Train the DCGAN model





image_path = './'
transform = transforms.Compose([
transforms.ToTensor(),
Expand Down Expand Up @@ -140,7 +169,7 @@ def make_generator_network(input_size, n_filters):

class Discriminator(nn.Module):
def __init__(self, n_filters):
super(Discriminator, self).__init__()
super().__init__()
self.network = nn.Sequential(
nn.Conv2d(1, n_filters, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2),
Expand Down Expand Up @@ -292,7 +321,7 @@ def create_samples(g_model, input_z):
image = epoch_samples[e-1][j]
ax.imshow(image, cmap='gray_r')

# plt.savefig('images/ch17-dcgan-samples.pdf')
# plt.savefig('figures/ch17-dcgan-samples.pdf')
plt.show()


Expand Down Expand Up @@ -335,7 +364,7 @@ def make_generator_network_wgan(input_size, n_filters):

class DiscriminatorWGAN(nn.Module):
def __init__(self, n_filters):
super(DiscriminatorWGAN, self).__init__()
super().__init__()
self.network = nn.Sequential(
nn.Conv2d(1, n_filters, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2),
Expand Down Expand Up @@ -368,6 +397,7 @@ def forward(self, input):




def gradient_penalty(real_data, generated_data):
batch_size = real_data.size(0)

Expand Down Expand Up @@ -474,7 +504,7 @@ def g_train_wgan(x):
image = epoch_samples_wgan[e-1][j]
ax.imshow(image, cmap='gray_r')

# plt.savefig('images/ch17-wgan-gp-samples.pdf')
# plt.savefig('figures/ch17-wgan-gp-samples.pdf')
plt.show()


Expand All @@ -496,8 +526,3 @@ def g_train_wgan(x):








5 changes: 0 additions & 5 deletions ch18/ch18_part2.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,3 @@ def forward(self, data):








12 changes: 12 additions & 0 deletions update_python_from_notebook.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/bin/bash

for ch in ch[0-9][0-9] ; do
pushd "${ch}"
for ipynb in *.ipynb ; do
py="${ipynb/ipynb/py}"
if [ -e "${py}" ]; then
python ../.convert_notebook_to_script.py --input "${ipynb}" --output "${py}"
fi
done
popd
done

0 comments on commit d1caac3

Please sign in to comment.