code
stringlengths 2.5k
6.36M
| kind
stringclasses 2
values | parsed_code
stringlengths 0
404k
| quality_prob
float64 0
0.98
| learning_prob
float64 0.03
1
|
---|---|---|---|---|
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```
# Selecting subway stations by geographical coordinates
It turns out that all but four of the largest 100 tech companies are located within a small slice of Manhattan, New York. The code below defines that region, which we will then use to filter for subway stations where we anticipate people will be more receptive to a women-in-tech conference. [Click here for the link to the article.](https://www.builtinnyc.com/2016/12/13/big-tech-companies-nyc-locations)
```
#coordinates for tech companies centered around World Trade Center (smaller circle)
point1 = (40.708984, -74.0111239) #SW Corner
point2 = (40.712274, -74.007657) #SE Corner
point3 = (40.714746, -74.009200) #NE Corner
point4 = (40.714830, -74.016226) #NW corner
#coordinates that include almost all large tech companies(larger circle)
point5 = (40.762261, -73.966260) #NE corner
point6 = (40.701598, -74.012487) #SE corner
point7 = (40.767958, -73.995653) #W corner
def coords_max_min(points):
'''
Accepts a list of coordinate pairs, [(latitude, longitude)].
Returns a tuple with the maximum and minimum longitude and lattitudes
(max_lat, min_lat, max_longs, min_longs)
'''
lats, longs = [], []
for point in points:
lats.append(point[0])
longs.append(point[1])
return (max(lats), min(lats), max(longs), min(longs))
shorter_points = [point1, point2, point3, point4]
longer_points = [point5, point6, point7]
station_entrances = pd.read_csv('http://web.mta.info/developers/data/nyct/subway/StationEntrances.csv')
station_entrances.head()
```
## Getting the short-list of companies located within the higher concentration nucleus in lower-west Manhattan
Here we use the `coords_max_min` function to get the maximum and minimum latitutude and longitude points for filtering stations.
```
lat_max, lat_min, long_max, long_min = coords_max_min(shorter_points)
#Filters out stations outside of max & min lat/long coordinates
short_list = station_entrances[(station_entrances['Station_Latitude'] > lat_min) & (station_entrances['Station_Latitude'] < lat_max)\
& (station_entrances['Station_Longitude'] > long_min) & (station_entrances['Station_Longitude'] < long_max)]
short_list.describe()
set(short_list['Station_Name']) #Unique stations within the concentration of tech firms around World Trade Center
```
## Getting a broader swath of Manhattan
The coordinates used in this list select for a map of Manhattan.
```
lat_max, lat_min, long_max, long_min = coords_max_min(longer_points)
#Filters out all stations outside of Silicon Alley
longer_list = station_entrances[(station_entrances['Station_Latitude'] > lat_min) & (station_entrances['Station_Latitude'] < lat_max)\
& (station_entrances['Station_Longitude'] > long_min) & (station_entrances['Station_Longitude'] < long_max)]
longer_list
set(longer_list['Station_Name']) #Unique stations within entire span of Silicon Alley
longer_list['Station_Name'].nunique()
longer_list.groupby(['Station_Name']).size() #Size possibly worth considering for best stations to send street team
longer_list.loc[longer_list['Station_Name'] == 'Grand Central-42nd St'] #Checking if large # of rows means duplicate stations
longer_list.groupby(['Division','Line','Station_Name']).size() #Looking for duplicate stations within larger python Set of stations
longer_list.groupby(['Station_Name', 'Line', 'Division']).size() #Checking for duplicate stations
short_list.groupby(['East_West_Street', 'North_South_Street', 'Station_Name']).size()
longer_list.to_pickle('longer_list.pkl')
del longer_list
```
|
github_jupyter
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#coordinates for tech companies centered around World Trade Center (smaller circle)
point1 = (40.708984, -74.0111239) #SW Corner
point2 = (40.712274, -74.007657) #SE Corner
point3 = (40.714746, -74.009200) #NE Corner
point4 = (40.714830, -74.016226) #NW corner
#coordinates that include almost all large tech companies(larger circle)
point5 = (40.762261, -73.966260) #NE corner
point6 = (40.701598, -74.012487) #SE corner
point7 = (40.767958, -73.995653) #W corner
def coords_max_min(points):
'''
Accepts a list of coordinate pairs, [(latitude, longitude)].
Returns a tuple with the maximum and minimum longitude and lattitudes
(max_lat, min_lat, max_longs, min_longs)
'''
lats, longs = [], []
for point in points:
lats.append(point[0])
longs.append(point[1])
return (max(lats), min(lats), max(longs), min(longs))
shorter_points = [point1, point2, point3, point4]
longer_points = [point5, point6, point7]
station_entrances = pd.read_csv('http://web.mta.info/developers/data/nyct/subway/StationEntrances.csv')
station_entrances.head()
lat_max, lat_min, long_max, long_min = coords_max_min(shorter_points)
#Filters out stations outside of max & min lat/long coordinates
short_list = station_entrances[(station_entrances['Station_Latitude'] > lat_min) & (station_entrances['Station_Latitude'] < lat_max)\
& (station_entrances['Station_Longitude'] > long_min) & (station_entrances['Station_Longitude'] < long_max)]
short_list.describe()
set(short_list['Station_Name']) #Unique stations within the concentration of tech firms around World Trade Center
lat_max, lat_min, long_max, long_min = coords_max_min(longer_points)
#Filters out all stations outside of Silicon Alley
longer_list = station_entrances[(station_entrances['Station_Latitude'] > lat_min) & (station_entrances['Station_Latitude'] < lat_max)\
& (station_entrances['Station_Longitude'] > long_min) & (station_entrances['Station_Longitude'] < long_max)]
longer_list
set(longer_list['Station_Name']) #Unique stations within entire span of Silicon Alley
longer_list['Station_Name'].nunique()
longer_list.groupby(['Station_Name']).size() #Size possibly worth considering for best stations to send street team
longer_list.loc[longer_list['Station_Name'] == 'Grand Central-42nd St'] #Checking if large # of rows means duplicate stations
longer_list.groupby(['Division','Line','Station_Name']).size() #Looking for duplicate stations within larger python Set of stations
longer_list.groupby(['Station_Name', 'Line', 'Division']).size() #Checking for duplicate stations
short_list.groupby(['East_West_Street', 'North_South_Street', 'Station_Name']).size()
longer_list.to_pickle('longer_list.pkl')
del longer_list
| 0.474875 | 0.871365 |
# Overview
This notebook introduces you MONAI's image transformation module.
```
# Copyright 2020 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import numpy as np
import torch
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import monai
from monai.transforms import \
LoadNifti, LoadNiftid, AddChanneld, ScaleIntensityRanged, \
Rand3DElasticd, RandAffined, \
Spacingd, Orientationd
monai.config.print_config()
```
## Data sources
Starting from a list of filenames.
The following is a simple python script
to group pairs of image and label from `Task09_Spleen/imagesTr` and `Task09_Spleen/labelsTr`
folder.
```
data_root = 'temp/Task09_Spleen'
import os
import glob
train_images = sorted(glob.glob(os.path.join(data_root, 'imagesTr', '*.nii.gz')))
train_labels = sorted(glob.glob(os.path.join(data_root, 'labelsTr', '*.nii.gz')))
data_dicts = [{'image': image_name, 'label': label_name}
for image_name, label_name in zip(train_images, train_labels)]
train_data_dicts, val_data_dicts = data_dicts[:-9], data_dicts[-9:]
```
The image file names are organised into a list of dictionaries.
```
train_data_dicts[0]
```
The list of data dictionaries, `train_data_dicts`, could be used by
PyTorch's data loader.
For example,
```python
from torch.utils.data import DataLoader
data_loader = DataLoader(train_data_dicts)
for training_sample in data_loader:
# run the deep learning training with training_sample
```
The rest of this tutorial presents a set of "transforms"
converting `train_data_dict` into data arrays that
will eventually be consumed by the deep learning models.
## Load the NIfTI files
One design choice of MONAI is that it provides not only the high-level workflow components,
but also relatively lower level APIs in their minimal functioning form.
For example, a `LoadNifti` class is a simple callable wrapper of the underlying `Nibabel` image loader.
After constructing the loader with a few necessary system parameters,
calling the loader instance with a NIfTI filename will return the image data arrays, as well as the metadata -- such as affine information and voxel sizes.
```
loader = LoadNifti(dtype=np.float32)
image, metadata = loader(train_data_dicts[0]['image'])
print('input:', train_data_dicts[0]['image'])
print('image shape', image.shape)
print('image affine', metadata['affine'])
print('image pixdim', metadata['pixdim'])
```
Oftentimes, we want to load a group of inputs as a training sample.
For example training a supervised image segmentation network requires a pair of image and label as a training sample.
To ensure a group of inputs are beining preprocessed consistently,
MONAI also provides dictionary-based interfaces for the minimal functioning transforms.
`LoadNiftid` is the corresponding dict-based version of `LoadNifti`:
```
loader = LoadNiftid(keys=('image', 'label'))
data_dict = loader(train_data_dicts[0])
print('input:', train_data_dicts[0])
print('image shape', data_dict['image'].shape)
print('label shape', data_dict['label'].shape)
print('image pixdim', data_dict['image.pixdim'])
image, label = data_dict['image'], data_dict['label']
plt.figure('visualise', (8, 4))
plt.subplot(1, 2, 1)
plt.title('image')
plt.imshow(image[:, :, 30], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('label')
plt.imshow(label[:, :, 30])
plt.show()
```
## Add the channel dimension
Most of MONAI's image transformations assume that the input data has the shape:
`[num_channels, spatial_dim_1, spatial_dim_2, ... ,spatial_dim_n]`
so that they could be interpreted consistently (as "channel-first" is commonly used in PyTorch).
Here the input image has shape `(512, 512, 55)` which isn't in the acceptable shape (missing the channel dimension),
we therefore create a transform which is called to updat the shape:
```
add_channel = AddChanneld(keys=['image', 'label'])
datac_dict = add_channel(data_dict)
print('image shape', datac_dict['image'].shape)
```
Now we are ready to do some intensity and spatial transforms.
## Resample to a consistent voxel size
The input volumes might have different voxel sizes.
The following transform is created to normlise the volumes to have (1.5, 1.5, 5.) millimetre voxel size.
The transform is set to read the original voxel size information from `data_dict['image.affine']`,
which is from the corresponding NIfTI file, loaded earlier by `LoadNiftid`.
```
spacing = Spacingd(keys=['image', 'label'],
pixdim=(1.5, 1.5, 5.), interp_order=(2, 0), mode='nearest')
data_dict = spacing(datac_dict)
print('image shape:', data_dict['image'].shape)
print('label shape:', data_dict['label'].shape)
print('image affine after Spacing\n', data_dict['image.affine'])
print('label affine after Spacing\n', data_dict['label.affine'])
```
To track the spacing changes, the data_dict was updated by `Spacingd`:
- An `image.original_affine` key is added to the `data_dict`, logs the original affine.
- An `image.affine` key is updated to have the current affine.
```
image, label = data_dict['image'], data_dict['label']
plt.figure('visualise', (8, 4))
plt.subplot(1, 2, 1)
plt.title('image')
plt.imshow(image[0, :, :, 30], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('label')
plt.imshow(label[0, :, :, 30])
plt.show()
```
## Reorientation to a designated axes codes
Sometimes it is nice to have all the input volumes in a consistent axes orientation.
The default axis labels are Left (L), Right (R), Posterior (P), Anterior (A), Inferior (I), Superior (S).
The following transform is created to reorientate the volumes to have 'Posterior, Left, Inferior' (PLI) orientation:
```
spacing = Orientationd(keys=['image', 'label'], axcodes='PLI')
data_dict = spacing(data_dict)
print('image shape:', data_dict['image'].shape)
print('label shape:', data_dict['label'].shape)
print('image affine after Spacing\n', data_dict['image.affine'])
print('label affine after Spacing\n', data_dict['label.affine'])
image, label = data_dict['image'], data_dict['label']
plt.figure('visualise', (8, 4))
plt.subplot(1, 2, 1)
plt.title('image')
plt.imshow(image[0, :, :, 30], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('label')
plt.imshow(label[0, :, :, 30])
plt.show()
```
## Random affine transformation
The following affine transformation is defined to output a (300, 300, 50) image patch.
The patch location is randomly chosen in a range of (-40, 40), (-40, 40), (-2, 2) in x, y, and z axes respectively.
The translation is relative to the image centre.
The 3D rotation angle is randomly chosen from (-45, 45) degrees around the z axis, and 5 degrees around x and y axes.
The random scaling factor is randomly chosen from (1.0 - 0.15, 1.0 + 0.15) along each axis.
```
rand_affine = RandAffined(keys=['image', 'label'], mode=('bilinear', 'nearest'), prob=1.0,
spatial_size=(300, 300, 50),
translate_range=(40, 40, 2),
rotate_range=(np.pi/36, np.pi/36, np.pi*4),
scale_range=(0.15, 0.15, 0.15),
padding_mode='border')
```
You can rerun this cell to generate a different randomised version of the original image.
```
affined_data_dict = rand_affine(data_dict)
print('image shape', affined_data_dict['image'].shape)
image, label = affined_data_dict['image'][0], affined_data_dict['label'][0]
plt.figure('visualise', (12, 6))
plt.subplot(1, 2, 1)
plt.title('image')
plt.imshow(image[:, :, 15], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('label')
plt.imshow(label[:, :, 15], cmap='gray')
plt.show()
```
## Random elastic deformation
Similarly, the following elastic deformation is defined to output a (300, 300, 10) image patch.
The image is resampled from a combination of affine transformations and elastic deformations.
`sigma_range` controls the smoothness of the deformation (larger than 15 could be slow on CPU)
`magnitude_rnage` controls the amplitude of the deformation (large than 500, the image becomes unrealistic).
```
rand_elastic = Rand3DElasticd(
keys=['image', 'label'], mode=('bilinear', 'nearest'), prob=1.0,
sigma_range=(5, 8),
magnitude_range=(100, 200),
spatial_size=(300, 300, 10),
translate_range=(50, 50, 2),
rotate_range=(np.pi/36, np.pi/36, np.pi*2),
scale_range=(0.15, 0.15, 0.15),
padding_mode='border')
```
You can rerun this cell to generate a different randomised version of the original image.
```
deformed_data_dict = rand_elastic(data_dict)
print('image shape', deformed_data_dict['image'].shape)
image, label = deformed_data_dict['image'][0], deformed_data_dict['label'][0]
plt.figure('visualise', (12, 6))
plt.subplot(1, 2, 1)
plt.title('image')
plt.imshow(image[:, :, 5], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('label')
plt.imshow(label[:, :, 5], cmap='gray')
plt.show()
```
|
github_jupyter
|
# Copyright 2020 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import numpy as np
import torch
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import monai
from monai.transforms import \
LoadNifti, LoadNiftid, AddChanneld, ScaleIntensityRanged, \
Rand3DElasticd, RandAffined, \
Spacingd, Orientationd
monai.config.print_config()
data_root = 'temp/Task09_Spleen'
import os
import glob
train_images = sorted(glob.glob(os.path.join(data_root, 'imagesTr', '*.nii.gz')))
train_labels = sorted(glob.glob(os.path.join(data_root, 'labelsTr', '*.nii.gz')))
data_dicts = [{'image': image_name, 'label': label_name}
for image_name, label_name in zip(train_images, train_labels)]
train_data_dicts, val_data_dicts = data_dicts[:-9], data_dicts[-9:]
train_data_dicts[0]
from torch.utils.data import DataLoader
data_loader = DataLoader(train_data_dicts)
for training_sample in data_loader:
# run the deep learning training with training_sample
loader = LoadNifti(dtype=np.float32)
image, metadata = loader(train_data_dicts[0]['image'])
print('input:', train_data_dicts[0]['image'])
print('image shape', image.shape)
print('image affine', metadata['affine'])
print('image pixdim', metadata['pixdim'])
loader = LoadNiftid(keys=('image', 'label'))
data_dict = loader(train_data_dicts[0])
print('input:', train_data_dicts[0])
print('image shape', data_dict['image'].shape)
print('label shape', data_dict['label'].shape)
print('image pixdim', data_dict['image.pixdim'])
image, label = data_dict['image'], data_dict['label']
plt.figure('visualise', (8, 4))
plt.subplot(1, 2, 1)
plt.title('image')
plt.imshow(image[:, :, 30], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('label')
plt.imshow(label[:, :, 30])
plt.show()
add_channel = AddChanneld(keys=['image', 'label'])
datac_dict = add_channel(data_dict)
print('image shape', datac_dict['image'].shape)
spacing = Spacingd(keys=['image', 'label'],
pixdim=(1.5, 1.5, 5.), interp_order=(2, 0), mode='nearest')
data_dict = spacing(datac_dict)
print('image shape:', data_dict['image'].shape)
print('label shape:', data_dict['label'].shape)
print('image affine after Spacing\n', data_dict['image.affine'])
print('label affine after Spacing\n', data_dict['label.affine'])
image, label = data_dict['image'], data_dict['label']
plt.figure('visualise', (8, 4))
plt.subplot(1, 2, 1)
plt.title('image')
plt.imshow(image[0, :, :, 30], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('label')
plt.imshow(label[0, :, :, 30])
plt.show()
spacing = Orientationd(keys=['image', 'label'], axcodes='PLI')
data_dict = spacing(data_dict)
print('image shape:', data_dict['image'].shape)
print('label shape:', data_dict['label'].shape)
print('image affine after Spacing\n', data_dict['image.affine'])
print('label affine after Spacing\n', data_dict['label.affine'])
image, label = data_dict['image'], data_dict['label']
plt.figure('visualise', (8, 4))
plt.subplot(1, 2, 1)
plt.title('image')
plt.imshow(image[0, :, :, 30], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('label')
plt.imshow(label[0, :, :, 30])
plt.show()
rand_affine = RandAffined(keys=['image', 'label'], mode=('bilinear', 'nearest'), prob=1.0,
spatial_size=(300, 300, 50),
translate_range=(40, 40, 2),
rotate_range=(np.pi/36, np.pi/36, np.pi*4),
scale_range=(0.15, 0.15, 0.15),
padding_mode='border')
affined_data_dict = rand_affine(data_dict)
print('image shape', affined_data_dict['image'].shape)
image, label = affined_data_dict['image'][0], affined_data_dict['label'][0]
plt.figure('visualise', (12, 6))
plt.subplot(1, 2, 1)
plt.title('image')
plt.imshow(image[:, :, 15], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('label')
plt.imshow(label[:, :, 15], cmap='gray')
plt.show()
rand_elastic = Rand3DElasticd(
keys=['image', 'label'], mode=('bilinear', 'nearest'), prob=1.0,
sigma_range=(5, 8),
magnitude_range=(100, 200),
spatial_size=(300, 300, 10),
translate_range=(50, 50, 2),
rotate_range=(np.pi/36, np.pi/36, np.pi*2),
scale_range=(0.15, 0.15, 0.15),
padding_mode='border')
deformed_data_dict = rand_elastic(data_dict)
print('image shape', deformed_data_dict['image'].shape)
image, label = deformed_data_dict['image'][0], deformed_data_dict['label'][0]
plt.figure('visualise', (12, 6))
plt.subplot(1, 2, 1)
plt.title('image')
plt.imshow(image[:, :, 5], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('label')
plt.imshow(label[:, :, 5], cmap='gray')
plt.show()
| 0.806052 | 0.964756 |
# Robot Sensors
A robot senses the world through cameras and other sensors, but these sensors are not perfectly accurate. In the video, you saw an example of a robot in a 1D world made of colored grid cells; all cells were either green or red. The robot then sensed that it was in a red grid cell.
The probability that this reading was accurate, which we'll call the prbability that the sensor has hit its target, `pHit`, was `0.6` and the probability that this reading was inaccurate (the sensor has missed its target) and the robot was *actually* in a green cell was `pMiss` equal to `0.2`.
In this notebook, let's go through how this works step by step.
### Uniform Distribution
The robot starts with a map with a length of 5 cells. Since the robot does not know where it is at first, the probability of being in any space is the same; a uniform distribution!
```
# importing resources
import matplotlib.pyplot as plt
import numpy as np
# ex. initialize_robot(5) = [0.2, 0.2, 0.2, 0.2, 0.2]
def initialize_robot(grid_length):
''' Takes in a grid length and returns
a uniform distribution of location probabilities'''
p = []
# create a list that has the value of 1/grid_length for each cell
for i in range(grid_length):
p.append(1.0/grid_length)
return p
```
I'll also include a helper function for visualizing this distribution. The below function, `display_map` will output a bar chart showing the probability that a robot is in each grid space. The y-axis has a range of 0 to 1 for the range of probabilities. For a uniform distribution, this will look like a flat line. You can choose the width of each bar to be <= 1 should you want to space these out.
```
def display_map(grid, bar_width=1):
if(len(grid) > 0):
x_labels = range(len(grid))
plt.bar(x_labels, height=grid, width=bar_width, color='b')
plt.xlabel('Grid Cell')
plt.ylabel('Probability')
plt.ylim(0, 1) # range of 0-1 for probability values
plt.title('Probability of the robot being at each cell in the grid')
plt.xticks(np.arange(min(x_labels), max(x_labels)+1, 1))
plt.show()
else:
print('Grid is empty')
# initialize a 5 cell, 1D world
p = initialize_robot(5)
display_map(p)
```
### Probability After Sense
Then the robot senses that it is in a red cell, and updates its probabilities. As per our example:
* The probability that it is sensing the correct color is `pHit = 0.6`.
* The probability that it is sensing the incorrect color (in this case: seeing red but *actually* in a green cell) is `pMiss = 0.2`
<img src='images/robot_sensing.png' width=50% height=50% />
#### Next, we write code that outputs a new grid, `p`, after multiplying each entry by pHit or pMiss at the appropriate places.
Remember that the red cells (cell 1 and 2) are "hits" and the other green cells are "misses."
Note that you may see values that are not exact due to how machines imperfectly represent floating points.
```
# given initial variables
p = initialize_robot(5)
pHit = 0.6
pMiss = 0.2
# Creates a new grid, with modified probabilities, after sensing
# All values are calculated by a product of 1. the sensing probability for a color (pHit for red)
# and 2. the current probability of a robot being in that location p[i]; all equal to 0.2 at first.
p[0] = p[0]*pMiss
p[1] = p[1]*pHit
p[2] = p[2]*pHit
p[3] = p[3]*pMiss
p[4] = p[4]*pMiss
print(p)
display_map(p)
```
You should see that the red grid cells (1 and 2) have a higher probability than the green cells. One thing that may look strange is how low these probability bars are, and you may have noticed that these don't accurately represent a probability distribution because the components of this list do not add up to 1!
### QUIZ: Compute the sum of all of these probabilities.
What do these values add up to and how do you think we can turn this into a probability distribution whose components do add up to 1?
In the next code cell, write code to sum up the values in the new world, `p`.
```
# What is the sum of all the values in p?
## TODO: add up all the values in the list of location probabilities to determine the answer
sum(p)
```
|
github_jupyter
|
# importing resources
import matplotlib.pyplot as plt
import numpy as np
# ex. initialize_robot(5) = [0.2, 0.2, 0.2, 0.2, 0.2]
def initialize_robot(grid_length):
''' Takes in a grid length and returns
a uniform distribution of location probabilities'''
p = []
# create a list that has the value of 1/grid_length for each cell
for i in range(grid_length):
p.append(1.0/grid_length)
return p
def display_map(grid, bar_width=1):
if(len(grid) > 0):
x_labels = range(len(grid))
plt.bar(x_labels, height=grid, width=bar_width, color='b')
plt.xlabel('Grid Cell')
plt.ylabel('Probability')
plt.ylim(0, 1) # range of 0-1 for probability values
plt.title('Probability of the robot being at each cell in the grid')
plt.xticks(np.arange(min(x_labels), max(x_labels)+1, 1))
plt.show()
else:
print('Grid is empty')
# initialize a 5 cell, 1D world
p = initialize_robot(5)
display_map(p)
# given initial variables
p = initialize_robot(5)
pHit = 0.6
pMiss = 0.2
# Creates a new grid, with modified probabilities, after sensing
# All values are calculated by a product of 1. the sensing probability for a color (pHit for red)
# and 2. the current probability of a robot being in that location p[i]; all equal to 0.2 at first.
p[0] = p[0]*pMiss
p[1] = p[1]*pHit
p[2] = p[2]*pHit
p[3] = p[3]*pMiss
p[4] = p[4]*pMiss
print(p)
display_map(p)
# What is the sum of all the values in p?
## TODO: add up all the values in the list of location probabilities to determine the answer
sum(p)
| 0.405566 | 0.991977 |
```
# default_exp performance
```
# Performance
> Paralellization for GPU and CPU
AlphaPept deals with high-throughput data. As this can be computationally intensive, we try to make all functions as performant as possible. To do so, we rely on two principles:
* **Compilation**
* **Parallelization**
A first step of **compilation** can be achieved by using NumPy arrays which are already heavily c-optimized. Net we consider three kinds of compilation:
* **Python** This allows to use no compilation
* **Numba** This allows to use just-in-time (JIT) compilation.
* **Cuda** This allows compilation on the GPU.
All of these compilation approaches can be combined with **parallelization** approaches. We consider the following possibilities:
* **No parallelization** Not all functionality can be parallelized.
* **Multithreading** This is only performant when Python's global interpreter lock (GIL) is released or when mostly using input-/output (IO) functions.
* **GPU** This is only available if an NVIDIA GPU is available and properly configured.
Note that not all compilation approaches can sensibly be combined with all parallelization approaches.
```
#export
COMPILATION_MODE_OPTIONS = [
"python",
"python-multithread",
"numba",
"numba-multithread",
"cuda", # Cuda is always multithreaded
]
```
Next we import all libraries, taking into account that not every machine has a GPU (with NVidia cuda cores) available:
```
#export
import functools
import math
import os
import logging
import psutil
import ast
# Parallelization
import multiprocessing
import threading
# Compilation
import numpy as np
import numba
from numba import cuda
try:
import cupy
cuda.get_current_device()
__GPU_AVAILABLE = True
except ModuleNotFoundError:
__GPU_AVAILABLE = False
cupy = None
logging.info("Cupy is not available")
except cuda.CudaSupportError:
__GPU_AVAILABLE = False
logging.info("Cuda device is not available")
def is_valid_compilation_mode(compilation_mode: str) -> None:
"""Check if the provided string is a valid compilation mode.
Args:
compilation_mode (str): The compilation mode to verify.
Raises:
ModuleNotFoundError: When trying to use an unavailable GPU.
NotImplementedError: When the compilation mode is not valid.
"""
if compilation_mode.startswith("cuda") and not __GPU_AVAILABLE:
raise ModuleNotFoundError('Cuda functions are not available.')
if compilation_mode not in COMPILATION_MODE_OPTIONS:
raise NotImplementedError(
f"Compilation mode '{compilation_mode}' is not available, "
"see COMPILATION_MODE_OPTIONS for available options."
)
```
By default, we will use `cuda` if it is available. If not, `numba-multithread` will be used as default.
```
#export
if __GPU_AVAILABLE:
COMPILATION_MODE = "cuda"
else:
COMPILATION_MODE = "numba-multithread"
```
To consistently use multiple threads or processes, we can set a global MAX_WORKER_COUNT parameter.
```
#export
MAX_WORKER_COUNT = psutil.cpu_count()
def set_worker_count(worker_count: int = 1, set_global: bool = True) -> int:
"""Parse and set the (global) number of threads.
Args:
worker_count (int): The number of workers.
If larger than available cores, it is trimmed to the available maximum.
If 0, it is set to the maximum cores available.
If negative, it indicates how many cores NOT to use.
Default is 1
set_global (bool): If False, the number of workers is only parsed to a valid value.
If True, the number of workers is saved as a global variable.
Default is True.
Returns:
int: The parsed worker_count.
"""
max_cpu_count = psutil.cpu_count()
if worker_count > max_cpu_count:
worker_count = max_cpu_count
else:
while worker_count <= 0:
worker_count += max_cpu_count
if set_global:
global MAX_WORKER_COUNT
MAX_WORKER_COUNT = worker_count
return worker_count
```
Compiled functions are intended to be very fast. However, they do not have the same flexibility as pure Python functions. In general, we recommend to use staticly defined compilation functions for optimal performance. We provide the option to define a default compilation mode for decorated functions, while also allowing to define the compilation mode for each individual function.
**NOTE**: Compiled functions are by default expected to be performed on a single thread. Thus, 'cuda' funtions are always assumed to be device functions which makes them callable from within the GPU, unless explicitly stated otherwise. Similarly, 'numba' functions are always assumed to bo 'nopython' and 'nogil'.
**NOTE** If the global compilation mode is set to Python, all decorators default to python, even if a specific compilation_mode is provided.
In addition, we allow to enable dynamic compilation, meaning the compilation mode of functions can be changed at runtime. Do note that this comes at the cost of some performance, as compilation needs to be done at runtime as well. Moreover, functions that are defined with dynamic compilation can not be called from within other compiled functions (with the exception of 'python' compilation, which means no compilation is actually performe|d).
**NOTE**: Dynamic compilation must be enabled before functions are decorated to take effect at runtime, otherwise they are statically compiled with the current settings at the time they are defined! Alternatively, statically compiled functions of a an 'imported_module' can reloaded (and thus statically be recompiled) with the commands:
```
import importlib
importlib.reload(imported_module)
```
```
#export
DYNAMIC_COMPILATION_ENABLED = False
def set_compilation_mode(
compilation_mode: str = None,
enable_dynamic_compilation: bool = None,
) -> None:
"""Set the global compilation mode to use.
Args:
compilation_mode (str): The compilation mode to use.
Will be checked with `is_valid_compilation_mode`.
Default is None
enable_dynamic_compilation (bool): Enable dynamic compilation.
If enabled, code will generally be slower and no other functions can
be called from within a compiled function anymore, as they are compiled at runtime.
WARNING: Enabling this is strongly disadvised in almost all cases!
Default is None.
"""
if enable_dynamic_compilation is not None:
global DYNAMIC_COMPILATION_ENABLED
DYNAMIC_COMPILATION_ENABLED = enable_dynamic_compilation
if compilation_mode is not None:
is_valid_compilation_mode(compilation_mode)
global COMPILATION_MODE
COMPILATION_MODE = compilation_mode
def compile_function(
_func: callable = None,
*,
compilation_mode: str = None,
**decorator_kwargs,
) -> callable:
"""A decorator to compile a given function.
Numba functions are by default set to use `nogil=True` and `nopython=True`,
unless explicitly defined otherwise.
Cuda functions are by default set to use `device=True`,
unless explicitly defined otherwise..
Args:
compilation_mode (str): The compilation mode to use.
Will be checked with `is_valid_compilation_mode`.
If None, the global COMPILATION_MODE will be used as soon as the function is decorated for static compilation.
If DYNAMIC_COMPILATION_ENABLED, the function will always be compiled at runtime and
thus by default returns a Python function.
Static recompilation can be enforced by reimporting a module containing
the function with importlib.reload(imported_module).
If COMPILATION_MODE is Python and not DYNAMIC_COMPILATION_ENABLED, no compilation will be used.
Default is None
**decorator_kwargs: Keyword arguments that will be passed to numba.jit or cuda.jit compilation decorators.
Returns:
callable: A decorated function that is compiled.
"""
if compilation_mode is None:
if DYNAMIC_COMPILATION_ENABLED:
compilation_mode = "dynamic"
else:
compilation_mode = COMPILATION_MODE
elif COMPILATION_MODE.startswith("python"):
compilation_mode = "python"
else:
is_valid_compilation_mode(compilation_mode)
def parse_compilation(current_compilation_mode, func):
if current_compilation_mode.startswith("python"):
compiled_function = __copy_func(func)
elif current_compilation_mode.startswith("numba"):
if "nogil" in decorator_kwargs:
if "nopython" in decorator_kwargs:
compiled_function = numba.jit(func, **decorator_kwargs)
else:
compiled_function = numba.jit(func, **decorator_kwargs, nopython=True)
elif "nopython" in decorator_kwargs:
compiled_function = numba.jit(func, **decorator_kwargs, nogil=True)
else:
compiled_function = numba.jit(func, **decorator_kwargs, nogil=True, nopython=True)
elif current_compilation_mode.startswith("cuda"):
if "device" in decorator_kwargs:
compiled_function = cuda.jit(func, **decorator_kwargs)
else:
compiled_function = cuda.jit(func, **decorator_kwargs, device=True)
return compiled_function
def decorated_function(func):
if compilation_mode != "dynamic":
is_valid_compilation_mode(compilation_mode)
static_compiled_function = parse_compilation(compilation_mode, func)
return functools.wraps(func)(static_compiled_function)
else:
def dynamic_compiled_function(*func_args, **func_kwargs):
compiled_function = parse_compilation(COMPILATION_MODE, func)
return compiled_function(*func_args, **func_kwargs)
return functools.wraps(func)(dynamic_compiled_function)
if _func is None:
return decorated_function
else:
return decorated_function(_func)
import types
import functools
def __copy_func(f):
"""Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)"""
g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__,
argdefs=f.__defaults__,
closure=f.__closure__)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
return g
```
Testing yields the expected results:
```
import types
set_compilation_mode(compilation_mode="numba-multithread")
@compile_function(compilation_mode="python")
def test_func_python(x):
"""Docstring test"""
x[0] += 1
@compile_function(compilation_mode="numba")
def test_func_numba(x):
"""Docstring test"""
x[0] += 1
set_compilation_mode(enable_dynamic_compilation=True)
@compile_function
def test_func_dynamic_runtime(x):
"""Docstring test"""
x[0] += 1
set_compilation_mode(enable_dynamic_compilation=False, compilation_mode="numba-multithread")
@compile_function
def test_func_static_runtime_numba(x):
"""Docstring test"""
x[0] += 1
a = np.zeros(1, dtype=np.int64)
assert(isinstance(test_func_python, types.FunctionType))
test_func_python(a)
assert(np.all(a == np.ones(1)))
a = np.zeros(1)
assert(isinstance(test_func_numba, numba.core.registry.CPUDispatcher))
test_func_numba(a)
assert(np.all(a == np.ones(1)))
if __GPU_AVAILABLE:
@compile_function(compilation_mode="cuda", device=None)
def test_func_cuda(x):
"""Docstring test"""
x[0] += 1
# Cuda function cannot be tested from outside the GPU
a = np.zeros(1)
assert(isinstance(test_func_cuda, numba.cuda.compiler.Dispatcher))
test_func_cuda.forall(1,1)(a)
assert(np.all(a == np.ones(1)))
set_compilation_mode(compilation_mode="python")
a = np.zeros(1)
assert(isinstance(test_func_static_runtime_numba, numba.core.registry.CPUDispatcher))
test_func_static_runtime_numba(a)
assert(np.all(a == np.ones(1)))
set_compilation_mode(compilation_mode="python")
a = np.zeros(1)
assert(isinstance(test_func_dynamic_runtime, types.FunctionType))
test_func_dynamic_runtime(a)
assert(np.all(a == np.ones(1)))
set_compilation_mode(compilation_mode="numba")
a = np.zeros(1)
assert(isinstance(test_func_dynamic_runtime, types.FunctionType))
test_func_dynamic_runtime(a)
assert(np.all(a == np.ones(1)))
# # Cuda function cannot be tested from outside the GPU
# set_compilation_mode(compilation_mode="cuda")
# a = np.zeros(1)
# assert(isinstance(test_func_dynamic_runtime, types.FunctionType))
# test_func_dynamic_runtime.forall(1,1)(a)
# assert(np.all(a == np.ones(1)))
```
Next, we define the 'performance_function' decorator to take full advantage of both compilation and parallelization for maximal performance. Note that a 'performance_function' can not return values. Instead, it should store results in provided buffer arrays.
```
#export
def performance_function(
_func: callable = None,
*,
worker_count: int = None,
compilation_mode: str = None,
**decorator_kwargs,
) -> callable:
"""A decorator to compile a given function and allow multithreading over an multiple indices.
NOTE This should only be used on functions that are compilable.
Functions that need to be decorated need to have an `index` argument as first argument.
If an iterable is provided to the decorated function,
the original (compiled) function will be applied to all elements of this iterable.
The most efficient way to provide iterables are with ranges, but numpy arrays work as well.
Functions can not return values,
results should be stored in buffer arrays inside thge function instead.
Args:
worker_count (int): The number of workers to use for multithreading.
If None, the global MAX_WORKER_COUNT is used at runtime.
Default is None.
compilation_mode (str): The compilation mode to use. Will be forwarded to the `compile_function` decorator.
**decorator_kwargs: Keyword arguments that will be passed to numba.jit or cuda.jit compilation decorators.
Returns:
callable: A decorated function that is compiled and parallelized.
"""
if worker_count is not None:
worker_count = set_worker_count(worker_count, set_global=False)
if compilation_mode is None:
if DYNAMIC_COMPILATION_ENABLED:
compilation_mode = "dynamic"
else:
compilation_mode = COMPILATION_MODE
elif COMPILATION_MODE.startswith("python"):
compilation_mode = "python"
else:
is_valid_compilation_mode(compilation_mode)
def _decorated_function(func):
if compilation_mode != "dynamic":
compiled_function = compile_function(
func,
compilation_mode=compilation_mode,
**decorator_kwargs
)
def _parallel_python(
compiled_function,
iterable,
start,
stop,
step,
*func_args
):
if start != -1:
for index in range(start, stop, step):
compiled_function(index, *func_args)
else:
for index in iterable:
compiled_function(index, *func_args)
_parallel_numba = numba.njit(nogil=True)(_parallel_python)
def _parallel_cuda(compiled_function, iterable, *func_args):
cuda_func_dict = {"cuda": cuda, "compiled_function": compiled_function}
# Cuda functions cannot handle tuple unpacking but need a fixed number of arguments.
if isinstance(iterable, range):
func_string = ", ".join(f"arg{i}" for i in range(len(func_args) + 3))
cuda_string = (
f"@cuda.jit\n"
f"def cuda_func({func_string}):\n"
f" index = arg0 + arg2 * cuda.grid(1)\n"
f" compiled_function(index, {func_string[18:]})\n"
)
exec(cuda_string, cuda_func_dict)
cuda_func_dict["cuda_func"].forall(len(iterable), 1)(
iterable.start,
iterable.stop,
iterable.step,
*func_args
)
else:
func_string = ", ".join(f"arg{i}" for i in range(len(func_args) + 1))
cuda_string = (
f"@cuda.jit\n"
f"def cuda_func({func_string}):\n"
f" index = arg0[cuda.grid(1)]\n"
f" compiled_function(index, {func_string[6:]})\n"
)
exec(cuda_string, cuda_func_dict)
cuda_func_dict["cuda_func"].forall(len(iterable), 1)(iterable, *func_args)
def _performance_function(iterable, *func_args):
if compilation_mode == "dynamic":
selected_compilation_mode = COMPILATION_MODE
_compiled_function = compile_function(
func,
compilation_mode=selected_compilation_mode,
**decorator_kwargs
)
else:
_compiled_function = compiled_function
selected_compilation_mode = compilation_mode
try:
iter(iterable)
except TypeError:
iterable = np.array([iterable])
if worker_count is None:
selected_worker_count = MAX_WORKER_COUNT
else:
selected_worker_count = worker_count
if selected_compilation_mode == "cuda":
_parallel_cuda(_compiled_function, iterable, *func_args)
else:
if "python" in selected_compilation_mode:
parallel_function = _parallel_python
elif "numba" in selected_compilation_mode:
parallel_function = _parallel_numba
else:
raise NotImplementedError(
f"Compilation mode {selected_compilation_mode} is not valid. "
"This error should not be possible, something is seriously wrong!!!"
)
if (selected_compilation_mode in ["python", "numba"]) or (selected_worker_count == 1):
iterable_is_range = isinstance(iterable, range)
x = np.empty(0, dtype=np.int64) if iterable_is_range else iterable
parallel_function(
_compiled_function,
np.empty(0, dtype=np.int64) if iterable_is_range else iterable,
iterable.start if iterable_is_range else -1,
iterable.stop if iterable_is_range else -1,
iterable.step if iterable_is_range else -1,
*func_args
)
else:
workers = []
for worker_id in range(selected_worker_count):
local_iterable = iterable[worker_id::selected_worker_count]
iterable_is_range = isinstance(local_iterable, range)
worker = threading.Thread(
target=parallel_function,
args=(
_compiled_function,
np.empty(0, dtype=np.int64) if iterable_is_range else local_iterable,
local_iterable.start if iterable_is_range else -1,
local_iterable.stop if iterable_is_range else -1,
local_iterable.step if iterable_is_range else -1,
*func_args
)
)
worker.start()
workers.append(worker)
for worker in workers:
worker.join()
del worker
return functools.wraps(func)(_performance_function)
if _func is None:
return _decorated_function
else:
return _decorated_function(_func)
```
We test this function with a simple smoothing algorithm.
```
def smooth_func(index, in_array, out_array, window_size):
min_index = max(index - window_size, 0)
max_index = min(index + window_size + 1, len(in_array))
smooth_value = 0
for i in range(min_index, max_index):
smooth_value += in_array[i]
out_array[index] += smooth_value / (max_index - min_index)
set_compilation_mode(compilation_mode="numba-multithread")
set_worker_count(0)
array_size = 10**6
smooth_factor = 10**4
# python test
in_array = np.arange(array_size)
out_array = np.zeros_like(in_array)
func = performance_function(compilation_mode="python")(smooth_func)
%time func(range(in_array[::100].shape[0]), in_array[::100], out_array[::100], smooth_factor//10) #too slow to test otherwise
# numba test
in_array = np.arange(array_size)
out_array = np.zeros_like(in_array)
func = performance_function(compilation_mode="numba")(smooth_func)
%time func(range(in_array.shape[0]), in_array, out_array, smooth_factor)
# numba-multithread test
in_array = np.arange(array_size)
out_array = np.zeros_like(in_array)
func = performance_function(compilation_mode="numba-multithread")(smooth_func)
%time func(range(in_array.shape[0]), in_array, out_array, smooth_factor)
# cuda test
if __GPU_AVAILABLE:
in_array = cupy.arange(array_size)
out_array = cupy.zeros_like(in_array)
func = performance_function(compilation_mode="cuda")(smooth_func)
%time func(range(in_array.shape[0]), in_array, out_array, smooth_factor)
%time tmp = out_array.get()
```
Finally, we also provide functionality to use multiprocessing instead of multithreading.
**NOTE**: There are some inherent limitation with the number of processes that Python can spawn. As such, no process Pool should use more than 50 processes.
```
#export
from multiprocessing import Pool
def AlphaPool(process_count: int) -> multiprocessing.Pool:
"""Create a multiprocessing.Pool object.
Args:
process_count (int): The number of processes.
If larger than available cores, it is trimmed to the available maximum.
Returns:
multiprocessing.Pool: A Pool object to parallelize functions with multiple processes.
"""
max_processes = psutil.cpu_count()
new_max = min(process_count, 50, max_processes)
if new_max == 0:
new_max = 1
logging.info(f"AlphaPool was set to {process_count} processes. Setting max to {new_max}.")
return Pool(new_max)
#hide
from nbdev.export import *
notebook2script()
```
|
github_jupyter
|
# default_exp performance
#export
COMPILATION_MODE_OPTIONS = [
"python",
"python-multithread",
"numba",
"numba-multithread",
"cuda", # Cuda is always multithreaded
]
#export
import functools
import math
import os
import logging
import psutil
import ast
# Parallelization
import multiprocessing
import threading
# Compilation
import numpy as np
import numba
from numba import cuda
try:
import cupy
cuda.get_current_device()
__GPU_AVAILABLE = True
except ModuleNotFoundError:
__GPU_AVAILABLE = False
cupy = None
logging.info("Cupy is not available")
except cuda.CudaSupportError:
__GPU_AVAILABLE = False
logging.info("Cuda device is not available")
def is_valid_compilation_mode(compilation_mode: str) -> None:
"""Check if the provided string is a valid compilation mode.
Args:
compilation_mode (str): The compilation mode to verify.
Raises:
ModuleNotFoundError: When trying to use an unavailable GPU.
NotImplementedError: When the compilation mode is not valid.
"""
if compilation_mode.startswith("cuda") and not __GPU_AVAILABLE:
raise ModuleNotFoundError('Cuda functions are not available.')
if compilation_mode not in COMPILATION_MODE_OPTIONS:
raise NotImplementedError(
f"Compilation mode '{compilation_mode}' is not available, "
"see COMPILATION_MODE_OPTIONS for available options."
)
#export
if __GPU_AVAILABLE:
COMPILATION_MODE = "cuda"
else:
COMPILATION_MODE = "numba-multithread"
#export
MAX_WORKER_COUNT = psutil.cpu_count()
def set_worker_count(worker_count: int = 1, set_global: bool = True) -> int:
"""Parse and set the (global) number of threads.
Args:
worker_count (int): The number of workers.
If larger than available cores, it is trimmed to the available maximum.
If 0, it is set to the maximum cores available.
If negative, it indicates how many cores NOT to use.
Default is 1
set_global (bool): If False, the number of workers is only parsed to a valid value.
If True, the number of workers is saved as a global variable.
Default is True.
Returns:
int: The parsed worker_count.
"""
max_cpu_count = psutil.cpu_count()
if worker_count > max_cpu_count:
worker_count = max_cpu_count
else:
while worker_count <= 0:
worker_count += max_cpu_count
if set_global:
global MAX_WORKER_COUNT
MAX_WORKER_COUNT = worker_count
return worker_count
import importlib
importlib.reload(imported_module)
#export
DYNAMIC_COMPILATION_ENABLED = False
def set_compilation_mode(
compilation_mode: str = None,
enable_dynamic_compilation: bool = None,
) -> None:
"""Set the global compilation mode to use.
Args:
compilation_mode (str): The compilation mode to use.
Will be checked with `is_valid_compilation_mode`.
Default is None
enable_dynamic_compilation (bool): Enable dynamic compilation.
If enabled, code will generally be slower and no other functions can
be called from within a compiled function anymore, as they are compiled at runtime.
WARNING: Enabling this is strongly disadvised in almost all cases!
Default is None.
"""
if enable_dynamic_compilation is not None:
global DYNAMIC_COMPILATION_ENABLED
DYNAMIC_COMPILATION_ENABLED = enable_dynamic_compilation
if compilation_mode is not None:
is_valid_compilation_mode(compilation_mode)
global COMPILATION_MODE
COMPILATION_MODE = compilation_mode
def compile_function(
_func: callable = None,
*,
compilation_mode: str = None,
**decorator_kwargs,
) -> callable:
"""A decorator to compile a given function.
Numba functions are by default set to use `nogil=True` and `nopython=True`,
unless explicitly defined otherwise.
Cuda functions are by default set to use `device=True`,
unless explicitly defined otherwise..
Args:
compilation_mode (str): The compilation mode to use.
Will be checked with `is_valid_compilation_mode`.
If None, the global COMPILATION_MODE will be used as soon as the function is decorated for static compilation.
If DYNAMIC_COMPILATION_ENABLED, the function will always be compiled at runtime and
thus by default returns a Python function.
Static recompilation can be enforced by reimporting a module containing
the function with importlib.reload(imported_module).
If COMPILATION_MODE is Python and not DYNAMIC_COMPILATION_ENABLED, no compilation will be used.
Default is None
**decorator_kwargs: Keyword arguments that will be passed to numba.jit or cuda.jit compilation decorators.
Returns:
callable: A decorated function that is compiled.
"""
if compilation_mode is None:
if DYNAMIC_COMPILATION_ENABLED:
compilation_mode = "dynamic"
else:
compilation_mode = COMPILATION_MODE
elif COMPILATION_MODE.startswith("python"):
compilation_mode = "python"
else:
is_valid_compilation_mode(compilation_mode)
def parse_compilation(current_compilation_mode, func):
if current_compilation_mode.startswith("python"):
compiled_function = __copy_func(func)
elif current_compilation_mode.startswith("numba"):
if "nogil" in decorator_kwargs:
if "nopython" in decorator_kwargs:
compiled_function = numba.jit(func, **decorator_kwargs)
else:
compiled_function = numba.jit(func, **decorator_kwargs, nopython=True)
elif "nopython" in decorator_kwargs:
compiled_function = numba.jit(func, **decorator_kwargs, nogil=True)
else:
compiled_function = numba.jit(func, **decorator_kwargs, nogil=True, nopython=True)
elif current_compilation_mode.startswith("cuda"):
if "device" in decorator_kwargs:
compiled_function = cuda.jit(func, **decorator_kwargs)
else:
compiled_function = cuda.jit(func, **decorator_kwargs, device=True)
return compiled_function
def decorated_function(func):
if compilation_mode != "dynamic":
is_valid_compilation_mode(compilation_mode)
static_compiled_function = parse_compilation(compilation_mode, func)
return functools.wraps(func)(static_compiled_function)
else:
def dynamic_compiled_function(*func_args, **func_kwargs):
compiled_function = parse_compilation(COMPILATION_MODE, func)
return compiled_function(*func_args, **func_kwargs)
return functools.wraps(func)(dynamic_compiled_function)
if _func is None:
return decorated_function
else:
return decorated_function(_func)
import types
import functools
def __copy_func(f):
"""Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)"""
g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__,
argdefs=f.__defaults__,
closure=f.__closure__)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
return g
import types
set_compilation_mode(compilation_mode="numba-multithread")
@compile_function(compilation_mode="python")
def test_func_python(x):
"""Docstring test"""
x[0] += 1
@compile_function(compilation_mode="numba")
def test_func_numba(x):
"""Docstring test"""
x[0] += 1
set_compilation_mode(enable_dynamic_compilation=True)
@compile_function
def test_func_dynamic_runtime(x):
"""Docstring test"""
x[0] += 1
set_compilation_mode(enable_dynamic_compilation=False, compilation_mode="numba-multithread")
@compile_function
def test_func_static_runtime_numba(x):
"""Docstring test"""
x[0] += 1
a = np.zeros(1, dtype=np.int64)
assert(isinstance(test_func_python, types.FunctionType))
test_func_python(a)
assert(np.all(a == np.ones(1)))
a = np.zeros(1)
assert(isinstance(test_func_numba, numba.core.registry.CPUDispatcher))
test_func_numba(a)
assert(np.all(a == np.ones(1)))
if __GPU_AVAILABLE:
@compile_function(compilation_mode="cuda", device=None)
def test_func_cuda(x):
"""Docstring test"""
x[0] += 1
# Cuda function cannot be tested from outside the GPU
a = np.zeros(1)
assert(isinstance(test_func_cuda, numba.cuda.compiler.Dispatcher))
test_func_cuda.forall(1,1)(a)
assert(np.all(a == np.ones(1)))
set_compilation_mode(compilation_mode="python")
a = np.zeros(1)
assert(isinstance(test_func_static_runtime_numba, numba.core.registry.CPUDispatcher))
test_func_static_runtime_numba(a)
assert(np.all(a == np.ones(1)))
set_compilation_mode(compilation_mode="python")
a = np.zeros(1)
assert(isinstance(test_func_dynamic_runtime, types.FunctionType))
test_func_dynamic_runtime(a)
assert(np.all(a == np.ones(1)))
set_compilation_mode(compilation_mode="numba")
a = np.zeros(1)
assert(isinstance(test_func_dynamic_runtime, types.FunctionType))
test_func_dynamic_runtime(a)
assert(np.all(a == np.ones(1)))
# # Cuda function cannot be tested from outside the GPU
# set_compilation_mode(compilation_mode="cuda")
# a = np.zeros(1)
# assert(isinstance(test_func_dynamic_runtime, types.FunctionType))
# test_func_dynamic_runtime.forall(1,1)(a)
# assert(np.all(a == np.ones(1)))
#export
def performance_function(
_func: callable = None,
*,
worker_count: int = None,
compilation_mode: str = None,
**decorator_kwargs,
) -> callable:
"""A decorator to compile a given function and allow multithreading over an multiple indices.
NOTE This should only be used on functions that are compilable.
Functions that need to be decorated need to have an `index` argument as first argument.
If an iterable is provided to the decorated function,
the original (compiled) function will be applied to all elements of this iterable.
The most efficient way to provide iterables are with ranges, but numpy arrays work as well.
Functions can not return values,
results should be stored in buffer arrays inside thge function instead.
Args:
worker_count (int): The number of workers to use for multithreading.
If None, the global MAX_WORKER_COUNT is used at runtime.
Default is None.
compilation_mode (str): The compilation mode to use. Will be forwarded to the `compile_function` decorator.
**decorator_kwargs: Keyword arguments that will be passed to numba.jit or cuda.jit compilation decorators.
Returns:
callable: A decorated function that is compiled and parallelized.
"""
if worker_count is not None:
worker_count = set_worker_count(worker_count, set_global=False)
if compilation_mode is None:
if DYNAMIC_COMPILATION_ENABLED:
compilation_mode = "dynamic"
else:
compilation_mode = COMPILATION_MODE
elif COMPILATION_MODE.startswith("python"):
compilation_mode = "python"
else:
is_valid_compilation_mode(compilation_mode)
def _decorated_function(func):
if compilation_mode != "dynamic":
compiled_function = compile_function(
func,
compilation_mode=compilation_mode,
**decorator_kwargs
)
def _parallel_python(
compiled_function,
iterable,
start,
stop,
step,
*func_args
):
if start != -1:
for index in range(start, stop, step):
compiled_function(index, *func_args)
else:
for index in iterable:
compiled_function(index, *func_args)
_parallel_numba = numba.njit(nogil=True)(_parallel_python)
def _parallel_cuda(compiled_function, iterable, *func_args):
cuda_func_dict = {"cuda": cuda, "compiled_function": compiled_function}
# Cuda functions cannot handle tuple unpacking but need a fixed number of arguments.
if isinstance(iterable, range):
func_string = ", ".join(f"arg{i}" for i in range(len(func_args) + 3))
cuda_string = (
f"@cuda.jit\n"
f"def cuda_func({func_string}):\n"
f" index = arg0 + arg2 * cuda.grid(1)\n"
f" compiled_function(index, {func_string[18:]})\n"
)
exec(cuda_string, cuda_func_dict)
cuda_func_dict["cuda_func"].forall(len(iterable), 1)(
iterable.start,
iterable.stop,
iterable.step,
*func_args
)
else:
func_string = ", ".join(f"arg{i}" for i in range(len(func_args) + 1))
cuda_string = (
f"@cuda.jit\n"
f"def cuda_func({func_string}):\n"
f" index = arg0[cuda.grid(1)]\n"
f" compiled_function(index, {func_string[6:]})\n"
)
exec(cuda_string, cuda_func_dict)
cuda_func_dict["cuda_func"].forall(len(iterable), 1)(iterable, *func_args)
def _performance_function(iterable, *func_args):
if compilation_mode == "dynamic":
selected_compilation_mode = COMPILATION_MODE
_compiled_function = compile_function(
func,
compilation_mode=selected_compilation_mode,
**decorator_kwargs
)
else:
_compiled_function = compiled_function
selected_compilation_mode = compilation_mode
try:
iter(iterable)
except TypeError:
iterable = np.array([iterable])
if worker_count is None:
selected_worker_count = MAX_WORKER_COUNT
else:
selected_worker_count = worker_count
if selected_compilation_mode == "cuda":
_parallel_cuda(_compiled_function, iterable, *func_args)
else:
if "python" in selected_compilation_mode:
parallel_function = _parallel_python
elif "numba" in selected_compilation_mode:
parallel_function = _parallel_numba
else:
raise NotImplementedError(
f"Compilation mode {selected_compilation_mode} is not valid. "
"This error should not be possible, something is seriously wrong!!!"
)
if (selected_compilation_mode in ["python", "numba"]) or (selected_worker_count == 1):
iterable_is_range = isinstance(iterable, range)
x = np.empty(0, dtype=np.int64) if iterable_is_range else iterable
parallel_function(
_compiled_function,
np.empty(0, dtype=np.int64) if iterable_is_range else iterable,
iterable.start if iterable_is_range else -1,
iterable.stop if iterable_is_range else -1,
iterable.step if iterable_is_range else -1,
*func_args
)
else:
workers = []
for worker_id in range(selected_worker_count):
local_iterable = iterable[worker_id::selected_worker_count]
iterable_is_range = isinstance(local_iterable, range)
worker = threading.Thread(
target=parallel_function,
args=(
_compiled_function,
np.empty(0, dtype=np.int64) if iterable_is_range else local_iterable,
local_iterable.start if iterable_is_range else -1,
local_iterable.stop if iterable_is_range else -1,
local_iterable.step if iterable_is_range else -1,
*func_args
)
)
worker.start()
workers.append(worker)
for worker in workers:
worker.join()
del worker
return functools.wraps(func)(_performance_function)
if _func is None:
return _decorated_function
else:
return _decorated_function(_func)
def smooth_func(index, in_array, out_array, window_size):
min_index = max(index - window_size, 0)
max_index = min(index + window_size + 1, len(in_array))
smooth_value = 0
for i in range(min_index, max_index):
smooth_value += in_array[i]
out_array[index] += smooth_value / (max_index - min_index)
set_compilation_mode(compilation_mode="numba-multithread")
set_worker_count(0)
array_size = 10**6
smooth_factor = 10**4
# python test
in_array = np.arange(array_size)
out_array = np.zeros_like(in_array)
func = performance_function(compilation_mode="python")(smooth_func)
%time func(range(in_array[::100].shape[0]), in_array[::100], out_array[::100], smooth_factor//10) #too slow to test otherwise
# numba test
in_array = np.arange(array_size)
out_array = np.zeros_like(in_array)
func = performance_function(compilation_mode="numba")(smooth_func)
%time func(range(in_array.shape[0]), in_array, out_array, smooth_factor)
# numba-multithread test
in_array = np.arange(array_size)
out_array = np.zeros_like(in_array)
func = performance_function(compilation_mode="numba-multithread")(smooth_func)
%time func(range(in_array.shape[0]), in_array, out_array, smooth_factor)
# cuda test
if __GPU_AVAILABLE:
in_array = cupy.arange(array_size)
out_array = cupy.zeros_like(in_array)
func = performance_function(compilation_mode="cuda")(smooth_func)
%time func(range(in_array.shape[0]), in_array, out_array, smooth_factor)
%time tmp = out_array.get()
#export
from multiprocessing import Pool
def AlphaPool(process_count: int) -> multiprocessing.Pool:
"""Create a multiprocessing.Pool object.
Args:
process_count (int): The number of processes.
If larger than available cores, it is trimmed to the available maximum.
Returns:
multiprocessing.Pool: A Pool object to parallelize functions with multiple processes.
"""
max_processes = psutil.cpu_count()
new_max = min(process_count, 50, max_processes)
if new_max == 0:
new_max = 1
logging.info(f"AlphaPool was set to {process_count} processes. Setting max to {new_max}.")
return Pool(new_max)
#hide
from nbdev.export import *
notebook2script()
| 0.728555 | 0.829837 |
# Project Milestones
Deliverable | Percent Complete | Estimated Completion Date | Percent Complete by Next Milestone
------------- |------------------:| --------------------------:|-----------------------------------:
Code | 25% | Apr. 11| 50%
Paper | 0% | Apr. 15 | 10%
Demo | 5% | Apr. 20 | 15%
Presentation | 0% | Apr.26 | 0%
### 1) No previous milestone. Milestones now set.
### 2) No previous milestone. No incomplete goals.
### 3) We need to finish our initial data manipulation, Manoj is working on this. We must also rewrite some windows batch files as bash commands, Greg is working on this. Then we will begin constructing a MLP to train with our dataset, Steven and Lian are working on this.
## Milestone 2
Deliverable | Percent Complete | Estimated Completion Date | Percent Complete by Next Milestone
------------- |------------------:| --------------------------:|-----------------------------------:
Code | 40% | Apr. 11| 75%
Paper | 0% | Apr. 15 | 10%
Demo | 10% | Apr. 20 | 25%
Presentation | 0% | Apr.26 | 0%
### 1) Unfortunatley, the data collection methods we are using are cumbersome and we are still working out how to correctly manipulate our training data set.
### 2) We have been focused on the data set and have just realized a new approach to train the neural net. This means we have not made progress on teh paper. Choosing the correct locations in our training data set will allow us to prepare our demo quickly.
### 3) We need to finish our initial data manipulation, Manoj and Greg are figuring out how to complete this. The MLP , Steven and Lian are working on this.
## Milestone 3
Deliverable | Percent Complete | Estimated Completion Date | Percent Complete by Next Milestone
------------- |------------------:| --------------------------:|-----------------------------------:
Code | 40% | Apr. 16| 100%
Paper | 0% | Apr. 15 | 10%
Demo | 10% | Apr. 20 | 25%
Presentation | 0% | Apr.26 | 0%
### 1) We are on track as per the last milestone. The new finish date for the code is Apr 16
### 2) The raw data and preproccessing have been refined. The introduction of the paper has been written. Our Neural net is showing good learning ability as of the first pass of data.
### 3) We need to take data and preprocess for the live demo, Manoj is making this happen. We need to ensure our NN is not over fitting and conduct testing, Greg and Steven are working on this. Lian is double checking all work and ensuring the paper is completed.
## Milestone 4
Deliverable | Percent Complete | Estimated Completion Date | Percent Complete by Next Milestone
------------- |------------------:| --------------------------:|-----------------------------------:
Code | 100% | Apr. 23| 100%
Paper | 100% | Apr. 23 | 100%
Demo | 100% | Apr. 23 | 100%
Presentation | 50% | Apr.30 | 100%
### 1) All code, demo, and paper are completed. Our group just needs to finess the presentation.
### 2) Our net trained well and can predict all testing (demo) locations correctly even though the data was taken at different times.
### 3) Each group member is being assigned a portion of the presentation to cover, this will ensure they have what they need to present. The group will be conducting practice runs on the 30th via skype.
|
github_jupyter
|
# Project Milestones
Deliverable | Percent Complete | Estimated Completion Date | Percent Complete by Next Milestone
------------- |------------------:| --------------------------:|-----------------------------------:
Code | 25% | Apr. 11| 50%
Paper | 0% | Apr. 15 | 10%
Demo | 5% | Apr. 20 | 15%
Presentation | 0% | Apr.26 | 0%
### 1) No previous milestone. Milestones now set.
### 2) No previous milestone. No incomplete goals.
### 3) We need to finish our initial data manipulation, Manoj is working on this. We must also rewrite some windows batch files as bash commands, Greg is working on this. Then we will begin constructing a MLP to train with our dataset, Steven and Lian are working on this.
## Milestone 2
Deliverable | Percent Complete | Estimated Completion Date | Percent Complete by Next Milestone
------------- |------------------:| --------------------------:|-----------------------------------:
Code | 40% | Apr. 11| 75%
Paper | 0% | Apr. 15 | 10%
Demo | 10% | Apr. 20 | 25%
Presentation | 0% | Apr.26 | 0%
### 1) Unfortunatley, the data collection methods we are using are cumbersome and we are still working out how to correctly manipulate our training data set.
### 2) We have been focused on the data set and have just realized a new approach to train the neural net. This means we have not made progress on teh paper. Choosing the correct locations in our training data set will allow us to prepare our demo quickly.
### 3) We need to finish our initial data manipulation, Manoj and Greg are figuring out how to complete this. The MLP , Steven and Lian are working on this.
## Milestone 3
Deliverable | Percent Complete | Estimated Completion Date | Percent Complete by Next Milestone
------------- |------------------:| --------------------------:|-----------------------------------:
Code | 40% | Apr. 16| 100%
Paper | 0% | Apr. 15 | 10%
Demo | 10% | Apr. 20 | 25%
Presentation | 0% | Apr.26 | 0%
### 1) We are on track as per the last milestone. The new finish date for the code is Apr 16
### 2) The raw data and preproccessing have been refined. The introduction of the paper has been written. Our Neural net is showing good learning ability as of the first pass of data.
### 3) We need to take data and preprocess for the live demo, Manoj is making this happen. We need to ensure our NN is not over fitting and conduct testing, Greg and Steven are working on this. Lian is double checking all work and ensuring the paper is completed.
## Milestone 4
Deliverable | Percent Complete | Estimated Completion Date | Percent Complete by Next Milestone
------------- |------------------:| --------------------------:|-----------------------------------:
Code | 100% | Apr. 23| 100%
Paper | 100% | Apr. 23 | 100%
Demo | 100% | Apr. 23 | 100%
Presentation | 50% | Apr.30 | 100%
### 1) All code, demo, and paper are completed. Our group just needs to finess the presentation.
### 2) Our net trained well and can predict all testing (demo) locations correctly even though the data was taken at different times.
### 3) Each group member is being assigned a portion of the presentation to cover, this will ensure they have what they need to present. The group will be conducting practice runs on the 30th via skype.
| 0.571886 | 0.745584 |
# Evaluation MIOST OI:
This notebook presents the evaluation of the SSH reconstructions based on the MIOST OI ([Ubelmann et al., 2020](https://www.essoar.org/doi/10.1002/essoar.10505014.1)) and performed for the **"2020a_SSH_mapping_NATL60" ocean data challenge**.
Two experiments are analysed:
> A) **Experiment 1**: MIOST SSH reconstruction with **4 nadir altimeters**
> B) **Experiment 2**: MIOST SSH reconstruction with **1 SWOT + 4 altimeters**
The evaluations are based on the methods & metrics described in the "example_data_eval.ipynb" notebook
```
import xarray as xr
import numpy
import hvplot.xarray
import pyinterp
import dask
import warnings
import xrft
import os
import sys
import pandas as pd
import logging
warnings.filterwarnings('ignore')
```
##### libraries versions
```
print('xarray', xr.__version__)
print('numpy', numpy.__version__)
print('hvplot', hvplot.__version__)
print('pyinterp', pyinterp.__version__)
print('dask', dask.__version__)
print('logging', logging.__version__)
print('xrft', xrft.__version__)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
sys.path.append('..')
from src.mod_oi import *
from src.mod_inout import *
from src.mod_regrid import *
from src.mod_eval import *
from src.mod_plot import *
```
##### Read Nature run SSH for mapping evaluation
```
if not os.path.exists('../dc_ref'):
print('dc_ref folder not found...')
print('download it...')
# Get nature run (it may take several minutes depending on your connection!!!!)
!wget https://ige-meom-opendap.univ-grenoble-alpes.fr/thredds/fileServer/meomopendap/extract/ocean-data-challenges/dc_data1/dc_ref.tar.gz
!tar -xvf dc_ref.tar.gz --directory ../
!rm -f dc_ref.tar.gz
dc_ref = xr.open_mfdataset('../dc_ref/*.nc', combine='nested', concat_dim='time', parallel=True)
dc_ref
# Domain for analysis
time_min = numpy.datetime64('2012-10-22') # domain min time
time_max = numpy.datetime64('2012-12-02') # domain max time
lon_min = -64.975 # domain min lon
lon_max = -55.007 # domain max lon
lat_min = 33.025 # domain min lat
lat_max = 42.9917 # domain max lat
```
##### Select time window sample for evaluation
```
dc_ref_sample = dc_ref.sel(time=slice(time_min, time_max),
lon=slice(lon_min, lon_max),
lat=slice(lat_min, lat_max), drop=True).resample(time='1D').mean()
del dc_ref
dc_ref_sample
```
#### - Evalutation MIOST OI with 4 nadirs (Experience 1)
```
# Read MIOST SSH reconstruction
!wget https://ige-meom-opendap.univ-grenoble-alpes.fr/thredds/fileServer/meomopendap/extract/ocean-data-challenges/dc_data1/dc_mapping/2020a_SSH_mapping_NATL60_MIOST_en_j1_tpn_g2.nc
ds_oi1_grid = xr.open_dataset('2020a_SSH_mapping_NATL60_MIOST_en_j1_tpn_g2.nc')
ds_oi1_grid
output_directory = '../results/'
if not os.path.exists(output_directory):
os.mkdir(output_directory)
%%time
# Regrid
ds_oi1_regrid = oi_regrid(ds_oi1_grid, dc_ref_sample)
# Eval
rmse_t_oi1, rmse_xy_oi1, leaderboard_nrmse, leaderboard_nrmse_std = rmse_based_scores(ds_oi1_regrid, dc_ref_sample)
psd_oi1, leaderboard_psds_score, leaderboard_psdt_score = psd_based_scores(ds_oi1_regrid, dc_ref_sample)
filename_rmse_t = output_directory + 'rmse_t_miost_ssh_reconstruction_2012-10-22-2012-12-02_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_rmse_xy = output_directory + 'rmse_xy_miost_ssh_reconstruction_2012-10-22-2012-12-02_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_psd = output_directory + 'psd_miost_ssh_reconstruction_2012-10-22-2012-12-02_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_dc_ref_sample = output_directory + 'dc_ref_2012-10-22-2012-12-02_sample.nc'
filename_oi_regrid = output_directory + 'miost_ssh_reconstruction_regridded_2012-10-22-2012-12-02_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
# Save results
# rmse_t_oi1.to_netcdf(filename_rmse_t)
# rmse_xy_oi1.to_netcdf(filename_rmse_xy)
psd_oi1.name = 'psd_score'
# psd_oi1.to_netcdf(filename_psd)
# dc_ref_sample.to_netcdf(filename_dc_ref_sample)
# ds_oi1_regrid.to_netcdf(filename_oi_regrid)
# Print leaderboard
data = [['miost 4 nadirs',
leaderboard_nrmse,
leaderboard_nrmse_std,
leaderboard_psds_score,
leaderboard_psdt_score,
'Multiscale mapping',
'eval_miost.ipynb']]
Leaderboard = pd.DataFrame(data,
columns=['Method',
"µ(RMSE) ",
"σ(RMSE)",
'λx (degree)',
'λt (days)',
'Notes',
'Reference'])
print("Summary of the leaderboard metrics:")
Leaderboard
print(Leaderboard.to_markdown())
```
#### - Evaluation MIOST OI with 1 swot + 4 nadirs (Experience 2)
```
# Read MIOST SSH reconstruction
!wget https://ige-meom-opendap.univ-grenoble-alpes.fr/thredds/fileServer/meomopendap/extract/ocean-data-challenges/dc_data1/dc_mapping/2020a_SSH_mapping_NATL60_MIOST_swot_en_j1_tpn_g2.nc
ds_oi2_grid = xr.open_dataset('2020a_SSH_mapping_NATL60_MIOST_swot_en_j1_tpn_g2.nc')
ds_oi2_grid
# Define outputs
output_directory = '../results/'
if not os.path.exists(output_directory):
os.mkdir(output_directory)
%%time
# Regrid
ds_oi2_regrid = oi_regrid(ds_oi2_grid, dc_ref_sample)
# Eval
rmse_t_oi2, rmse_xy_oi2, leaderboard_nrmse, leaderboard_nrmse_std = rmse_based_scores(ds_oi2_regrid, dc_ref_sample)
psd_oi2, leaderboard_psds_score, leaderboard_psdt_score = psd_based_scores(ds_oi2_regrid, dc_ref_sample)
filename_rmse_t = output_directory + 'rmse_t_miost_ssh_reconstruction_2012-10-22-2012-12-02_swot_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_rmse_xy = output_directory + 'rmse_xy_miost_ssh_reconstruction_2012-10-22-2012-12-02_swot_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_psd = output_directory + 'psd_miost_ssh_reconstruction_2012-10-22-2012-12-02_swot_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_dc_ref_sample = output_directory + 'dc_ref_2012-10-22-2012-12-02_sample.nc'
filename_oi_regrid = output_directory + 'miost_ssh_reconstruction_regridded_2012-10-22-2012-12-02_swot_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
# Save results
# rmse_t_oi2.to_netcdf(filename_rmse_t)
# rmse_xy_oi2.to_netcdf(filename_rmse_xy)
psd_oi2.name = 'psd_score'
# psd_oi2.to_netcdf(filename_psd)
# dc_ref_sample.to_netcdf(filename_dc_ref_sample)
# ds_oi2_regrid.to_netcdf(filename_oi_regrid)
# Print leaderboard
data = [['miost 1 swot + 4 nadirs',
leaderboard_nrmse,
leaderboard_nrmse_std,
leaderboard_psds_score,
leaderboard_psdt_score,
'Multiscale mapping',
'eval_miost.ipynb']]
Leaderboard = pd.DataFrame(data,
columns=['Method',
"µ(RMSE) ",
"σ(RMSE)",
'λx (degree)',
'λt (days)',
'Notes',
'Reference'])
print("Summary of the leaderboard metrics:")
Leaderboard
print(Leaderboard.to_markdown())
```
#### - PLOT EVALUATION SCORES
```
rmse_concat = xr.concat((rmse_t_oi1, rmse_t_oi2), dim='experiment')
rmse_concat['experiment'] = ["4 nadir", "1SWOT + 4 nadirs"]
rmse_concat.hvplot.line(x='time', y='rmse_t', by='experiment', ylim=(0, 1), cmap=['royalblue', 'lightcoral'], title='RMSE-based scores')
```
The figure above shows the time series of the RMSE scores for the reconstruction of SSH with 1 SWOT+ 4 nadirs and with 1 SWOT.
```
rmse_xy_concat = xr.concat((rmse_xy_oi1, rmse_xy_oi2), dim='experiment')
rmse_xy_concat['experiment'] = ["4 nadirs", "1 SWOT + 4 nadirs"]
rmse_xy_concat.hvplot.contourf(x='lon', y='lat', levels=list(numpy.arange(0.,0.75, 0.05)), height=300, width=400, cmap='Reds', subplots=True, by='experiment', clabel='RMSE[m]')
psd_concat = xr.concat((psd_oi1, psd_oi2), dim='experiment')
psd_concat['experiment'] = ["4 nadirs", "1 SWOT + 4 nadirs"]
plot_psd_score_v0(psd_concat)
```
The PSD-based score evaluates the spatio-temporal scales resolved in mapping (green area). Resolution limits can be defined as the contour where the PSD score = 0.5, black contour in the figure (i.e. space-time scales where the reconstruction SSH error level is 2 times lower than the real SSH signal). The figure above illustrates the spatio-temporal scales solved in each experiment 4 nadirs and 4 nadirs + 1 SWOT. It shows the slight increase in resolution capability from 4 nadirs altimeters to 4 nadirs + 1 SWOT altimeters for spatial wavelengths below 2 degrees.
|
github_jupyter
|
import xarray as xr
import numpy
import hvplot.xarray
import pyinterp
import dask
import warnings
import xrft
import os
import sys
import pandas as pd
import logging
warnings.filterwarnings('ignore')
print('xarray', xr.__version__)
print('numpy', numpy.__version__)
print('hvplot', hvplot.__version__)
print('pyinterp', pyinterp.__version__)
print('dask', dask.__version__)
print('logging', logging.__version__)
print('xrft', xrft.__version__)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
sys.path.append('..')
from src.mod_oi import *
from src.mod_inout import *
from src.mod_regrid import *
from src.mod_eval import *
from src.mod_plot import *
if not os.path.exists('../dc_ref'):
print('dc_ref folder not found...')
print('download it...')
# Get nature run (it may take several minutes depending on your connection!!!!)
!wget https://ige-meom-opendap.univ-grenoble-alpes.fr/thredds/fileServer/meomopendap/extract/ocean-data-challenges/dc_data1/dc_ref.tar.gz
!tar -xvf dc_ref.tar.gz --directory ../
!rm -f dc_ref.tar.gz
dc_ref = xr.open_mfdataset('../dc_ref/*.nc', combine='nested', concat_dim='time', parallel=True)
dc_ref
# Domain for analysis
time_min = numpy.datetime64('2012-10-22') # domain min time
time_max = numpy.datetime64('2012-12-02') # domain max time
lon_min = -64.975 # domain min lon
lon_max = -55.007 # domain max lon
lat_min = 33.025 # domain min lat
lat_max = 42.9917 # domain max lat
dc_ref_sample = dc_ref.sel(time=slice(time_min, time_max),
lon=slice(lon_min, lon_max),
lat=slice(lat_min, lat_max), drop=True).resample(time='1D').mean()
del dc_ref
dc_ref_sample
# Read MIOST SSH reconstruction
!wget https://ige-meom-opendap.univ-grenoble-alpes.fr/thredds/fileServer/meomopendap/extract/ocean-data-challenges/dc_data1/dc_mapping/2020a_SSH_mapping_NATL60_MIOST_en_j1_tpn_g2.nc
ds_oi1_grid = xr.open_dataset('2020a_SSH_mapping_NATL60_MIOST_en_j1_tpn_g2.nc')
ds_oi1_grid
output_directory = '../results/'
if not os.path.exists(output_directory):
os.mkdir(output_directory)
%%time
# Regrid
ds_oi1_regrid = oi_regrid(ds_oi1_grid, dc_ref_sample)
# Eval
rmse_t_oi1, rmse_xy_oi1, leaderboard_nrmse, leaderboard_nrmse_std = rmse_based_scores(ds_oi1_regrid, dc_ref_sample)
psd_oi1, leaderboard_psds_score, leaderboard_psdt_score = psd_based_scores(ds_oi1_regrid, dc_ref_sample)
filename_rmse_t = output_directory + 'rmse_t_miost_ssh_reconstruction_2012-10-22-2012-12-02_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_rmse_xy = output_directory + 'rmse_xy_miost_ssh_reconstruction_2012-10-22-2012-12-02_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_psd = output_directory + 'psd_miost_ssh_reconstruction_2012-10-22-2012-12-02_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_dc_ref_sample = output_directory + 'dc_ref_2012-10-22-2012-12-02_sample.nc'
filename_oi_regrid = output_directory + 'miost_ssh_reconstruction_regridded_2012-10-22-2012-12-02_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
# Save results
# rmse_t_oi1.to_netcdf(filename_rmse_t)
# rmse_xy_oi1.to_netcdf(filename_rmse_xy)
psd_oi1.name = 'psd_score'
# psd_oi1.to_netcdf(filename_psd)
# dc_ref_sample.to_netcdf(filename_dc_ref_sample)
# ds_oi1_regrid.to_netcdf(filename_oi_regrid)
# Print leaderboard
data = [['miost 4 nadirs',
leaderboard_nrmse,
leaderboard_nrmse_std,
leaderboard_psds_score,
leaderboard_psdt_score,
'Multiscale mapping',
'eval_miost.ipynb']]
Leaderboard = pd.DataFrame(data,
columns=['Method',
"µ(RMSE) ",
"σ(RMSE)",
'λx (degree)',
'λt (days)',
'Notes',
'Reference'])
print("Summary of the leaderboard metrics:")
Leaderboard
print(Leaderboard.to_markdown())
# Read MIOST SSH reconstruction
!wget https://ige-meom-opendap.univ-grenoble-alpes.fr/thredds/fileServer/meomopendap/extract/ocean-data-challenges/dc_data1/dc_mapping/2020a_SSH_mapping_NATL60_MIOST_swot_en_j1_tpn_g2.nc
ds_oi2_grid = xr.open_dataset('2020a_SSH_mapping_NATL60_MIOST_swot_en_j1_tpn_g2.nc')
ds_oi2_grid
# Define outputs
output_directory = '../results/'
if not os.path.exists(output_directory):
os.mkdir(output_directory)
%%time
# Regrid
ds_oi2_regrid = oi_regrid(ds_oi2_grid, dc_ref_sample)
# Eval
rmse_t_oi2, rmse_xy_oi2, leaderboard_nrmse, leaderboard_nrmse_std = rmse_based_scores(ds_oi2_regrid, dc_ref_sample)
psd_oi2, leaderboard_psds_score, leaderboard_psdt_score = psd_based_scores(ds_oi2_regrid, dc_ref_sample)
filename_rmse_t = output_directory + 'rmse_t_miost_ssh_reconstruction_2012-10-22-2012-12-02_swot_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_rmse_xy = output_directory + 'rmse_xy_miost_ssh_reconstruction_2012-10-22-2012-12-02_swot_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_psd = output_directory + 'psd_miost_ssh_reconstruction_2012-10-22-2012-12-02_swot_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
filename_dc_ref_sample = output_directory + 'dc_ref_2012-10-22-2012-12-02_sample.nc'
filename_oi_regrid = output_directory + 'miost_ssh_reconstruction_regridded_2012-10-22-2012-12-02_swot_jason1_topex-poseidon_interleaved_envisat_geosat2.nc'
# Save results
# rmse_t_oi2.to_netcdf(filename_rmse_t)
# rmse_xy_oi2.to_netcdf(filename_rmse_xy)
psd_oi2.name = 'psd_score'
# psd_oi2.to_netcdf(filename_psd)
# dc_ref_sample.to_netcdf(filename_dc_ref_sample)
# ds_oi2_regrid.to_netcdf(filename_oi_regrid)
# Print leaderboard
data = [['miost 1 swot + 4 nadirs',
leaderboard_nrmse,
leaderboard_nrmse_std,
leaderboard_psds_score,
leaderboard_psdt_score,
'Multiscale mapping',
'eval_miost.ipynb']]
Leaderboard = pd.DataFrame(data,
columns=['Method',
"µ(RMSE) ",
"σ(RMSE)",
'λx (degree)',
'λt (days)',
'Notes',
'Reference'])
print("Summary of the leaderboard metrics:")
Leaderboard
print(Leaderboard.to_markdown())
rmse_concat = xr.concat((rmse_t_oi1, rmse_t_oi2), dim='experiment')
rmse_concat['experiment'] = ["4 nadir", "1SWOT + 4 nadirs"]
rmse_concat.hvplot.line(x='time', y='rmse_t', by='experiment', ylim=(0, 1), cmap=['royalblue', 'lightcoral'], title='RMSE-based scores')
rmse_xy_concat = xr.concat((rmse_xy_oi1, rmse_xy_oi2), dim='experiment')
rmse_xy_concat['experiment'] = ["4 nadirs", "1 SWOT + 4 nadirs"]
rmse_xy_concat.hvplot.contourf(x='lon', y='lat', levels=list(numpy.arange(0.,0.75, 0.05)), height=300, width=400, cmap='Reds', subplots=True, by='experiment', clabel='RMSE[m]')
psd_concat = xr.concat((psd_oi1, psd_oi2), dim='experiment')
psd_concat['experiment'] = ["4 nadirs", "1 SWOT + 4 nadirs"]
plot_psd_score_v0(psd_concat)
| 0.293202 | 0.799716 |
```
# Load libraries
import numpy as np
import pandas as pd
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn import decomposition, preprocessing, svm
import seaborn as sns
sns.set_style('darkgrid')
import numpy as np
from scipy.stats import norm
from sklearn.preprocessing import StandardScaler
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
from sklearn.model_selection import train_test_split
from sklearn import ensemble
from sklearn.metrics import mean_absolute_error
from sklearn.externals import joblib
# Load dataset
heart_data = pd.read_csv("data//heart.csv")
heart_data.tail()
# 1 age: age in years
# 2 sex: sex (1 = male; 0 = female)
# 3 cp: chest pain type -- Value 1: typical angina -- Value 2: atypical angina -- Value 3: non-anginal pain -- Value 4: asymptomatic
# 4 trestbps: resting blood pressure (in mm Hg on admission to the hospital)
# 5 chol: serum cholestoral in mg/dl
# 6 fbs: (fasting blood sugar > 120 mg/dl) (1 = true; 0 = false)
# 7 restecg: resting electrocardiographic results -- Value 0: normal -- Value 1: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV) -- Value 2: showing probable or definite left ventricular hypertrophy by Estes' criteria
# 8 thalach: maximum heart rate achieved
# 9 exang: exercise induced angina (1 = yes; 0 = no) -- Exercise can cause an angina attack in someone with heart disease
# 10 oldpeak = ST depression induced by exercise relative to rest
# 11 slope: the slope of the peak exercise ST segment -- Value 1: upsloping -- Value 2: flat -- Value 3: downsloping
# 12 ca: number of major vessels (0-3) colored by flourosopy
# 13 thal: 3 = normal; 6 = fixed defect; 7 = reversable defect
# 14 target: the predicted attribute -- diagnosis of heart disease (angiographic disease status) -- Value 0: < 50% vessel diameter narrowing -- Value 1: > 50% vessel diameter narrowing
# Shape
print(heart_data.shape)
# Statistical description
heart_data.describe()
# From this, can tell that there is no missing data
# Class distribution to see how many are prone to heart attacks by the 'num' feature
print(heart_data.groupby('target').size())
fig, (ax1,ax2,ax3,ax4,ax5,ax6,ax7,ax8,ax9,ax10,ax11,ax12,ax13) = plt.subplots(13,1,figsize=(20,40))
sns.countplot(x='age', data=heart_data, ax=ax1)
sns.countplot(x='sex', data=heart_data, ax=ax2)
sns.countplot(x='cp', data=heart_data, ax=ax3)
sns.countplot(x='trestbps', data=heart_data, ax=ax4)
sns.countplot(x='chol', data=heart_data, ax=ax5)
sns.countplot(x='fbs', data=heart_data, ax=ax6)
sns.countplot(x='restecg', data=heart_data, ax=ax7)
sns.countplot(x='thalach', data=heart_data, ax=ax8)
sns.countplot(x='exang', data=heart_data, ax=ax9)
sns.countplot(x='oldpeak', data=heart_data, ax=ax10)
sns.countplot(x='slope', data=heart_data, ax=ax11)
sns.countplot(x='ca', data=heart_data, ax=ax12)
sns.countplot(x='thal', data=heart_data, ax=ax13)
# Features
X = heart_data.iloc[:,0:13]
# Classes / target
y = heart_data.iloc[:,-1]
# Get correlations of each features in dataset
corrmat = heart_data.corr()
top_corr_features = corrmat.index
plt.figure(figsize=(20,20))
# Plot heat map
g=sns.heatmap(heart_data[top_corr_features].corr(),annot=True,cmap="RdYlGn")
# Last row i.e target,
# target is correlated with other features,
# the features most highly correlated with target are:
# -- exang (-0.44)
# -- cp (0.43)
# -- oldpeak (-0.43)
# -- thalach (0.42)
# -- ca (-0.39)
# the features least correlated with target are:
# -- fbs (-0.028)
# -- chol (-0.085)
# Delete the fbs and chol columns
del heart_data['fbs']
del heart_data['chol']
heart_data.head()
#Shuffle the data
np.random.seed(18)
heart_data_shuffle = heart_data.iloc[np.random.permutation(len(heart_data))]
# Convert the Pandas dataframes into numpy arrays that can be used by scikit_learn
all_data = heart_data_shuffle[['age','sex','cp','trestbps','restecg','thalach','exang','oldpeak','slope','ca','thal', 'target']].values
# Create array of only the feature data
features = heart_data_shuffle[['age','sex','cp','trestbps','restecg','thalach','exang','oldpeak','slope','ca','thal']].values
# Separate array to contain target
targets = heart_data_shuffle['target'].values
# Also need array of the feature names - this will help later when exploring the data
feature_names = ['age','sex','cp','trestbps','restecg','thalach','exang','oldpeak','slope','ca','thal']
# print the features array of feature data
features
# Save the new heart attack data csv
df = pd.DataFrame(all_data, columns = ['age','sex','cp','trestbps','restecg','thalach','exang','oldpeak','slope','ca','thal','target'])
df.to_csv('new_heart_attack.csv')
# Normalize the attribute data using preprocessing.StandardScaler()
# Normalization means adjusting values measured on different scales to a common scale
from sklearn import preprocessing
scaler = preprocessing.StandardScaler()
features_scaled = scaler.fit_transform(features)
features_scaled
# scaler has calculated the mean and scaling factor to standardize each feature
scaler_mean = scaler.mean_
scaler_mean
scaler_scale = scaler.scale_
scaler_scale
# Split the data into the sets for training and testing
import numpy
from sklearn.model_selection import train_test_split
seed = 18
(training_inputs,
testing_inputs,
training_targets,
testing_targets) = train_test_split(features_scaled,
targets,
test_size=0.20,
train_size=0.80,
random_state=seed)
# DecisionTreeClassifier, fit to training data
clf= DecisionTreeClassifier(random_state=seed)
# Train the classifier on the training set
clf.fit(training_inputs, training_targets)
# Display the resulting decision tree
from IPython.display import Image
from sklearn.externals.six import StringIO
from sklearn import tree
from pydotplus import graph_from_dot_data
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data, feature_names=feature_names)
graph = graph_from_dot_data(dot_data.getvalue())
Image(graph.create_png())
# Using test data to measure the accuracy of the decision tree model
clf.score(testing_inputs, testing_targets)
# Using K-Fold cross validation to measure of your model's accuracy (K=10)
from sklearn.model_selection import cross_val_score
clf = DecisionTreeClassifier(random_state=seed)
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# Using RandomForestClassifier
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=10, random_state=seed)
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# SVM
from sklearn import svm
C = 1.0
svc = svm.SVC(kernel='linear', C=C)
cv_scores = cross_val_score(svc, features_scaled, targets, cv=10)
cv_scores.mean()
# KNeighborsClassifier
from sklearn import neighbors
clf = neighbors.KNeighborsClassifier(n_neighbors=10)
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# Trying different values of K for KNN
# Using for loop to run KNN with K values ranging from 1 to 10
# See if K makes a substantial difference.
for i in range(1, 10):
clf = neighbors.KNeighborsClassifier(n_neighbors=i)
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
print (i, cv_scores.mean())
# The best in this range is k=8
# Naive Bayes
from sklearn.naive_bayes import MultinomialNB
scaler = preprocessing.MinMaxScaler()
features_minmax = scaler.fit_transform(features)
clf = MultinomialNB()
cv_scores = cross_val_score(clf, features_minmax, targets, cv=10)
cv_scores.mean()
#GaussianNB
clf = GaussianNB()
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# Logistic Regression
clf = LogisticRegression()
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# LinearDiscriminantAnalysis
clf = LinearDiscriminantAnalysis()
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# DecisionTreeClassifier: 0.7689432703003337
# RandomForestClassifier: 0.8086206896551724
# SVM: 0.8353170189098998
# KNeighborsClassifier(k=10): 0.8348720800889877, when k=8: 0.8514386355209492
# Naive Bayes: 0.7882832777159807
# GaussianNB: 0.8217463848720801
# Logistic Regression: 0.832091212458287
# LinearDiscriminantAnalysis: 0.8319836855765665
# KNeighborsClassifier(k=8) is the best algorithm.
# Make predictions with testing data
knc = neighbors.KNeighborsClassifier(n_neighbors=8)
knc.fit(training_inputs, training_targets)
predictions = knc.predict(testing_inputs)
print("Accuracy:")
print(accuracy_score(testing_targets, predictions))
print()
print("Confusion matrix:")
print(confusion_matrix(testing_targets, predictions))
print()
print("Classification report:")
print(classification_report(testing_targets, predictions))
import pickle
pickle.dump(knc, open('models//trained_heart_attack_model.pkl', 'wb'))
knc_model = pickle.load(open('models//trained_heart_attack_model.pkl', 'rb'))
knc_model
print(classification_report(testing_targets, knc_model.predict(testing_inputs)))
# To prove that it is the same model that was saved (dumped) and loaded
#--- Find the error rate on the training set to check accuracy of our models predictions
# Pass in the y values which are the correct answers from the training data set
# Then we call svc_model.predict function on training features/inputs
# This will generate a prediction using our training model for each entry in the training data set
# scikit-learn will compare the predictions to the expected answers and tell us how close we are
mse = mean_absolute_error(training_targets, knc_model.predict(training_inputs))
print("Training Set Mean Absolute Error: %.4f" % mse)
#--- Find the error rate on the test set
# Do same calculation for the test data set but pass in the test data instead of the training data
mse = mean_absolute_error(testing_targets, knc_model.predict(testing_inputs))
print("Test Set Mean Absolute Error: %.4f" % mse)
# Inputs
# age = float(input("Enter age: "))
# sex = float(input("Enter 1 = male; 0 = female: "))
# cp = float(input("Enter cp (chest pain type) -- Value 1: typical angina -- Value 2: atypical angina -- Value 3: non-anginal pain -- Value 4: asymptomatic: "))
# trestbps = float(input("Enter trestbps (resting blood pressure in mm Hg on admission to the hospital): "))
# restecg = float(input("Enter restecg (resting electrocardiographic results) -- Value 0: normal -- Value 1: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV) -- Value 2: showing probable or definite left ventricular hypertrophy by Estes' criteria: "))
# thalach = float(input("Enter thalach (maximum heart rate achieved): "))
# exang = float(input("Enter exang (exercise induced angina) (1 = yes; 0 = no): "))
# oldpeak = float(input("Enter oldpeak (ST depression induced by exercise relative to rest): "))
# slope = float(input("Enter slope (the slope of the peak exercise ST segment) -- Value 1: upsloping -- Value 2: flat -- Value 3: downsloping: "))
# ca = float(input("Enter ca (number of major vessels (0-3) colored by flourosopy): "))
# thal = float(input("Enter thal (3 = normal; 6 = fixed defect; 7 = reversable defect): "))
age = 47.0
sex = 1.0
cp = 2.0
trestbps = 138.0
restecg = 0.0
thalach = 156.0
exang = 0.0
oldpeak = 0.0
slope = 2.0
ca = 0.0
thal = 2.0
# target: the predicted attribute -- diagnosis of heart disease (angiographic disease status)
# -- 0: < 50% vessel diameter narrowing (Low chance of heart attack/disease)
# -- 1: > 50% vessel diameter narrowing (High chance of heart attack/disease)
# Use the same scaler factors on the new data
scaler = preprocessing.StandardScaler()
features_scaled = scaler.fit_transform(features)
data = np.array([[age, sex, cp, trestbps, restecg, thalach, exang, oldpeak, slope, ca, thal]])
data_scaled = scaler.transform(data)
data_scaled
# Make a prediction against prediction features
prediction = knc_model.predict(data_scaled)
print(prediction)
if prediction == 0:
print("Low chance of heart attack/disease")
elif prediction == 1:
print("High chance of heart attack/disease")
else:
print("Unable to make a prediction")
```
|
github_jupyter
|
# Load libraries
import numpy as np
import pandas as pd
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn import decomposition, preprocessing, svm
import seaborn as sns
sns.set_style('darkgrid')
import numpy as np
from scipy.stats import norm
from sklearn.preprocessing import StandardScaler
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
from sklearn.model_selection import train_test_split
from sklearn import ensemble
from sklearn.metrics import mean_absolute_error
from sklearn.externals import joblib
# Load dataset
heart_data = pd.read_csv("data//heart.csv")
heart_data.tail()
# 1 age: age in years
# 2 sex: sex (1 = male; 0 = female)
# 3 cp: chest pain type -- Value 1: typical angina -- Value 2: atypical angina -- Value 3: non-anginal pain -- Value 4: asymptomatic
# 4 trestbps: resting blood pressure (in mm Hg on admission to the hospital)
# 5 chol: serum cholestoral in mg/dl
# 6 fbs: (fasting blood sugar > 120 mg/dl) (1 = true; 0 = false)
# 7 restecg: resting electrocardiographic results -- Value 0: normal -- Value 1: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV) -- Value 2: showing probable or definite left ventricular hypertrophy by Estes' criteria
# 8 thalach: maximum heart rate achieved
# 9 exang: exercise induced angina (1 = yes; 0 = no) -- Exercise can cause an angina attack in someone with heart disease
# 10 oldpeak = ST depression induced by exercise relative to rest
# 11 slope: the slope of the peak exercise ST segment -- Value 1: upsloping -- Value 2: flat -- Value 3: downsloping
# 12 ca: number of major vessels (0-3) colored by flourosopy
# 13 thal: 3 = normal; 6 = fixed defect; 7 = reversable defect
# 14 target: the predicted attribute -- diagnosis of heart disease (angiographic disease status) -- Value 0: < 50% vessel diameter narrowing -- Value 1: > 50% vessel diameter narrowing
# Shape
print(heart_data.shape)
# Statistical description
heart_data.describe()
# From this, can tell that there is no missing data
# Class distribution to see how many are prone to heart attacks by the 'num' feature
print(heart_data.groupby('target').size())
fig, (ax1,ax2,ax3,ax4,ax5,ax6,ax7,ax8,ax9,ax10,ax11,ax12,ax13) = plt.subplots(13,1,figsize=(20,40))
sns.countplot(x='age', data=heart_data, ax=ax1)
sns.countplot(x='sex', data=heart_data, ax=ax2)
sns.countplot(x='cp', data=heart_data, ax=ax3)
sns.countplot(x='trestbps', data=heart_data, ax=ax4)
sns.countplot(x='chol', data=heart_data, ax=ax5)
sns.countplot(x='fbs', data=heart_data, ax=ax6)
sns.countplot(x='restecg', data=heart_data, ax=ax7)
sns.countplot(x='thalach', data=heart_data, ax=ax8)
sns.countplot(x='exang', data=heart_data, ax=ax9)
sns.countplot(x='oldpeak', data=heart_data, ax=ax10)
sns.countplot(x='slope', data=heart_data, ax=ax11)
sns.countplot(x='ca', data=heart_data, ax=ax12)
sns.countplot(x='thal', data=heart_data, ax=ax13)
# Features
X = heart_data.iloc[:,0:13]
# Classes / target
y = heart_data.iloc[:,-1]
# Get correlations of each features in dataset
corrmat = heart_data.corr()
top_corr_features = corrmat.index
plt.figure(figsize=(20,20))
# Plot heat map
g=sns.heatmap(heart_data[top_corr_features].corr(),annot=True,cmap="RdYlGn")
# Last row i.e target,
# target is correlated with other features,
# the features most highly correlated with target are:
# -- exang (-0.44)
# -- cp (0.43)
# -- oldpeak (-0.43)
# -- thalach (0.42)
# -- ca (-0.39)
# the features least correlated with target are:
# -- fbs (-0.028)
# -- chol (-0.085)
# Delete the fbs and chol columns
del heart_data['fbs']
del heart_data['chol']
heart_data.head()
#Shuffle the data
np.random.seed(18)
heart_data_shuffle = heart_data.iloc[np.random.permutation(len(heart_data))]
# Convert the Pandas dataframes into numpy arrays that can be used by scikit_learn
all_data = heart_data_shuffle[['age','sex','cp','trestbps','restecg','thalach','exang','oldpeak','slope','ca','thal', 'target']].values
# Create array of only the feature data
features = heart_data_shuffle[['age','sex','cp','trestbps','restecg','thalach','exang','oldpeak','slope','ca','thal']].values
# Separate array to contain target
targets = heart_data_shuffle['target'].values
# Also need array of the feature names - this will help later when exploring the data
feature_names = ['age','sex','cp','trestbps','restecg','thalach','exang','oldpeak','slope','ca','thal']
# print the features array of feature data
features
# Save the new heart attack data csv
df = pd.DataFrame(all_data, columns = ['age','sex','cp','trestbps','restecg','thalach','exang','oldpeak','slope','ca','thal','target'])
df.to_csv('new_heart_attack.csv')
# Normalize the attribute data using preprocessing.StandardScaler()
# Normalization means adjusting values measured on different scales to a common scale
from sklearn import preprocessing
scaler = preprocessing.StandardScaler()
features_scaled = scaler.fit_transform(features)
features_scaled
# scaler has calculated the mean and scaling factor to standardize each feature
scaler_mean = scaler.mean_
scaler_mean
scaler_scale = scaler.scale_
scaler_scale
# Split the data into the sets for training and testing
import numpy
from sklearn.model_selection import train_test_split
seed = 18
(training_inputs,
testing_inputs,
training_targets,
testing_targets) = train_test_split(features_scaled,
targets,
test_size=0.20,
train_size=0.80,
random_state=seed)
# DecisionTreeClassifier, fit to training data
clf= DecisionTreeClassifier(random_state=seed)
# Train the classifier on the training set
clf.fit(training_inputs, training_targets)
# Display the resulting decision tree
from IPython.display import Image
from sklearn.externals.six import StringIO
from sklearn import tree
from pydotplus import graph_from_dot_data
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data, feature_names=feature_names)
graph = graph_from_dot_data(dot_data.getvalue())
Image(graph.create_png())
# Using test data to measure the accuracy of the decision tree model
clf.score(testing_inputs, testing_targets)
# Using K-Fold cross validation to measure of your model's accuracy (K=10)
from sklearn.model_selection import cross_val_score
clf = DecisionTreeClassifier(random_state=seed)
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# Using RandomForestClassifier
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=10, random_state=seed)
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# SVM
from sklearn import svm
C = 1.0
svc = svm.SVC(kernel='linear', C=C)
cv_scores = cross_val_score(svc, features_scaled, targets, cv=10)
cv_scores.mean()
# KNeighborsClassifier
from sklearn import neighbors
clf = neighbors.KNeighborsClassifier(n_neighbors=10)
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# Trying different values of K for KNN
# Using for loop to run KNN with K values ranging from 1 to 10
# See if K makes a substantial difference.
for i in range(1, 10):
clf = neighbors.KNeighborsClassifier(n_neighbors=i)
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
print (i, cv_scores.mean())
# The best in this range is k=8
# Naive Bayes
from sklearn.naive_bayes import MultinomialNB
scaler = preprocessing.MinMaxScaler()
features_minmax = scaler.fit_transform(features)
clf = MultinomialNB()
cv_scores = cross_val_score(clf, features_minmax, targets, cv=10)
cv_scores.mean()
#GaussianNB
clf = GaussianNB()
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# Logistic Regression
clf = LogisticRegression()
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# LinearDiscriminantAnalysis
clf = LinearDiscriminantAnalysis()
cv_scores = cross_val_score(clf, features_scaled, targets, cv=10)
cv_scores.mean()
# DecisionTreeClassifier: 0.7689432703003337
# RandomForestClassifier: 0.8086206896551724
# SVM: 0.8353170189098998
# KNeighborsClassifier(k=10): 0.8348720800889877, when k=8: 0.8514386355209492
# Naive Bayes: 0.7882832777159807
# GaussianNB: 0.8217463848720801
# Logistic Regression: 0.832091212458287
# LinearDiscriminantAnalysis: 0.8319836855765665
# KNeighborsClassifier(k=8) is the best algorithm.
# Make predictions with testing data
knc = neighbors.KNeighborsClassifier(n_neighbors=8)
knc.fit(training_inputs, training_targets)
predictions = knc.predict(testing_inputs)
print("Accuracy:")
print(accuracy_score(testing_targets, predictions))
print()
print("Confusion matrix:")
print(confusion_matrix(testing_targets, predictions))
print()
print("Classification report:")
print(classification_report(testing_targets, predictions))
import pickle
pickle.dump(knc, open('models//trained_heart_attack_model.pkl', 'wb'))
knc_model = pickle.load(open('models//trained_heart_attack_model.pkl', 'rb'))
knc_model
print(classification_report(testing_targets, knc_model.predict(testing_inputs)))
# To prove that it is the same model that was saved (dumped) and loaded
#--- Find the error rate on the training set to check accuracy of our models predictions
# Pass in the y values which are the correct answers from the training data set
# Then we call svc_model.predict function on training features/inputs
# This will generate a prediction using our training model for each entry in the training data set
# scikit-learn will compare the predictions to the expected answers and tell us how close we are
mse = mean_absolute_error(training_targets, knc_model.predict(training_inputs))
print("Training Set Mean Absolute Error: %.4f" % mse)
#--- Find the error rate on the test set
# Do same calculation for the test data set but pass in the test data instead of the training data
mse = mean_absolute_error(testing_targets, knc_model.predict(testing_inputs))
print("Test Set Mean Absolute Error: %.4f" % mse)
# Inputs
# age = float(input("Enter age: "))
# sex = float(input("Enter 1 = male; 0 = female: "))
# cp = float(input("Enter cp (chest pain type) -- Value 1: typical angina -- Value 2: atypical angina -- Value 3: non-anginal pain -- Value 4: asymptomatic: "))
# trestbps = float(input("Enter trestbps (resting blood pressure in mm Hg on admission to the hospital): "))
# restecg = float(input("Enter restecg (resting electrocardiographic results) -- Value 0: normal -- Value 1: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV) -- Value 2: showing probable or definite left ventricular hypertrophy by Estes' criteria: "))
# thalach = float(input("Enter thalach (maximum heart rate achieved): "))
# exang = float(input("Enter exang (exercise induced angina) (1 = yes; 0 = no): "))
# oldpeak = float(input("Enter oldpeak (ST depression induced by exercise relative to rest): "))
# slope = float(input("Enter slope (the slope of the peak exercise ST segment) -- Value 1: upsloping -- Value 2: flat -- Value 3: downsloping: "))
# ca = float(input("Enter ca (number of major vessels (0-3) colored by flourosopy): "))
# thal = float(input("Enter thal (3 = normal; 6 = fixed defect; 7 = reversable defect): "))
age = 47.0
sex = 1.0
cp = 2.0
trestbps = 138.0
restecg = 0.0
thalach = 156.0
exang = 0.0
oldpeak = 0.0
slope = 2.0
ca = 0.0
thal = 2.0
# target: the predicted attribute -- diagnosis of heart disease (angiographic disease status)
# -- 0: < 50% vessel diameter narrowing (Low chance of heart attack/disease)
# -- 1: > 50% vessel diameter narrowing (High chance of heart attack/disease)
# Use the same scaler factors on the new data
scaler = preprocessing.StandardScaler()
features_scaled = scaler.fit_transform(features)
data = np.array([[age, sex, cp, trestbps, restecg, thalach, exang, oldpeak, slope, ca, thal]])
data_scaled = scaler.transform(data)
data_scaled
# Make a prediction against prediction features
prediction = knc_model.predict(data_scaled)
print(prediction)
if prediction == 0:
print("Low chance of heart attack/disease")
elif prediction == 1:
print("High chance of heart attack/disease")
else:
print("Unable to make a prediction")
| 0.737064 | 0.592136 |
```
import casadi as ca
import sys
sys.path.insert(0, '../python/pyecca')
import matplotlib.pyplot as plt
from pyecca.util import rk4
import numpy as np
from casadi.tools.graph import dotgraph
from IPython.display import Image
def draw_graph(expr):
return Image(dotgraph(expr).create_png())
def numerical(x_end, n_x):
"""
Edit this function and setup an optimal control problem that minimizes the time
it takes for a ball rolling a long a curve to reach the end of the path assuming it
starts at a height of 1 m and ends at a height of 0 m and the length of the path is
x_end m.
"""
g = 9.81 # (m/s^2)
x = np.linspace(0, x_end, n_x) # x position where path changes
dx = x[1] - x[0] # path steps width
n_dy = n_x - 1 # number of height changes we need to find
dy0 = -(1/n_dy)*np.ones(n_dy) # initial guess for height change along path
dy_opt = dy0 # TODO, find optimal change in y along path
t = 0
y = 1
dy_vect = ca.SX.sym('dy_vect', n_dy)
for i in range(n_dy):
dy = dy_vect[i]
# dy1 = dy_vect[i+1]
d = np.sqrt(dx**2 + dy**2)
y1 = y + dy
vbar = (np.sqrt(2*g*(1-y)) + np.sqrt(2*g*(1-y1)))/2
# dt = d/vbar
y = y1
t += d/vbar
y_final = y
t_final = t
nlp = {'x':dy_vect, 'f':t_final,'g':y_final}
S = ca.nlpsol('S', 'ipopt', nlp, {
'print_time': 0,
'ipopt': {
'sb': 'yes',
'print_level': 0,
}
})
res = S(x0=dy0, lbg=0, ubg=0)
dy_opt = res['x']
print(res)
y_opt = ca.vertcat(1, 1 + np.cumsum(dy_opt))
return x, y_opt
# NLP declaration to solve for boundary condition of brachistochrone
def analytical(x_end, n_x):
c = ca.SX.sym('c')
theta_f = ca.SX.sym('theta_f')
xf = c*(theta_f - np.sin(theta_f))
yf = 1 - c*(1 - np.cos(theta_f))
nlp = {'x':ca.vertcat(c, theta_f), 'f':0,'g':ca.vertcat(xf-x_end,yf)}
S = ca.nlpsol('S', 'ipopt', nlp, {
'print_time': 0,
'ipopt': {
'sb': 'yes',
'print_level': 0,
}
})
res = S(x0=(1, np.pi), lbg=(0, 0), ubg=(0, 0))
C_opt = float(res['x'][0])
theta_f_opt = float(res['x'][1])
theta = np.linspace(0, theta_f_opt, n_x)
xa = C_opt*(theta - np.sin(theta))
ya = 1 - C_opt*(1 - np.cos(theta))
return xa, ya
n_x = 100 # number of points for approximation of path
x_end = 3 # final x position when height is zero
# analytical solution
xa, ya = analytical(x_end=x_end, n_x=100)
# numerical solution
x, y_opt = numerical(x_end=x_end, n_x=n_x)
# plot
plt.title('brachistochrone')
plt.plot(x, y_opt, label='numerical')
plt.plot(xa, ya, 'r--', label='analytical', alpha=0.5)
plt.grid(True)
plt.xlabel('x, m')
plt.ylabel('z, m')
plt.legend()
```
|
github_jupyter
|
import casadi as ca
import sys
sys.path.insert(0, '../python/pyecca')
import matplotlib.pyplot as plt
from pyecca.util import rk4
import numpy as np
from casadi.tools.graph import dotgraph
from IPython.display import Image
def draw_graph(expr):
return Image(dotgraph(expr).create_png())
def numerical(x_end, n_x):
"""
Edit this function and setup an optimal control problem that minimizes the time
it takes for a ball rolling a long a curve to reach the end of the path assuming it
starts at a height of 1 m and ends at a height of 0 m and the length of the path is
x_end m.
"""
g = 9.81 # (m/s^2)
x = np.linspace(0, x_end, n_x) # x position where path changes
dx = x[1] - x[0] # path steps width
n_dy = n_x - 1 # number of height changes we need to find
dy0 = -(1/n_dy)*np.ones(n_dy) # initial guess for height change along path
dy_opt = dy0 # TODO, find optimal change in y along path
t = 0
y = 1
dy_vect = ca.SX.sym('dy_vect', n_dy)
for i in range(n_dy):
dy = dy_vect[i]
# dy1 = dy_vect[i+1]
d = np.sqrt(dx**2 + dy**2)
y1 = y + dy
vbar = (np.sqrt(2*g*(1-y)) + np.sqrt(2*g*(1-y1)))/2
# dt = d/vbar
y = y1
t += d/vbar
y_final = y
t_final = t
nlp = {'x':dy_vect, 'f':t_final,'g':y_final}
S = ca.nlpsol('S', 'ipopt', nlp, {
'print_time': 0,
'ipopt': {
'sb': 'yes',
'print_level': 0,
}
})
res = S(x0=dy0, lbg=0, ubg=0)
dy_opt = res['x']
print(res)
y_opt = ca.vertcat(1, 1 + np.cumsum(dy_opt))
return x, y_opt
# NLP declaration to solve for boundary condition of brachistochrone
def analytical(x_end, n_x):
c = ca.SX.sym('c')
theta_f = ca.SX.sym('theta_f')
xf = c*(theta_f - np.sin(theta_f))
yf = 1 - c*(1 - np.cos(theta_f))
nlp = {'x':ca.vertcat(c, theta_f), 'f':0,'g':ca.vertcat(xf-x_end,yf)}
S = ca.nlpsol('S', 'ipopt', nlp, {
'print_time': 0,
'ipopt': {
'sb': 'yes',
'print_level': 0,
}
})
res = S(x0=(1, np.pi), lbg=(0, 0), ubg=(0, 0))
C_opt = float(res['x'][0])
theta_f_opt = float(res['x'][1])
theta = np.linspace(0, theta_f_opt, n_x)
xa = C_opt*(theta - np.sin(theta))
ya = 1 - C_opt*(1 - np.cos(theta))
return xa, ya
n_x = 100 # number of points for approximation of path
x_end = 3 # final x position when height is zero
# analytical solution
xa, ya = analytical(x_end=x_end, n_x=100)
# numerical solution
x, y_opt = numerical(x_end=x_end, n_x=n_x)
# plot
plt.title('brachistochrone')
plt.plot(x, y_opt, label='numerical')
plt.plot(xa, ya, 'r--', label='analytical', alpha=0.5)
plt.grid(True)
plt.xlabel('x, m')
plt.ylabel('z, m')
plt.legend()
| 0.373419 | 0.80837 |
## Leveraging World Events to Predict E-Commerce Consumer Demand under Anomaly
```
import sys
sys.path.append('.')
sys.path.append('../')
import os
import os.path as path
import datetime
import pandas as pd
import random
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import darts
from darts import TimeSeries
import cufflinks as cf
cf.go_offline()
from plotly.offline import plot, download_plotlyjs, init_notebook_mode, plot, iplot
from IPython.display import display, Math, Markdown
from IPython.display import display, Markdown, clear_output
import ipywidgets as widgets
%load_ext autoreload
%autoreload 2
```
## Import Functions
```
import config as proj_config
cache_path = proj_config.CACHE_DIR
data_path = proj_config.DATA_DIR
events_data_path = proj_config.EVENTS_DATASET_DIR
categories_path = cache_path + '/categories_events/'
from demand_prediction.general_functions import get_file_path, get_df_table, load_table_cache, save_table_cache, get_pred_dates
from demand_prediction.dataset_functions import split_data, create_events_df
from demand_prediction.ts_models import train_models, test_models, save_model, load_model
from demand_prediction.events_models import load_events_model, save_events_model, calc_events_ts
from demand_prediction.neural_prophet_model import NeuralProphetEvents, reformat_events_name, get_events_for_neural_prophet, get_neural_prophet_results
from demand_prediction.lstm_models import get_lstm_results
from demand_prediction.tcn_models import get_tcn_results
from demand_prediction.results_functions import get_all_k_metrics
```
# Datasets
## Events
```
world_events = get_df_table("events/world_events_dataset_from_1980")
world_events.head()
```
## Ecommerce
Use the following random time series as an expample or provide your own time series.
Please make sure that the ts is a DataFrame that contains one column which is the product sales, and the index is the dates.
```
dates_example = pd.date_range("2018-06-01", "2020-12-31",freq='d')
values_example = np.random.randint(100,2000,size=(len(dates_example)))
categ_data = pd.DataFrame({'date': dates_example, 'Quantity': values_example})
categ_data.index = categ_data['date']
categ_data = categ_data.drop(columns=['date'])
```
## Time Series
```
leaf_name = 'Football Cards'
categ_data.iplot(title=leaf_name, xTitle='Date', yTitle='Sales', theme='white', colors=['steelblue'])
```
### Events Dataset
```
data = create_events_df(categ_data, world_events, emb_only=True)
events_dates = list(set(data['date']))
```
### Hyper-Parameters
```
ts_cache = True
neural_cache = True
lstm_cache = True
lstm_df_cache = True
tcn_cache = True
tcn_df_cache = True
results_cache = True
n_in = 365
window_size = 2
prediction_time = 30
device = 'cpu' # use 'cuda:2' if you have GPUs
total_pred = pd.DataFrame()
start_pred_list = get_pred_dates('2020-01-01', '2021-01-01')
for start_pred_time in tqdm(start_pred_list):
pred_path = cache_path + "/saved_results/final_results_" + leaf_name + "_" + str(start_pred_time) + "_predictions"
if pred_path and os.path.isfile(pred_path):
total_pred = pd.read_pickle(pred_path)
else:
X_train, X_test = split_data(data, start_pred_time)
time_series = TimeSeries.from_dataframe(categ_data, value_cols='Quantity')
train, test_ts = time_series.split_before(pd.Timestamp(start_pred_time))
test = test_ts[:prediction_time]
events_all = pd.concat([X_train, X_test])
train_df, test_df = train.pd_dataframe(), test.pd_dataframe()
train_dates, test_dates = train_df.index.values, test_df.index.values
res_prediction = test_models(test, test_name=leaf_name, start_pred_time=start_pred_time, train=train, use_cache=ts_cache)
lstm_predictions = get_lstm_results(train, test, train_df, test_df, events_all, start_pred_time, leaf_name, n_in, window_size, categ_data, device, lstm_df_cache, lstm_cache)
tcn_predictions = get_tcn_results(train, test, train_df, test_df, events_all, start_pred_time, leaf_name, n_in, window_size, categ_data, device, tcn_df_cache, tcn_cache)
neural_predictions = get_neural_prophet_results(train, test, events_all, leaf_name, events_dates, start_pred_time, neural_cache)
total_pred = pd.concat([total_pred, pd.concat([res_prediction, lstm_predictions, tcn_predictions, neural_predictions], axis=1)])
os.makedirs(os.path.dirname(pred_path), exist_ok=True)
total_pred.to_pickle(pred_path)
```
# Prediction Plot
```
total_pred = total_pred[total_pred.index >= start_pred_list[0]]
pred_df = total_pred[['Real Quantity', 'LSTM', 'GAN - Event LSTM', 'Event LSTM', 'Weighted Event LSTM', 'ARIMA', 'Prophet', 'NeuralProphet', 'GAN - Event CNN']]
pred_df.iplot(title = leaf_name + " - All Models", xTitle='Date', yTitle='Sales', theme='white')
```
# Metrics@K
```
get_all_k_metrics(total_pred)
```
|
github_jupyter
|
import sys
sys.path.append('.')
sys.path.append('../')
import os
import os.path as path
import datetime
import pandas as pd
import random
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import darts
from darts import TimeSeries
import cufflinks as cf
cf.go_offline()
from plotly.offline import plot, download_plotlyjs, init_notebook_mode, plot, iplot
from IPython.display import display, Math, Markdown
from IPython.display import display, Markdown, clear_output
import ipywidgets as widgets
%load_ext autoreload
%autoreload 2
import config as proj_config
cache_path = proj_config.CACHE_DIR
data_path = proj_config.DATA_DIR
events_data_path = proj_config.EVENTS_DATASET_DIR
categories_path = cache_path + '/categories_events/'
from demand_prediction.general_functions import get_file_path, get_df_table, load_table_cache, save_table_cache, get_pred_dates
from demand_prediction.dataset_functions import split_data, create_events_df
from demand_prediction.ts_models import train_models, test_models, save_model, load_model
from demand_prediction.events_models import load_events_model, save_events_model, calc_events_ts
from demand_prediction.neural_prophet_model import NeuralProphetEvents, reformat_events_name, get_events_for_neural_prophet, get_neural_prophet_results
from demand_prediction.lstm_models import get_lstm_results
from demand_prediction.tcn_models import get_tcn_results
from demand_prediction.results_functions import get_all_k_metrics
world_events = get_df_table("events/world_events_dataset_from_1980")
world_events.head()
dates_example = pd.date_range("2018-06-01", "2020-12-31",freq='d')
values_example = np.random.randint(100,2000,size=(len(dates_example)))
categ_data = pd.DataFrame({'date': dates_example, 'Quantity': values_example})
categ_data.index = categ_data['date']
categ_data = categ_data.drop(columns=['date'])
leaf_name = 'Football Cards'
categ_data.iplot(title=leaf_name, xTitle='Date', yTitle='Sales', theme='white', colors=['steelblue'])
data = create_events_df(categ_data, world_events, emb_only=True)
events_dates = list(set(data['date']))
ts_cache = True
neural_cache = True
lstm_cache = True
lstm_df_cache = True
tcn_cache = True
tcn_df_cache = True
results_cache = True
n_in = 365
window_size = 2
prediction_time = 30
device = 'cpu' # use 'cuda:2' if you have GPUs
total_pred = pd.DataFrame()
start_pred_list = get_pred_dates('2020-01-01', '2021-01-01')
for start_pred_time in tqdm(start_pred_list):
pred_path = cache_path + "/saved_results/final_results_" + leaf_name + "_" + str(start_pred_time) + "_predictions"
if pred_path and os.path.isfile(pred_path):
total_pred = pd.read_pickle(pred_path)
else:
X_train, X_test = split_data(data, start_pred_time)
time_series = TimeSeries.from_dataframe(categ_data, value_cols='Quantity')
train, test_ts = time_series.split_before(pd.Timestamp(start_pred_time))
test = test_ts[:prediction_time]
events_all = pd.concat([X_train, X_test])
train_df, test_df = train.pd_dataframe(), test.pd_dataframe()
train_dates, test_dates = train_df.index.values, test_df.index.values
res_prediction = test_models(test, test_name=leaf_name, start_pred_time=start_pred_time, train=train, use_cache=ts_cache)
lstm_predictions = get_lstm_results(train, test, train_df, test_df, events_all, start_pred_time, leaf_name, n_in, window_size, categ_data, device, lstm_df_cache, lstm_cache)
tcn_predictions = get_tcn_results(train, test, train_df, test_df, events_all, start_pred_time, leaf_name, n_in, window_size, categ_data, device, tcn_df_cache, tcn_cache)
neural_predictions = get_neural_prophet_results(train, test, events_all, leaf_name, events_dates, start_pred_time, neural_cache)
total_pred = pd.concat([total_pred, pd.concat([res_prediction, lstm_predictions, tcn_predictions, neural_predictions], axis=1)])
os.makedirs(os.path.dirname(pred_path), exist_ok=True)
total_pred.to_pickle(pred_path)
total_pred = total_pred[total_pred.index >= start_pred_list[0]]
pred_df = total_pred[['Real Quantity', 'LSTM', 'GAN - Event LSTM', 'Event LSTM', 'Weighted Event LSTM', 'ARIMA', 'Prophet', 'NeuralProphet', 'GAN - Event CNN']]
pred_df.iplot(title = leaf_name + " - All Models", xTitle='Date', yTitle='Sales', theme='white')
get_all_k_metrics(total_pred)
| 0.256459 | 0.629091 |
<a href="https://colab.research.google.com/github/manasdesai/QSTP_Aerial-Robotics_2021/blob/main/Week4.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
%matplotlib inline
```
Implement a GH Filter for the data that is generated below. Play with the function and see how your filter performs. \\
Refer to the Chapter on G-H Filter from [Kalman and Bayesian Filters](https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python/blob/master/01-g-h-filter.ipynb)
```
def function(t):
"""This is a linear combination of sine and cosine fucntions
Implement your own function and play with the filter
"""
return 2 * np.sin(t/100) + 5 * np.cos(t/350)
T = np.arange(0, 1000, 1.5)
values = [function(t) for t in T]
plt.plot(T, values, color="red", alpha=0.75, label="Actual Data")
plt.title("Actual")
plt.legend();
# Add noise to the measurement
def noise(val):
# x = mu + y * std (Std Normal to Gaussian)
return val + np.random.randn() * 0.5
values_noisy = [noise(val) for val in values]
plt.scatter(list(T), values_noisy, color="black", alpha=0.5, s=1, label="Noisy")
# plt.plot(T, values, color="red", alpha=0.75, label="Actual")
plt.title("Noisy vs Actual")
plt.legend();
```
# Task I
Filter the list `values_noisy` using a GH Filter and get an estimate close to the real Value. You can plot `values_filtered`, `values_noisy` and `values` to get to know how filtering works
```
"""Implement a GH_Filter Here"""
def GHFilter(noisy_values: list, g: float, h: float)->list:
filtered_values = []
# Adjust and play with G and H values. You can also plot filtered
# data for various g and h values also
g = g # 0.9
h = h # 0.1
dt=1
# Implement the Algorithm here
x_est = 5
dx=0.02
filtered_values = []
for z in noisy_values:
# prediction step
x_pred = x_est + (dx*dt)
dx = dx
# update step
residual = z - x_pred
dx = dx + h * (residual) / dt
x_est = x_pred + g * residual
filtered_values.append(x_est)
return np.array(filtered_values)
return filtered_values
g = 0.55
h = 0.015
values_filtered = GHFilter(values_noisy,g, h)
plt.scatter(list(T), values_noisy, color="black", alpha=0.5, s=1, label="Noisy")
plt.plot(T, values, color="red", alpha=0.75, label="Actual")
plt.plot(T, values_filtered, color="green", alpha=0.75, label="Filtered")
plt.title("Noisy vs Filtered vs Actual")
plt.legend();
```
# Task II: Track the drone
My drone is travelling in 3D. But my sensors are a mess. Use three GH Filters to filter `x, y, z` given the data
```
# Data Generation
T = np.arange(0, 10, 0.1)
# Actual data
z = T
x = 2 * np.sin(z) + 3 * np.cos(z)
y = 0.03 * z**2 + 0.0022 * z **3 - 0.3 **z
# Noisy
z_noisy = z + np.random.randn(z.shape[0]) * 0.1
x_noisy = x + np.random.randn(z.shape[0]) * 0.25
y_noisy = y + np.random.randn(z.shape[0]) * 0.5
fig = plt.figure(figsize=(10, 10))
ax = plt.axes(projection="3d")
ax.plot3D(x, y, z, 'gray', label="Actual")
ax.scatter3D(x_noisy, y_noisy, z_noisy, c=x_noisy, cmap="Blues", label="Noisy")
plt.title("3D Data")
plt.legend();
# For a better visualisation, use plotly
# This is only for plotting. Dont panic if you dont understand this
# Refer to https://plotly.com/python/3d-line-plots/
import plotly.graph_objects as go
fig = go.Figure(data=[go.Scatter3d(
x=x_noisy, y=y_noisy, z=z_noisy, name="Noisy",
marker=dict(
size=4,
color=z,
colorscale='Viridis',
),
line=dict(
color='blue',
width=0.1
)), go.Scatter3d(
x=x, y=y, z=z, name="Actual",
marker=dict(
size=1,
color=z,
colorscale='Viridis',
),
line=dict(
color='red',
width=5
)
)])
fig.update_layout(
width=800,
height=700,
autosize=False,
scene=dict(
camera=dict(
up=dict(
x=0,
y=0,
z=1
),
eye=dict(
x=0,
y=1.0707,
z=1,
)
),
aspectratio = dict( x=1, y=1, z=0.7 ),
aspectmode = 'manual'
),
)
fig.show()
# Implement three GH Filters to obtain the filtered output
def GHFilter_x(x_noisy: list,g: float,h: float,dt):
x_filtered = []
# Adjust and play with G and H values. You can also plot filtered
# data for various g and h values also
g = g # 0.9
h = h # 0.1
# Implement the Algorithm here
x_est =3
dx=0.05
for z in x_noisy:
# prediction step
x_pred = x_est + (dx*dt)
dx = dx
# update step
residual = z - x_pred
dx = dx + h * (residual) / dt
x_est = x_pred + g * residual
x_filtered.append(x_est)
return np.array(x_filtered)
def GHFilter_z(z_noisy: list,g: float,h: float,dt):
z_filtered=[]
z_est=0
dz=0.05
for z in z_noisy:
z_pred=z_est+ (dz*dt)
dz=dz
residual=z-z_pred
dz=dz+(h*residual)/dt
z_est=z_pred+(g*residual)
z_filtered.append(z_est)
return np.array(z_filtered)
def GHFilter_y(y_noisy: list,g: float,h: float,dt):
y_filtered=[]
y_est=-1
dy=0.05
for z in y_noisy:
y_pred=y_est+(dy*dt)
dy=dy
residual=z-y_pred
dy=dy+(h*residual)/dt
y_est=y_pred+(g*residual)
y_filtered.append(y_est)
return np.array(y_filtered)
# Store them in numpy arrays x_filtered, y_filtered, z_filtered
# Plot Results
dt=0.05
x_filtered=GHFilter_x(x_noisy,0.05,0.05,dt)
y_filtered=GHFilter_y(y_noisy,0.06,0.015,dt)
z_filtered=GHFilter_z(z_noisy,0.05,0.015,dt)
fig = plt.figure(figsize=(10, 10))
ax = plt.axes(projection="3d")
ax.plot3D(x, y, z, 'gray', label="Actual")
ax.plot3D(x_filtered, y_filtered, z_filtered, 'red', label="Filtered")
ax.scatter3D(x_noisy, y_noisy, z_noisy, c=x_noisy, cmap="Blues", label="Noisy")
plt.title("3D Data")
plt.legend();
```
|
github_jupyter
|
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
%matplotlib inline
def function(t):
"""This is a linear combination of sine and cosine fucntions
Implement your own function and play with the filter
"""
return 2 * np.sin(t/100) + 5 * np.cos(t/350)
T = np.arange(0, 1000, 1.5)
values = [function(t) for t in T]
plt.plot(T, values, color="red", alpha=0.75, label="Actual Data")
plt.title("Actual")
plt.legend();
# Add noise to the measurement
def noise(val):
# x = mu + y * std (Std Normal to Gaussian)
return val + np.random.randn() * 0.5
values_noisy = [noise(val) for val in values]
plt.scatter(list(T), values_noisy, color="black", alpha=0.5, s=1, label="Noisy")
# plt.plot(T, values, color="red", alpha=0.75, label="Actual")
plt.title("Noisy vs Actual")
plt.legend();
"""Implement a GH_Filter Here"""
def GHFilter(noisy_values: list, g: float, h: float)->list:
filtered_values = []
# Adjust and play with G and H values. You can also plot filtered
# data for various g and h values also
g = g # 0.9
h = h # 0.1
dt=1
# Implement the Algorithm here
x_est = 5
dx=0.02
filtered_values = []
for z in noisy_values:
# prediction step
x_pred = x_est + (dx*dt)
dx = dx
# update step
residual = z - x_pred
dx = dx + h * (residual) / dt
x_est = x_pred + g * residual
filtered_values.append(x_est)
return np.array(filtered_values)
return filtered_values
g = 0.55
h = 0.015
values_filtered = GHFilter(values_noisy,g, h)
plt.scatter(list(T), values_noisy, color="black", alpha=0.5, s=1, label="Noisy")
plt.plot(T, values, color="red", alpha=0.75, label="Actual")
plt.plot(T, values_filtered, color="green", alpha=0.75, label="Filtered")
plt.title("Noisy vs Filtered vs Actual")
plt.legend();
# Data Generation
T = np.arange(0, 10, 0.1)
# Actual data
z = T
x = 2 * np.sin(z) + 3 * np.cos(z)
y = 0.03 * z**2 + 0.0022 * z **3 - 0.3 **z
# Noisy
z_noisy = z + np.random.randn(z.shape[0]) * 0.1
x_noisy = x + np.random.randn(z.shape[0]) * 0.25
y_noisy = y + np.random.randn(z.shape[0]) * 0.5
fig = plt.figure(figsize=(10, 10))
ax = plt.axes(projection="3d")
ax.plot3D(x, y, z, 'gray', label="Actual")
ax.scatter3D(x_noisy, y_noisy, z_noisy, c=x_noisy, cmap="Blues", label="Noisy")
plt.title("3D Data")
plt.legend();
# For a better visualisation, use plotly
# This is only for plotting. Dont panic if you dont understand this
# Refer to https://plotly.com/python/3d-line-plots/
import plotly.graph_objects as go
fig = go.Figure(data=[go.Scatter3d(
x=x_noisy, y=y_noisy, z=z_noisy, name="Noisy",
marker=dict(
size=4,
color=z,
colorscale='Viridis',
),
line=dict(
color='blue',
width=0.1
)), go.Scatter3d(
x=x, y=y, z=z, name="Actual",
marker=dict(
size=1,
color=z,
colorscale='Viridis',
),
line=dict(
color='red',
width=5
)
)])
fig.update_layout(
width=800,
height=700,
autosize=False,
scene=dict(
camera=dict(
up=dict(
x=0,
y=0,
z=1
),
eye=dict(
x=0,
y=1.0707,
z=1,
)
),
aspectratio = dict( x=1, y=1, z=0.7 ),
aspectmode = 'manual'
),
)
fig.show()
# Implement three GH Filters to obtain the filtered output
def GHFilter_x(x_noisy: list,g: float,h: float,dt):
x_filtered = []
# Adjust and play with G and H values. You can also plot filtered
# data for various g and h values also
g = g # 0.9
h = h # 0.1
# Implement the Algorithm here
x_est =3
dx=0.05
for z in x_noisy:
# prediction step
x_pred = x_est + (dx*dt)
dx = dx
# update step
residual = z - x_pred
dx = dx + h * (residual) / dt
x_est = x_pred + g * residual
x_filtered.append(x_est)
return np.array(x_filtered)
def GHFilter_z(z_noisy: list,g: float,h: float,dt):
z_filtered=[]
z_est=0
dz=0.05
for z in z_noisy:
z_pred=z_est+ (dz*dt)
dz=dz
residual=z-z_pred
dz=dz+(h*residual)/dt
z_est=z_pred+(g*residual)
z_filtered.append(z_est)
return np.array(z_filtered)
def GHFilter_y(y_noisy: list,g: float,h: float,dt):
y_filtered=[]
y_est=-1
dy=0.05
for z in y_noisy:
y_pred=y_est+(dy*dt)
dy=dy
residual=z-y_pred
dy=dy+(h*residual)/dt
y_est=y_pred+(g*residual)
y_filtered.append(y_est)
return np.array(y_filtered)
# Store them in numpy arrays x_filtered, y_filtered, z_filtered
# Plot Results
dt=0.05
x_filtered=GHFilter_x(x_noisy,0.05,0.05,dt)
y_filtered=GHFilter_y(y_noisy,0.06,0.015,dt)
z_filtered=GHFilter_z(z_noisy,0.05,0.015,dt)
fig = plt.figure(figsize=(10, 10))
ax = plt.axes(projection="3d")
ax.plot3D(x, y, z, 'gray', label="Actual")
ax.plot3D(x_filtered, y_filtered, z_filtered, 'red', label="Filtered")
ax.scatter3D(x_noisy, y_noisy, z_noisy, c=x_noisy, cmap="Blues", label="Noisy")
plt.title("3D Data")
plt.legend();
| 0.793426 | 0.980729 |
<br>
<br>
<center>
# 人工智能高阶人才培训班
<br>
> ## 第三课:人工智能基础架构与工具(3)——Keras入门
</center>
<br>
# keras整体架构

**BLAS**(Basic Linear Algebra Subprograms)即基础线性代数子程序库,里面拥有大量已经编写好的关于线性代数运算的程序。
**Eigen** 是一个高层次的C ++库,有效支持线性代数,矩阵和矢量运算,数值分析及其相关的算法。
# keras库介绍
+ 概念:keras是一个高层深度学习API,可以在TensorFlow,CNTK或Theano基础上运行
+ 目标:快速实验,能够以最快的速度将想法付诸现实
+ 设计原则:
+ 用户友好: 提供简单一致的API
+ 模块性:一个模型可以是一个序列或者一个计算图
+ 扩展性:可以参照现有充足的模块示例定制满足需求的模块
+ 基于python:不需要单独的模型配置文件,完全使用python描述
# 模型结构
>keras中有两类模型:
+ 序列模型(the Sequential model)
+ 使用函数API的模型(the Model class used with the functional API)
## 序列模型
序列模型各层之间是依次顺序的线性关系,模型结构通过一个列表来制定或者逐层添加网络结构
```
import warnings
warnings.filterwarnings('ignore')
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Activation
# 方法一:通过传递一个层定义的列表
model_list = Sequential([
Dense(32, input_shape=(784,)),
Activation('relu'),
Dense(10),
Activation('softmax'),
])
# 方法二:直接使用add添加层
model_add = Sequential()
model_add.add(Dense(32, input_dim=784))
model_add.add(Activation('relu'))
```
### 程序示例
使用TensorFlow训练Fashion-MNist数据集
Fashion-MNIST,是去年8月底德国研究机构Zalando Research发布的一个数据集,其中训练集包含60000个样本,测试集包含10000个样本,分为10类。样本都来自日常穿着的衣裤鞋包,每一个都是28×28的灰度图。

```
import warnings
warnings.filterwarnings('ignore')
import datetime
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
```
#### 导入数据
```
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
```
Fashion-MNIST数据集中有十类样本,标签分别是:
T恤 0
裤子 1
套头衫 2
裙子 3
外套 4
凉鞋 5
衬衫 6
运动鞋 7
包 8
踝靴 9
```
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
```
#### 数据可视化分析
```
train_images.shape
len(train_labels)
train_labels
len(test_labels)
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
train_images = train_images / 255.0
test_images = test_images / 255.0
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()
```
#### 构建模型
```
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
```
#### 训练模型
```
model.fit(train_images, train_labels, epochs=10)
```
#### 评估模型
```
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
```
#### 使用模型进行预测
```
predictions = model.predict(test_images)
predictions[0]
np.argmax(predictions[0])
```
##### Helper Funcitons
```
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array, true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array, true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
# Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()
```
#### 在TensorBoard中查看信息
```
# add callback
log_dir="logs/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = keras.callbacks.TensorBoard(
log_dir=log_dir, histogram_freq=1)
# train
model.fit(train_images, train_labels,
epochs=10,
verbose=1,
validation_data=(test_images,test_labels),
callbacks=[tensorboard_callback])
```
### 模型的相关信息
```
print('模型层信息','\n',model.layers,'\n') # 返回模型的层信息
print('模型输入信息','\n',model.inputs,'\n') # 返回输入的信息
print('模型输出信息','\n',model.outputs,'\n') # 模型输出相关的信息
print('模型概览','\n')
print(model.summary(),'\n')# 作用等同于for utils.print_summary
print('模型配置信息','\n',model.get_config(),'\n') #以字典形式返回模型配置信息
```
## 函数模型
详见:[官方文档 Function API](https://keras.io/zh/getting-started/functional-api-guide/)
支持多输入多输出,层之间的链接更灵活,每个层都可以独立调用

### 程序示例
函数式API
```python
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
# 这部分返回一个张量
inputs = Input(shape=(784,))
# 层的实例是可调用的,它以张量为参数,并且返回一个张量
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x)
# 这部分创建了一个包含输入层和三个全连接层的模型
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(data, labels) # 开始训练
```
**定义多输入多输出模型**
```python
model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])
```
## 两种模型的区别
+ Sequential模型,
+ 只有一个输入和输出,而且网络是层的线性堆叠
+ 这种模型编译速度快,操作上也比较简单
+ 基于Function API的模型(以前被称为Graph,即图模型)
+ 支持多输入多输出,层与层之间可以任意链接,所有层都是可以随意调用的
+ 编译速度慢
# 重要部件
## 损失函数的定义
更多内容详见:[官方文档](https://keras.io/zh/losses/)
>损失函数,是编译时所需的两个参数之一
```python
model.compile(loss='mean_squared_error', optimizer='sgd')
```
**常见损失函数:**
+ 分类问题:
+ 交叉熵损失/负似然对数
+ categorical_crossentropy多分类交叉熵损失:`categorical_crossentropy`
+ BinaryCrossentropy二分类交叉损失: `binary_crossentropy`
+ Hinge loss 合页损失/多分类SVM损失
+ 回归问题
+ MeanSquaredError(MSE) 均方误差/平方损失/L2损失:回归问题中最常用的损失函数
+ 调用: `mean_squared_error(y_true,y_pred)`
+ 优点:有利于梯度下降,误差大时下降快,误差小时下降慢,有利于函数收敛
+ 缺点:受明显偏离正常范围的离群样本的影响较大
+ MeanAbsoluteError(MAE) 平均绝对误差/L1损失:想额外增强对离群样本的健壮性时使用
+ 调用:`mean_absolute_error(y_true,y_pred)`
+ 优点:克服了MSE的缺点, 受偏离正常范围的离群样本影响较小
+ 缺点:收敛速度比MSE慢,因为当误差大或小时都保持同等速度下降,而且在某一点处还不可导,计算机求导比较困难
+ Huber loss 胡伯损失:是一个带参数的损失函数,集合了MSE和MAE的优点,但是需要手动调参。降低了对离群点的惩罚程度
+ 当预测偏差小于$\delta$时,采用MSE
+ 当预测偏差大于$\delta$时,采用线性误差
## Metrics
更多内容详见:[官方文档](https://keras.io/zh/metrics/)
> 用于判断模型的好坏,在模型编译阶段使用
```python
model.compile(loss='mean_squared_error',
optimizer='sgd',
metrics=['mae', 'acc'])
```
常见的指标有:
+ Accuracy(简写为:'acc')
+ AUC,Precision, Recall等(这三个在keras版本更新之后已经移除,需要自己手动实现) [参考实现](https://stackoverflow.com/questions/43076609/how-to-calculate-precision-and-recall-in-keras)
+ MAE,MSE等
#### 自定义评价函数
自定义评价函数应该在编译的时候(compile)传递进去。该函数需要以 (y_true, y_pred) 作为输入参数,并返回一个张量作为输出结果。
```python
import keras.backend as K
def mean_pred(y_true, y_pred):
return K.mean(y_pred)
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy', mean_pred])
```
## Optimizers
```python
from keras import optimizers
sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer=sgd)
```
更多内容详见: [官方文档](https://keras.io/zh/optimizers/)
优化器选择,keras中内置的包括:
+ SGD随机梯度下降
```python
keras.optimizers.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False)
```
+ Adam 优化器
```python
keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
```
+ 还有RMSprop,Adagrad,Adadelta,Adamax等优化器
其中:
+ RMSprop优化器通常是训练循环神经网络RNN的不错选择。
+ Adagrad优化器是一种具有特定参数学习率的优化器,它根据参数在训练期间的更新频率进行自适应调整。参数接收的更新越多,更新越小。
+ Adadelta优化器是 Adagrad 的一个具有更强鲁棒性的的扩展版本
+ Adam优化器本质上是 RMSProp 与动量 momentum 的结合
+ Nadam优化器是采用 Nesterov momentum 版本的 Adam 优化器。
## [Callbacks](https://keras.io/zh/callbacks/)
> 用于模型的训练阶段(是fit()函数的一个参数)
回调函数是一个函数的合集,会在训练的阶段中所使用。你可以使用回调函数来查看训练模型的内在状态和统计。你可以传递一个列表的回调函数(作为 callbacks 关键字参数)到 Sequential 或 Model 类型的 .fit() 方法。在训练时,相应的回调函数的方法就会被在各自的阶段被调用。
常见用途:
1. **keras.callbacks.History()** keras中模型默认回调History函数,每轮训练收集损失和准确率,如果有测试集,也会收集测试集的数据。<br>
PS:这个对象是自动启用的,不需要显示调用
```python
history = model.fit(X, Y, validation_split=0.33, nb_epoch=150, batch_size=10, verbose=0) # list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
```
2. **ModelCheckpoint** 根据需求定制何时或何种情况下需要保存模型权重<br>
可以效果变好就保存;也可以只保存最好的模型
```python
# 效果变好就保存
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# checkpoint
filepath="weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5"
# 只保存最好的模型 只需要将文件名改成固定的(新的好的覆盖旧的) filepath="weights.best.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True,
mode='max')
callbacks_list = [checkpoint]
# Fit the model
model.fit(X, Y, validation_split=0.33, nb_epoch=150, batch_size=10,
callbacks=callbacks_list, verbose=0)
```
3. **EarlyStopping** 根据条件提前停止模型,可以加快训练速度,也可以在一定程度上防止过拟合 常用ModelCheckPoint联用
```python
from keras.callbacks import EarlyStopping
EarlyStopping(monitor='val_loss',patience=10)
# monitor: 监控的数据 patience:能够容忍多少个epoch内都没有improvement
```
4. **LearningRateScheduler** 可以控制学习速度,取当前的轮数,返回学习速率
```python
def step_decay(epoch):
"""
输入一个epoch序号,输出学习率
"""
initial_lrate = 0.1
drop = 0.5
epochs_drop = 10.0
lrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop))
# initial_lrate初始的速度,drop是减速频率,epochdrop是降低多少
return lrate
sgd = SGD(lr=0.0, momentum=0.9, decay=0.0, nesterov=False) model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy'])
# learning schedule callback
lrate = LearningRateScheduler(step_decay)
callbacks_list = [lrate]
```
5.**Tensorboard** 可视化训练结果,如果电脑上已经安装了TensorFlow,可以通过控制台启动它
```python
# 控制台启动
tensorboard --logdir=og_dir
# 路径保持和存储的log文件路径一致,然后浏览器访问http://localhost:6006/ 即可
# 模型中调用tensorboard
from keras.callbacks import TensorBoard
og_dir = 'C:\\Users\\Lido_Lee\\Downloads\\IMDb_callback'
#加入tensorboard callback
callbacks = [TensorBoard(log_dir=log_dir, histogram_freq=1,embeddings_freq=0,embeddings_layer_names=None,),....]
```
# 扩展资料
1. [Deep Learning with Keras and Tensorflow](https://wizardforcel.gitbooks.io/deep-learning-keras-tensorflow/content/)
2. [Huber-loss](https://www.cnblogs.com/nowgood/p/Huber-Loss.html)
3. [损失函数简介](jiqizhixin.com/articles/091202)
4. [常用二分类损失函数和回归函数](http://www.cs.cornell.edu/courses/cs4780/2015fa/web/lecturenotes/lecturenote10.html)
5. [keras优化器介绍](https://blog.csdn.net/u013249853/article/details/89148990)
|
github_jupyter
|
import warnings
warnings.filterwarnings('ignore')
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Activation
# 方法一:通过传递一个层定义的列表
model_list = Sequential([
Dense(32, input_shape=(784,)),
Activation('relu'),
Dense(10),
Activation('softmax'),
])
# 方法二:直接使用add添加层
model_add = Sequential()
model_add.add(Dense(32, input_dim=784))
model_add.add(Activation('relu'))
import warnings
warnings.filterwarnings('ignore')
import datetime
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images.shape
len(train_labels)
train_labels
len(test_labels)
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
train_images = train_images / 255.0
test_images = test_images / 255.0
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=10)
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
predictions = model.predict(test_images)
predictions[0]
np.argmax(predictions[0])
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array, true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array, true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
# Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()
# add callback
log_dir="logs/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = keras.callbacks.TensorBoard(
log_dir=log_dir, histogram_freq=1)
# train
model.fit(train_images, train_labels,
epochs=10,
verbose=1,
validation_data=(test_images,test_labels),
callbacks=[tensorboard_callback])
print('模型层信息','\n',model.layers,'\n') # 返回模型的层信息
print('模型输入信息','\n',model.inputs,'\n') # 返回输入的信息
print('模型输出信息','\n',model.outputs,'\n') # 模型输出相关的信息
print('模型概览','\n')
print(model.summary(),'\n')# 作用等同于for utils.print_summary
print('模型配置信息','\n',model.get_config(),'\n') #以字典形式返回模型配置信息
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
# 这部分返回一个张量
inputs = Input(shape=(784,))
# 层的实例是可调用的,它以张量为参数,并且返回一个张量
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x)
# 这部分创建了一个包含输入层和三个全连接层的模型
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(data, labels) # 开始训练
model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])
model.compile(loss='mean_squared_error', optimizer='sgd')
model.compile(loss='mean_squared_error',
optimizer='sgd',
metrics=['mae', 'acc'])
import keras.backend as K
def mean_pred(y_true, y_pred):
return K.mean(y_pred)
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy', mean_pred])
from keras import optimizers
sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer=sgd)
keras.optimizers.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False)
keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
history = model.fit(X, Y, validation_split=0.33, nb_epoch=150, batch_size=10, verbose=0) # list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
# 效果变好就保存
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# checkpoint
filepath="weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5"
# 只保存最好的模型 只需要将文件名改成固定的(新的好的覆盖旧的) filepath="weights.best.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True,
mode='max')
callbacks_list = [checkpoint]
# Fit the model
model.fit(X, Y, validation_split=0.33, nb_epoch=150, batch_size=10,
callbacks=callbacks_list, verbose=0)
from keras.callbacks import EarlyStopping
EarlyStopping(monitor='val_loss',patience=10)
# monitor: 监控的数据 patience:能够容忍多少个epoch内都没有improvement
def step_decay(epoch):
"""
输入一个epoch序号,输出学习率
"""
initial_lrate = 0.1
drop = 0.5
epochs_drop = 10.0
lrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop))
# initial_lrate初始的速度,drop是减速频率,epochdrop是降低多少
return lrate
sgd = SGD(lr=0.0, momentum=0.9, decay=0.0, nesterov=False) model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy'])
# learning schedule callback
lrate = LearningRateScheduler(step_decay)
callbacks_list = [lrate]
# 控制台启动
tensorboard --logdir=og_dir
# 路径保持和存储的log文件路径一致,然后浏览器访问http://localhost:6006/ 即可
# 模型中调用tensorboard
from keras.callbacks import TensorBoard
og_dir = 'C:\\Users\\Lido_Lee\\Downloads\\IMDb_callback'
#加入tensorboard callback
callbacks = [TensorBoard(log_dir=log_dir, histogram_freq=1,embeddings_freq=0,embeddings_layer_names=None,),....]
| 0.752013 | 0.85183 |
# Representing Qubit States
To continue further in this course, we need a way of writing down qubit states. You will see by the end of chapter 2, that using only vectors and matrices we can write down the state of any set of qubits and any quantum operation. **Before you continue**, you should be comfortable with complex numbers. Knowledge of linear algebra will help, although there are reminders of important concepts scattered throughout. If you need a more in-depth explanation or refresher, you can check out the mathematics prerequisite [here](../ch-prerequisites/linear_algebra.ipynb).
## Contents
1. [Classical vs Quantum Bits](#cvsq)
1.1 [Statevectors](#statevectors)
1.2 [Qubit Notation](#notation)
1.3 [Exploring Qubits with Qiskit](#exploring-qubits)
2. [The Rules of Measurement](#rules-measurement)
2.1 [A Very Important Rule](#important-rule)
2.2 [The Implications of this Rule](#implications)
3. [The Bloch Sphere](#bloch-sphere)
3.1 [Describing the Restricted Qubit State](#bloch-sphere-1)
3.2 [Visually Representing a Qubit State](#bloch-sphere-2)
## 1. Classical vs Quantum Bits <a id="cvsq"></a>
### 1.1 Statevectors<a id="statevectors"></a>
In quantum physics we use _statevectors_ to describe the state of our system. This is different from classical physics where we generally just use numbers. For example, say we wanted to describe the position of a car along a track, this is a classical system so we could use a number $x$:

$$ x=4 $$
Alternatively, we could instead use a collection of numbers in a vector called a _statevector._ Each element in the statevector contains the probability of finding the car in a certain place:

$$
|x\rangle = \begin{bmatrix} 0\\ \vdots \\ 0 \\ 1 \\ 0 \\ \vdots \\ 0 \end{bmatrix}
\begin{matrix} \\ \\ \\ \leftarrow \\ \\ \\ \\ \end{matrix}
\begin{matrix} \\ \\ \text{Probability of} \\ \text{car being at} \\ \text{position 4} \\ \\ \\ \end{matrix}
$$
This isn’t limited to position, we could also keep a statevector of all the possible speeds the car could have, and all the possible colours the car could be. With classical systems (like the car example above), this is a silly thing to do as it requires keeping huge vectors when we only really need one number. But as we will see in this chapter, statevectors happen to be a very good way of keeping track of quantum systems, including quantum computers.
### 1.2 Qubit Notation <a id="notation"></a>
Say we want to write down the state of a of classical bit (`c`), we just use the numbers `0` and `1`:
c = 0
This is fine, as a classical bit always has a definite state. With qubits however, this restriction is lifted and we have probabilities of measuring different states. Each state a qubit can be measured in has an _amplitude_ (a complex number), and we need to keep track of these complex numbers. A qubit is a two-level system, so upon measurement* we will find it in one of two states:
$$ |0\rangle \quad \& \quad |1\rangle $$
<div style="font-size: .75em"> *This is only true for one type of measurement, but do not worry about this now, we will discuss this in a future section.</div>
This means we need to keep track of two complex numbers. Vectors happen to be a great way of doing this:
$$ |q_0\rangle = \begin{bmatrix} \tfrac{1}{\sqrt{2}} \\ \tfrac{i}{\sqrt{2}} \end{bmatrix} $$
Here we use the elements of the vector ($|q_0\rangle$) to store a ‘list’ of the complex amplitudes of the states $|0\rangle$ and $|1\rangle$. In this case, $|0\rangle$ has amplitude $\tfrac{1}{\sqrt{2}}$ and $|1\rangle$ has amplitude $\tfrac{i}{\sqrt{2}}$. Notice that we denote a column vector by enclosing it between the $|$ and $\rangle$ symbols. The state's amplitude is related to the probability of measuring the qubit in that state. If our qubit is definitely in the state $|0\rangle$, the amplitude of $|0\rangle$ is 1, and the amplitude of $|1\rangle$ is 0. Thus we can write:
$$ |0\rangle = \begin{bmatrix} 1 \\ 0 \end{bmatrix} $$
And similarly:
$$ |1\rangle = \begin{bmatrix} 0 \\ 1 \end{bmatrix} $$
Note that $|0\rangle$ and $|1\rangle$ form an orthonormal basis, and we can represent any 2D vector with a combination of $|0\rangle$ and $|1\rangle$. Knowing this, we can write the state of our qubit in the alternative form:
$$ |q_0\rangle = \tfrac{1}{\sqrt{2}}|0\rangle + \tfrac{i}{\sqrt{2}}|1\rangle $$
<br>
<details style="border: 1px solid black; border-radius: 3px; padding: 10px;">
<summary>Reminder: Matrix Addition and Multiplication by Scalars (Click here to expand)</summary>
<p>To add two vectors, we add their elements together:
$$|a\rangle = \begin{bmatrix}a_0 \\ a_1 \\ \vdots \\ a_n \end{bmatrix}, \quad
|b\rangle = \begin{bmatrix}b_0 \\ b_1 \\ \vdots \\ b_n \end{bmatrix}$$
$$|a\rangle + |b\rangle = \begin{bmatrix}a_0 + b_0 \\ a_1 + b_1 \\ \vdots \\ a_n + b_n \end{bmatrix} $$
</p>
<p>And to multiply a vector by a scalar, we multiply each element by the scalar:
$$x|a\rangle = \begin{bmatrix}x \times a_0 \\ x \times a_1 \\ \vdots \\ x \times a_n \end{bmatrix}$$
</p>
<p>These two rules are used to rewrite the vector $|q_0\rangle$ (as shown above):
$$
\begin{aligned}
|q_0\rangle & = \tfrac{1}{\sqrt{2}}|0\rangle + \tfrac{i}{\sqrt{2}}|1\rangle \\
& = \tfrac{1}{\sqrt{2}}\begin{bmatrix}1\\0\end{bmatrix} + \tfrac{i}{\sqrt{2}}\begin{bmatrix}0\\1\end{bmatrix}\\
& = \begin{bmatrix}\tfrac{1}{\sqrt{2}}\\0\end{bmatrix} + \begin{bmatrix}0\\\tfrac{i}{\sqrt{2}}\end{bmatrix}\\
& = \begin{bmatrix}\tfrac{1}{\sqrt{2}} \\ \tfrac{i}{\sqrt{2}} \end{bmatrix}\\
\end{aligned}
$$
</details>
<br>
<details style="border: 1px solid black; border-radius: 3px; padding: 10px;">
<summary>Reminder: Orthonormal Bases (Click here to expand)</summary>
<p>
It was stated before that the two vectors $|0\rangle$ and $|1\rangle$ are orthonormal, this means they are both <i>orthogonal</i> and <i>normalised</i>. Orthogonal means the vectors are at right angles:
</p><p><img src="images/basis.svg"></p>
<p>And normalised means their magnitudes (length of the arrow) is equal to 1. The two vectors $|0\rangle$ and $|1\rangle$ are <i>linearly independent</i>, which means we cannot describe $|0\rangle$ in terms of $|1\rangle$, and vice versa. However, using both the vectors $|0\rangle$ and $|1\rangle$, and our rules of addition and multiplication by scalars, we can describe all possible vectors in 2D space:
</p><p><img src="images/basis2.svg"></p>
<p>Because the vectors $|0\rangle$ and $|1\rangle$ are linearly independent, and can be used to describe any vector in 2D space using vector addition and scalar multiplication, we say the vectors $|0\rangle$ and $|1\rangle$ form a <i>basis</i>. In this case, since they are both orthogonal and normalised, we call it an <i>orthonormal basis</i>.
</details>
<br>
This vector, $|q_0\rangle$ is called the qubit's _statevector,_ it tells us everything we could possibly know about this qubit. Since both $|0\rangle$ and $|1\rangle$ have non-zero amplitudes, the qubit is said to be in a _superposition_ of the states $|0\rangle$ and $|1\rangle$.
### 1.3 Exploring Qubits with Qiskit <a id="exploring-qubits"></a>
```
from qiskit import *
from qiskit.visualization import plot_histogram, plot_bloch_vector
from math import sqrt, pi
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
```
In our quantum circuits, our qubits always start out in the state $|0\rangle$. We can use the qiskit function `Initialize()` to transform this into any state. We give `Initialize()` the vector we want, and apply it to the circuit:
```
from qiskit.extensions import Initialize # Import the Inititialize function
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
inital_state = [0,1] # Define initial_state as |1>
init_op = Initialize(inital_state) # Create Initialisation Operation for state |1>
qc.append(init_op,[0]) # Apply initialisation operation to the qubit (it's index is 0)
qc.draw() # Let's view our circuit
```
We can then use one of Qiskit’s simulators to view the resulting state of our qubit.
```
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
out_state = execute(qc,backend).result().get_statevector() # Do the simulation, returning the state vector
print(out_state) # Display the output state vector
```
**Note:** Python uses `j` to represent $i$ in complex numbers. We see a vector with two complex elements: `0.+0.j` = 0, and `1.+0.j` = 1.
Let’s now measure our qubit as we would in a real quantum computer and see the result:
```
qc.measure_all()
qc.draw()
results = execute(qc,backend).result().get_counts()
plot_histogram(results)
```
We can see that we (unsurprisingly) have a 100% chance of measuring $|1\rangle$. This time, let’s instead put our qubit into a superposition and see what happens. We will use the state $|q_0\rangle$ from earlier in this section:
$$ |q_0\rangle = \tfrac{1}{\sqrt{2}}|0\rangle + \tfrac{i}{\sqrt{2}}|1\rangle $$
```
# Must redefine our circuit
qc = QuantumCircuit(1)
# Define state |q>
inital_state = [1/sqrt(2), complex(0,1/sqrt(2))]
# Create Initialisation Operation for state |q>
init_op = Initialize(inital_state)
# Add our initialisation operation to the circuit (the qubit's index is 0)
qc.append(init_op,[0])
# Execute the circuit and print the result
state = execute(qc,backend).result().get_statevector()
print(state)
results = execute(qc,backend).result().get_counts()
plot_histogram(results)
```
We can see we have equal probability of measuring either $|0\rangle$ or $|1\rangle$. To explain this, we need to talk about measurement.
## 2. The Rules of Measurement <a id="rules-measurement"></a>
### 2.1 A Very Important Rule <a id="important-rule"></a>
There is a simple rule for measurement. To find the probability of measuring a state $|\psi \rangle$ in the state $|x\rangle$ we do:
$$p(|x\rangle) = | \langle \psi| x \rangle|^2$$
<br>
<details style="border: 1px solid black; border-radius: 3px; padding: 10px;">
<summary>Reminder: The Inner Product (Click here to expand)</summary>
<p>There are different ways to multiply vectors, here we use the <i>inner product</i>. The inner product is a generalisation of the <i>dot product</i> which you may already be familiar with. In this guide, we use the inner product between a bra (row vector) and a ket (column vector), and it follows this rule:
$$\langle a| = \begin{bmatrix}a_0^*, & a_1^*, & \dots & a_n^* \end{bmatrix}, \quad
|b\rangle = \begin{bmatrix}b_0 \\ b_1 \\ \vdots \\ b_n \end{bmatrix}$$
$$\langle a|b\rangle = a_0^* b_0 + a_1^* b_1 \dots a_n^* b_n$$
</p>
<p>We can see that the inner product of two vectors always gives us a scalar. A useful thing to remember is that the inner product of two orthogonal vectors is 0, for example if we have the orthogonal vectors $|0\rangle$ and $|1\rangle$:
$$\langle1|0\rangle = \begin{bmatrix} 0 , & 1\end{bmatrix}\begin{bmatrix}1 \\ 0\end{bmatrix} = 0$$
</p>
<p>Additionally, remember that the vectors $|0\rangle$ and $|1\rangle$ are also normalised (magnitudes are equal to 1):
$$
\begin{aligned}
\langle0|0\rangle & = \begin{bmatrix} 1 , & 0\end{bmatrix}\begin{bmatrix}1 \\ 0\end{bmatrix} = 1 \\
\langle1|1\rangle & = \begin{bmatrix} 0 , & 1\end{bmatrix}\begin{bmatrix}0 \\ 1\end{bmatrix} = 1
\end{aligned}
$$
</p>
</details>
<br>
Where $|x\rangle$ can be any qubit state. To find the probability of measuring $|x\rangle$, we take the inner product of $|x\rangle$ and the state we are measuring (in this case $|\psi\rangle$), then square the magnitude. This may seem a little convoluted, but it will soon become second nature.
If we look at the state $|q_0\rangle$ from before, we can see the probability of measuring $|0\rangle$ is indeed $0.5$:
$$
\begin{aligned}
|q_0\rangle & = \tfrac{1}{\sqrt{2}}|0\rangle + \tfrac{i}{\sqrt{2}}|1\rangle \\
\langle q_0| & = \tfrac{1}{\sqrt{2}}\langle0| - \tfrac{i}{\sqrt{2}}\langle 1| \\
\langle q_0| 0 \rangle & = \tfrac{1}{\sqrt{2}}\langle 0|0\rangle - \tfrac{i}{\sqrt{2}}\langle 1|0\rangle \\
\langle q_0| 0 \rangle & = \tfrac{1}{\sqrt{2}}\cdot 1 - \tfrac{i}{\sqrt{2}} \cdot 0\\
\langle q_0| 0 \rangle & = \tfrac{1}{\sqrt{2}}\\
|\langle q_0| 0 \rangle|^2 & = \tfrac{1}{2}
\end{aligned}
$$
You should verify the probability of measuring $|1\rangle$ as an exercise.
### 2.2 The Implications of this Rule <a id="implications"></a>
### #1 Normalisation
This rule implies three things, the first is that the statevector should be normalised to 1.
If we want the probabilities to add up to 1 (which they should!) we need the magnitude of the state vector to be 1.
$$ \langle\psi|\psi\rangle = 1 \\ $$
Thus if:
$$ |\psi\rangle = \alpha|0\rangle + \beta|1\rangle $$
Then:
$$ \sqrt{|\alpha|^2 + |\beta|^2} = 1 $$
This explains the factors of $\sqrt{2}$ you have seen throughout this chapter. In fact, if we try to give `Initialize()` a vector that isn’t normalised, it will give us an error:
```
vector = [1,1]
Initialize(vector)
```
#### Quick Exercise
1. Create a state vector that will give a $1/3$ probability of measuring $|0\rangle$.
2. Create a different state vector that will give the same measurement probabilities.
3. Verify that the probability of measuring $|1\rangle$ for these two states is $2/3$.
You can check your answer in the widget below:
```
from widgets import state_vector_exercise
state_vector_exercise(target=1/3)
```
### #2 Global Phase
The second implication is that the total phase of the qubit (global phase) does not matter to us, only the difference in phase between $|0\rangle$ and $|1\rangle$ (relative phase). This is because the global phase disappears when we calculate the measurement probability. For example, the two states:
$$|a\rangle = \tfrac{1}{\sqrt{2}}\begin{bmatrix}1 \\ i\end{bmatrix} \quad \& \quad |b\rangle = \tfrac{1}{\sqrt{2}}\begin{bmatrix}i \\ -1\end{bmatrix}$$
Are equivalent to us, since we can multiply one by a factor of $i$ to get the other:
$$
\begin{aligned}
i\times\tfrac{1}{\sqrt{2}}\begin{bmatrix}1 \\ i\end{bmatrix} & = \tfrac{1}{\sqrt{2}}\begin{bmatrix}i \\ -1\end{bmatrix}\\
\\
i|a\rangle & = |b\rangle
\end{aligned}
$$
And when we calculate the measurement probability:
$$ |\langle x|a\rangle|^2 = |\langle x|i|a\rangle|^2 = |\langle x|b\rangle|^2 $$
### #3 The Observer Effect
We know that the amplitudes contain information about the probability of us finding the qubit in a specific state, but once we have measured the qubit, we know with certainty what the state of the qubit is. For example, if we measure a qubit in the state:
$$ |q\rangle = \alpha|0\rangle + \beta|1\rangle$$
And find it in the state $|0\rangle$, if we measure again, there is a 100% chance of finding the qubit in the state $|0\rangle$. This means the act of measuring _changes_ the state of our qubits.
$$ |q\rangle = \begin{bmatrix} \alpha \\ \beta \end{bmatrix} \xrightarrow{\text{Measure }|0\rangle} |q\rangle = |0\rangle = \begin{bmatrix} 1 \\ 0 \end{bmatrix}$$
In fact, measuring not only changes the state of our qubits, it _destroys_ the superposition of our qubit, replacing it with one of two definite states. As a result, we almost always place the measurements at the end of our circuit. We sometimes refer to this destructive measurement as _collapsing_ the state of the qubit.
We can demonstrate this using Qiskit’s statevector simulator. Let's initialise a qubit in superposition:
```
qc = QuantumCircuit(1) # Redefine qc
initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j]
init_state = Initialize(inital_state)
qc.append(init_state, [0])
qc.draw()
```
This circuit initialises our qubit in the state:
$$ |q\rangle = \tfrac{i}{\sqrt{2}}|0\rangle + \tfrac{1}{\sqrt{2}}|1\rangle $$
We can verify this using the simulator:
```
state = execute(qc,backend).result().get_statevector()
print("Qubit State = " + str(state))
```
We can see here the qubit is initialised in the state ` [0.70710678+0.j, 0.+0.70710678j]`, which is:
$$ |q\rangle = \tfrac{1}{\sqrt{2}}|0\rangle + \tfrac{i}{\sqrt{2}}|1\rangle $$
Qiskit has changed the global phase of the qubit, but due to the second implication, we know this is fine. Let’s now measure this qubit:
```
qc.measure_all()
qc.draw()
```
When we simulate this entire circuit, we can see that one of the amplitudes is _always_ 0:
```
state = execute(qc,backend).result().get_statevector()
print("State of Measured Qubit = " + str(state))
```
You can re-run this cell a few times to reinitialise the qubit and measure it again. You will notice that either outcome is equally probable, but that the state of the qubit is never a superposition of $|0\rangle$ and $|1\rangle$. Somewhat interestingly, the global phase on the state $|1\rangle$ survives, but since this is global phase, we can never measure it on a real quantum computer.
### A Note about Quantum Simulators
We can see that writing down a qubit’s state requires keeping track of two complex numbers, but when using a real quantum computer we will only ever receive a yes-or-no (`0` or `1`) answer for each qubit. The output of a 10-qubit quantum computer will look like this:
`0110111110`
Just 10 digits, no superposition or complex amplitudes. When using a real quantum computer, we cannot see the states of our qubits mid-computation, as this would destroy them! This behaviour is not ideal for learning, so Qiskit provides different quantum simulators: The `qasm_simulator` behaves as if you are interacting with a real quantum computer, and will not allow you to use `.get_statevector()`. Alternatively, `statevector_simulator`, (which we have been using in this chapter) does allow peaking at the quantum states before measurement, as we have seen.
## 3. The Bloch Sphere <a id="bloch-sphere"></a>
### 3.1 Describing the Restricted Qubit State <a id="bloch-sphere-1"></a>
We saw earlier in this chapter that the general state of a qubit ($|q\rangle$) is:
$$
|q\rangle = \alpha|0\rangle + \beta|1\rangle
$$
$$
\alpha, \beta \in \mathbb{C}
$$
(The second line tells us $\alpha$ and $\beta$ are complex numbers). The first two implications in section 2 tell us that we cannot differentiate between some of these states. This means we can be more specific in our description of the qubit.
Firstly, since we cannot measure global phase, we can only measure the difference in phase between the states $|0\rangle$ and $|1\rangle$. Instead of having $\alpha$ and $\beta$ be complex, we can confine them to the real numbers and add a term to tell us the relative phase between them:
$$
|q\rangle = \alpha|0\rangle + e^{i\phi}\beta|1\rangle
$$
$$
\alpha, \beta, \phi \in \mathbb{R}
$$
Finally, since the qubit state must be normalised, i.e.
$$
\sqrt{\alpha^2 + \beta^2} = 1
$$
we can use the trigonometric identity:
$$
\sqrt{\sin^2{x} + \cos^2{x}} = 1
$$
to describe the real $\alpha$ and $\beta$ in terms of one variable, $\theta$:
$$
\alpha = \cos{\tfrac{\theta}{2}}, \quad \beta=\sin{\tfrac{\theta}{2}}
$$
From this we can describe the state of any qubit using the two variables $\phi$ and $\theta$:
$$
|q\rangle = \cos{\tfrac{\theta}{2}}|0\rangle + e^{i\phi}\sin{\tfrac{\theta}{2}}|1\rangle
$$
$$
\theta, \phi \in \mathbb{R}
$$
### 3.2 Visually Representing a Qubit State <a id="bloch-sphere-2"></a>
We want to plot our general qubit state:
$$
|q\rangle = \cos{\tfrac{\theta}{2}}|0\rangle + e^{i\phi}\sin{\tfrac{\theta}{2}}|1\rangle
$$
If we interpret $\theta$ and $\phi$ as spherical co-ordinates ($r = 1$, since the magnitude of the qubit state is $1$), we can plot any qubit state on the surface of a sphere, known as the _Bloch sphere._
Below we have plotted a qubit in the state $|{+}\rangle$. In this case, $\theta = \pi/2$ and $\phi = 0$.
(Qiskit has a function to plot a bloch sphere, `plot_bloch_vector()`, but at the time of writing it only takes cartesian coordinates. We have included a function that does the conversion automatically).
```
from widgets import plot_bloch_vector_spherical
coords = [pi/2,0,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates
```
#### Warning!
When first learning about qubit states, it's easy to confuse the qubits _statevector_ with it's _Bloch vector_. Remember the statevector is the vector disucssed in [1.1](#notation), that holds the amplitudes for the two states our qubit can be in. The Bloch vector is a visualisation tool that maps the 2D, complex statevector onto real, 3D space.
#### Quick Exercise
Use `plot_bloch_sphere_spherical()` to plot a qubit in the states:
1. $|0\rangle$
2. $|1\rangle$
3. $\tfrac{1}{\sqrt{2}}(|0\rangle + |1\rangle)$
4. $\tfrac{1}{\sqrt{2}}(|0\rangle - i|1\rangle)$
5. $\begin{bmatrix}i\\1\end{bmatrix}$
We have also included below a widget that converts from spherical co-ordinates to cartesian, for use with `plot_bloch_vector()`:
```
from widgets import bloch_calc
bloch_calc()
import qiskit
qiskit.__qiskit_version__
```
|
github_jupyter
|
from qiskit import *
from qiskit.visualization import plot_histogram, plot_bloch_vector
from math import sqrt, pi
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
from qiskit.extensions import Initialize # Import the Inititialize function
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
inital_state = [0,1] # Define initial_state as |1>
init_op = Initialize(inital_state) # Create Initialisation Operation for state |1>
qc.append(init_op,[0]) # Apply initialisation operation to the qubit (it's index is 0)
qc.draw() # Let's view our circuit
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
out_state = execute(qc,backend).result().get_statevector() # Do the simulation, returning the state vector
print(out_state) # Display the output state vector
qc.measure_all()
qc.draw()
results = execute(qc,backend).result().get_counts()
plot_histogram(results)
# Must redefine our circuit
qc = QuantumCircuit(1)
# Define state |q>
inital_state = [1/sqrt(2), complex(0,1/sqrt(2))]
# Create Initialisation Operation for state |q>
init_op = Initialize(inital_state)
# Add our initialisation operation to the circuit (the qubit's index is 0)
qc.append(init_op,[0])
# Execute the circuit and print the result
state = execute(qc,backend).result().get_statevector()
print(state)
results = execute(qc,backend).result().get_counts()
plot_histogram(results)
vector = [1,1]
Initialize(vector)
from widgets import state_vector_exercise
state_vector_exercise(target=1/3)
qc = QuantumCircuit(1) # Redefine qc
initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j]
init_state = Initialize(inital_state)
qc.append(init_state, [0])
qc.draw()
state = execute(qc,backend).result().get_statevector()
print("Qubit State = " + str(state))
qc.measure_all()
qc.draw()
state = execute(qc,backend).result().get_statevector()
print("State of Measured Qubit = " + str(state))
from widgets import plot_bloch_vector_spherical
coords = [pi/2,0,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates
from widgets import bloch_calc
bloch_calc()
import qiskit
qiskit.__qiskit_version__
| 0.695338 | 0.994259 |
## Import with a generic data structure
This is similar to number 2, but starts using a structured data format to capture variables, which helps with explicit defaults.
There's not much advantage to doing it this way--arguable the code is more complex--but it starts to become more useful with more complex processing; see recipe 3.
```
# This format for this data structure is:
# data_capture_dict = {
# '<SCHEDULE NAME>': {
# 'groups': {
# '<REPEATING GROUP (TABLE) NAME>': {
# '<IRSX VARIABLE NAME': {
# 'header':'<HEADER IN OUR OUTPUT CSV FILE>',
# 'default': <DEFAULT VALUE TO USE IF IT'S MISSING
data_capture_dict = {
'IRS990ScheduleJ': {
'groups': {
'SkdJRltdOrgOffcrTrstKyEmpl': {
'PrsnNm': {'header':'name'},
'BsnssNmLn1Txt': {'header':'business_name1'},
'BsnssNmLn2Txt': {'header':'business_name2'},
'TtlTxt': {'header':'title'},
'TtlCmpnstnFlngOrgAmt': {
'header':'org_comp',
'default':0
},
'TtlCmpnstnRltdOrgsAmt': {
'header':'related_comp',
'default':0
},
}
}
}
}
import unicodecsv as csv
from irsx.xmlrunner import XMLRunner
# read the whole file in here, it's not very long
file_rows = []
# We're using the output of part 1
with open('pdxefilers.csv', 'rb') as infile:
reader = csv.DictReader(infile)
for row in reader:
file_rows.append(row)
len(file_rows)
# the name of the output file
outfilename ="employees.csv"
outfile = open(outfilename , 'wb')
# the header rows as they'll appear in the output
headers = ["period", "ein", "object_id", "taxpayer_name", "name", "business_name1", "business_name2", "title", "org_comp", "related_comp"]
# start up a dictwriter, ignore extra rows
dw = csv.DictWriter(outfile, headers, extrasaction='ignore')
dw.writeheader()
# get an XMLRunner -- this is what actually does the parsin
xml_runner = XMLRunner()
```
## Figure out what to extract
Data from each repeating group should go to it's own file, otherwise it won't make sense.
To figure out what to capture, I started by looking at schedule J: http://www.irsx.info/#IRS990ScheduleJ
Then I went to the table details and picked the rows I wanted from the repeating group:
http://www.irsx.info/metadata/groups/SkdJRltdOrgOffcrTrstKyEmpl.html
Note that it's common for director/employee names in schedule J to get listed as businessname
```
def run_filing(filing, metadata_row, dw):
parsed_filing = xml_runner.run_filing(filing)
if not parsed_filing:
print("Skipping filing %s(filings with pre-2013 filings are skipped)\n row details: %s" % (filing, metadata_row))
return None
schedule_list = parsed_filing.list_schedules()
for sked in data_capture_dict.keys():
if sked in schedule_list:
parsed_skeds = parsed_filing.get_parsed_sked(sked)
if parsed_skeds:
parsed_sked = parsed_skeds[0]
else:
continue
for group in data_capture_dict[sked]['groups']:
#print("Extracting from repeating group %s" % group)
try:
groups = parsed_sked['groups'][group]
#print("Found %s groups for %s" % (len(groups), group))
except KeyError:
print("No groups found for %s\n" % group)
continue
# Get the individual variables we're gonna pull
capture_dict = data_capture_dict[sked]['groups'][group]
# We know the grops are there, extract from each one
for parsed_group in groups:
# Store the data for the new csv output file here
row_data = {}
# Get rows from the metadata row we passed in
row_data['period'] = metadata_row['TAX_PERIOD_x']
row_data['ein'] = metadata_row['EIN']
row_data['object_id'] = metadata_row['OBJECT_ID']
row_data['taxpayer_name'] = metadata_row['TAXPAYER_NAME']
for variablename in capture_dict.keys():
try:
val = parsed_group[variablename]
csv_header = capture_dict[variablename]['header']
row_data[csv_header] = val
except KeyError:
try:
default = capture_dict[variablename]['default']
csv_header = capture_dict[variablename]['header']
row_data[csv_header]=default
except KeyError:
pass
dw.writerow(row_data)
DEMO_MAX = 1000
for count, row in enumerate(file_rows):
this_object_id = row['OBJECT_ID']
run_filing(this_object_id, row, dw)
# Don't run endlessly during a demo:
if(count > DEMO_MAX):
break
if count%100==0:
print("Processed %s filings" % count)
# outfile.close()
```
|
github_jupyter
|
# This format for this data structure is:
# data_capture_dict = {
# '<SCHEDULE NAME>': {
# 'groups': {
# '<REPEATING GROUP (TABLE) NAME>': {
# '<IRSX VARIABLE NAME': {
# 'header':'<HEADER IN OUR OUTPUT CSV FILE>',
# 'default': <DEFAULT VALUE TO USE IF IT'S MISSING
data_capture_dict = {
'IRS990ScheduleJ': {
'groups': {
'SkdJRltdOrgOffcrTrstKyEmpl': {
'PrsnNm': {'header':'name'},
'BsnssNmLn1Txt': {'header':'business_name1'},
'BsnssNmLn2Txt': {'header':'business_name2'},
'TtlTxt': {'header':'title'},
'TtlCmpnstnFlngOrgAmt': {
'header':'org_comp',
'default':0
},
'TtlCmpnstnRltdOrgsAmt': {
'header':'related_comp',
'default':0
},
}
}
}
}
import unicodecsv as csv
from irsx.xmlrunner import XMLRunner
# read the whole file in here, it's not very long
file_rows = []
# We're using the output of part 1
with open('pdxefilers.csv', 'rb') as infile:
reader = csv.DictReader(infile)
for row in reader:
file_rows.append(row)
len(file_rows)
# the name of the output file
outfilename ="employees.csv"
outfile = open(outfilename , 'wb')
# the header rows as they'll appear in the output
headers = ["period", "ein", "object_id", "taxpayer_name", "name", "business_name1", "business_name2", "title", "org_comp", "related_comp"]
# start up a dictwriter, ignore extra rows
dw = csv.DictWriter(outfile, headers, extrasaction='ignore')
dw.writeheader()
# get an XMLRunner -- this is what actually does the parsin
xml_runner = XMLRunner()
def run_filing(filing, metadata_row, dw):
parsed_filing = xml_runner.run_filing(filing)
if not parsed_filing:
print("Skipping filing %s(filings with pre-2013 filings are skipped)\n row details: %s" % (filing, metadata_row))
return None
schedule_list = parsed_filing.list_schedules()
for sked in data_capture_dict.keys():
if sked in schedule_list:
parsed_skeds = parsed_filing.get_parsed_sked(sked)
if parsed_skeds:
parsed_sked = parsed_skeds[0]
else:
continue
for group in data_capture_dict[sked]['groups']:
#print("Extracting from repeating group %s" % group)
try:
groups = parsed_sked['groups'][group]
#print("Found %s groups for %s" % (len(groups), group))
except KeyError:
print("No groups found for %s\n" % group)
continue
# Get the individual variables we're gonna pull
capture_dict = data_capture_dict[sked]['groups'][group]
# We know the grops are there, extract from each one
for parsed_group in groups:
# Store the data for the new csv output file here
row_data = {}
# Get rows from the metadata row we passed in
row_data['period'] = metadata_row['TAX_PERIOD_x']
row_data['ein'] = metadata_row['EIN']
row_data['object_id'] = metadata_row['OBJECT_ID']
row_data['taxpayer_name'] = metadata_row['TAXPAYER_NAME']
for variablename in capture_dict.keys():
try:
val = parsed_group[variablename]
csv_header = capture_dict[variablename]['header']
row_data[csv_header] = val
except KeyError:
try:
default = capture_dict[variablename]['default']
csv_header = capture_dict[variablename]['header']
row_data[csv_header]=default
except KeyError:
pass
dw.writerow(row_data)
DEMO_MAX = 1000
for count, row in enumerate(file_rows):
this_object_id = row['OBJECT_ID']
run_filing(this_object_id, row, dw)
# Don't run endlessly during a demo:
if(count > DEMO_MAX):
break
if count%100==0:
print("Processed %s filings" % count)
# outfile.close()
| 0.118538 | 0.722747 |
<img src="../images/demos/FIUM.png" width="350px" class="pull-right" style="display: inline-block">
# Visión Artificial
### 4º de Grado en Ingeniería Informática
Curso 2019-2020<br>
Prof. [*Alberto Ruiz*](http://dis.um.es/profesores/alberto)
## Recursos
- [libro de Szeliski](http://szeliski.org/Book/drafts/SzeliskiBook_20100903_draft.pdf)
- [OpenCV](https://opencv.org/), [tutoriales en Python](https://docs.opencv.org/4.1.0/d6/d00/tutorial_py_root.html)
- [scikit-image](http://scikit-image.org/), [scikit-learn](http://scikit-learn.org)
- [datasets](https://en.wikipedia.org/wiki/List_of_datasets_for_machine_learning_research#Image_data)
- [Python](https://docs.python.org/3.6/)
- [numpy](http://www.numpy.org/), [scipy](http://docs.scipy.org/doc/scipy/reference/)
- [matplotlib](http://matplotlib.org/index.html)
## Clases
### 0. Presentación (3/2/20)
[introducción](intro.ipynb), [instalación](install.ipynb), [Python](python.ipynb)
- Introducción a la asignatura
- Repaso de Python, numpy y matplotib
### 1. Introducción a la imagen digital (10/2/20)
[imagen](imagen.ipynb), [gráficas](graphs.ipynb), [canales de color](color.ipynb), [indexado/stacks](stacks.ipynb), [dispositivos de captura](captura.ipynb)
- Imagen digital: rows, cols, depth, step. Planar or pixel order. Tipo de pixel: byte vs float
- Color encoding: RGB vs YUV vs HSV
- Campo de visión (FOV, *field of view*, parámetro $f$)
- Coordendas de pixel, coordenadas normalizadas (indep de resolución), coordenadas calibradas (independiente del FOV).
- Aspect ratio. Resize.
- ROI, masks
- Manipulación: slice regions, "stack" de imágenes
- primitivas gráficas
- captura: webcams, cameras ip, archivos de vídeo, v4l2-ctl, etc. Load / save.
- entornos de conda, pyqtgraph, pycharm, spyder
- Herramientas: formatos de imagen, imagemagick, gimp, mplayer/mencoder/ffmpeg, etc.
### 2. Manipulación de imágenes
[histograma](histogram.ipynb), [efecto chroma](chroma.ipynb), [segmentación por color](colorseg.ipynb)
<br>
[cuantización de color](codebook.ipynb), [transformaciones de dominio](lookup.ipynb)
- Histograma, transformaciones de valor (brillo, contraste), ecualización
- Transformaciones de dominio (deformaciones), lookup table.
- chroma key
- reproyección de histograma
### 3. Filtros digitales
[filtros de imagen](filtros.ipynb), [análisis frecuencial](fourier.ipynb), [filtrado inverso](inversefilt.ipynb)
- lineal
- convolution
- máscaras para paso alto, bajo, etc.
- separabilidad
- integral image, box filter
- dominio frecuencial
- [inverse filtering](http://yuzhikov.com/articles/BlurredImagesRestoration1.htm), [Wiener](https://www.cis.rit.edu/class/simg782/lectures/lecture_16/lec782_05_16.pdf)
- no lineal
- mediana
- min, max
- algoritmos generales
- Gaussian filter
- separabilidad
- cascading
- Fourier
- [morphological operations](http://docs.opencv.org/master/d9/d61/tutorial_py_morphological_ops.html#gsc.tab=0)
- structuring element
- dilate, erode
- open, close
- gradient
- fill holes
- Transformada de distancia
### 4. Detección de bordes
[detección de bordes](bordes.ipynb), [Canny nms en C](cannyC.ipynb)
- gradiente: visualización como *vector field*
- operador de Canny
- transformada de Hough
- Histograma de orientaciones del gradiente (HOG)
- implementación simple de HOG
- detección de *pedestrians*
- face landmarks (dlib)
### 5. Flujo óptico
[elipse de incertidumbre](covarianza.ipynb), [optical flow](harris.ipynb)
- elipse de incertidumbre
- cross-correlation
- corners (Harris)
- Lucas-Kanade
### 6. Análisis frecuencial
(Conclusión del capítulo 3)
### 7. *Keypoints*
[keypoints](keypoints.ipynb), [bag of visual words](bag-of-words.ipynb)
- modelo cuadrático
- blobs / saddle points (Hessian)
- SIFT
### 8. Reconocimiento de formas
[shapes](shapes.ipynb), [transformada de distancia](transf-dist.ipynb)
- umbralización
- análisis de regiones (componentes conexas, transformada de distancia)
- manipulación de contornos
- invariantes frecuenciales de forma
### 9. *Deep learning*
[machine learning](machine-learning.ipynb), [tensorflow](tensorflow.ipynb)
- Repaso de *Machine Learning* y *Pattern Recognition*
- Repaso de computación neuronal
- Introducción a la redes convolucionales
- *Deep Learning* en visión artificial.
### X. Otras técnicas
[varios](varios.ipynb), [textura](textura.ipynb), [`grabcut.py`](../code/grabcut.py)
- Detección de caras mediante *adaboost* ([Viola & Jones, 2001](https://en.wikipedia.org/wiki/Viola%E2%80%93Jones_object_detection_framework))
- Segmentación de objetos mediante *GrabCut* ([Rother et al. 2004](https://cvg.ethz.ch/teaching/cvl/2012/grabcut-siggraph04.pdf), [tutorial](http://docs.opencv.org/3.2.0/d8/d83/tutorial_py_grabcut.html))
- Clasificación de texturas mediante *LBP* ([Wang and He, 1990](http://www.academia.edu/download/46467306/0031-3203_2890_2990135-820160614-8960-12m30mo.pdf), [wiki](https://en.wikipedia.org/wiki/Local_binary_patterns))
- Herramientas para OCR (*[tesseract](https://github.com/tesseract-ocr)*)
- Herramientas para códigos de barras y QR (*[zbar](http://zbar.sourceforge.net/)*)
- Detección de elipses
### 10. Coordenadas homogéneas
Comenzamos el estudio de la geometría visual.
[perspectiva](geovis.ipynb), [coordenadas homogéneas](coordhomog.ipynb), [sistemas de ecuaciones](sistecs.ipynb)
Transformaciones lineales
- espacios lineales, vectores
- transformaciones lineales, matrices
- producto escalar (**dot** product)
- producto vectorial (**cross** product)
- puntos, rectas, planos, meet & join
Geometría del plano
- coordenadas homogéneas
- interpretación como rayos
- puntos y rectas del plano
- incidencia e intersección, dualidad
- puntos del infinito, recta del infinito
- manejo natural de puntos del infinito
- horizonte de un plano
### 11. Transformaciones del plano
[transformaciones del plano](transf2D.ipynb)
- Desplazamientos, rotaciones, escalado uniforme, escalado general, proyectividad.
- Grupos euclídeo, similar, afín, proyectivo.
- Propiedades invariantes de cada grupo.
- Representación como matriz homogénea $3\times 3$ y tipos de matriz de cada grupo.
- *Cross ratio* de 4 puntos en una recta. De 5 rectas.
- Estimación de transformaciones a partir de correspondencias.
- Aplicaciones: rectificación de planos, mosaico de imágenes.
Avanzado
- Transformación de rectas. Covarianza y contravarianza.
- Cónicas: incidencia, tangencia, (pole-polar), cónica dual, transformación.
- Objetos invariantes en cada grupo de transformaciones.
### 12. Modelo de cámara
[modelo de la cámara](camera.ipynb)
- Espacio proyectivo: puntos y líneas 3D, planos, grados de libertad, plano del infinito, analogía con 2D.
- Grupos de transformaciones 3D: y sus invariantes.
- Modelo pinhole (proyección), cámara oscura, lente.
- Transformación de perspectiva: proyección $\mathcal P^3 \rightarrow\mathcal P ^2$.
- cámara calibrada C=PRT, 6 dof, parámetros extrínsecos o pose.
- calibración, distorsión radial.
- Matriz de cámara estándar $M=K[R|t]$.
- Matriz de calibración $K$ y campo visual. Calibración "a ojo" de una cámara mediante estimación de su FOV.
- PnP (*pose from n points*).
- Realidad aumentada.
- Anatomía de la cámara
- Rotaciones sintéticas
Experimentos
- Rectificación de planos mediante rotaciones sintéticas.
- Experimenta con [ARToolkit](http://artoolkit.org).
- Echa un vistazo a [PTAM](http://www.robots.ox.ac.uk/~gk/PTAM)
- Navegación visual de robots.
- Haz un programa que capture con la webcam la imagen de un sudoku y lo resuelva.
### 13. Visión estéreo
[stereo](stereo.ipynb), [stereo-challenge](stereo-challenge.ipynb)
- Triangulación
- Geometría epipolar
- Extracción de cámaras
- Rectificación estéreo
- Mapas de profundidad
Experimentos
- Reproduce los experimentos con un par estéreo tomado con tu propia cámara usando el *tracker* de puntos estudiado en una clase anterior.
- Intenta poner en marcha el sistema [VisualSFM](http://ccwu.me/vsfm/).
## Notebooks
1. [introducción](intro.ipynb)
1. [instalación](install.ipynb)
1. [Python](python.ipynb)
1. [dispositivos de captura](captura.ipynb)
1. [imagen](imagen.ipynb)
1. [gráficas](graphs.ipynb)
1. [canales de color](color.ipynb)
1. [indexado, stacks](stacks.ipynb)
1. [histograma](histogram.ipynb)
1. [efecto chroma](chroma.ipynb)
1. [segmentación por color](colorseg.ipynb)
1. [cuantización de color](codebook.ipynb)
1. [transformaciones de dominio](lookup.ipynb)
1. [filtros de imagen](filtros.ipynb)
1. [análisis frecuencial](fourier.ipynb)
1. [filtrado inverso](inversefilt.ipynb)
1. [transformada de distancia](transf-dist.ipynb)
1. [detección de bordes](bordes.ipynb)
1. [técnicas auxiliares](ipmisc.ipynb)
1. [Canny nms en C](cannyC.ipynb)
1. [elipse de incertidumbre](covarianza.ipynb)
1. [optical flow](harris.ipynb)
1. [keypoints](keypoints.ipynb)
1. [bag of visual words](bag-of-words.ipynb)
1. [sistemas de ecuaciones](sistecs.ipynb)
1. [textura](textura.ipynb)
1. [shapes](shapes.ipynb)
1. [varios](varios.ipynb)
1. [perspectiva](geovis.ipynb)
1. [coordenadas homogéneas](coordhomog.ipynb)
1. [transformaciones del plano](transf2D.ipynb)
1. [DLT](DLT.ipynb)
1. [modelo de cámara](camera.ipynb)
1. [visión stereo](stereo.ipynb)
1. [stereo-challenge](stereo-challenge.ipynb)
1. [machine learning](machine-learning.ipynb)
1. [tensorflow](tensorflow.ipynb)
## Ejemplos de código
1. [`hello.py`](../code/hello.py): lee imagen de archivo, la reescala, muestra y sobreescribe un texto.
1. [`webcam.py`](../code/webcam.py): muestra la secuencia de imágenes capturadas por una webcam.
1. [`2cams.py`](../code/2cams.py): combina las imágenes tomadas por dos cámaras.
1. [`player.py`](../code/player.py): función auxiliar que permite aplicar una cierta función a la secuencia de imágenes, con opción de guardar (S) y parar el vídeo (espacio).
1. [`mouse.py`](../code/mouse.py): ejemplo de captura de eventos de ratón.
1. [`trackbar.py`](../code/trackbar.py): ejemplo de parámetro interactivo.
1. [`stream.py`](../code/stream.py): ejemplo de uso de la fuente genérica de imágenes "mkStream".
1. [`stream2.py`](../code/stream2.py): ejemplo de mkStream para leer un conjunto de imágenes en disco mostrándolas y avanzando de una en una pulsando una tecla.
1. [`deque.py`](../code/deque.py): procesamiento de las $n$ imágenes más recientes.
1. [`mjpegserver.py`](../code/mjpegserver.py): servidor de secuencias de video en formato mjpeg.
1. [`histogram.py`](../code/histogram.py): histograma en vivo con opencv.
1. [`histogram2.py`](../code/histogram2.py): histograma en vivo con matplotlib.
1. [`surface.py`](../code/surface.py): superficie 3D de niveles de gris en vivo usando pyqtgraph.
1. [`backsub.py`](../code/backsub.py): eliminación de fondo mediante MOG2.
1. [`server.py`](../code/server.py): ejemplo de servidor web de imágenes capturadas con la webcam.
1. [`bot`](../code/bot): bots de [Telegram](https://python-telegram-bot.org/).
1. [`reprohist.py`](../code/reprohist.py): reproyección de histograma.
1. [`camshift.py`](../code/camshift.py): tracking mediante reproyección de histograma.
1. [`grabcut.py`](../code/grabcut.py): segmentación de objetos interactiva mediante GrabCut.
1. [`spectral.py`](../code/spectral.py): FFT en vivo.
1. [`thread`](../code/thread): captura y procesamiento concurrente.
1. [`testC.py`](../code/testC.py), [`inC`](../code/inC): Interfaz C-numpy.
1. [`hog/pedestrian.py`](../code/hog/pedestrian.py): detector de peatones de opencv.
1. [`hog/facelandmarks.py`](../code/hog/facelandmarks.py): detector de caras y landmarks de dlib.
1. [`hog/hog0.py`](../code/hog/hog0.py): experimentos con hog.
1. [`regressor.py`](../code/regressor.py): predictor directo de la posición de una región.
1. [`sift.py`](../code/sift.py): demostración de la detección de keypoints y búsqueda de coincidencias en imágenes en vivo.
1. [`lk_base.py`](../code/lk_base.py), [`lk_track.py`](../code/lk_track.py): seguimiento de puntos con el método de Lucas-Kanade.
1. [`inception.py`](../code/inception.py): clasificación de objetos con la red convolucional InceptionV3 entrenada con la base de datos imagenet, disponible en keras.
1. [`openpose.py`](../code/openpose.py): estimación de postura de cuerpo humano mediante [openpose](https://github.com/ildoonet/tf-pose-estimation).
1. [`stitcher.py`](../code/stitcher.py): construcción automática de panoramas.
1. [`pose.py`](../code/pose.py), [`pose3D.py`](../code/pose3D.py): estimación de cámara y realidad aumentada.
## Ejercicios propuestos
**1**. Pon en marcha el entorno de trabajo, incluyendo entre otros, los módulos y herramientas jupyter, spyder/pycharm, opencv, numpy, matplolib.
**2**. Estima de forma aproximada el campo de visión ([FOV](https://en.wikipedia.org/wiki/Angle_of_view)) y parámetro $f$ de tu cámara. Determina a qué altura habría que ponerla para obtener una vista cenital completa de un campo de baloncesto. Calcula la altura de una pelota sobre el suelo a partir de su tamaño en la imagen.
Realiza una calibración precisa de tu cámara mediante múltiples imágenes de un *chessboard* y compara con el resultado anterior.
### Curso anterior
Modifica los canales de color (brillo, saturación, etc.) de una secuencia de imágenes en vivo con un "trackbar".
Amplia `player.py` o `stream.py` para seleccionar con el ratón una región de interés (ROI) y almacenar los recortes en una lista, y opcionalmente en disco. Este programa nos servirá como base para futuros ejercicios.
Construye un detector de movimiento basado en una sencilla diferencia de imágenes sucesivas. Opcionalmente puedes hacer un generador que filtre la secuencia de imágenes dejando pasar solo los frames estáticos (o, alternativamente, los que han sufrido un cambio apreciable. En este caso no hace falta detectar las zonas con movimiento). Puedes apoyarte en `deque.py`. Opcional: a) Limitar la detección a una región de interés. b) Guardar 2 ó 3 segundos de la secuencia detectada en un archivo de vídeo o imagen gif.
Implementa el efecto chroma con imágenes en vivo de la webcam. Pulsando una tecla se captura el fondo y los objetos que aparezcan se superponen en otra imagen o secuencia de video. Compara el resultado con el método automático de eliminación de fondo ilustrado en `backsub.py`.
Construye un clasificador de objetos en base a la similitud de los histogramas de color del ROI (de los 3 canales por separado). Apóyate en 3.
Implementa la segmentación por color usando reproyección de histogramas en un programa que admite como argumento a) una carpeta con trozos de imágen que sirven como muestras de color y b) otra imagen o secuencia de video que deseamos clasificar. El resultado puede ser un conjunto de máscaras para cada clase, o una "imagen de etiquetas", donde diferentes colores indican cada una de las regiones.
Muestra el efecto de diferentes filtros sobre la imagen en vivo de la webcam. Selecciona con el teclado el filtro deseado y modifica sus posibles parámetros (p.ej. el nivel de suavizado) con las teclas de flecha. Es conveniente permitir la selección de un ROI para comparar el resultado del filtro con el resto de la imagen.
Construye un servidor web sencillo usando [flask](http://flask.pocoo.org/) que muestre una cierta transformación, especificada en la url, de las imágenes tomadas con la cámara. Apóyate en `server.py`.
Escribe una aplicación de tu invención que utilice los [marcadores de cara](https://ibug.doc.ic.ac.uk/resources/facial-point-annotations/) obtenidos por el *shape detector* disponible en [dlib](http://dlib.net/) (ejemplo `/hog/facelandmarks.py`).
Estima de forma aproximada la velocidad angular de rotación de la cámara (grados/segundo) analizando las trayectorias obtenidas por el *tracker* de Lucas-Kanade (ejemplo `lk_track.py`).
Escribe una aplicación de reconocimiento de objetos con la webcam basada en el número de coincidencias de *keypoints*. Pulsando una tecla se pueden ir guardando modelos (p. ej. carátulas de CD, portadas de libros, cuadros de pintores, etc.). Cuando detectamos que la imagen está bastante quieta, o cuando se pulse otra tecla, calculamos los puntos de interés de la imagen actual y sus descriptores y comprobamos si hay suficientes coincidencias con los de algún modelo.
Escribe una aplicación de reconocimiento de siluetas con la webcam basado en descriptores frecuenciales.
Escribe una aplicación de reconocimiento de dígitos manuscritos con la webcam. Compara el clasificador gaussiano y la red convolucional explicada en el capítulo de machine learning.
Rectifica la imagen de un plano para medir distancias (tomando manualmente referencias conocidas). Por ejemplo, mide la distancia entre las monedas en `coins.png` o la distancia a la que se realiza el disparo en `gol-eder.png`.
Crea automáticamente un mosaico panorámico ajustando varias imágenes (>2). Recuerda que debe tratarse de una escena plana o de una escena cualquiera vista desde el mismo centro de proyección.
Crea un efecto de realidad aumentada dinámico.
Haz un programa capaz de rellenar un sudoku que se observa en la imagen en vivo de la webcam.
Resuelve los problemas planteados en el notebook [stereo-challenge](stereo-challenge.ipynb).
|
github_jupyter
|
<img src="../images/demos/FIUM.png" width="350px" class="pull-right" style="display: inline-block">
# Visión Artificial
### 4º de Grado en Ingeniería Informática
Curso 2019-2020<br>
Prof. [*Alberto Ruiz*](http://dis.um.es/profesores/alberto)
## Recursos
- [libro de Szeliski](http://szeliski.org/Book/drafts/SzeliskiBook_20100903_draft.pdf)
- [OpenCV](https://opencv.org/), [tutoriales en Python](https://docs.opencv.org/4.1.0/d6/d00/tutorial_py_root.html)
- [scikit-image](http://scikit-image.org/), [scikit-learn](http://scikit-learn.org)
- [datasets](https://en.wikipedia.org/wiki/List_of_datasets_for_machine_learning_research#Image_data)
- [Python](https://docs.python.org/3.6/)
- [numpy](http://www.numpy.org/), [scipy](http://docs.scipy.org/doc/scipy/reference/)
- [matplotlib](http://matplotlib.org/index.html)
## Clases
### 0. Presentación (3/2/20)
[introducción](intro.ipynb), [instalación](install.ipynb), [Python](python.ipynb)
- Introducción a la asignatura
- Repaso de Python, numpy y matplotib
### 1. Introducción a la imagen digital (10/2/20)
[imagen](imagen.ipynb), [gráficas](graphs.ipynb), [canales de color](color.ipynb), [indexado/stacks](stacks.ipynb), [dispositivos de captura](captura.ipynb)
- Imagen digital: rows, cols, depth, step. Planar or pixel order. Tipo de pixel: byte vs float
- Color encoding: RGB vs YUV vs HSV
- Campo de visión (FOV, *field of view*, parámetro $f$)
- Coordendas de pixel, coordenadas normalizadas (indep de resolución), coordenadas calibradas (independiente del FOV).
- Aspect ratio. Resize.
- ROI, masks
- Manipulación: slice regions, "stack" de imágenes
- primitivas gráficas
- captura: webcams, cameras ip, archivos de vídeo, v4l2-ctl, etc. Load / save.
- entornos de conda, pyqtgraph, pycharm, spyder
- Herramientas: formatos de imagen, imagemagick, gimp, mplayer/mencoder/ffmpeg, etc.
### 2. Manipulación de imágenes
[histograma](histogram.ipynb), [efecto chroma](chroma.ipynb), [segmentación por color](colorseg.ipynb)
<br>
[cuantización de color](codebook.ipynb), [transformaciones de dominio](lookup.ipynb)
- Histograma, transformaciones de valor (brillo, contraste), ecualización
- Transformaciones de dominio (deformaciones), lookup table.
- chroma key
- reproyección de histograma
### 3. Filtros digitales
[filtros de imagen](filtros.ipynb), [análisis frecuencial](fourier.ipynb), [filtrado inverso](inversefilt.ipynb)
- lineal
- convolution
- máscaras para paso alto, bajo, etc.
- separabilidad
- integral image, box filter
- dominio frecuencial
- [inverse filtering](http://yuzhikov.com/articles/BlurredImagesRestoration1.htm), [Wiener](https://www.cis.rit.edu/class/simg782/lectures/lecture_16/lec782_05_16.pdf)
- no lineal
- mediana
- min, max
- algoritmos generales
- Gaussian filter
- separabilidad
- cascading
- Fourier
- [morphological operations](http://docs.opencv.org/master/d9/d61/tutorial_py_morphological_ops.html#gsc.tab=0)
- structuring element
- dilate, erode
- open, close
- gradient
- fill holes
- Transformada de distancia
### 4. Detección de bordes
[detección de bordes](bordes.ipynb), [Canny nms en C](cannyC.ipynb)
- gradiente: visualización como *vector field*
- operador de Canny
- transformada de Hough
- Histograma de orientaciones del gradiente (HOG)
- implementación simple de HOG
- detección de *pedestrians*
- face landmarks (dlib)
### 5. Flujo óptico
[elipse de incertidumbre](covarianza.ipynb), [optical flow](harris.ipynb)
- elipse de incertidumbre
- cross-correlation
- corners (Harris)
- Lucas-Kanade
### 6. Análisis frecuencial
(Conclusión del capítulo 3)
### 7. *Keypoints*
[keypoints](keypoints.ipynb), [bag of visual words](bag-of-words.ipynb)
- modelo cuadrático
- blobs / saddle points (Hessian)
- SIFT
### 8. Reconocimiento de formas
[shapes](shapes.ipynb), [transformada de distancia](transf-dist.ipynb)
- umbralización
- análisis de regiones (componentes conexas, transformada de distancia)
- manipulación de contornos
- invariantes frecuenciales de forma
### 9. *Deep learning*
[machine learning](machine-learning.ipynb), [tensorflow](tensorflow.ipynb)
- Repaso de *Machine Learning* y *Pattern Recognition*
- Repaso de computación neuronal
- Introducción a la redes convolucionales
- *Deep Learning* en visión artificial.
### X. Otras técnicas
[varios](varios.ipynb), [textura](textura.ipynb), [`grabcut.py`](../code/grabcut.py)
- Detección de caras mediante *adaboost* ([Viola & Jones, 2001](https://en.wikipedia.org/wiki/Viola%E2%80%93Jones_object_detection_framework))
- Segmentación de objetos mediante *GrabCut* ([Rother et al. 2004](https://cvg.ethz.ch/teaching/cvl/2012/grabcut-siggraph04.pdf), [tutorial](http://docs.opencv.org/3.2.0/d8/d83/tutorial_py_grabcut.html))
- Clasificación de texturas mediante *LBP* ([Wang and He, 1990](http://www.academia.edu/download/46467306/0031-3203_2890_2990135-820160614-8960-12m30mo.pdf), [wiki](https://en.wikipedia.org/wiki/Local_binary_patterns))
- Herramientas para OCR (*[tesseract](https://github.com/tesseract-ocr)*)
- Herramientas para códigos de barras y QR (*[zbar](http://zbar.sourceforge.net/)*)
- Detección de elipses
### 10. Coordenadas homogéneas
Comenzamos el estudio de la geometría visual.
[perspectiva](geovis.ipynb), [coordenadas homogéneas](coordhomog.ipynb), [sistemas de ecuaciones](sistecs.ipynb)
Transformaciones lineales
- espacios lineales, vectores
- transformaciones lineales, matrices
- producto escalar (**dot** product)
- producto vectorial (**cross** product)
- puntos, rectas, planos, meet & join
Geometría del plano
- coordenadas homogéneas
- interpretación como rayos
- puntos y rectas del plano
- incidencia e intersección, dualidad
- puntos del infinito, recta del infinito
- manejo natural de puntos del infinito
- horizonte de un plano
### 11. Transformaciones del plano
[transformaciones del plano](transf2D.ipynb)
- Desplazamientos, rotaciones, escalado uniforme, escalado general, proyectividad.
- Grupos euclídeo, similar, afín, proyectivo.
- Propiedades invariantes de cada grupo.
- Representación como matriz homogénea $3\times 3$ y tipos de matriz de cada grupo.
- *Cross ratio* de 4 puntos en una recta. De 5 rectas.
- Estimación de transformaciones a partir de correspondencias.
- Aplicaciones: rectificación de planos, mosaico de imágenes.
Avanzado
- Transformación de rectas. Covarianza y contravarianza.
- Cónicas: incidencia, tangencia, (pole-polar), cónica dual, transformación.
- Objetos invariantes en cada grupo de transformaciones.
### 12. Modelo de cámara
[modelo de la cámara](camera.ipynb)
- Espacio proyectivo: puntos y líneas 3D, planos, grados de libertad, plano del infinito, analogía con 2D.
- Grupos de transformaciones 3D: y sus invariantes.
- Modelo pinhole (proyección), cámara oscura, lente.
- Transformación de perspectiva: proyección $\mathcal P^3 \rightarrow\mathcal P ^2$.
- cámara calibrada C=PRT, 6 dof, parámetros extrínsecos o pose.
- calibración, distorsión radial.
- Matriz de cámara estándar $M=K[R|t]$.
- Matriz de calibración $K$ y campo visual. Calibración "a ojo" de una cámara mediante estimación de su FOV.
- PnP (*pose from n points*).
- Realidad aumentada.
- Anatomía de la cámara
- Rotaciones sintéticas
Experimentos
- Rectificación de planos mediante rotaciones sintéticas.
- Experimenta con [ARToolkit](http://artoolkit.org).
- Echa un vistazo a [PTAM](http://www.robots.ox.ac.uk/~gk/PTAM)
- Navegación visual de robots.
- Haz un programa que capture con la webcam la imagen de un sudoku y lo resuelva.
### 13. Visión estéreo
[stereo](stereo.ipynb), [stereo-challenge](stereo-challenge.ipynb)
- Triangulación
- Geometría epipolar
- Extracción de cámaras
- Rectificación estéreo
- Mapas de profundidad
Experimentos
- Reproduce los experimentos con un par estéreo tomado con tu propia cámara usando el *tracker* de puntos estudiado en una clase anterior.
- Intenta poner en marcha el sistema [VisualSFM](http://ccwu.me/vsfm/).
## Notebooks
1. [introducción](intro.ipynb)
1. [instalación](install.ipynb)
1. [Python](python.ipynb)
1. [dispositivos de captura](captura.ipynb)
1. [imagen](imagen.ipynb)
1. [gráficas](graphs.ipynb)
1. [canales de color](color.ipynb)
1. [indexado, stacks](stacks.ipynb)
1. [histograma](histogram.ipynb)
1. [efecto chroma](chroma.ipynb)
1. [segmentación por color](colorseg.ipynb)
1. [cuantización de color](codebook.ipynb)
1. [transformaciones de dominio](lookup.ipynb)
1. [filtros de imagen](filtros.ipynb)
1. [análisis frecuencial](fourier.ipynb)
1. [filtrado inverso](inversefilt.ipynb)
1. [transformada de distancia](transf-dist.ipynb)
1. [detección de bordes](bordes.ipynb)
1. [técnicas auxiliares](ipmisc.ipynb)
1. [Canny nms en C](cannyC.ipynb)
1. [elipse de incertidumbre](covarianza.ipynb)
1. [optical flow](harris.ipynb)
1. [keypoints](keypoints.ipynb)
1. [bag of visual words](bag-of-words.ipynb)
1. [sistemas de ecuaciones](sistecs.ipynb)
1. [textura](textura.ipynb)
1. [shapes](shapes.ipynb)
1. [varios](varios.ipynb)
1. [perspectiva](geovis.ipynb)
1. [coordenadas homogéneas](coordhomog.ipynb)
1. [transformaciones del plano](transf2D.ipynb)
1. [DLT](DLT.ipynb)
1. [modelo de cámara](camera.ipynb)
1. [visión stereo](stereo.ipynb)
1. [stereo-challenge](stereo-challenge.ipynb)
1. [machine learning](machine-learning.ipynb)
1. [tensorflow](tensorflow.ipynb)
## Ejemplos de código
1. [`hello.py`](../code/hello.py): lee imagen de archivo, la reescala, muestra y sobreescribe un texto.
1. [`webcam.py`](../code/webcam.py): muestra la secuencia de imágenes capturadas por una webcam.
1. [`2cams.py`](../code/2cams.py): combina las imágenes tomadas por dos cámaras.
1. [`player.py`](../code/player.py): función auxiliar que permite aplicar una cierta función a la secuencia de imágenes, con opción de guardar (S) y parar el vídeo (espacio).
1. [`mouse.py`](../code/mouse.py): ejemplo de captura de eventos de ratón.
1. [`trackbar.py`](../code/trackbar.py): ejemplo de parámetro interactivo.
1. [`stream.py`](../code/stream.py): ejemplo de uso de la fuente genérica de imágenes "mkStream".
1. [`stream2.py`](../code/stream2.py): ejemplo de mkStream para leer un conjunto de imágenes en disco mostrándolas y avanzando de una en una pulsando una tecla.
1. [`deque.py`](../code/deque.py): procesamiento de las $n$ imágenes más recientes.
1. [`mjpegserver.py`](../code/mjpegserver.py): servidor de secuencias de video en formato mjpeg.
1. [`histogram.py`](../code/histogram.py): histograma en vivo con opencv.
1. [`histogram2.py`](../code/histogram2.py): histograma en vivo con matplotlib.
1. [`surface.py`](../code/surface.py): superficie 3D de niveles de gris en vivo usando pyqtgraph.
1. [`backsub.py`](../code/backsub.py): eliminación de fondo mediante MOG2.
1. [`server.py`](../code/server.py): ejemplo de servidor web de imágenes capturadas con la webcam.
1. [`bot`](../code/bot): bots de [Telegram](https://python-telegram-bot.org/).
1. [`reprohist.py`](../code/reprohist.py): reproyección de histograma.
1. [`camshift.py`](../code/camshift.py): tracking mediante reproyección de histograma.
1. [`grabcut.py`](../code/grabcut.py): segmentación de objetos interactiva mediante GrabCut.
1. [`spectral.py`](../code/spectral.py): FFT en vivo.
1. [`thread`](../code/thread): captura y procesamiento concurrente.
1. [`testC.py`](../code/testC.py), [`inC`](../code/inC): Interfaz C-numpy.
1. [`hog/pedestrian.py`](../code/hog/pedestrian.py): detector de peatones de opencv.
1. [`hog/facelandmarks.py`](../code/hog/facelandmarks.py): detector de caras y landmarks de dlib.
1. [`hog/hog0.py`](../code/hog/hog0.py): experimentos con hog.
1. [`regressor.py`](../code/regressor.py): predictor directo de la posición de una región.
1. [`sift.py`](../code/sift.py): demostración de la detección de keypoints y búsqueda de coincidencias en imágenes en vivo.
1. [`lk_base.py`](../code/lk_base.py), [`lk_track.py`](../code/lk_track.py): seguimiento de puntos con el método de Lucas-Kanade.
1. [`inception.py`](../code/inception.py): clasificación de objetos con la red convolucional InceptionV3 entrenada con la base de datos imagenet, disponible en keras.
1. [`openpose.py`](../code/openpose.py): estimación de postura de cuerpo humano mediante [openpose](https://github.com/ildoonet/tf-pose-estimation).
1. [`stitcher.py`](../code/stitcher.py): construcción automática de panoramas.
1. [`pose.py`](../code/pose.py), [`pose3D.py`](../code/pose3D.py): estimación de cámara y realidad aumentada.
## Ejercicios propuestos
**1**. Pon en marcha el entorno de trabajo, incluyendo entre otros, los módulos y herramientas jupyter, spyder/pycharm, opencv, numpy, matplolib.
**2**. Estima de forma aproximada el campo de visión ([FOV](https://en.wikipedia.org/wiki/Angle_of_view)) y parámetro $f$ de tu cámara. Determina a qué altura habría que ponerla para obtener una vista cenital completa de un campo de baloncesto. Calcula la altura de una pelota sobre el suelo a partir de su tamaño en la imagen.
Realiza una calibración precisa de tu cámara mediante múltiples imágenes de un *chessboard* y compara con el resultado anterior.
### Curso anterior
Modifica los canales de color (brillo, saturación, etc.) de una secuencia de imágenes en vivo con un "trackbar".
Amplia `player.py` o `stream.py` para seleccionar con el ratón una región de interés (ROI) y almacenar los recortes en una lista, y opcionalmente en disco. Este programa nos servirá como base para futuros ejercicios.
Construye un detector de movimiento basado en una sencilla diferencia de imágenes sucesivas. Opcionalmente puedes hacer un generador que filtre la secuencia de imágenes dejando pasar solo los frames estáticos (o, alternativamente, los que han sufrido un cambio apreciable. En este caso no hace falta detectar las zonas con movimiento). Puedes apoyarte en `deque.py`. Opcional: a) Limitar la detección a una región de interés. b) Guardar 2 ó 3 segundos de la secuencia detectada en un archivo de vídeo o imagen gif.
Implementa el efecto chroma con imágenes en vivo de la webcam. Pulsando una tecla se captura el fondo y los objetos que aparezcan se superponen en otra imagen o secuencia de video. Compara el resultado con el método automático de eliminación de fondo ilustrado en `backsub.py`.
Construye un clasificador de objetos en base a la similitud de los histogramas de color del ROI (de los 3 canales por separado). Apóyate en 3.
Implementa la segmentación por color usando reproyección de histogramas en un programa que admite como argumento a) una carpeta con trozos de imágen que sirven como muestras de color y b) otra imagen o secuencia de video que deseamos clasificar. El resultado puede ser un conjunto de máscaras para cada clase, o una "imagen de etiquetas", donde diferentes colores indican cada una de las regiones.
Muestra el efecto de diferentes filtros sobre la imagen en vivo de la webcam. Selecciona con el teclado el filtro deseado y modifica sus posibles parámetros (p.ej. el nivel de suavizado) con las teclas de flecha. Es conveniente permitir la selección de un ROI para comparar el resultado del filtro con el resto de la imagen.
Construye un servidor web sencillo usando [flask](http://flask.pocoo.org/) que muestre una cierta transformación, especificada en la url, de las imágenes tomadas con la cámara. Apóyate en `server.py`.
Escribe una aplicación de tu invención que utilice los [marcadores de cara](https://ibug.doc.ic.ac.uk/resources/facial-point-annotations/) obtenidos por el *shape detector* disponible en [dlib](http://dlib.net/) (ejemplo `/hog/facelandmarks.py`).
Estima de forma aproximada la velocidad angular de rotación de la cámara (grados/segundo) analizando las trayectorias obtenidas por el *tracker* de Lucas-Kanade (ejemplo `lk_track.py`).
Escribe una aplicación de reconocimiento de objetos con la webcam basada en el número de coincidencias de *keypoints*. Pulsando una tecla se pueden ir guardando modelos (p. ej. carátulas de CD, portadas de libros, cuadros de pintores, etc.). Cuando detectamos que la imagen está bastante quieta, o cuando se pulse otra tecla, calculamos los puntos de interés de la imagen actual y sus descriptores y comprobamos si hay suficientes coincidencias con los de algún modelo.
Escribe una aplicación de reconocimiento de siluetas con la webcam basado en descriptores frecuenciales.
Escribe una aplicación de reconocimiento de dígitos manuscritos con la webcam. Compara el clasificador gaussiano y la red convolucional explicada en el capítulo de machine learning.
Rectifica la imagen de un plano para medir distancias (tomando manualmente referencias conocidas). Por ejemplo, mide la distancia entre las monedas en `coins.png` o la distancia a la que se realiza el disparo en `gol-eder.png`.
Crea automáticamente un mosaico panorámico ajustando varias imágenes (>2). Recuerda que debe tratarse de una escena plana o de una escena cualquiera vista desde el mismo centro de proyección.
Crea un efecto de realidad aumentada dinámico.
Haz un programa capaz de rellenar un sudoku que se observa en la imagen en vivo de la webcam.
Resuelve los problemas planteados en el notebook [stereo-challenge](stereo-challenge.ipynb).
| 0.758511 | 0.968081 |
# Maxpooling Layer
In this notebook, we add and visualize the output of a maxpooling layer in a CNN.
A convolutional layer + activation function, followed by a pooling layer, and a linear layer (to create a desired output size) make up the basic layers of a CNN.
<img src='notebook_ims/CNN_all_layers.png' height=50% width=50% />
### Import the image
```
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# TODO: Feel free to try out your own images here by changing img_path
# to a file path to another image on your computer!
img_path = 'data/udacity_sdc.png'
# load color image
bgr_img = cv2.imread(img_path)
# convert to grayscale
gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY)
# normalize, rescale entries to lie in [0,1]
gray_img = gray_img.astype("float32")/255
# plot image
plt.imshow(gray_img, cmap='gray')
plt.show()
```
### Define and visualize the filters
```
import numpy as np
## TODO: Feel free to modify the numbers here, to try out another filter!
filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]])
print('Filter shape: ', filter_vals.shape)
# Defining four different filters,
# all of which are linear combinations of the `filter_vals` defined above
# define four filters
filter_1 = filter_vals
filter_2 = -filter_1
filter_3 = filter_1.T
filter_4 = -filter_3
filters = np.array([filter_1, filter_2, filter_3, filter_4])
# For an example, print out the values of filter 1
print('Filter 1: \n', filter_1)
```
### Define convolutional and pooling layers
You've seen how to define a convolutional layer, next is a:
* Pooling layer
In the next cell, we initialize a convolutional layer so that it contains all the created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/stable/_modules/torch/nn/modules/pooling.html), with a kernel size of (2x2) so you can see that the image resolution has been reduced after this step!
A maxpooling layer reduces the x-y size of an input and only keeps the most *active* pixel values. Below is an example of a 2x2 pooling kernel, with a stride of 2, applied to a small patch of grayscale pixel values; reducing the size of the patch by a factor of 4. Only the maximum pixel values in 2x2 remain in the new, pooled output.
<img src='notebook_ims/maxpooling_ex.png' height=50% width=50% />
```
import torch
import torch.nn as nn
import torch.nn.functional as F
# define a neural network with a convolutional layer with four filters
# AND a pooling layer of size (2, 2)
class Net(nn.Module):
def __init__(self, weight):
super(Net, self).__init__()
# initializes the weights of the convolutional layer to be the weights of the 4 defined filters
k_height, k_width = weight.shape[2:]
# defines the convolutional layer, assumes there are 4 grayscale filters
# torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False)
self.conv.weight = torch.nn.Parameter(weight)
# define a pooling layer
self.pool = nn.MaxPool2d(2, 2)
def forward(self, x):
# calculates the output of a convolutional layer
# pre- and post-activation
conv_x = self.conv(x)
activated_x = F.relu(conv_x)
# applies pooling layer
pooled_x = self.pool(activated_x)
# returns all layers
return conv_x, activated_x, pooled_x
# instantiate the model and set the weights
weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor)
model = Net(weight)
# print out the layer in the network
print(model)
```
### Visualize the output of each filter
First, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through.
```
# helper function for visualizing the output of a given layer
# default number of filters is 4
def viz_layer(layer, n_filters= 4):
fig = plt.figure(figsize=(20, 20))
for i in range(n_filters):
ax = fig.add_subplot(1, n_filters, i+1)
# grab layer outputs
ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray')
ax.set_title('Output %s' % str(i+1))
```
Let's look at the output of a convolutional layer after a ReLu activation function is applied.
#### ReLU activation
A ReLU function turns all negative pixel values in 0's (black). See the equation pictured below for input pixel values, `x`.
<img src='notebook_ims/relu_ex.png' height=50% width=50% />
```
# plot original image
plt.imshow(gray_img, cmap='gray')
# visualize all filters
fig = plt.figure(figsize=(12, 6))
fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05)
for i in range(4):
ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[])
ax.imshow(filters[i], cmap='gray')
ax.set_title('Filter %s' % str(i+1))
# convert the image into an input Tensor
gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1)
# get all the layers
conv_layer, activated_layer, pooled_layer = model(gray_img_tensor)
# visualize the output of the activated conv layer
viz_layer(activated_layer)
```
### Visualize the output of the pooling layer
Then, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area.
Take a look at the values on the x, y axes to see how the image has changed size.
```
# visualize the output of the pooling layer
viz_layer(pooled_layer)
```
|
github_jupyter
|
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# TODO: Feel free to try out your own images here by changing img_path
# to a file path to another image on your computer!
img_path = 'data/udacity_sdc.png'
# load color image
bgr_img = cv2.imread(img_path)
# convert to grayscale
gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY)
# normalize, rescale entries to lie in [0,1]
gray_img = gray_img.astype("float32")/255
# plot image
plt.imshow(gray_img, cmap='gray')
plt.show()
import numpy as np
## TODO: Feel free to modify the numbers here, to try out another filter!
filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]])
print('Filter shape: ', filter_vals.shape)
# Defining four different filters,
# all of which are linear combinations of the `filter_vals` defined above
# define four filters
filter_1 = filter_vals
filter_2 = -filter_1
filter_3 = filter_1.T
filter_4 = -filter_3
filters = np.array([filter_1, filter_2, filter_3, filter_4])
# For an example, print out the values of filter 1
print('Filter 1: \n', filter_1)
import torch
import torch.nn as nn
import torch.nn.functional as F
# define a neural network with a convolutional layer with four filters
# AND a pooling layer of size (2, 2)
class Net(nn.Module):
def __init__(self, weight):
super(Net, self).__init__()
# initializes the weights of the convolutional layer to be the weights of the 4 defined filters
k_height, k_width = weight.shape[2:]
# defines the convolutional layer, assumes there are 4 grayscale filters
# torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False)
self.conv.weight = torch.nn.Parameter(weight)
# define a pooling layer
self.pool = nn.MaxPool2d(2, 2)
def forward(self, x):
# calculates the output of a convolutional layer
# pre- and post-activation
conv_x = self.conv(x)
activated_x = F.relu(conv_x)
# applies pooling layer
pooled_x = self.pool(activated_x)
# returns all layers
return conv_x, activated_x, pooled_x
# instantiate the model and set the weights
weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor)
model = Net(weight)
# print out the layer in the network
print(model)
# helper function for visualizing the output of a given layer
# default number of filters is 4
def viz_layer(layer, n_filters= 4):
fig = plt.figure(figsize=(20, 20))
for i in range(n_filters):
ax = fig.add_subplot(1, n_filters, i+1)
# grab layer outputs
ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray')
ax.set_title('Output %s' % str(i+1))
# plot original image
plt.imshow(gray_img, cmap='gray')
# visualize all filters
fig = plt.figure(figsize=(12, 6))
fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05)
for i in range(4):
ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[])
ax.imshow(filters[i], cmap='gray')
ax.set_title('Filter %s' % str(i+1))
# convert the image into an input Tensor
gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1)
# get all the layers
conv_layer, activated_layer, pooled_layer = model(gray_img_tensor)
# visualize the output of the activated conv layer
viz_layer(activated_layer)
# visualize the output of the pooling layer
viz_layer(pooled_layer)
| 0.685423 | 0.988668 |
# CSCI 40520U: Assignment 4
In this assignment, you to implement an end-to-end program execution pipeline that compiles source code directly to the runtime backend objects, and then run the compiled program.
You must complete the following:
1. Implement a grammar in `src/PL.g4` to support the minimal features required to run the four programs given in this worksheet.
2. Implement several kotlin classes in `src/backend.kt` for:
- the compiled runtime backend objects
- the visitor class that performs compilation using SDD
Some skeleton code is provided in `src/`, and a Makefile is provided to help you perform the compilation.
**Note: this notebook should be reloaded and rerun each time you recompile the dependencies of `mygrammar.*` and `backend.*`.**
```
@file:DependsOn(".")
@file:DependsOn("/data/shared/antlr-4.9.1-complete.jar")
import org.antlr.v4.runtime.*
import backend.*
import mygrammar.*
```
## The programs
In this program, we display the concatenation of two strings.
The `++` operator performs string concatenation, separated by a whitespace.
```
val source1 = """
x = "Hello";
y = "World";
// Expect "Hello world"
print(x ++ y);
"""
```
In this program, we declare a function
which prints a message based on the
parameters `name` and `message`.
The program then invokes the function with
two arguments.
```
val source2 = """
function greeting(name, message) {
x = "Hi,";
x = x ++ "my name is" ++ name ++ ".";
print(x);
}
greeting("Albert", "How are you?");
"""
```
The programming language must support for loops that can iterate over an integer range.
This program computes the sum of integers
`[10, 11, 12, ... 20]`.
```
val source3 = """
sum = 0
for(i in 10..20) {
sum = sum + i
}
sum
"""
```
This program defines the factorial function using the for loop construct.
The program then invokes the function to compute the factorial of 5.
```
val source4 = """
function factorial(n) {
prod = 1
for(i in 1 .. n) {
prod = prod * i
}
prod
}
factorial(5)
"""
```
## Parsing
In your implementation, you must implement a function:
```
fun parse(source: String): PLParser.ProgramContext
```
which constructs the parse tree from the source code.
```
fun parse(source: String): PLParser.ProgramContext {
val input = CharStreams.fromString(source)
val lexer = PLLexer(input)
val tokens = CommonTokenStream(lexer)
val parser = PLParser(tokens)
return parser.program()
}
val tree1 = parse(source1)
val tree2 = parse(source2)
val tree3 = parse(source3)
val tree4 = parse(source4)
```
## Compilation
Your `backend.kt` must provide a visitor class `Compiler` which will perform the SDD to build the backend runtime objects based
on the parse tree. Using the compiler, we can compile each of the parse trees.
```
val program1 = Compiler().visit(tree1)
val program2 = Compiler().visit(tree2)
val program3 = Compiler().visit(tree3)
val program4 = Compiler().visit(tree4)
```
## Execution
We can how run each of the programs by using the standard `eval(...)` method.
```
fun execute(program: Expr?) {
if(program == null) {
println("Program is null.")
return
}
try {
val data = program.eval(Context())
println("> ${data}")
} catch(e: Exception) {
println("[err] ${e}")
}
}
execute(program1)
execute(program2)
execute(program3)
execute(program4)
```
|
github_jupyter
|
@file:DependsOn(".")
@file:DependsOn("/data/shared/antlr-4.9.1-complete.jar")
import org.antlr.v4.runtime.*
import backend.*
import mygrammar.*
val source1 = """
x = "Hello";
y = "World";
// Expect "Hello world"
print(x ++ y);
"""
val source2 = """
function greeting(name, message) {
x = "Hi,";
x = x ++ "my name is" ++ name ++ ".";
print(x);
}
greeting("Albert", "How are you?");
"""
val source3 = """
sum = 0
for(i in 10..20) {
sum = sum + i
}
sum
"""
val source4 = """
function factorial(n) {
prod = 1
for(i in 1 .. n) {
prod = prod * i
}
prod
}
factorial(5)
"""
fun parse(source: String): PLParser.ProgramContext
fun parse(source: String): PLParser.ProgramContext {
val input = CharStreams.fromString(source)
val lexer = PLLexer(input)
val tokens = CommonTokenStream(lexer)
val parser = PLParser(tokens)
return parser.program()
}
val tree1 = parse(source1)
val tree2 = parse(source2)
val tree3 = parse(source3)
val tree4 = parse(source4)
val program1 = Compiler().visit(tree1)
val program2 = Compiler().visit(tree2)
val program3 = Compiler().visit(tree3)
val program4 = Compiler().visit(tree4)
fun execute(program: Expr?) {
if(program == null) {
println("Program is null.")
return
}
try {
val data = program.eval(Context())
println("> ${data}")
} catch(e: Exception) {
println("[err] ${e}")
}
}
execute(program1)
execute(program2)
execute(program3)
execute(program4)
| 0.23231 | 0.951097 |
This notebook checks the expansion identities given in Section 2 and Appendix A in the paper.
Notation:
* $t$ is the target, $c$ is the center, $s$ is the source
* $p$ is the expansion order
* $\cos \theta = \frac{(t - c) \cdot (s - c)}{(|t - c| |s - c|}$
# Utilities
Define a utility function that checks for convergence of an identity.
The kernel is a function of the form $K(s, t)$.
The identity to be checked is a function of the form $Id(s, c, t, p)$.
```
import numpy as np
import numpy.linalg as la
import itertools
TESTS = 5
DIM = 3
ORDERS = np.array([3, 4, 5, 6, 7])
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
def verify_identity(knl, identity):
np.random.seed(0)
samples = 2 * np.random.random((3*TESTS, DIM)) - 1
for s, c, t in grouper(samples, 3):
if la.norm(t - c) > la.norm(s - c):
s, t = t, s
errors = []
true_val = knl(s, t)
for order in ORDERS:
errors.append(np.max(np.abs(true_val - identity(s, c, t, order))))
conv_factor = np.exp(np.polyfit(1 + ORDERS, np.log(errors), 1)[0])
assert conv_factor < min(1, 1.3 * la.norm(t - c) / la.norm(s - c)), conv_factor
print("Verified!")
```
And an auxiliary function to compute Legendre polynomial values.
```
def legvals(x, n):
pjm2 = 1
pjm1 = x
vals = np.zeros(1 + n)
derivs = np.zeros(1 + n)
vals[0] = 1
derjm2 = 0
derjm1 = 1
if n == 0:
return vals, derivs
vals[1] = x
derivs[1] = 1
if n == 1:
return vals, derivs
for j in range(2, n + 1):
pj = ( (2*j-1)*x*pjm1-(j-1)*pjm2 ) / j
vals[j] = pj
derj = (2*j-1)*(pjm1+x*derjm1)-(j-1)*derjm2
derj = derj / j
derivs[j] = derj
derjm2 = derjm1
derjm1 = derj
pjm2 = pjm1
pjm1 = pj
return vals, derivs
```
# Spherical Harmonics
The spherical harmonic addition theorem states that
$$ P_n(\cos \theta) = \frac{4 \pi}{2n+1} \sum_{m=-n}^n Y^m_n(\theta_x, \phi_x) \overline{Y^{m}_n(\theta_y, \phi_y)}. $$
```
def cart2polar(x):
# Uses NumPy convention
r = la.norm(x)
theta = np.arctan2(x[1], x[0])
phi = np.arccos(x[2] / r)
return (r, theta, phi)
np.random.seed(0)
x, y = np.random.random((2, 3))
x /= la.norm(x)
y /= la.norm(y)
cos_theta = np.dot(x, y)
_, theta_x, phi_x = cart2polar(x)
_, theta_y, phi_y = cart2polar(y)
n = 5
lvals, _ = legvals(cos_theta, n)
from scipy.special import sph_harm
# This uses NumPy's spherical harmonics, which are different from those defined in
# the paper, but still satisfy the addition theorem.
sph_harm_x = sph_harm(np.arange(-n, 1+n), n, theta_x, phi_x)
sph_harm_y = sph_harm(np.arange(-n, 1+n), n, theta_y, phi_y)
assert np.allclose(np.vdot(sph_harm_x, sph_harm_y), lvals[-1] * (2*n+1) / (4*np.pi))
```
# Laplace Identities
The Laplace Green's function $\mathcal{G}$:
$$ \mathcal{G}(t, s) = (4 \pi)^{-1} |t - s|^{-1}. $$
The target-specific expansion for the Laplace Green's function:
$$ \mathcal{G}(t, s) = (4 \pi)^{-1} \sum_{n=0}^\infty \frac{|t-c|^n}{|s-c|^{n+1}} P_n(\cos \theta). $$
```
def ts_l3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, _ = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1
* r**k * rho**-(k+1)
* lvals[k]
for k in range(0, 1+p))
def k_l3d(s, t):
return 1 / (4 * np.pi * la.norm(s - t))
verify_identity(k_l3d, ts_l3d)
```
The $t$-gradient of the Laplace Green's function:
$$ \nabla_t \mathcal{G}(t, s) = -(4 \pi)^{-1} \frac{(t-s)}{|t-s|^{3}}. $$
The target-specific expansion for the $t$-gradient:
$$ \nabla_t \mathcal{G}(t, s) = (4 \pi)^{-1} \sum_{n=1}^\infty
\frac{|t-c|^{n-1}}{|s-c|^{n+1}}
\left(
n \frac{t - c}{|t-c|}
P_n(\cos \theta)
+
\left[
\frac{s-c}{|s-c|}
- \frac{t-c}{|t-c|} \cos(\theta)
\right]
P_n'(\cos \theta) \right)
. $$
```
def ts_tgrad_l3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, derivs = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1 * r**(k-1) * rho**-(k+1)
* (
k * (t - c) / r * lvals[k]
+ ((s - c) / rho - ((t - c) / r) * cos_theta) * derivs[k]
) for k in range(1, 1+p))
def k_tgrad_l3d(s, t):
val = -(t-s) / (4*np.pi * la.norm(t-s)**3)
return val
verify_identity(k_tgrad_l3d, ts_tgrad_l3d)
```
The $s$-gradient of the Laplace Green's function:
$$ \nabla_s \mathcal{G}(t, s) = (4 \pi)^{-1} \frac{(t-s)}{|t-s|^{3}}. $$
The target-specific expansion for the $s$-gradient:
$$ \nabla_s \mathcal{G}(t, s) = (4 \pi)^{-1}
\sum_{n=0}^\infty
\frac{|t-c|^{n}}{|s-c|^{n+2}}
\left(
-(n+1) \frac{s - c}{|s - c|}
P_n(\cos \theta)
+
\left[
\frac{t-c}{|t-c|}
- \frac{s-c}{|s-c|} \cos(\theta)
\right]
P_n'(\cos \theta) \right)
. $$
```
def ts_sgrad_l3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, derivs = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1 * r**k * rho**-(k+2)
* (
-(k + 1) * (s - c) / rho * lvals[k]
+((t - c) / r - ((s - c) / rho) * cos_theta) * derivs[k]
) for k in range(0, 1 + p))
def k_sgrad_l3d(s, t):
val = (t-s) / (4*np.pi * la.norm(t-s)**3)
return val
verify_identity(k_sgrad_l3d, ts_sgrad_l3d)
```
# Helmholtz Case
The Green's function for the Helmholtz equation:
$$ \mathcal{G}_k(t, s) = \frac{e^{ik|t-s|}}{4 \pi |t - s|}. $$
The target-specific expansion for the Green's function:
$$ \mathcal{G}_k(t, s) = (4 \pi)^{-1} ik \sum_{n=0}^\infty (2n+1) j_n(k|t-c|) h_n(k|s-c|) P_n(\cos \theta). $$
```
HELMHOLTZ_K = 3
from scipy.special import spherical_jn as jn, spherical_yn as yn
def hn(n, x, derivative=False):
return jn(n, x, derivative) + 1j * yn(n, x, derivative)
def ts_h3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, _ = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1
* 1j * HELMHOLTZ_K
* (2*k + 1)
* jn(k, HELMHOLTZ_K * r)
* hn(k, HELMHOLTZ_K * rho)
* lvals[k]
for k in range(0, 1+p))
def k_h3d(s, t):
x = la.norm(t - s)
return np.exp(1j * HELMHOLTZ_K * x) / (4 * np.pi * x)
verify_identity(k_h3d, ts_h3d)
```
The $t$-gradient of the Green's function:
$$\nabla_t \mathcal{G}_k(t, s) =
(4\pi)^{-1} e^{ik|t-s|} \left( \frac{ik(t-s)}{|t-s|^2} - \frac{(t-s)}{|t-s|^3} \right).
$$
The target-specific expansion for the $t$-gradient:
$$\nabla_t \mathcal{G}_k(t, s) = (4 \pi)^{-1} ik \sum_{n=0}^\infty (2n+1) \frac{h_n(k|s-c|)}{|t-c|} \left( k(t-c)j_n'(k|t-c|)P_n(\cos \theta) + \left[ \frac{s-c}{|s-c|} - \frac{t-c}{|t-c|} \cos \theta \right] j_n(k|t-c|) P_n'(\cos \theta) \right).
$$
```
def ts_tgrad_h3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, derivs = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1
* 1j * HELMHOLTZ_K
* (2*k + 1)
* hn(k, HELMHOLTZ_K * rho) / r
* (
HELMHOLTZ_K * (t - c) * jn(k, HELMHOLTZ_K * r, True) * lvals[k]
+ (
((s - c) / rho - (t-c) * cos_theta / r)
* jn(k, HELMHOLTZ_K * r)) * derivs[k]
) for k in range(0, 1+p))
def k_tgrad_h3d(s, t):
x = la.norm(t - s)
return (
1/(4*np.pi)
* np.exp(1j * HELMHOLTZ_K * x)
* (1j * HELMHOLTZ_K * (t - s) / x**2 - (t - s)/x**3))
verify_identity(k_tgrad_h3d, ts_tgrad_h3d)
```
The $s$-gradient of the Green's function:
$$\nabla_s \mathcal{G}_k(t, s) =
(4\pi)^{-1} e^{ik|t-s|} \left(\frac{(t-s)}{|t-s|^3} - \frac{ik(t-s)}{|t-s|^2} \right).
$$
The target-specific expansion for the $s$-gradient:
$$\nabla_s \mathcal{G}_k(t, s) = (4 \pi)^{-1} ik \sum_{n=0}^\infty (2n+1) \frac{j_n(k|t-c|)}{|s-c|} \left( k(s-c)h_n'(k|s-c|)P_n(\cos \theta) + \left[ \frac{t-c}{|t-c|} - \frac{s-c}{|s-c|} \cos \theta \right] h_n(k|s-c|) P_n'(\cos \theta) \right).
$$
```
def ts_sgrad_h3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, derivs = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1
* 1j * HELMHOLTZ_K
* (2*k + 1)
* jn(k, HELMHOLTZ_K * r) / rho
* (
HELMHOLTZ_K * (s - c) * hn(k, HELMHOLTZ_K * rho, True) * lvals[k]
+ (
((t - c) / r - (s-c) * cos_theta / rho)
* hn(k, HELMHOLTZ_K * rho)) * derivs[k]
) for k in range(0, 1+p))
def k_sgrad_h3d(s, t):
x = la.norm(t - s)
return (
1/(4*np.pi)
* np.exp(1j * HELMHOLTZ_K * x)
* (((t - s)/x**3) - 1j * HELMHOLTZ_K * (t - s) / x**2))
verify_identity(k_sgrad_h3d, ts_sgrad_h3d)
```
|
github_jupyter
|
import numpy as np
import numpy.linalg as la
import itertools
TESTS = 5
DIM = 3
ORDERS = np.array([3, 4, 5, 6, 7])
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
def verify_identity(knl, identity):
np.random.seed(0)
samples = 2 * np.random.random((3*TESTS, DIM)) - 1
for s, c, t in grouper(samples, 3):
if la.norm(t - c) > la.norm(s - c):
s, t = t, s
errors = []
true_val = knl(s, t)
for order in ORDERS:
errors.append(np.max(np.abs(true_val - identity(s, c, t, order))))
conv_factor = np.exp(np.polyfit(1 + ORDERS, np.log(errors), 1)[0])
assert conv_factor < min(1, 1.3 * la.norm(t - c) / la.norm(s - c)), conv_factor
print("Verified!")
def legvals(x, n):
pjm2 = 1
pjm1 = x
vals = np.zeros(1 + n)
derivs = np.zeros(1 + n)
vals[0] = 1
derjm2 = 0
derjm1 = 1
if n == 0:
return vals, derivs
vals[1] = x
derivs[1] = 1
if n == 1:
return vals, derivs
for j in range(2, n + 1):
pj = ( (2*j-1)*x*pjm1-(j-1)*pjm2 ) / j
vals[j] = pj
derj = (2*j-1)*(pjm1+x*derjm1)-(j-1)*derjm2
derj = derj / j
derivs[j] = derj
derjm2 = derjm1
derjm1 = derj
pjm2 = pjm1
pjm1 = pj
return vals, derivs
def cart2polar(x):
# Uses NumPy convention
r = la.norm(x)
theta = np.arctan2(x[1], x[0])
phi = np.arccos(x[2] / r)
return (r, theta, phi)
np.random.seed(0)
x, y = np.random.random((2, 3))
x /= la.norm(x)
y /= la.norm(y)
cos_theta = np.dot(x, y)
_, theta_x, phi_x = cart2polar(x)
_, theta_y, phi_y = cart2polar(y)
n = 5
lvals, _ = legvals(cos_theta, n)
from scipy.special import sph_harm
# This uses NumPy's spherical harmonics, which are different from those defined in
# the paper, but still satisfy the addition theorem.
sph_harm_x = sph_harm(np.arange(-n, 1+n), n, theta_x, phi_x)
sph_harm_y = sph_harm(np.arange(-n, 1+n), n, theta_y, phi_y)
assert np.allclose(np.vdot(sph_harm_x, sph_harm_y), lvals[-1] * (2*n+1) / (4*np.pi))
def ts_l3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, _ = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1
* r**k * rho**-(k+1)
* lvals[k]
for k in range(0, 1+p))
def k_l3d(s, t):
return 1 / (4 * np.pi * la.norm(s - t))
verify_identity(k_l3d, ts_l3d)
def ts_tgrad_l3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, derivs = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1 * r**(k-1) * rho**-(k+1)
* (
k * (t - c) / r * lvals[k]
+ ((s - c) / rho - ((t - c) / r) * cos_theta) * derivs[k]
) for k in range(1, 1+p))
def k_tgrad_l3d(s, t):
val = -(t-s) / (4*np.pi * la.norm(t-s)**3)
return val
verify_identity(k_tgrad_l3d, ts_tgrad_l3d)
def ts_sgrad_l3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, derivs = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1 * r**k * rho**-(k+2)
* (
-(k + 1) * (s - c) / rho * lvals[k]
+((t - c) / r - ((s - c) / rho) * cos_theta) * derivs[k]
) for k in range(0, 1 + p))
def k_sgrad_l3d(s, t):
val = (t-s) / (4*np.pi * la.norm(t-s)**3)
return val
verify_identity(k_sgrad_l3d, ts_sgrad_l3d)
HELMHOLTZ_K = 3
from scipy.special import spherical_jn as jn, spherical_yn as yn
def hn(n, x, derivative=False):
return jn(n, x, derivative) + 1j * yn(n, x, derivative)
def ts_h3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, _ = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1
* 1j * HELMHOLTZ_K
* (2*k + 1)
* jn(k, HELMHOLTZ_K * r)
* hn(k, HELMHOLTZ_K * rho)
* lvals[k]
for k in range(0, 1+p))
def k_h3d(s, t):
x = la.norm(t - s)
return np.exp(1j * HELMHOLTZ_K * x) / (4 * np.pi * x)
verify_identity(k_h3d, ts_h3d)
def ts_tgrad_h3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, derivs = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1
* 1j * HELMHOLTZ_K
* (2*k + 1)
* hn(k, HELMHOLTZ_K * rho) / r
* (
HELMHOLTZ_K * (t - c) * jn(k, HELMHOLTZ_K * r, True) * lvals[k]
+ (
((s - c) / rho - (t-c) * cos_theta / r)
* jn(k, HELMHOLTZ_K * r)) * derivs[k]
) for k in range(0, 1+p))
def k_tgrad_h3d(s, t):
x = la.norm(t - s)
return (
1/(4*np.pi)
* np.exp(1j * HELMHOLTZ_K * x)
* (1j * HELMHOLTZ_K * (t - s) / x**2 - (t - s)/x**3))
verify_identity(k_tgrad_h3d, ts_tgrad_h3d)
def ts_sgrad_h3d(s, c, t, p):
r = la.norm(t - c)
rho = la.norm(s - c)
cos_theta = np.dot(s - c, t - c) / (r * rho)
lvals, derivs = legvals(cos_theta, p)
return sum(
(4 * np.pi) ** -1
* 1j * HELMHOLTZ_K
* (2*k + 1)
* jn(k, HELMHOLTZ_K * r) / rho
* (
HELMHOLTZ_K * (s - c) * hn(k, HELMHOLTZ_K * rho, True) * lvals[k]
+ (
((t - c) / r - (s-c) * cos_theta / rho)
* hn(k, HELMHOLTZ_K * rho)) * derivs[k]
) for k in range(0, 1+p))
def k_sgrad_h3d(s, t):
x = la.norm(t - s)
return (
1/(4*np.pi)
* np.exp(1j * HELMHOLTZ_K * x)
* (((t - s)/x**3) - 1j * HELMHOLTZ_K * (t - s) / x**2))
verify_identity(k_sgrad_h3d, ts_sgrad_h3d)
| 0.63624 | 0.959516 |
It has been suggested by Nick that I can compute a Fischer Forecast with the VDF by just doing finite different around each point in the parameter space. Gonna try to do that here.
```
%matplotlib inline
from matplotlib import pyplot as plt
import seaborn as sns
sns.set()
from pearce.emulator import LemonPepperWet, NashvilleHot
import numpy as np
from os import path
import h5py
from copy import deepcopy
from scipy.linalg import inv
peaked=False
```
```
training_file ='/u/ki/swmclau2/des/Aemulators/vdf_hsab_box0/PearceHSABVDFBox0.hdf5'
test_file = '/u/ki/swmclau2/des/vdf_hsab_box0_test/PearceHSABVDF.hdf5'
obs='vdf'
```
```
fixed_params = {'z':0.0, 'cosmo':0}
fiducial_hod = {'sigma_logM':0.2, 'logM0': 13.0, 'logM1': 14.0,
'alpha':1.0,'conc_gal_bias': 1.0,\
'mean_occupation_centrals_assembias_param1': 0.0,
'mean_occupation_satellites_assembias_param1': 0.0}
np.random.seed(0)
emu = LemonPepperWet(training_file,# hyperparams=hyperparams,\
fixed_params = fixed_params,\
downsample_factor = 1.0 )
pnames = emu.get_param_names()
pbounds = [emu.get_param_bounds(p) for p in pnames]
pnames
from pearce.mocks.kittens import TrainingBox
cat = TrainingBox(0, system='ki-ls')
cat.load(1.0, HOD='hsabZheng07')
from scipy.optimize import minimize_scalar
def add_logMmin(hod_params, cat):
hod_params['logMmin'] = 13.0 #initial guess
#cat.populate(hod_params) #may be overkill, but will ensure params are written everywhere
def func(logMmin, hod_params):
hod_params.update({'logMmin':logMmin})
return (cat.calc_analytic_nd(hod_params, min_ptcl=100) - 5e-4)**2
res = minimize_scalar(func, bounds = (12,15), args = (hod_params,), options = {'maxiter':100}, method = 'Bounded')
# assuming this doens't fail
print 'logMmin', res.x
hod_params['logMmin'] = res.x
add_logMmin(fiducial_hod, cat)
r_bins = np.logspace(-0.3, 2.0, 21)
def calc_vdf_n_times(N, hod, n_ran=1e6):
#N = 5
vals = np.zeros((N, len(r_bins)-1))
for i in xrange(N):
#print i
cat.populate(hod)
vals[i] = cat.calc_vdf(r_bins, n_ran=n_ran)
return vals
def calc_xi_n_times(N, hod):
#N = 5
vals = np.zeros((N, len(r_bins)-1))
for i in xrange(N):
#print i
cat.populate(hod)
vals[i] = cat.calc_xi(r_bins)#, n_ran=n_ran)
return vals
N = 100
from time import time
t0 = time()
vdf_vals= calc_vdf_n_times(N, fiducial_hod)
t1 = time()
xi_vals = calc_xi_n_times(N, fiducial_hod)
t2 = time()
print t1-t0, t2-t1
print t1- t0
vdf_covmat = np.cov(vdf_vals, rowvar=False)
vdf_covmat[vdf_covmat==0] = 1e-12
vdf_covmat+=np.diag(np.ones(vdf_covmat.shape[0])*1e-12)
xi_covmat = np.cov(xi_vals, rowvar=False)
#vdf_covmat[covmat==0] = 1e-12
xi_covmat+=np.diag(np.ones(xi_covmat.shape[0])*1e-12)
plt.plot(np.sqrt(np.diag(xi_covmat))/np.mean(xi_vals, axis=0))
plt.plot(np.sqrt(np.diag(vdf_covmat))/np.mean(vdf_vals, axis=0))
plt.xscale('log')
def cov_to_corr(cov):
std = np.sqrt(np.diag(cov))
denom = np.outer(std, std)
return cov/denom
plt.imshow(cov_to_corr(vdf_covmat))
plt.imshow(cov_to_corr(xi_covmat))
inv_vdf_covmat = inv(vdf_covmat)
inv_xi_covmat = inv(xi_covmat)
plt.imshow(cov_to_corr(inv_vdf_covmat))
plt.imshow(cov_to_corr(inv_xi_covmat))
fd_vdf_vals = np.zeros((len(pnames), 2, N, len(r_bins)-1))
fd_xi_vals = np.zeros((len(pnames), 2, N, len(r_bins)-1))
step_sizes = np.zeros((len(pnames), ))
for i, (name, bound) in enumerate(zip(pnames, pbounds)):
hod = deepcopy(fiducial_hod)
step_size = (bound[1]-bound[0])/10
vals = (hod[name]-step_size, hod[name]+step_size)
print name#, step_size
step_sizes[i] = step_size
for j,v in enumerate(vals):
hod[name]=v
out = calc_vdf_n_times(N, hod)
fd_vdf_vals[i,j] = out
out = calc_xi_n_times(N, hod)
fd_xi_vals[i,j] = out
pbounds
def deriv(fd_vals, step_sizes):
avg_vals = fd_vals.mean(axis=2)
deriv = (avg_vals[:, 1] - avg_vals[:,0]).T/(2*step_sizes)
return deriv.T
d_vdf = deriv(fd_vdf_vals, step_sizes)
d_xi = deriv(fd_xi_vals, step_sizes)
emu.scale_bin_centers
for i, name in enumerate(pnames):
plt.plot(emu.scale_bin_centers, d_vdf[i], label = name)
plt.legend(loc='best')
plt.xscale('log')
for i, name in enumerate(pnames):
plt.plot(emu.scale_bin_centers, d_xi[i], label = name)
plt.legend(loc='best')
plt.xscale('log')
vdf_fischer_mat = np.dot(d_vdf, np.dot(inv_vdf_covmat, d_vdf.T))
xi_fischer_mat = np.dot(d_xi, np.dot(inv_xi_covmat, d_xi.T))
vdf_info_mat = inv(vdf_fischer_mat)
xi_info_mat = inv(xi_fischer_mat)
```
```
from matplotlib.patches import Ellipse
def ellipse_plot(inv_fisher, mean_x, mean_y, xname, yname, fig, ax, co):
#alpha paramaters for 1 and 2 sigma contours
alpha1 = 1.52
alpha2 = 2.48
#extracting relevant params from the input inverse fisher matrix
sigma_x2 = inv_fisher[0][0]
sigma_y2 = inv_fisher[1][1]
sigma_xy = inv_fisher[0][1]
#building a^2 and b^2 for the ellipse
a2 = (sigma_x2 + sigma_y2)/2. + np.sqrt((sigma_x2 - sigma_y2)**2/4. + sigma_xy**2)
b2 = (sigma_x2 + sigma_y2)/2. - np.sqrt((sigma_x2 - sigma_y2)**2/4. + sigma_xy**2)
#print a2, b2
#tilt angle
tan2theta = 2.*(sigma_xy)/(sigma_x2 - sigma_y2)
ang = -0.5*np.arctan(tan2theta)
#print ang
#plotting 1 and 2 sigma contours
ell = Ellipse(xy = [mean_x, mean_y], height = alpha1*np.sqrt(a2), width = alpha1*np.sqrt(b2), angle = np.degrees(ang), alpha=0.5, fill=True, color=co)
ell2 = Ellipse(xy = [mean_x, mean_y], height = alpha2*np.sqrt(a2), width = alpha2*np.sqrt(b2), angle = np.degrees(ang), alpha=0.35, fill=True, color=co)
#adding patches, axis names, etc
ax.add_patch(ell)
ax.add_patch(ell2)
#ax.set_aspect('equal')
ax.autoscale()
ax.set_xlabel(xname)
ax.set_ylabel(yname)
size = len(pnames)*3
fig, axes = plt.subplots(ncols=len(pnames)-1, nrows=len(pnames)-1, figsize=((size,size)))
bool_slice = np.zeros_like(xi_info_mat).astype(bool)
for i, name1 in enumerate(pnames):
for j, name2 in enumerate(pnames[:i]):
ellipse_plot(vdf_info_mat[np.ix_([i,j],[i,j])], fiducial_hod[name1], fiducial_hod[name2], name1, name2, fig, axes[j][i-1], co = 'b')
ellipse_plot(1e6*xi_info_mat[np.ix_([i,j],[i,j])], fiducial_hod[name1], fiducial_hod[name2], name1, name2, fig, axes[j][i-1], co = 'r')
```
|
github_jupyter
|
%matplotlib inline
from matplotlib import pyplot as plt
import seaborn as sns
sns.set()
from pearce.emulator import LemonPepperWet, NashvilleHot
import numpy as np
from os import path
import h5py
from copy import deepcopy
from scipy.linalg import inv
peaked=False
training_file ='/u/ki/swmclau2/des/Aemulators/vdf_hsab_box0/PearceHSABVDFBox0.hdf5'
test_file = '/u/ki/swmclau2/des/vdf_hsab_box0_test/PearceHSABVDF.hdf5'
obs='vdf'
fixed_params = {'z':0.0, 'cosmo':0}
fiducial_hod = {'sigma_logM':0.2, 'logM0': 13.0, 'logM1': 14.0,
'alpha':1.0,'conc_gal_bias': 1.0,\
'mean_occupation_centrals_assembias_param1': 0.0,
'mean_occupation_satellites_assembias_param1': 0.0}
np.random.seed(0)
emu = LemonPepperWet(training_file,# hyperparams=hyperparams,\
fixed_params = fixed_params,\
downsample_factor = 1.0 )
pnames = emu.get_param_names()
pbounds = [emu.get_param_bounds(p) for p in pnames]
pnames
from pearce.mocks.kittens import TrainingBox
cat = TrainingBox(0, system='ki-ls')
cat.load(1.0, HOD='hsabZheng07')
from scipy.optimize import minimize_scalar
def add_logMmin(hod_params, cat):
hod_params['logMmin'] = 13.0 #initial guess
#cat.populate(hod_params) #may be overkill, but will ensure params are written everywhere
def func(logMmin, hod_params):
hod_params.update({'logMmin':logMmin})
return (cat.calc_analytic_nd(hod_params, min_ptcl=100) - 5e-4)**2
res = minimize_scalar(func, bounds = (12,15), args = (hod_params,), options = {'maxiter':100}, method = 'Bounded')
# assuming this doens't fail
print 'logMmin', res.x
hod_params['logMmin'] = res.x
add_logMmin(fiducial_hod, cat)
r_bins = np.logspace(-0.3, 2.0, 21)
def calc_vdf_n_times(N, hod, n_ran=1e6):
#N = 5
vals = np.zeros((N, len(r_bins)-1))
for i in xrange(N):
#print i
cat.populate(hod)
vals[i] = cat.calc_vdf(r_bins, n_ran=n_ran)
return vals
def calc_xi_n_times(N, hod):
#N = 5
vals = np.zeros((N, len(r_bins)-1))
for i in xrange(N):
#print i
cat.populate(hod)
vals[i] = cat.calc_xi(r_bins)#, n_ran=n_ran)
return vals
N = 100
from time import time
t0 = time()
vdf_vals= calc_vdf_n_times(N, fiducial_hod)
t1 = time()
xi_vals = calc_xi_n_times(N, fiducial_hod)
t2 = time()
print t1-t0, t2-t1
print t1- t0
vdf_covmat = np.cov(vdf_vals, rowvar=False)
vdf_covmat[vdf_covmat==0] = 1e-12
vdf_covmat+=np.diag(np.ones(vdf_covmat.shape[0])*1e-12)
xi_covmat = np.cov(xi_vals, rowvar=False)
#vdf_covmat[covmat==0] = 1e-12
xi_covmat+=np.diag(np.ones(xi_covmat.shape[0])*1e-12)
plt.plot(np.sqrt(np.diag(xi_covmat))/np.mean(xi_vals, axis=0))
plt.plot(np.sqrt(np.diag(vdf_covmat))/np.mean(vdf_vals, axis=0))
plt.xscale('log')
def cov_to_corr(cov):
std = np.sqrt(np.diag(cov))
denom = np.outer(std, std)
return cov/denom
plt.imshow(cov_to_corr(vdf_covmat))
plt.imshow(cov_to_corr(xi_covmat))
inv_vdf_covmat = inv(vdf_covmat)
inv_xi_covmat = inv(xi_covmat)
plt.imshow(cov_to_corr(inv_vdf_covmat))
plt.imshow(cov_to_corr(inv_xi_covmat))
fd_vdf_vals = np.zeros((len(pnames), 2, N, len(r_bins)-1))
fd_xi_vals = np.zeros((len(pnames), 2, N, len(r_bins)-1))
step_sizes = np.zeros((len(pnames), ))
for i, (name, bound) in enumerate(zip(pnames, pbounds)):
hod = deepcopy(fiducial_hod)
step_size = (bound[1]-bound[0])/10
vals = (hod[name]-step_size, hod[name]+step_size)
print name#, step_size
step_sizes[i] = step_size
for j,v in enumerate(vals):
hod[name]=v
out = calc_vdf_n_times(N, hod)
fd_vdf_vals[i,j] = out
out = calc_xi_n_times(N, hod)
fd_xi_vals[i,j] = out
pbounds
def deriv(fd_vals, step_sizes):
avg_vals = fd_vals.mean(axis=2)
deriv = (avg_vals[:, 1] - avg_vals[:,0]).T/(2*step_sizes)
return deriv.T
d_vdf = deriv(fd_vdf_vals, step_sizes)
d_xi = deriv(fd_xi_vals, step_sizes)
emu.scale_bin_centers
for i, name in enumerate(pnames):
plt.plot(emu.scale_bin_centers, d_vdf[i], label = name)
plt.legend(loc='best')
plt.xscale('log')
for i, name in enumerate(pnames):
plt.plot(emu.scale_bin_centers, d_xi[i], label = name)
plt.legend(loc='best')
plt.xscale('log')
vdf_fischer_mat = np.dot(d_vdf, np.dot(inv_vdf_covmat, d_vdf.T))
xi_fischer_mat = np.dot(d_xi, np.dot(inv_xi_covmat, d_xi.T))
vdf_info_mat = inv(vdf_fischer_mat)
xi_info_mat = inv(xi_fischer_mat)
from matplotlib.patches import Ellipse
def ellipse_plot(inv_fisher, mean_x, mean_y, xname, yname, fig, ax, co):
#alpha paramaters for 1 and 2 sigma contours
alpha1 = 1.52
alpha2 = 2.48
#extracting relevant params from the input inverse fisher matrix
sigma_x2 = inv_fisher[0][0]
sigma_y2 = inv_fisher[1][1]
sigma_xy = inv_fisher[0][1]
#building a^2 and b^2 for the ellipse
a2 = (sigma_x2 + sigma_y2)/2. + np.sqrt((sigma_x2 - sigma_y2)**2/4. + sigma_xy**2)
b2 = (sigma_x2 + sigma_y2)/2. - np.sqrt((sigma_x2 - sigma_y2)**2/4. + sigma_xy**2)
#print a2, b2
#tilt angle
tan2theta = 2.*(sigma_xy)/(sigma_x2 - sigma_y2)
ang = -0.5*np.arctan(tan2theta)
#print ang
#plotting 1 and 2 sigma contours
ell = Ellipse(xy = [mean_x, mean_y], height = alpha1*np.sqrt(a2), width = alpha1*np.sqrt(b2), angle = np.degrees(ang), alpha=0.5, fill=True, color=co)
ell2 = Ellipse(xy = [mean_x, mean_y], height = alpha2*np.sqrt(a2), width = alpha2*np.sqrt(b2), angle = np.degrees(ang), alpha=0.35, fill=True, color=co)
#adding patches, axis names, etc
ax.add_patch(ell)
ax.add_patch(ell2)
#ax.set_aspect('equal')
ax.autoscale()
ax.set_xlabel(xname)
ax.set_ylabel(yname)
size = len(pnames)*3
fig, axes = plt.subplots(ncols=len(pnames)-1, nrows=len(pnames)-1, figsize=((size,size)))
bool_slice = np.zeros_like(xi_info_mat).astype(bool)
for i, name1 in enumerate(pnames):
for j, name2 in enumerate(pnames[:i]):
ellipse_plot(vdf_info_mat[np.ix_([i,j],[i,j])], fiducial_hod[name1], fiducial_hod[name2], name1, name2, fig, axes[j][i-1], co = 'b')
ellipse_plot(1e6*xi_info_mat[np.ix_([i,j],[i,j])], fiducial_hod[name1], fiducial_hod[name2], name1, name2, fig, axes[j][i-1], co = 'r')
| 0.261142 | 0.753444 |
# 1710 - Preparing results
```
# Imports
import sys
import os
import time
import math
import random
# Add the path to the parent directory to augment search for module
par_dir = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
if par_dir not in sys.path:
sys.path.append(par_dir)
# Plotting import
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Import the utils for plotting the metrics
from plot_utils import plot_utils
from plot_utils import notebook_utils_2
from sklearn.preprocessing import label_binarize
from sklearn.metrics import roc_curve, auc
# Fix the colour scheme for each particle type
color_dict = {"gamma":"red", "e":"blue", "mu":"green"}
# Fix the numpy seed
np.random.seed(42)
# Plot the ROC curve for one vs another class
def plot_new_ROC(softmaxes, labels, energies, softmax_index_dict, label_0, label_1,
min_energy=0, max_energy=1500, show_plot=False, save_path=None):
assert softmaxes is not None
assert labels is not None
assert softmax_index_dict is not None
assert softmaxes.shape[0] == labels.shape[0]
assert label_0 in softmax_index_dict.keys()
assert label_1 in softmax_index_dict.keys()
#------------------------------------------------------------------------
# Create a boolean map to select events in the user-defined energy range
#------------------------------------------------------------------------
energy_slice_map = [False for i in range(len(energies))]
for i in range(len(energies)):
if(energies[i] >= min_energy and energies[i] < max_energy):
energy_slice_map[i] = True
curr_softmax = softmaxes[energy_slice_map]
curr_labels = labels[energy_slice_map]
#------------------------------------------------------------------------
# Extract the softmax and true label values for signal and background events
#------------------------------------------------------------------------
# Extract the useful softmax and labels from the input arrays
softmax_0 = curr_softmax[curr_labels==softmax_index_dict[label_0]]
labels_0 = curr_labels[curr_labels==softmax_index_dict[label_0]]
softmax_1 = curr_softmax[curr_labels==softmax_index_dict[label_1]]
labels_1 = curr_labels[curr_labels==softmax_index_dict[label_1]]
# Add the two arrays
softmax = np.concatenate((softmax_0, softmax_1), axis=0)
labels = np.concatenate((labels_0, labels_1), axis=0)
#------------------------------------------------------------------------
# Compute the ROC curve and the AUC for class corresponding to label 0
#------------------------------------------------------------------------
fpr, tpr, threshold = roc_curve(labels, softmax[:,softmax_index_dict[label_0]], pos_label=softmax_index_dict[label_0])
roc_auc = auc(fpr, tpr)
inv_fpr = []
for i in fpr:
inv_fpr.append(1/i) if i != 0 else inv_fpr.append(1/1e-3)
if show_plot or save_path is not None:
# TNR vs TPR plot
fig, ax = plt.subplots(figsize=(16,9),facecolor="w")
ax.tick_params(axis="both", labelsize=20)
ax.plot(tpr, inv_fpr, color=color_dict[label_0],
label=r"$\{0}$, AUC ${1:0.3f}$".format(label_0, roc_auc) if label_0 is not "e" else r"${0}$, AUC ${1:0.3f}$".format(label_0, roc_auc),
linewidth=1.0, marker=".", markersize=4.0, markerfacecolor=color_dict[label_0])
# Show coords of individual points near x = 0.2, 0.5, 0.8
todo = {0.2: True, 0.5: True, 0.8: True}
for xy in zip(tpr, inv_fpr):
xy = (round(xy[0], 2), round(xy[1], 2))
for point in todo.keys():
if xy[0] >= point and todo[point]:
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data', fontsize=18, bbox=dict(boxstyle="square", fc="w"))
todo[point] = False
ax.grid(True, which='both', color='grey')
xlabel = r"$\{0}$ signal efficiency".format(label_0) if label_0 is not "e" else r"${0}$ signal efficiency".format(label_0)
ylabel = r"$\{0}$ background rejection".format(label_1) if label_1 is not "e" else r"${0}$ background rejection".format(label_1)
ax.set_xlabel(xlabel, fontsize=20)
ax.set_ylabel(ylabel, fontsize=20)
ax.set_title(r"${0} \leq E < {1}$".format(round(min_energy,2), round(max_energy,2)), fontsize=20)
ax.legend(loc="upper right", prop={"size":20})
plt.margins(0.1)
plt.yscale("log")
if save_path is not None:
plt.savefig(save_path)
if show_plot:
plt.show()
plt.clf() # Clear the current figure
plt.close() # Close the opened window
return fpr, tpr, threshold, roc_auc
# Plot the ROC curve for one vs another class
def plot_old_ROC(softmaxes, labels, energies, softmax_index_dict, label_0, label_1,
min_energy=0, max_energy=1500, show_plot=False, save_path=None):
assert softmaxes is not None
assert labels is not None
assert softmax_index_dict is not None
assert softmaxes.shape[0] == labels.shape[0]
assert label_0 in softmax_index_dict.keys()
assert label_1 in softmax_index_dict.keys()
#------------------------------------------------------------------------
# Create a boolean map to select events in the user-defined energy range
#------------------------------------------------------------------------
energy_slice_map = [False for i in range(len(energies))]
for i in range(len(energies)):
if(energies[i] >= min_energy and energies[i] < max_energy):
energy_slice_map[i] = True
curr_softmax = softmaxes[energy_slice_map]
curr_labels = labels[energy_slice_map]
#------------------------------------------------------------------------
# Extract the softmax and true label values for signal and background events
#------------------------------------------------------------------------
# Extract the useful softmax and labels from the input arrays
softmax_0 = curr_softmax[curr_labels==softmax_index_dict[label_0]]
labels_0 = curr_labels[curr_labels==softmax_index_dict[label_0]]
softmax_1 = curr_softmax[curr_labels==softmax_index_dict[label_1]]
labels_1 = curr_labels[curr_labels==softmax_index_dict[label_1]]
# Add the two arrays
softmax = np.concatenate((softmax_0, softmax_1), axis=0)
labels = np.concatenate((labels_0, labels_1), axis=0)
#------------------------------------------------------------------------
# Compute the ROC curve and the AUC for class corresponding to label 0
#------------------------------------------------------------------------
fpr, tpr, threshold = roc_curve(labels, softmax[:,softmax_index_dict[label_0]], pos_label=softmax_index_dict[label_0])
roc_auc = auc(fpr, tpr)
tnr = 1. - fpr
if show_plot or save_path is not None:
# TNR vs TPR plot
fig, ax = plt.subplots(figsize=(16,9),facecolor="w")
ax.tick_params(axis="both", labelsize=20)
ax.plot(tpr, tnr, color=color_dict[label_0],
label=r"$\{0}$, AUC ${1:0.3f}$".format(label_0, roc_auc) if label_0 is not "e" else r"${0}$, AUC ${1:0.3f}$".format(label_0, roc_auc),
linewidth=1.0, marker=".", markersize=4.0, markerfacecolor=color_dict[label_0])
# Show coords of individual points near x = 0.2, 0.5, 0.8
todo = {0.2: True, 0.5: True, 0.8: True}
for xy in zip(tpr, tnr):
xy = (round(xy[0], 3), round(xy[1], 3))
for point in todo.keys():
if xy[0] >= point and todo[point]:
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data', fontsize=18, bbox=dict(boxstyle="square", fc="w"))
todo[point] = False
ax.grid(True, which='both', color='grey')
xlabel = r"$\{0}$ signal efficiency".format(label_0) if label_0 is not "e" else r"${0}$ signal efficiency".format(label_0)
ylabel = r"$\{0}$ background rejection".format(label_1) if label_1 is not "e" else r"${0}$ background rejection".format(label_1)
ax.set_xlabel(xlabel, fontsize=20)
ax.set_ylabel(ylabel, fontsize=20)
ax.set_title(r"${0} \leq E < {1}$".format(round(min_energy,2), round(max_energy,2)), fontsize=20)
ax.legend(loc="upper right", prop={"size":20})
plt.margins(0.1)
if save_path is not None:
plt.savefig(save_path)
if show_plot:
plt.show()
plt.clf() # Clear the current figure
plt.close() # Close the opened window
return fpr, tpr, threshold, roc_auc
num_samples = [11250, 22500, 45000]
#dumps = ["20191017_183731", "20191017_184856", "20191017_185007"]
dumps = ["20200113_105809"]
#dump_dir = "/home/akajal/WatChMaL/VAE/dumps/"
dump_dir = "/home/ttuinstr/VAE/dumps/"
dump_file = "/test_validation_iteration_dump.npz"
softmax_index_dict = {"gamma":0, "e":1, "mu":2}
for num_sample, dump in zip(num_samples, dumps):
print("-------------------------------------------------------------")
print("Plotting the ROC curve for supervised CNN trained using {0} samples".format(num_sample))
print("-------------------------------------------------------------")
test_dump_path = dump_dir + dump + dump_file
test_dump_np = np.load(test_dump_path)
test_softmax = test_dump_np['softmax'].reshape(-1, 3)
test_labels = test_dump_np['labels'].reshape(-1)
test_energies = test_dump_np['energies'].reshape(-1)
roc_metrics = plot_new_ROC(test_softmax, test_labels, test_energies,
softmax_index_dict, "e", "gamma", min_energy=0,
max_energy=2000, show_plot=True)
roc_metrics = plot_old_ROC(test_softmax, test_labels, test_energies,
softmax_index_dict, "e", "gamma", min_energy=0,
max_energy=2000, show_plot=True)
num_samples = [7200000, 7200000, 7200000, 7200000]
dumps = ["20191017_113817", "20191017_113625", "20191017_113417", "20191017_113156"]
dump_dir = "/home/akajal/WatChMaL/VAE/dumps/"
dump_file = "/test_validation_iteration_dump.npz"
softmax_index_dict = {"gamma":0, "e":1, "mu":2}
for num_sample, dump in zip(num_samples, dumps):
print("-------------------------------------------------------------")
print("Plotting the ROC curve for supervised CNN trained using {0} samples".format(num_sample))
print("-------------------------------------------------------------")
test_dump_path = dump_dir + dump + dump_file
test_dump_np = np.load(test_dump_path)
test_softmax = test_dump_np['softmax'].reshape(-1, 3)
test_labels = test_dump_np['labels'].reshape(-1)
test_energies = test_dump_np['energies'].reshape(-1)
roc_metrics = plot_new_ROC(test_softmax, test_labels, test_energies,
softmax_index_dict, "e", "gamma", min_energy=0,
max_energy=2000, show_plot=True)
roc_metrics = plot_old_ROC(test_softmax, test_labels, test_energies,
softmax_index_dict, "e", "gamma", min_energy=0,
max_energy=2000, show_plot=True)
```
|
github_jupyter
|
# Imports
import sys
import os
import time
import math
import random
# Add the path to the parent directory to augment search for module
par_dir = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
if par_dir not in sys.path:
sys.path.append(par_dir)
# Plotting import
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Import the utils for plotting the metrics
from plot_utils import plot_utils
from plot_utils import notebook_utils_2
from sklearn.preprocessing import label_binarize
from sklearn.metrics import roc_curve, auc
# Fix the colour scheme for each particle type
color_dict = {"gamma":"red", "e":"blue", "mu":"green"}
# Fix the numpy seed
np.random.seed(42)
# Plot the ROC curve for one vs another class
def plot_new_ROC(softmaxes, labels, energies, softmax_index_dict, label_0, label_1,
min_energy=0, max_energy=1500, show_plot=False, save_path=None):
assert softmaxes is not None
assert labels is not None
assert softmax_index_dict is not None
assert softmaxes.shape[0] == labels.shape[0]
assert label_0 in softmax_index_dict.keys()
assert label_1 in softmax_index_dict.keys()
#------------------------------------------------------------------------
# Create a boolean map to select events in the user-defined energy range
#------------------------------------------------------------------------
energy_slice_map = [False for i in range(len(energies))]
for i in range(len(energies)):
if(energies[i] >= min_energy and energies[i] < max_energy):
energy_slice_map[i] = True
curr_softmax = softmaxes[energy_slice_map]
curr_labels = labels[energy_slice_map]
#------------------------------------------------------------------------
# Extract the softmax and true label values for signal and background events
#------------------------------------------------------------------------
# Extract the useful softmax and labels from the input arrays
softmax_0 = curr_softmax[curr_labels==softmax_index_dict[label_0]]
labels_0 = curr_labels[curr_labels==softmax_index_dict[label_0]]
softmax_1 = curr_softmax[curr_labels==softmax_index_dict[label_1]]
labels_1 = curr_labels[curr_labels==softmax_index_dict[label_1]]
# Add the two arrays
softmax = np.concatenate((softmax_0, softmax_1), axis=0)
labels = np.concatenate((labels_0, labels_1), axis=0)
#------------------------------------------------------------------------
# Compute the ROC curve and the AUC for class corresponding to label 0
#------------------------------------------------------------------------
fpr, tpr, threshold = roc_curve(labels, softmax[:,softmax_index_dict[label_0]], pos_label=softmax_index_dict[label_0])
roc_auc = auc(fpr, tpr)
inv_fpr = []
for i in fpr:
inv_fpr.append(1/i) if i != 0 else inv_fpr.append(1/1e-3)
if show_plot or save_path is not None:
# TNR vs TPR plot
fig, ax = plt.subplots(figsize=(16,9),facecolor="w")
ax.tick_params(axis="both", labelsize=20)
ax.plot(tpr, inv_fpr, color=color_dict[label_0],
label=r"$\{0}$, AUC ${1:0.3f}$".format(label_0, roc_auc) if label_0 is not "e" else r"${0}$, AUC ${1:0.3f}$".format(label_0, roc_auc),
linewidth=1.0, marker=".", markersize=4.0, markerfacecolor=color_dict[label_0])
# Show coords of individual points near x = 0.2, 0.5, 0.8
todo = {0.2: True, 0.5: True, 0.8: True}
for xy in zip(tpr, inv_fpr):
xy = (round(xy[0], 2), round(xy[1], 2))
for point in todo.keys():
if xy[0] >= point and todo[point]:
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data', fontsize=18, bbox=dict(boxstyle="square", fc="w"))
todo[point] = False
ax.grid(True, which='both', color='grey')
xlabel = r"$\{0}$ signal efficiency".format(label_0) if label_0 is not "e" else r"${0}$ signal efficiency".format(label_0)
ylabel = r"$\{0}$ background rejection".format(label_1) if label_1 is not "e" else r"${0}$ background rejection".format(label_1)
ax.set_xlabel(xlabel, fontsize=20)
ax.set_ylabel(ylabel, fontsize=20)
ax.set_title(r"${0} \leq E < {1}$".format(round(min_energy,2), round(max_energy,2)), fontsize=20)
ax.legend(loc="upper right", prop={"size":20})
plt.margins(0.1)
plt.yscale("log")
if save_path is not None:
plt.savefig(save_path)
if show_plot:
plt.show()
plt.clf() # Clear the current figure
plt.close() # Close the opened window
return fpr, tpr, threshold, roc_auc
# Plot the ROC curve for one vs another class
def plot_old_ROC(softmaxes, labels, energies, softmax_index_dict, label_0, label_1,
min_energy=0, max_energy=1500, show_plot=False, save_path=None):
assert softmaxes is not None
assert labels is not None
assert softmax_index_dict is not None
assert softmaxes.shape[0] == labels.shape[0]
assert label_0 in softmax_index_dict.keys()
assert label_1 in softmax_index_dict.keys()
#------------------------------------------------------------------------
# Create a boolean map to select events in the user-defined energy range
#------------------------------------------------------------------------
energy_slice_map = [False for i in range(len(energies))]
for i in range(len(energies)):
if(energies[i] >= min_energy and energies[i] < max_energy):
energy_slice_map[i] = True
curr_softmax = softmaxes[energy_slice_map]
curr_labels = labels[energy_slice_map]
#------------------------------------------------------------------------
# Extract the softmax and true label values for signal and background events
#------------------------------------------------------------------------
# Extract the useful softmax and labels from the input arrays
softmax_0 = curr_softmax[curr_labels==softmax_index_dict[label_0]]
labels_0 = curr_labels[curr_labels==softmax_index_dict[label_0]]
softmax_1 = curr_softmax[curr_labels==softmax_index_dict[label_1]]
labels_1 = curr_labels[curr_labels==softmax_index_dict[label_1]]
# Add the two arrays
softmax = np.concatenate((softmax_0, softmax_1), axis=0)
labels = np.concatenate((labels_0, labels_1), axis=0)
#------------------------------------------------------------------------
# Compute the ROC curve and the AUC for class corresponding to label 0
#------------------------------------------------------------------------
fpr, tpr, threshold = roc_curve(labels, softmax[:,softmax_index_dict[label_0]], pos_label=softmax_index_dict[label_0])
roc_auc = auc(fpr, tpr)
tnr = 1. - fpr
if show_plot or save_path is not None:
# TNR vs TPR plot
fig, ax = plt.subplots(figsize=(16,9),facecolor="w")
ax.tick_params(axis="both", labelsize=20)
ax.plot(tpr, tnr, color=color_dict[label_0],
label=r"$\{0}$, AUC ${1:0.3f}$".format(label_0, roc_auc) if label_0 is not "e" else r"${0}$, AUC ${1:0.3f}$".format(label_0, roc_auc),
linewidth=1.0, marker=".", markersize=4.0, markerfacecolor=color_dict[label_0])
# Show coords of individual points near x = 0.2, 0.5, 0.8
todo = {0.2: True, 0.5: True, 0.8: True}
for xy in zip(tpr, tnr):
xy = (round(xy[0], 3), round(xy[1], 3))
for point in todo.keys():
if xy[0] >= point and todo[point]:
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data', fontsize=18, bbox=dict(boxstyle="square", fc="w"))
todo[point] = False
ax.grid(True, which='both', color='grey')
xlabel = r"$\{0}$ signal efficiency".format(label_0) if label_0 is not "e" else r"${0}$ signal efficiency".format(label_0)
ylabel = r"$\{0}$ background rejection".format(label_1) if label_1 is not "e" else r"${0}$ background rejection".format(label_1)
ax.set_xlabel(xlabel, fontsize=20)
ax.set_ylabel(ylabel, fontsize=20)
ax.set_title(r"${0} \leq E < {1}$".format(round(min_energy,2), round(max_energy,2)), fontsize=20)
ax.legend(loc="upper right", prop={"size":20})
plt.margins(0.1)
if save_path is not None:
plt.savefig(save_path)
if show_plot:
plt.show()
plt.clf() # Clear the current figure
plt.close() # Close the opened window
return fpr, tpr, threshold, roc_auc
num_samples = [11250, 22500, 45000]
#dumps = ["20191017_183731", "20191017_184856", "20191017_185007"]
dumps = ["20200113_105809"]
#dump_dir = "/home/akajal/WatChMaL/VAE/dumps/"
dump_dir = "/home/ttuinstr/VAE/dumps/"
dump_file = "/test_validation_iteration_dump.npz"
softmax_index_dict = {"gamma":0, "e":1, "mu":2}
for num_sample, dump in zip(num_samples, dumps):
print("-------------------------------------------------------------")
print("Plotting the ROC curve for supervised CNN trained using {0} samples".format(num_sample))
print("-------------------------------------------------------------")
test_dump_path = dump_dir + dump + dump_file
test_dump_np = np.load(test_dump_path)
test_softmax = test_dump_np['softmax'].reshape(-1, 3)
test_labels = test_dump_np['labels'].reshape(-1)
test_energies = test_dump_np['energies'].reshape(-1)
roc_metrics = plot_new_ROC(test_softmax, test_labels, test_energies,
softmax_index_dict, "e", "gamma", min_energy=0,
max_energy=2000, show_plot=True)
roc_metrics = plot_old_ROC(test_softmax, test_labels, test_energies,
softmax_index_dict, "e", "gamma", min_energy=0,
max_energy=2000, show_plot=True)
num_samples = [7200000, 7200000, 7200000, 7200000]
dumps = ["20191017_113817", "20191017_113625", "20191017_113417", "20191017_113156"]
dump_dir = "/home/akajal/WatChMaL/VAE/dumps/"
dump_file = "/test_validation_iteration_dump.npz"
softmax_index_dict = {"gamma":0, "e":1, "mu":2}
for num_sample, dump in zip(num_samples, dumps):
print("-------------------------------------------------------------")
print("Plotting the ROC curve for supervised CNN trained using {0} samples".format(num_sample))
print("-------------------------------------------------------------")
test_dump_path = dump_dir + dump + dump_file
test_dump_np = np.load(test_dump_path)
test_softmax = test_dump_np['softmax'].reshape(-1, 3)
test_labels = test_dump_np['labels'].reshape(-1)
test_energies = test_dump_np['energies'].reshape(-1)
roc_metrics = plot_new_ROC(test_softmax, test_labels, test_energies,
softmax_index_dict, "e", "gamma", min_energy=0,
max_energy=2000, show_plot=True)
roc_metrics = plot_old_ROC(test_softmax, test_labels, test_energies,
softmax_index_dict, "e", "gamma", min_energy=0,
max_energy=2000, show_plot=True)
| 0.549157 | 0.566678 |
# Chapter 16
# Exercise 8
Embedded Reber grammars were used by Hochreiter and Schmidhuber in their paper about LSTMs. They are artificial grammars that produce strings such as “BPBTSXXVPSEPE.” Check out Jenny Orr’s nice introduction to this topic. Choose a particular embedded Reber grammar (such as the one represented on Jenny Orr’s page), then train an RNN to identify whether a string respects that grammar or not. You will first need to write a function capable of generating a training batch containing about 50% strings that respect the grammar, and 50% that don’t.
```
from collections import defaultdict
from random import choice, random, sample
from tensorflow import keras
import tensorflow as tf
from reber import *
```
## Reber
```
reber_edges = ((0,1,'B'), (1,2,'T'), (1,3,'P'), (2,2,'S'), (2,4,'X'), (3,3,'T'), (3,5,'V'), (4,3,'X'), (4,6,'S'), (5,4,'P'), (5,6,'V'), (6,None,'E'))
node_dict = dict_from_edges(reber_edges)
node_dict
sentence = generate_sentence(node_dict)
sentence
string_from_sentence(sentence)
unique_letters(sentence)
unique_letters(reber_edges)
sentence_edge = sentence[3]
sentence_edge
corrupted_sentence_edge = corrupt_edge(sentence_edge, reber_edges)
corrupted_sentence_edge
corrupted_sentence = corrupt_sentence(sentence, reber_edges, 2)
corrupted_sentence
```
## Embedder Reber Grammar
```
embedded_reber_edges = ((0,1,'B'), (1,2,'T'), (1,3,'P'), (2,4,reber_edges), (3,5,reber_edges), (4,6, 'T'), (5,6,'P'), (6,None,'E'))
embedded_reber_edges = flatten_embedded_edges(embedded_reber_edges)
embedded_reber_edges
node_dict = dict_from_edges(embedded_reber_edges)
node_dict
sentence = generate_sentence(node_dict)
sentence
string_from_sentence(sentence)
corrupt_sentence(sentence, embedded_reber_edges, 3)
```
## Generate Training Data
We will write a generator function that produces a reber sentence. With equal probability, the sentence will be corrupted (label 0). If corrupted, the number of corruptions is randonmly determined.
```
def generate_reber_training_sample(max_corruptions, edges, node_dict, allowed_chars):
sentence = generate_sentence(node_dict)
if random() < .5:
num_corruptions = choice(range(1,max_corruptions+1))
sentence = corrupt_sentence(sentence, edges, num_corruptions)
label = 0
else:
label = 1
s = string_from_sentence(sentence)
x = string_to_ids(s, allowed_chars)
x = tf.ragged.constant(x, dtype=tf.int8, ragged_rank=0)
y = tf.constant(label, dtype=tf.int8)
return (x, y)
def training_data_generator(max_corruptions, edges, n=10000):
node_dict = dict_from_edges(edges)
allowed_chars = unique_letters(edges)
for i in range(n):
yield generate_reber_training_sample(max_corruptions, edges, node_dict, allowed_chars)
```
## Train a model
```
max_corruptions = 3
embedding_size = 5
input_dim = len(unique_letters(embedded_reber_edges)) + 1
data = tf.data.Dataset.from_generator(lambda: training_data_generator(max_corruptions, embedded_reber_edges),
output_types=(tf.int8, tf.int8), output_shapes=(tf.TensorShape([None]), tf.TensorShape([])))
data = data.padded_batch(32).prefetch(1)
model = keras.models.Sequential([
keras.layers.Embedding(input_dim=input_dim, output_dim=embedding_size, mask_zero=True),
keras.layers.GRU(30),
keras.layers.Dense(1, activation="sigmoid")
])
optimizer = keras.optimizers.Nadam(learning_rate = 0.01)
model.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=["accuracy"])
history = model.fit(data, epochs=20)
```
Let's see how well an LSTM layer works
```
model_lstm = keras.models.Sequential([
keras.layers.Embedding(input_dim=input_dim, output_dim=embedding_size, mask_zero=True),
keras.layers.LSTM(30),
keras.layers.Dense(1, activation="sigmoid")
])
model_lstm.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=["accuracy"])
history_lstm = model_lstm.fit(data, epochs=20)
```
Finally, let's try a SimpleRNN
```
model_rnn = keras.models.Sequential([
keras.layers.Embedding(input_dim=input_dim, output_dim=embedding_size, mask_zero=True),
keras.layers.SimpleRNN(30, return_sequences=True),
keras.layers.SimpleRNN(30, return_sequences=True),
keras.layers.SimpleRNN(30),
keras.layers.Dense(1, activation="sigmoid")
])
model_rnn.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=["accuracy"])
history_rnn = model_rnn.fit(data, epochs=20)
```
# Exercise 9
_Exercise: Train an Encoder–Decoder model that can convert a date string from one format to another (e.g., from "April 22, 2019" to "2019-04-22")._
First, we need a method to generate dates in different formats
```
from tensorflow import keras
import tensorflow as tf
import tensorflow_addons as tfa
```
## Character level seq-to-seq model
```
from date_translation import *
x,y = generate_training_dates(100)
CHARS = list(set(''.join(x)))
x[0]
CHARS.index(x[0][0])
CHARS
preprocess_dates(x)
preprocess_dates(y)
np.random.seed(42)
X_train, Y_train = generate_training_data(20000)
X_valid, Y_valid = generate_training_data(2000)
X_test, Y_test = generate_training_data(2000)
X_train[0]
embedding_size = 32
max_char_in = tf.math.reduce_max(X_train).numpy()
max_char_out = tf.math.reduce_max(Y_train).numpy()
input_length = X_train.shape[1]
output_length = Y_train.shape[1]
max_char_in
encoder = keras.models.Sequential([
keras.layers.Embedding(input_dim=max_char_in+1, output_dim=embedding_size, input_shape=[input_length]),
keras.layers.LSTM(128)
])
decoder = keras.models.Sequential([
keras.layers.LSTM(128, return_sequences=True),
keras.layers.Dense(max_char_out+1, activation='softmax')
])
model = keras.models.Sequential([
encoder,
keras.layers.RepeatVector(output_length),
decoder
])
optimizer = keras.optimizers.Nadam()
model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, Y_train, epochs=20, validation_data=(X_valid, Y_valid))
X_train
```
# Exercise 11
_Use one of the recent language models (e.g., GPT) to generate more convincing Shakespearean text._
```
from random import choice, seed
from tensorflow import keras
from transformers import TFGPT2LMHeadModel, GPT2Tokenizer
```
## Load data
```
shakespeare_url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
filepath = keras.utils.get_file("shakespeare.txt", shakespeare_url)
with open(filepath) as f:
shakespeare_text = f.read()
```
## Tokenization
GPT-2 uses byte-pair encoding
```
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
print(tokenizer('Good morning all!'))
```
## Model
```
model = TFGPT2LMHeadModel.from_pretrained("gpt2")
```
## Text generation - No Fine Tuning
```
shakespeare_lines = shakespeare_text.split('\n')
seed(142)
prompt = choice(shakespeare_lines)
print(prompt)
encoded_prompt = tokenizer.encode(prompt, add_special_tokens=False, return_tensors='tf')
print(encoded_prompt)
num_sentences = 5
max_num_tokens = 50
generated_sequences = model.generate(
input_ids=encoded_prompt,
max_length = max_num_tokens,
do_sample = True,
temperature=1.0,
top_k=0,
top_p=0.9,
repetition_penalty=1.0,
num_return_sequences=num_sentences)
for sequence in generated_sequences:
sentence = tokenizer.decode(sequence, clean_up_tokenization_spaces=True)
print(sentence)
print("-" * 80)
```
## Fine tuning
Training script for fine tuning language models in huggingface is published [here](https://github.com/huggingface/transformers/tree/master/examples/language-modeling)
```
train_size = len(shakespeare_lines) * 90 // 100
with open("train_shakespeare.txt", 'w') as f:
f.write('\n'.join(shakespeare_lines[:train_size]))
with open("valid_shakespeare.txt", 'w') as f:
f.write('\n'.join(shakespeare_lines[train_size:]))
!python run_clm.py \
--model_type gpt2 \
--model_name_or_path gpt2 \
--train_file "train_shakespeare.txt" \
--do_train \
--validation_file "valid_shakespeare.txt" \
--do_eval \
--num_train_epochs 5 \
--per_gpu_train_batch_size 1 \
--output_dir /gpt2_shakespeare/
model_finetunes = TFGPT2LMHeadModel.from_pretrained("gpt2_shakespeare/", from_pt=True)
generated_sequences = model_finetunes.generate(
input_ids=encoded_prompt,
max_length = max_num_tokens,
do_sample = True,
temperature=1.0,
top_k=0,
top_p=0.9,
repetition_penalty=1.0,
num_return_sequences=num_sentences)
for sequence in generated_sequences:
sentence = tokenizer.decode(sequence, clean_up_tokenization_spaces=True)
print(sentence)
print("-" * 80)
```
|
github_jupyter
|
from collections import defaultdict
from random import choice, random, sample
from tensorflow import keras
import tensorflow as tf
from reber import *
reber_edges = ((0,1,'B'), (1,2,'T'), (1,3,'P'), (2,2,'S'), (2,4,'X'), (3,3,'T'), (3,5,'V'), (4,3,'X'), (4,6,'S'), (5,4,'P'), (5,6,'V'), (6,None,'E'))
node_dict = dict_from_edges(reber_edges)
node_dict
sentence = generate_sentence(node_dict)
sentence
string_from_sentence(sentence)
unique_letters(sentence)
unique_letters(reber_edges)
sentence_edge = sentence[3]
sentence_edge
corrupted_sentence_edge = corrupt_edge(sentence_edge, reber_edges)
corrupted_sentence_edge
corrupted_sentence = corrupt_sentence(sentence, reber_edges, 2)
corrupted_sentence
embedded_reber_edges = ((0,1,'B'), (1,2,'T'), (1,3,'P'), (2,4,reber_edges), (3,5,reber_edges), (4,6, 'T'), (5,6,'P'), (6,None,'E'))
embedded_reber_edges = flatten_embedded_edges(embedded_reber_edges)
embedded_reber_edges
node_dict = dict_from_edges(embedded_reber_edges)
node_dict
sentence = generate_sentence(node_dict)
sentence
string_from_sentence(sentence)
corrupt_sentence(sentence, embedded_reber_edges, 3)
def generate_reber_training_sample(max_corruptions, edges, node_dict, allowed_chars):
sentence = generate_sentence(node_dict)
if random() < .5:
num_corruptions = choice(range(1,max_corruptions+1))
sentence = corrupt_sentence(sentence, edges, num_corruptions)
label = 0
else:
label = 1
s = string_from_sentence(sentence)
x = string_to_ids(s, allowed_chars)
x = tf.ragged.constant(x, dtype=tf.int8, ragged_rank=0)
y = tf.constant(label, dtype=tf.int8)
return (x, y)
def training_data_generator(max_corruptions, edges, n=10000):
node_dict = dict_from_edges(edges)
allowed_chars = unique_letters(edges)
for i in range(n):
yield generate_reber_training_sample(max_corruptions, edges, node_dict, allowed_chars)
max_corruptions = 3
embedding_size = 5
input_dim = len(unique_letters(embedded_reber_edges)) + 1
data = tf.data.Dataset.from_generator(lambda: training_data_generator(max_corruptions, embedded_reber_edges),
output_types=(tf.int8, tf.int8), output_shapes=(tf.TensorShape([None]), tf.TensorShape([])))
data = data.padded_batch(32).prefetch(1)
model = keras.models.Sequential([
keras.layers.Embedding(input_dim=input_dim, output_dim=embedding_size, mask_zero=True),
keras.layers.GRU(30),
keras.layers.Dense(1, activation="sigmoid")
])
optimizer = keras.optimizers.Nadam(learning_rate = 0.01)
model.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=["accuracy"])
history = model.fit(data, epochs=20)
model_lstm = keras.models.Sequential([
keras.layers.Embedding(input_dim=input_dim, output_dim=embedding_size, mask_zero=True),
keras.layers.LSTM(30),
keras.layers.Dense(1, activation="sigmoid")
])
model_lstm.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=["accuracy"])
history_lstm = model_lstm.fit(data, epochs=20)
model_rnn = keras.models.Sequential([
keras.layers.Embedding(input_dim=input_dim, output_dim=embedding_size, mask_zero=True),
keras.layers.SimpleRNN(30, return_sequences=True),
keras.layers.SimpleRNN(30, return_sequences=True),
keras.layers.SimpleRNN(30),
keras.layers.Dense(1, activation="sigmoid")
])
model_rnn.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=["accuracy"])
history_rnn = model_rnn.fit(data, epochs=20)
from tensorflow import keras
import tensorflow as tf
import tensorflow_addons as tfa
from date_translation import *
x,y = generate_training_dates(100)
CHARS = list(set(''.join(x)))
x[0]
CHARS.index(x[0][0])
CHARS
preprocess_dates(x)
preprocess_dates(y)
np.random.seed(42)
X_train, Y_train = generate_training_data(20000)
X_valid, Y_valid = generate_training_data(2000)
X_test, Y_test = generate_training_data(2000)
X_train[0]
embedding_size = 32
max_char_in = tf.math.reduce_max(X_train).numpy()
max_char_out = tf.math.reduce_max(Y_train).numpy()
input_length = X_train.shape[1]
output_length = Y_train.shape[1]
max_char_in
encoder = keras.models.Sequential([
keras.layers.Embedding(input_dim=max_char_in+1, output_dim=embedding_size, input_shape=[input_length]),
keras.layers.LSTM(128)
])
decoder = keras.models.Sequential([
keras.layers.LSTM(128, return_sequences=True),
keras.layers.Dense(max_char_out+1, activation='softmax')
])
model = keras.models.Sequential([
encoder,
keras.layers.RepeatVector(output_length),
decoder
])
optimizer = keras.optimizers.Nadam()
model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, Y_train, epochs=20, validation_data=(X_valid, Y_valid))
X_train
from random import choice, seed
from tensorflow import keras
from transformers import TFGPT2LMHeadModel, GPT2Tokenizer
shakespeare_url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
filepath = keras.utils.get_file("shakespeare.txt", shakespeare_url)
with open(filepath) as f:
shakespeare_text = f.read()
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
print(tokenizer('Good morning all!'))
model = TFGPT2LMHeadModel.from_pretrained("gpt2")
shakespeare_lines = shakespeare_text.split('\n')
seed(142)
prompt = choice(shakespeare_lines)
print(prompt)
encoded_prompt = tokenizer.encode(prompt, add_special_tokens=False, return_tensors='tf')
print(encoded_prompt)
num_sentences = 5
max_num_tokens = 50
generated_sequences = model.generate(
input_ids=encoded_prompt,
max_length = max_num_tokens,
do_sample = True,
temperature=1.0,
top_k=0,
top_p=0.9,
repetition_penalty=1.0,
num_return_sequences=num_sentences)
for sequence in generated_sequences:
sentence = tokenizer.decode(sequence, clean_up_tokenization_spaces=True)
print(sentence)
print("-" * 80)
train_size = len(shakespeare_lines) * 90 // 100
with open("train_shakespeare.txt", 'w') as f:
f.write('\n'.join(shakespeare_lines[:train_size]))
with open("valid_shakespeare.txt", 'w') as f:
f.write('\n'.join(shakespeare_lines[train_size:]))
!python run_clm.py \
--model_type gpt2 \
--model_name_or_path gpt2 \
--train_file "train_shakespeare.txt" \
--do_train \
--validation_file "valid_shakespeare.txt" \
--do_eval \
--num_train_epochs 5 \
--per_gpu_train_batch_size 1 \
--output_dir /gpt2_shakespeare/
model_finetunes = TFGPT2LMHeadModel.from_pretrained("gpt2_shakespeare/", from_pt=True)
generated_sequences = model_finetunes.generate(
input_ids=encoded_prompt,
max_length = max_num_tokens,
do_sample = True,
temperature=1.0,
top_k=0,
top_p=0.9,
repetition_penalty=1.0,
num_return_sequences=num_sentences)
for sequence in generated_sequences:
sentence = tokenizer.decode(sequence, clean_up_tokenization_spaces=True)
print(sentence)
print("-" * 80)
| 0.715623 | 0.913213 |
Водопьян А.О. Хабибуллин Р.А. 2019 г.
## Давление насыщения нефти газом
<a id="Pb"></a>
### Давление насыщения, корреляция Стендинга
<a id="Pb_Standing"></a>
Корреляция Стендинга для оценки давления насыщения нефти газом.
$$ P_b = 0.5197 \left( \frac{R_{sb}}{\gamma_g}\right)^{0.83} 10 ^{y_g} $$
где
$P_b$ - давление насыщения, $МПа$
$R_{sb}$ - газосодержание при давлении насыщения, $м^3/м^3 $
$\gamma_g$ - относительная плотность газа, безразмерная величина
$y_g$ - мольная доля газа, $ y_g = 1.225 +0.00164 T - \frac{ 1.769}{\gamma_o}$
$\gamma_o$ - относительная плотность нефти, безразмерная величина
$ T $ - температура, $ ^{\circ}\mathrm{K}$
Корреляции Standing базируются на 105 экспериментально определенных давлениях насыщения нефтяных систем Калифорнии. Диапазоны значений основных свойств, использованных для разработки данной корреляции, приведены в таблице ниже.
| <p align="left"> Параметр | Диапазон |
| :--- | :--- |
| <p align="left"> давление насыщения,$P_b$ , $ МПа $ | 0.896…48.263 |
| <p align="left"> температура, $^{\circ}\mathrm{K} $ | 310…400 |
| <p align="left"> газосодержание при давлении насыщения, $R_{sb}$ , $м^3/м^3 $ | 3.6…254 |
| <p align="left"> относительная плотность нефти по воде, $\gamma_o$ | 0.725…0.956 |
| <p align="left"> относительная плотность газа, $\gamma_g$ | 0.59…0.95 |
ref "A Pressure-Volume-Temperature Correlation for Mixtures of California Oil and Gases", M.B. Standing, Drill. & Prod. Prac., API, 1947.
```
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from sympy import *
init_printing()
import sys
sys.path.append('../')
import uniflocpy.uPVT.PVT_correlations as PVT
# Корреляция Стендинга для давления насыщения реализована
# в виде функции unf_pb_Standing_MPaa в модуле PVT_correlations.
# Подробные данные по функции включая исходный код приведены ниже
PVT.unf_pb_Standing_MPaa??
```
в приведеном коде использована коррекция значений давления насыщения при низких значениях газосодержания при давлении насыщения для обеспечения выхода на значение $P_b = 1$ при $R{sb} = 0$
<img src="pics/Pb-Standing_comparison.png" width="600" >
---
Построим пару графиков, используя приведенную функцию
```
# параметры определяющие диапазоны значений для построения графиков
rsb_set=np.arange(1,300,10)
t_set=np.arange(273,380,30)
t_set_def=np.array([313])
gg_set=np.arange(0.6,1,0.1)
gg_set_def=np.array([0.8])
go_set=np.arange(0.8,1,0.05)
go_set_def=np.array([0.86])
# функция для автоматизации построения графиков по давлению насыщения
def prep_plot(func,tset,goset,ggset,plot_title,plot_xlab,plot_ylab):
for t in tset:
for gg in ggset:
for go in goset:
pb_set=[]
for rsb in rsb_set:
pb_set.append(func(rsb,t_K = t,gamma_gas = gg,gamma_oil = go))
plt.plot(rsb_set, pb_set, label='t = %1.0f $ ^{\circ}\mathrm{K}$'%t +
' $\gamma_g$ = %1.2f'%gg +
' $\gamma_o$ = %1.2f'%go)
plt.title(plot_title)
plt.ylabel(plot_ylab, color = 'black')
plt.xlabel(plot_xlab, color = 'black')
plt.legend()
# код для построения графиков
plt.figure(figsize=(15,8))
f = PVT.unf_pb_Standing_MPaa
# рисуем первый график
plt.subplot(221)
prep_plot(f,t_set,go_set_def,gg_set_def,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.grid()
# рисуем второй график
plt.subplot(222)
prep_plot(f,t_set_def,go_set,gg_set_def,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.grid()
# рисуем третий график
plt.subplot(223)
prep_plot(f,t_set_def,go_set_def,gg_set,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, wspace=0.35)
# рисуем все
plt.grid()
plt.show()
```
---
<a id="Pb_Valco"></a>
### Давление насыщения, корреляция Valko McCain
Корреляция Valco McCain (2003) для оценки давления насыщения нефти газом разработана на основе банка данных нефтей со всего мира. На рисунке показаны источники данных, которые были использованы авторами для настройки корреляции.
<img src="pics/McCain_corr_sources.png" width="400" >
Диапазоны значений основных свойств (1745 значений), использованных для разработки данной корреляции, приведены в таблице ниже.
| <p align="left"> Параметр | Мин|Среднее|Макс|
| :--- | :---: |:---:|:---:|
| <p align="left"> давление насыщения,$P_b$ , $ МПа $ | 0.55 |15.0|45.5|
| <p align="left"> температура, $^{\circ}\mathrm{С} $ | 15 |85|172|
| <p align="left"> газосодержание при давлении насыщения, $R_{sb}$ , $м^3/м^3 $ | 2 |104|395|
| <p align="left"> относительная плотность нефти по воде, $\gamma_o$ | 0.724 |0.846|1.02|
| <p align="left"> относительная плотность газа на сепараторе, $\gamma_g$ | 0.555 |0.838|1.685|
По результатам сравнений с замеренными значениями абсолютная значение средней относительной ошибки (AARE) для корреляции составляет около 11%. Авторы отмечают, что полученная точность соответствует точности замеров использованных для построения корреляции и для построения более точных зависимостей потребуется сбор новых данных с повышенной точностью.
$$
ln P_b = 7.475 + 0.713 z + 0.0075 z^2
$$
где
$$
z = z_1+z_2+z_3+z_4
$$
$$
z_1 = -5.48 - 0.0375\cdot ln R_{sb}+0.281\cdot (ln R_{sb})^2 - 0.0206\cdot (ln R_{sb})^3
$$
$$
z_2 = 1.27 - 0.0449\cdot API +4.36 \cdot 10^{-4} API^2 -4.76 \cdot 10^{-6} API^3
$$
$$
z_3 = 4.51 - 10.84 \cdot \gamma_{gSP} +8.39\cdot \gamma_{gSP}^2 -2.34\cdot \gamma_{gSP}^3
$$
$$
z_4 = -0.7835 + 6.23 \cdot 10^{-3} \cdot T_R - 1.22 \cdot 10^{-5} \cdot T_R^2+ 1.03 \cdot 10^{-8} \cdot T_R^3
$$
где
* $p_b$ - давление насыщения, $psia$
* $R_{sb}$ - газосодержание при давлении насыщения, ${scf}/{STB}$
* $\gamma_{gSP}$ - удельная плотность газа, отобранного на сепараторе, безразмерная величина
* $T_R$ - пластовая температура, $F$
ref Reservoir oil bubblepoint pressures revisited; solution gas-oil ratios and surface gas specific gravities. P.P.Valko, W.D.McCain Jr. Journal of petroleum science and engineering 37(2003) 153-169
---
#### Пребразование единиц измерения для корреляции Валко Маккейна
```
# объявления переменных необходимых для преобразования единиц в вырожении
rsb_scfSTB, rsb_m3m3 = symbols('R_sb[scfSTB] R_sb[m3m3]')
API, gamma_o = symbols('API gamma_o')
gamma_gSP = symbols('gamma_gSP')
T_RF,T_RK = symbols('T_R[F] T_R[K]')
z,z1,z2,z3,z4 = symbols('z,z1,z2,z3,z4')
p_bpsia, p_bMPaa = symbols('p_b[psia],p_b[MPaa]')
# определение алгоритма расчета в американских промысловых единицах
eq1 = Eq(z,z1+z2+z3+z4)
eq2 = Eq(z1, -5.48 - 0.03758 * ln(rsb_scfSTB)+ 0.281* ln(rsb_scfSTB)**2 - 0.0206* ln(rsb_scfSTB)**3)
eq3 = Eq(z2, 1.27 - 0.0449* API +4.36 * 10**-4 *API**2 -4.76 * 10**-6 *API**3)
eq4 = Eq(z3, 4.51- 10.84 *gamma_gSP +8.39*gamma_gSP**2 -2.34*gamma_gSP**3 )
eq5 = Eq(z4, -0.7835 + 6.23 * 10**-3 * T_RF - 1.22 * 10**-5 * T_RF**2+ 1.03 * 10**-8 * T_RF**3)
eq6 =Eq(ln(p_bpsia),(7.475 + 0.713 * z + 0.0075 * z**2))
# покажем выражения в печатном виде
display(eq6)
display(eq1)
display(eq2)
display(eq3)
display(eq4)
display(eq5)
# выражения для преобразования единиц измерения из американских промысловых в практические метрические
scfSTB_to_m3m3 = rsb_m3m3/0.178107606679035
API_to_gamma_o = 141.5/gamma_o-131.5
F_to_K = T_RK*9/5-459.67
psi_to_MPa = p_bMPaa * 14.6959 * 10.1325
# покажем выражения в печатном виде
display(Eq(rsb_scfSTB , scfSTB_to_m3m3))
display(Eq(API,API_to_gamma_o))
display(Eq(T_RF,F_to_K))
display(Eq(p_bpsia,psi_to_MPa))
# преобразование алгоритма в метрические единицы с использованием символьных вычислений
eq2_m=simplify(eq2.subs(rsb_scfSTB,scfSTB_to_m3m3))
eq3_m=simplify(eq3.subs(API,API_to_gamma_o))
eq5_m=simplify(eq5.subs(T_RF,F_to_K))
eq6_m=eq6.subs(p_bpsia, psi_to_MPa)
eq8=solve(eq6_m,p_bMPaa)
eq9=Eq(p_bMPaa, eq8[0])
# вывод результатов преобразований
display(eq9)
display(eq1)
display(eq2_m)
display(eq3_m)
display(eq4)
display(eq5_m)
# расчет реализован в функции unf_pb_Valko_MPaa
PVT.unf_pb_Valko_MPaa??
plt.figure(figsize=(15,8))
f = PVT.unf_pb_Valko_MPaa
# рисуем первый график
plt.subplot(221)
prep_plot(f,t_set,go_set_def,gg_set_def,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.grid()
# рисуем второй график
plt.subplot(222)
prep_plot(f,t_set_def,go_set,gg_set_def,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.grid()
# рисуем третий график
plt.subplot(223)
prep_plot(f,t_set_def,go_set_def,gg_set,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, wspace=0.35)
# рисуем все
plt.grid()
plt.show()
```
в приведеном коде использована коррекция значений давления насыщения при низких значениях газосодержания при давлении насыщения для обеспечения выхода на значение $P_b = 1$ при $R{sb} = 0$ и при больших значениях газосодержания
<img src="pics/Pb-Valko_comparison.png" width="600" >
следует отметить, что в отличии от корреляций типа Стендинга корреляция Валко Макейна хорошо описывает исходный набор данных в пределах области применимости, но дает нефизичные результаты за пределами диапазона применимости. Приведенная в коде корректировке может частично сгладить экспраполированные значения, но лучше при проведении расчетов контролировать, чтобы корреляция применялась в пределах диапазона примемости.
```
PVT.unf_pb_AlMarhoun_MPaa??
```
|
github_jupyter
|
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from sympy import *
init_printing()
import sys
sys.path.append('../')
import uniflocpy.uPVT.PVT_correlations as PVT
# Корреляция Стендинга для давления насыщения реализована
# в виде функции unf_pb_Standing_MPaa в модуле PVT_correlations.
# Подробные данные по функции включая исходный код приведены ниже
PVT.unf_pb_Standing_MPaa??
# параметры определяющие диапазоны значений для построения графиков
rsb_set=np.arange(1,300,10)
t_set=np.arange(273,380,30)
t_set_def=np.array([313])
gg_set=np.arange(0.6,1,0.1)
gg_set_def=np.array([0.8])
go_set=np.arange(0.8,1,0.05)
go_set_def=np.array([0.86])
# функция для автоматизации построения графиков по давлению насыщения
def prep_plot(func,tset,goset,ggset,plot_title,plot_xlab,plot_ylab):
for t in tset:
for gg in ggset:
for go in goset:
pb_set=[]
for rsb in rsb_set:
pb_set.append(func(rsb,t_K = t,gamma_gas = gg,gamma_oil = go))
plt.plot(rsb_set, pb_set, label='t = %1.0f $ ^{\circ}\mathrm{K}$'%t +
' $\gamma_g$ = %1.2f'%gg +
' $\gamma_o$ = %1.2f'%go)
plt.title(plot_title)
plt.ylabel(plot_ylab, color = 'black')
plt.xlabel(plot_xlab, color = 'black')
plt.legend()
# код для построения графиков
plt.figure(figsize=(15,8))
f = PVT.unf_pb_Standing_MPaa
# рисуем первый график
plt.subplot(221)
prep_plot(f,t_set,go_set_def,gg_set_def,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.grid()
# рисуем второй график
plt.subplot(222)
prep_plot(f,t_set_def,go_set,gg_set_def,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.grid()
# рисуем третий график
plt.subplot(223)
prep_plot(f,t_set_def,go_set_def,gg_set,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, wspace=0.35)
# рисуем все
plt.grid()
plt.show()
# объявления переменных необходимых для преобразования единиц в вырожении
rsb_scfSTB, rsb_m3m3 = symbols('R_sb[scfSTB] R_sb[m3m3]')
API, gamma_o = symbols('API gamma_o')
gamma_gSP = symbols('gamma_gSP')
T_RF,T_RK = symbols('T_R[F] T_R[K]')
z,z1,z2,z3,z4 = symbols('z,z1,z2,z3,z4')
p_bpsia, p_bMPaa = symbols('p_b[psia],p_b[MPaa]')
# определение алгоритма расчета в американских промысловых единицах
eq1 = Eq(z,z1+z2+z3+z4)
eq2 = Eq(z1, -5.48 - 0.03758 * ln(rsb_scfSTB)+ 0.281* ln(rsb_scfSTB)**2 - 0.0206* ln(rsb_scfSTB)**3)
eq3 = Eq(z2, 1.27 - 0.0449* API +4.36 * 10**-4 *API**2 -4.76 * 10**-6 *API**3)
eq4 = Eq(z3, 4.51- 10.84 *gamma_gSP +8.39*gamma_gSP**2 -2.34*gamma_gSP**3 )
eq5 = Eq(z4, -0.7835 + 6.23 * 10**-3 * T_RF - 1.22 * 10**-5 * T_RF**2+ 1.03 * 10**-8 * T_RF**3)
eq6 =Eq(ln(p_bpsia),(7.475 + 0.713 * z + 0.0075 * z**2))
# покажем выражения в печатном виде
display(eq6)
display(eq1)
display(eq2)
display(eq3)
display(eq4)
display(eq5)
# выражения для преобразования единиц измерения из американских промысловых в практические метрические
scfSTB_to_m3m3 = rsb_m3m3/0.178107606679035
API_to_gamma_o = 141.5/gamma_o-131.5
F_to_K = T_RK*9/5-459.67
psi_to_MPa = p_bMPaa * 14.6959 * 10.1325
# покажем выражения в печатном виде
display(Eq(rsb_scfSTB , scfSTB_to_m3m3))
display(Eq(API,API_to_gamma_o))
display(Eq(T_RF,F_to_K))
display(Eq(p_bpsia,psi_to_MPa))
# преобразование алгоритма в метрические единицы с использованием символьных вычислений
eq2_m=simplify(eq2.subs(rsb_scfSTB,scfSTB_to_m3m3))
eq3_m=simplify(eq3.subs(API,API_to_gamma_o))
eq5_m=simplify(eq5.subs(T_RF,F_to_K))
eq6_m=eq6.subs(p_bpsia, psi_to_MPa)
eq8=solve(eq6_m,p_bMPaa)
eq9=Eq(p_bMPaa, eq8[0])
# вывод результатов преобразований
display(eq9)
display(eq1)
display(eq2_m)
display(eq3_m)
display(eq4)
display(eq5_m)
# расчет реализован в функции unf_pb_Valko_MPaa
PVT.unf_pb_Valko_MPaa??
plt.figure(figsize=(15,8))
f = PVT.unf_pb_Valko_MPaa
# рисуем первый график
plt.subplot(221)
prep_plot(f,t_set,go_set_def,gg_set_def,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.grid()
# рисуем второй график
plt.subplot(222)
prep_plot(f,t_set_def,go_set,gg_set_def,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.grid()
# рисуем третий график
plt.subplot(223)
prep_plot(f,t_set_def,go_set_def,gg_set,
'Давление насыщения от газосодержания',
'$R_{sb}, м^3/м^3$',
'$P_b, MPa$')
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, wspace=0.35)
# рисуем все
plt.grid()
plt.show()
PVT.unf_pb_AlMarhoun_MPaa??
| 0.179567 | 0.949012 |
```
%run "Common setup.ipynb"
%reload_ext autoreload
%autoreload 2
from SALib.analyze.delta import analyze
def incremental_delta_analysis(lower, upper, step=1):
res, idx = [], []
for reps in range(lower, upper, step):
try:
results = analyze(CIM_SPEC, numeric_vals[:reps], np_res[:reps], seed=101)
except np.linalg.LinAlgError:
res.append(np.nan)
idx.append(reps)
continue
total = results.to_df()
res.append(total.loc[tgt_param, 'S1'])
idx.append(reps)
# End for
return res, idx
# End incremental_delta_analysis()
numeric_samples = pd.read_csv(f'{DATA_DIR}oat_mc_10_samples.csv', index_col=0)
numeric_samples = numeric_samples[perturbed_cols]
numeric_vals = numeric_samples.values
# Coupling disabled
# DMIM does not work when there is no change in parameter values
oat_no_irrigation_results = pd.read_csv(f'{DATA_DIR}oat_no_irrigation_10_results.csv', index_col=0)
oat_no_irrigation_results['Avg. $/ML'].fillna(oat_no_irrigation_results["Avg. Annual Profit ($M)"], inplace=True)
np_res = oat_no_irrigation_results.loc[:, tgt_metric].values
runs = np_res.shape[0]
res, idx = incremental_delta_analysis(54, runs+1, 54)
# plot_incremental_results(res, idx)
disabled = pd.DataFrame({'S1': res}, index=idx)
# Coupling enabled
oat_with_irrigation_results = pd.read_csv(f'{DATA_DIR}oat_with_irrigation_10_results.csv', index_col=0)
oat_with_irrigation_results['Avg. $/ML'].fillna(oat_with_irrigation_results["Avg. Annual Profit ($M)"], inplace=True)
np_res = oat_with_irrigation_results.loc[:, tgt_metric].values
runs = np_res.shape[0]
res, idx = incremental_delta_analysis(54, runs+1, 54)
enabled = pd.DataFrame({'S1': res}, index=idx)
fig, axes = plt.subplots(1,2, figsize=(12,4), sharey=True, sharex=True)
labels = [str(i) for i in idx]
disabled.loc[:, 'S1'].plot(kind='bar',
legend=None,
title='Disabled',
ax=axes[0],
use_index=True,
rot=45,
width=0.8,
edgecolor='C0')
enabled.loc[:, 'S1'].plot(kind='bar',
legend=None,
title='Enabled',
ax=axes[1],
use_index=True,
rot=45,
width=0.8,
edgecolor='C0').legend(
bbox_to_anchor=(1.35, 0.65)
)
fig.suptitle("DMIM Analysis", x=0.5, y=1.05, fontsize=22)
plt.xlabel("$N$", x=-0.1, labelpad=15);
fig.savefig(FIG_DIR+'DMIM_larger_sample.png', dpi=300, bbox_inches='tight')
```
---
With full results
```
tgt_result_idx = all_outputs.columns.tolist().index("SW Allocation Index")
numeric_samples = to_numeric_samples(all_inputs)[perturbed_cols]
param_idx = numeric_samples.columns.tolist().index(tgt_param)
numeric_vals = numeric_samples.values
# numeric_vals = numeric_vals[idx, :]
np_res = all_outputs.values[:, tgt_result_idx]
np_res = np_res.astype('float64')
rows = np_res.shape[0]
res, idx = incremental_delta_analysis(54, rows, 54)
pd.DataFrame({'S1': res[::2]}, index=idx[::2]).plot(kind='bar', figsize=(16,4))
```
|
github_jupyter
|
%run "Common setup.ipynb"
%reload_ext autoreload
%autoreload 2
from SALib.analyze.delta import analyze
def incremental_delta_analysis(lower, upper, step=1):
res, idx = [], []
for reps in range(lower, upper, step):
try:
results = analyze(CIM_SPEC, numeric_vals[:reps], np_res[:reps], seed=101)
except np.linalg.LinAlgError:
res.append(np.nan)
idx.append(reps)
continue
total = results.to_df()
res.append(total.loc[tgt_param, 'S1'])
idx.append(reps)
# End for
return res, idx
# End incremental_delta_analysis()
numeric_samples = pd.read_csv(f'{DATA_DIR}oat_mc_10_samples.csv', index_col=0)
numeric_samples = numeric_samples[perturbed_cols]
numeric_vals = numeric_samples.values
# Coupling disabled
# DMIM does not work when there is no change in parameter values
oat_no_irrigation_results = pd.read_csv(f'{DATA_DIR}oat_no_irrigation_10_results.csv', index_col=0)
oat_no_irrigation_results['Avg. $/ML'].fillna(oat_no_irrigation_results["Avg. Annual Profit ($M)"], inplace=True)
np_res = oat_no_irrigation_results.loc[:, tgt_metric].values
runs = np_res.shape[0]
res, idx = incremental_delta_analysis(54, runs+1, 54)
# plot_incremental_results(res, idx)
disabled = pd.DataFrame({'S1': res}, index=idx)
# Coupling enabled
oat_with_irrigation_results = pd.read_csv(f'{DATA_DIR}oat_with_irrigation_10_results.csv', index_col=0)
oat_with_irrigation_results['Avg. $/ML'].fillna(oat_with_irrigation_results["Avg. Annual Profit ($M)"], inplace=True)
np_res = oat_with_irrigation_results.loc[:, tgt_metric].values
runs = np_res.shape[0]
res, idx = incremental_delta_analysis(54, runs+1, 54)
enabled = pd.DataFrame({'S1': res}, index=idx)
fig, axes = plt.subplots(1,2, figsize=(12,4), sharey=True, sharex=True)
labels = [str(i) for i in idx]
disabled.loc[:, 'S1'].plot(kind='bar',
legend=None,
title='Disabled',
ax=axes[0],
use_index=True,
rot=45,
width=0.8,
edgecolor='C0')
enabled.loc[:, 'S1'].plot(kind='bar',
legend=None,
title='Enabled',
ax=axes[1],
use_index=True,
rot=45,
width=0.8,
edgecolor='C0').legend(
bbox_to_anchor=(1.35, 0.65)
)
fig.suptitle("DMIM Analysis", x=0.5, y=1.05, fontsize=22)
plt.xlabel("$N$", x=-0.1, labelpad=15);
fig.savefig(FIG_DIR+'DMIM_larger_sample.png', dpi=300, bbox_inches='tight')
tgt_result_idx = all_outputs.columns.tolist().index("SW Allocation Index")
numeric_samples = to_numeric_samples(all_inputs)[perturbed_cols]
param_idx = numeric_samples.columns.tolist().index(tgt_param)
numeric_vals = numeric_samples.values
# numeric_vals = numeric_vals[idx, :]
np_res = all_outputs.values[:, tgt_result_idx]
np_res = np_res.astype('float64')
rows = np_res.shape[0]
res, idx = incremental_delta_analysis(54, rows, 54)
pd.DataFrame({'S1': res[::2]}, index=idx[::2]).plot(kind='bar', figsize=(16,4))
| 0.42919 | 0.461805 |
# Puts ALL WISE Astrometry reference catalogues into GAIA reference frame
<img src=https://avatars1.githubusercontent.com/u/7880370?s=200&v=4>
The WISE catalogues were produced by ../dmu16_allwise/make_wise_samples_for_stacking.csh
In the catalogue, we keep:
- The position;
- The chi^2
This astrometric correction is adapted from master list code (dmu1_ml_XMM-LSS/1.8_SERVS.ipynb) written by Yannick Rohlly and Raphael Shirley
```
field="SA13"
from herschelhelp_internal import git_version
print("This notebook was run with herschelhelp_internal version: \n{}".format(git_version()))
%matplotlib inline
#%config InlineBackend.figure_format = 'svg'
import matplotlib.pyplot as plt
plt.rc('figure', figsize=(10, 6))
from collections import OrderedDict
import os
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.table import Column, Table
import numpy as np
from herschelhelp_internal.flagging import gaia_flag_column
from herschelhelp_internal.masterlist import nb_astcor_diag_plot, remove_duplicates
from herschelhelp_internal.utils import astrometric_correction, flux_to_mag
OUT_DIR = os.environ.get('TMP_DIR', "../dmu16_allwise/data/")
try:
os.makedirs(OUT_DIR)
except FileExistsError:
pass
RA_COL = "servs_ra"
DEC_COL = "servs_dec"
## I - Reading in WISE astrometric catalogue
wise = Table.read(f"../dmu16_allwise/data/Allwise_PSF_stack_{field}.fits")
wise_coords=SkyCoord(wise['ra'], wise['dec'])
epoch = 2009
wise[:10].show_in_notebook()
```
## III - Astrometry correction
We match the astrometry to the Gaia one. We limit the Gaia catalogue to sources with a g band flux between the 30th and the 70th percentile. Some quick tests show that this give the lower dispersion in the results.
```
#gaia = Table.read("./dmu17_XMM-LSS/data/GAIA_XMM-LSS.fits")
print(f"../../dmu0/dmu0_GAIA/data/GAIA_{field}.fits")
gaia = Table.read(f"../../dmu0/dmu0_GAIA/data/GAIA_{field}.fits")
gaia_coords = SkyCoord(gaia['ra'], gaia['dec'])
nb_astcor_diag_plot(wise_coords.ra, wise_coords.dec,
gaia_coords.ra, gaia_coords.dec, near_ra0=True)
delta_ra, delta_dec = astrometric_correction(
wise_coords,
gaia_coords, near_ra0=True
)
print("RA correction: {}".format(delta_ra))
print("Dec correction: {}".format(delta_dec))
print( wise["ra"])
print(delta_ra.to(u.deg))
#wise["ra"] += delta_ra.to(u.deg)
wise["ra"] = wise["ra"]+ delta_ra.to(u.deg)
wise["dec"] = wise["dec"]+ delta_dec.to(u.deg)
nb_astcor_diag_plot(wise["ra"], wise["dec"],
gaia_coords.ra, gaia_coords.dec, near_ra0=True)
```
## V - Saving to disk
```
wise.write(f"../dmu16_allwise/data/Allwise_PSF_stack_GAIA_{field}.fits", overwrite=True)
```
|
github_jupyter
|
field="SA13"
from herschelhelp_internal import git_version
print("This notebook was run with herschelhelp_internal version: \n{}".format(git_version()))
%matplotlib inline
#%config InlineBackend.figure_format = 'svg'
import matplotlib.pyplot as plt
plt.rc('figure', figsize=(10, 6))
from collections import OrderedDict
import os
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.table import Column, Table
import numpy as np
from herschelhelp_internal.flagging import gaia_flag_column
from herschelhelp_internal.masterlist import nb_astcor_diag_plot, remove_duplicates
from herschelhelp_internal.utils import astrometric_correction, flux_to_mag
OUT_DIR = os.environ.get('TMP_DIR', "../dmu16_allwise/data/")
try:
os.makedirs(OUT_DIR)
except FileExistsError:
pass
RA_COL = "servs_ra"
DEC_COL = "servs_dec"
## I - Reading in WISE astrometric catalogue
wise = Table.read(f"../dmu16_allwise/data/Allwise_PSF_stack_{field}.fits")
wise_coords=SkyCoord(wise['ra'], wise['dec'])
epoch = 2009
wise[:10].show_in_notebook()
#gaia = Table.read("./dmu17_XMM-LSS/data/GAIA_XMM-LSS.fits")
print(f"../../dmu0/dmu0_GAIA/data/GAIA_{field}.fits")
gaia = Table.read(f"../../dmu0/dmu0_GAIA/data/GAIA_{field}.fits")
gaia_coords = SkyCoord(gaia['ra'], gaia['dec'])
nb_astcor_diag_plot(wise_coords.ra, wise_coords.dec,
gaia_coords.ra, gaia_coords.dec, near_ra0=True)
delta_ra, delta_dec = astrometric_correction(
wise_coords,
gaia_coords, near_ra0=True
)
print("RA correction: {}".format(delta_ra))
print("Dec correction: {}".format(delta_dec))
print( wise["ra"])
print(delta_ra.to(u.deg))
#wise["ra"] += delta_ra.to(u.deg)
wise["ra"] = wise["ra"]+ delta_ra.to(u.deg)
wise["dec"] = wise["dec"]+ delta_dec.to(u.deg)
nb_astcor_diag_plot(wise["ra"], wise["dec"],
gaia_coords.ra, gaia_coords.dec, near_ra0=True)
wise.write(f"../dmu16_allwise/data/Allwise_PSF_stack_GAIA_{field}.fits", overwrite=True)
| 0.460046 | 0.745699 |
# 1. Example of training GNNs for Graph Classification
GRB provides easy-to-use APIs to train GNNs, facilitating the entire process from loading graph data, building GNN models, to evaluation and inference. Here is an example for the task of graph classification.
Contents
- [Load Dataset](#Load-Dataset)
- [Build Model](#Build-Model)
- [Training](#Training)
- [Inference](#Inference)
- [Evaluation](#Evaluation)
```
import os
import torch
import grb.utils as utils
```
## 1.1. Load Dataset
```
from grb.dataset import CogDLDataset
dataset_name = "mutag"
dataset = CogDLDataset(name=dataset_name,
data_dir="../../data/")
```
## 1.2. Build Model
GRB supports models based on pure Pytorch, CogDL or DGL. The following is an example of GCNGC (GCN for Graph Classification) implemented by pure Pytorch. Other models can be found in ``grb/model/torch``, ``grb/model/cogdl``, or ``grb/model/dgl``.
### 1.2.1. GCNGC (Graph Convolutional Network for Graph Classification)
```
from grb.model.torch import GCNGC
model_name = "gcngc"
model = GCNGC(in_features=dataset.num_features,
out_features=dataset.num_classes,
hidden_features=64,
n_layers=3,
residual=False,
dropout=0.5)
print("Number of parameters: {}.".format(utils.get_num_params(model)))
print(model)
```
## 1.3. Training
GRB provides ``grb.trainer.trainer`` that facilitates the training process of GNNs. For Graph Classification task, a mini-batch training on graphs is applied. Multiple graphs are merged into a large graph, then the results are pooled to predict label for each graph.
```
save_dir = "./saved_models/{}/{}".format(dataset_name, model_name)
save_name = "model.pt"
device = "cuda:0"
batch_size = 20
from grb.trainer.trainer import GraphTrainer
trainer = GraphTrainer(dataset=dataset,
batch_size=batch_size,
optimizer=torch.optim.Adam(model.parameters(), lr=0.01),
loss=torch.nn.functional.cross_entropy,
lr_scheduler=False,
early_stop=True,
early_stop_patience=50,
device=device)
trainer.train(model=model,
n_epoch=200,
eval_every=1,
save_after=0,
save_dir=save_dir,
save_name=save_name,
verbose=False)
```
## 1.4. Inference
```
model = torch.load(os.path.join(save_dir, save_name))
model = model.to(device)
model.eval()
# by trainer
pred = trainer.inference(model)
```
## 1.5 Evaluation
```
# by trainer
test_score = trainer.evaluate(model, dataset.index_test)
print("Test score: {:.4f}".format(test_score))
```
|
github_jupyter
|
import os
import torch
import grb.utils as utils
from grb.dataset import CogDLDataset
dataset_name = "mutag"
dataset = CogDLDataset(name=dataset_name,
data_dir="../../data/")
from grb.model.torch import GCNGC
model_name = "gcngc"
model = GCNGC(in_features=dataset.num_features,
out_features=dataset.num_classes,
hidden_features=64,
n_layers=3,
residual=False,
dropout=0.5)
print("Number of parameters: {}.".format(utils.get_num_params(model)))
print(model)
save_dir = "./saved_models/{}/{}".format(dataset_name, model_name)
save_name = "model.pt"
device = "cuda:0"
batch_size = 20
from grb.trainer.trainer import GraphTrainer
trainer = GraphTrainer(dataset=dataset,
batch_size=batch_size,
optimizer=torch.optim.Adam(model.parameters(), lr=0.01),
loss=torch.nn.functional.cross_entropy,
lr_scheduler=False,
early_stop=True,
early_stop_patience=50,
device=device)
trainer.train(model=model,
n_epoch=200,
eval_every=1,
save_after=0,
save_dir=save_dir,
save_name=save_name,
verbose=False)
model = torch.load(os.path.join(save_dir, save_name))
model = model.to(device)
model.eval()
# by trainer
pred = trainer.inference(model)
# by trainer
test_score = trainer.evaluate(model, dataset.index_test)
print("Test score: {:.4f}".format(test_score))
| 0.567577 | 0.950041 |
# Recommendation System
## Knowledge Based
#### (Soumitra Dnyaneshwar Edake)
```
#imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import datetime
%matplotlib inline
```
### Build the DataFrames
```
def get_cleaned_df():
path_movies = 'data/movies_clean.csv'
path_reviews = 'data/reviews_clean.csv'
if not os.path.exists(path_reviews):
print('Cleaning REVIEW data')
reviews = pd.read_csv('data/ratings.dat', delimiter='::', header=None,
names=['user_id', 'movie_id', 'rating', 'timestamp'],
dtype={'movie_id': object, 'user_id': object, 'timestamp': object},
engine='python')
change_timestamp = lambda val: datetime.datetime.fromtimestamp(int(val)).strftime('%Y-%m-%d %H:%M:%S')
reviews['date'] = reviews['timestamp'].apply(change_timestamp)
print("Saving cleaned REVIEW data")
reviews.to_csv('data/reviews_clean.csv')
else:
print('Loading cleaned REVIEW data')
reviews = pd.read_csv('data/reviews_clean.csv')
if not os.path.exists(path_movies):
print('Cleaning MOVIE data')
movies = pd.read_csv('data/movies.dat', delimiter='::', header=None,
names=['movie_id', 'movie', 'genre'],
dtype={'movie_id': object},
engine='python')
movies = dummy_genres(movies)
movies = dummy_dates(movies)
print("Saving cleaned MOVIE data")
movies.to_csv('data/movies_clean.csv')
else:
print('Loading cleaned MOVIE data')
movies = pd.read_csv('data/movies_clean.csv')
print('done')
return movies, reviews
def get_split_genres(genres):
def split_genres(val):
try:
if val.find(gene) >-1:
return 1
else:
return 0
except AttributeError:
return 0
for gene in genres:
movies[gene] = movies['genre'].apply(split_genres)
return movies
def dummy_genres(movies):
genres = list()
for val in movies.genre:
try:
genres.extend(val.split('|'))
except AttributeError:
pass
genres = set(genres)
movies = get_split_genres(genres)
return movies
def get_add_movie_year():
def add_movie_year(val):
if val[:2] == yr:
return 1
else:
return 0
for yr in ['18', '19', '20']:
movies[str(yr) + "00's"] = movies['date'].apply(add_movie_year)
return movies
def dummy_dates(movies):
create_date = lambda val: val[-5:-1] if val[-1] == ')' else np.nan
movies['date'] = movies['movie'].apply(create_date)
movies = get_add_movie_year()
return movies
```
Load Cleaned DataFrames
```
movies, reviews = get_cleaned_df()
movies.columns, reviews.columns
del movies['Unnamed: 0']
del reviews['Unnamed: 0']
movies.columns, reviews.columns
```
Now we have our Dataset
```
movies.head()
reviews.head()
```
### Ranking System
```
def create_ranked_df(movies, reviews):
movie_ratings = reviews.groupby('movie_id')['rating']
avg_ratings = movie_ratings.mean()
num_ratings = movie_ratings.count()
last_rating = pd.DataFrame(reviews.groupby('movie_id').max()['date'])
last_rating.columns = ['last_rating']
rating_count_df = pd.DataFrame({'avg_rating': avg_ratings, 'num_ratings': num_ratings})
rating_count_df = rating_count_df.join(last_rating)
movie_recs = movies.set_index('movie_id').join(rating_count_df)
ranked_movies = movie_recs.sort_values(['avg_rating', 'num_ratings', 'last_rating'], ascending=False)
ranked_movies = ranked_movies[ranked_movies['num_ratings'] > 4]
return ranked_movies
def popular_recommendations(user_id, n_top, ranked_movies):
top_movies = list(ranked_movies['movie'][:n_top])
return top_movies
```
Using above functions, we get the array of movies ordered by popularity
```
ranked_movies = create_ranked_df(movies, reviews)
ranked_movies.head()
```
Now lets make some recommendations
```
user = '1202'
no_of_recommendations = 5
popular_recommendations(user, no_of_recommendations, ranked_movies)
user = '4302'
no_of_recommendations = 10
popular_recommendations(user, no_of_recommendations, ranked_movies)
```
For now, there is no use of user_id in the recommendation system, as we are
ranking the movies based on the knowledge we have like ratings and genre
### Adding a Filter system
```
def filter_rec(user_id, n_top, ranked_movies, years=None, genres=None):
if years is not None:
ranked_movies = ranked_movies[ranked_movies['date'].isin(years)]
if genres is not None:
num_genre_match = ranked_movies[genres].sum(axis=1)
ranked_movies = ranked_movies.loc[num_genre_match > 0, :]
# create top movies list
top_movies = list(ranked_movies['movie'][:n_top])
return top_movies
filter_rec('1', 20, ranked_movies, years=['2015', '2016', '2017', '2018'], genres=['History'])
filter_rec('53968', 5, ranked_movies, years=['2015', '2016', '2017', '2018'])
filter_rec('70000', 10, ranked_movies, genres=['History', 'News'])
```
And thats it /
|
github_jupyter
|
#imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import datetime
%matplotlib inline
def get_cleaned_df():
path_movies = 'data/movies_clean.csv'
path_reviews = 'data/reviews_clean.csv'
if not os.path.exists(path_reviews):
print('Cleaning REVIEW data')
reviews = pd.read_csv('data/ratings.dat', delimiter='::', header=None,
names=['user_id', 'movie_id', 'rating', 'timestamp'],
dtype={'movie_id': object, 'user_id': object, 'timestamp': object},
engine='python')
change_timestamp = lambda val: datetime.datetime.fromtimestamp(int(val)).strftime('%Y-%m-%d %H:%M:%S')
reviews['date'] = reviews['timestamp'].apply(change_timestamp)
print("Saving cleaned REVIEW data")
reviews.to_csv('data/reviews_clean.csv')
else:
print('Loading cleaned REVIEW data')
reviews = pd.read_csv('data/reviews_clean.csv')
if not os.path.exists(path_movies):
print('Cleaning MOVIE data')
movies = pd.read_csv('data/movies.dat', delimiter='::', header=None,
names=['movie_id', 'movie', 'genre'],
dtype={'movie_id': object},
engine='python')
movies = dummy_genres(movies)
movies = dummy_dates(movies)
print("Saving cleaned MOVIE data")
movies.to_csv('data/movies_clean.csv')
else:
print('Loading cleaned MOVIE data')
movies = pd.read_csv('data/movies_clean.csv')
print('done')
return movies, reviews
def get_split_genres(genres):
def split_genres(val):
try:
if val.find(gene) >-1:
return 1
else:
return 0
except AttributeError:
return 0
for gene in genres:
movies[gene] = movies['genre'].apply(split_genres)
return movies
def dummy_genres(movies):
genres = list()
for val in movies.genre:
try:
genres.extend(val.split('|'))
except AttributeError:
pass
genres = set(genres)
movies = get_split_genres(genres)
return movies
def get_add_movie_year():
def add_movie_year(val):
if val[:2] == yr:
return 1
else:
return 0
for yr in ['18', '19', '20']:
movies[str(yr) + "00's"] = movies['date'].apply(add_movie_year)
return movies
def dummy_dates(movies):
create_date = lambda val: val[-5:-1] if val[-1] == ')' else np.nan
movies['date'] = movies['movie'].apply(create_date)
movies = get_add_movie_year()
return movies
movies, reviews = get_cleaned_df()
movies.columns, reviews.columns
del movies['Unnamed: 0']
del reviews['Unnamed: 0']
movies.columns, reviews.columns
movies.head()
reviews.head()
def create_ranked_df(movies, reviews):
movie_ratings = reviews.groupby('movie_id')['rating']
avg_ratings = movie_ratings.mean()
num_ratings = movie_ratings.count()
last_rating = pd.DataFrame(reviews.groupby('movie_id').max()['date'])
last_rating.columns = ['last_rating']
rating_count_df = pd.DataFrame({'avg_rating': avg_ratings, 'num_ratings': num_ratings})
rating_count_df = rating_count_df.join(last_rating)
movie_recs = movies.set_index('movie_id').join(rating_count_df)
ranked_movies = movie_recs.sort_values(['avg_rating', 'num_ratings', 'last_rating'], ascending=False)
ranked_movies = ranked_movies[ranked_movies['num_ratings'] > 4]
return ranked_movies
def popular_recommendations(user_id, n_top, ranked_movies):
top_movies = list(ranked_movies['movie'][:n_top])
return top_movies
ranked_movies = create_ranked_df(movies, reviews)
ranked_movies.head()
user = '1202'
no_of_recommendations = 5
popular_recommendations(user, no_of_recommendations, ranked_movies)
user = '4302'
no_of_recommendations = 10
popular_recommendations(user, no_of_recommendations, ranked_movies)
def filter_rec(user_id, n_top, ranked_movies, years=None, genres=None):
if years is not None:
ranked_movies = ranked_movies[ranked_movies['date'].isin(years)]
if genres is not None:
num_genre_match = ranked_movies[genres].sum(axis=1)
ranked_movies = ranked_movies.loc[num_genre_match > 0, :]
# create top movies list
top_movies = list(ranked_movies['movie'][:n_top])
return top_movies
filter_rec('1', 20, ranked_movies, years=['2015', '2016', '2017', '2018'], genres=['History'])
filter_rec('53968', 5, ranked_movies, years=['2015', '2016', '2017', '2018'])
filter_rec('70000', 10, ranked_movies, genres=['History', 'News'])
| 0.272315 | 0.637849 |
# IPython-Magie
IPython ermöglicht nicht nur Python interaktiv zu verwenden, sondern erweitert auch die Python-Syntax um sog. *Magic Commands*, die mit dem Präfix `%` versehen werden. Sie wurden entwickelt, um häufig auftretende Probleme bei der Datenanalyse schnell und einfach lösen zu können. Dabei wird zwischen zwei verschiedenen Arten von *Magic Commands* unterschieden:
* *line magics*, die durch einen einzelnen `%`-Präfix gekennzeichnet sind und auf einer einzelnen Eingabezeile ausgeführt werden
* *cell magics*, denen ein doppeltes Symbol `%%` vorangestellt wird und die innerhalb einer Notebook-Zelle ausgeführt werden.
## Externen Code ausführen: `%run`
Wenn ihr anfangt, umfangreicheren Code zu entwickeln, arbeitet ihr vermutlich sowohl in IPython für interaktive Erkundungen als auch in einem Texteditor zum Speichern von Code, den ihr wiederverwenden möchtet. Mit der `%run`-Magie könnt ihr diesen Code direkt in eurer IPython-Sitzung ausführen.
Stellt euch vor, ihr hättet eine `myscript.py`-Datei mit folgendem Inhalt erstellt:
``` Python
def square(x):
return x ** 2
for N in range(1, 4):
print(N, "squared is", square(N))
```
```
%run myscript.py
```
Beachtet, dass nach dem Ausführen dieses Skripts alle darin definierten Funktionen für die Verwendung in eurer IPython-Sitzung verfügbar sind:
```
square(4)
```
Es gibt verschiedene Möglichkeiten, die Ausführung eures Codes zu verbessern. Wie üblich, könnt ihr euch die Dokumentation in IPython anzeigen lassen mit `%run?`.
## Timing-Code ausführen: `%timeit`
Ein weiteres Beispiel für eine Magic-Funktion ist `%timeit`, die automatisch die Ausführungszeit der darauf folgenden einzeiligen Python-Anweisung ermittelt. So können wir uns z.B. die Performance einer *list comprehension* ausgeben lassen mit:
```
%timeit L = [n ** 2 for n in range(1000)]
```
Der Vorteil von `%timeit` ist, dass bei kurzen Befehlen automatisch mehrere Läufe ausgeführt werden, um robustere Ergebnisse zu erzielen. Bei mehrzeiligen Anweisungen wird durch Hinzufügen eines zweiten `%`-Zeichens eine Zellenmagie erzeugt, die mehrere Eingabezeilen verarbeiten kann. Hier ist zum Beispiel die äquivalente Konstruktion mit einer `for`-Schleife:
```
%%timeit
L = []
for n in range(1000):
L.append(n ** 2)
```
Wir können sofort erkennen, dass die *list comprehension* etwa 10% schneller ist als das entsprechende Äquivalent mit einer `for` Schleife. Ausführlicher beschreiben wir Performance-Messungen und -Optimierungen dann in [Profiling](../../refactoring/performance/ipython-profiler.ipynb).
## Code anderer Interpreter ausführen
IPython verfügt über eine `%%script`-Magie, mit der ihr eine Zelle in einem Unterprozess eines Interpreters auf eurem System ausführen könnt, z.B. `bash`, `ruby`, `perl`, `zsh`, `R` usw. Dies kann auch ein eigenes Skript sein, das Eingaben in ` stdin` erwartet. Hierzu wird einfach eine Pfadangabe oder ein Shell-Befehl an das Programm übergeben, das in der `%%script`-Zeile angegeben ist. Der Rest der Zelle wird von diesem Skript ausgeführt, `stdout` oder `err` aus dem Unterprozess erfasst und angezeigt.
```
%%script python2
import sys
print 'Python %s' % sys.version
%%script python3
import sys
print('Python: %s' % sys.version)
%%ruby
puts "Ruby #{RUBY_VERSION}"
%%bash
echo "$BASH"
```
Ihr könnt `stdout` und `err` aus diesen Unterprozessen in Python-Variablen erfassen:
```
%%bash --out output --err error
echo "stdout"
echo "stderr" >&2
print(error)
print(output)
```
## Standard-`script`-Magie konfigurieren
Die Liste der Aliase für die `script`-Magie ist konfigurierbar. Standardmäßig können ggf. einige gängige Interpreter verwendet werden. Ihr könnt jedoch in `ipython_config.py` auch eigene Interpreter angeben:
```
c.ScriptMagics.scripts = ['R', 'pypy', 'myprogram']
c.ScriptMagics.script_paths = {'myprogram': '/path/to/myprogram'}
```
## Hilfe-Funktionen: `?`, `%magic` und `%lsmagic`
Wie normale Python-Funktionen verfügen auch die magischen IPython-Funktionen über *docstrings*, auf die einfach zugegriffen werden können. Um z.B. die Dokumentation der `%timeit`-Magie zu lesen, gebt einfach Folgendes ein:
```
%timeit?
```
Auf die Dokumentation für andere Funktionen kann auf ähnliche Weise zugegriffen werden. Um auf eine allgemeine Beschreibung der verfügbaren `%magic`-Funktionen einschließlich einiger Beispiele zuzugreifen, könnt ihr Folgendes eingeben:
```
%magic
```
Um schnell eine Liste aller verfügbaren `magic`-Funktionen zu erhalten, gebt Folgendes ein:
```
%lsmagic
```
Ihr könnt auch einfach eure eigenen `magic`-Funktionen definieren. Weitere Informationen hierzu erhaltet ihr unter [Defining custom magics](https://ipython.readthedocs.io/en/stable/config/custommagics.html).
|
github_jupyter
|
Beachtet, dass nach dem Ausführen dieses Skripts alle darin definierten Funktionen für die Verwendung in eurer IPython-Sitzung verfügbar sind:
Es gibt verschiedene Möglichkeiten, die Ausführung eures Codes zu verbessern. Wie üblich, könnt ihr euch die Dokumentation in IPython anzeigen lassen mit `%run?`.
## Timing-Code ausführen: `%timeit`
Ein weiteres Beispiel für eine Magic-Funktion ist `%timeit`, die automatisch die Ausführungszeit der darauf folgenden einzeiligen Python-Anweisung ermittelt. So können wir uns z.B. die Performance einer *list comprehension* ausgeben lassen mit:
Der Vorteil von `%timeit` ist, dass bei kurzen Befehlen automatisch mehrere Läufe ausgeführt werden, um robustere Ergebnisse zu erzielen. Bei mehrzeiligen Anweisungen wird durch Hinzufügen eines zweiten `%`-Zeichens eine Zellenmagie erzeugt, die mehrere Eingabezeilen verarbeiten kann. Hier ist zum Beispiel die äquivalente Konstruktion mit einer `for`-Schleife:
Wir können sofort erkennen, dass die *list comprehension* etwa 10% schneller ist als das entsprechende Äquivalent mit einer `for` Schleife. Ausführlicher beschreiben wir Performance-Messungen und -Optimierungen dann in [Profiling](../../refactoring/performance/ipython-profiler.ipynb).
## Code anderer Interpreter ausführen
IPython verfügt über eine `%%script`-Magie, mit der ihr eine Zelle in einem Unterprozess eines Interpreters auf eurem System ausführen könnt, z.B. `bash`, `ruby`, `perl`, `zsh`, `R` usw. Dies kann auch ein eigenes Skript sein, das Eingaben in ` stdin` erwartet. Hierzu wird einfach eine Pfadangabe oder ein Shell-Befehl an das Programm übergeben, das in der `%%script`-Zeile angegeben ist. Der Rest der Zelle wird von diesem Skript ausgeführt, `stdout` oder `err` aus dem Unterprozess erfasst und angezeigt.
Ihr könnt `stdout` und `err` aus diesen Unterprozessen in Python-Variablen erfassen:
## Standard-`script`-Magie konfigurieren
Die Liste der Aliase für die `script`-Magie ist konfigurierbar. Standardmäßig können ggf. einige gängige Interpreter verwendet werden. Ihr könnt jedoch in `ipython_config.py` auch eigene Interpreter angeben:
## Hilfe-Funktionen: `?`, `%magic` und `%lsmagic`
Wie normale Python-Funktionen verfügen auch die magischen IPython-Funktionen über *docstrings*, auf die einfach zugegriffen werden können. Um z.B. die Dokumentation der `%timeit`-Magie zu lesen, gebt einfach Folgendes ein:
Auf die Dokumentation für andere Funktionen kann auf ähnliche Weise zugegriffen werden. Um auf eine allgemeine Beschreibung der verfügbaren `%magic`-Funktionen einschließlich einiger Beispiele zuzugreifen, könnt ihr Folgendes eingeben:
Um schnell eine Liste aller verfügbaren `magic`-Funktionen zu erhalten, gebt Folgendes ein:
| 0.421076 | 0.822153 |
JAX-TensorFlow interoperation with JAX2TF
============================================================
Link: go/jax2tf-colab
*Contact: [email protected], [email protected] (September 2020)*
[](https://colab.sandbox.google.com/github/google/jax/blob/master/jax/experimental/jax2tf/JAX2TF_getting_started.ipynb)
This Colab demonstrates how to take a model written and trained in JAX
(or Flax), and convert it with [JAX2TF](https://github.com/google/jax/tree/master/jax/experimental/jax2tf) in order to use
TensorFlow tools on it. We will demonstrate saving to SavedModel,
reusing it in TF Hub, optionally with fine tuning.
# Overview
The section ["Getting started with JAX2TF"](#scrollTo=yUShtu6TOYkw)
shows the basics of using JAX2TF on a very simple JAX function,
converting it for execution with TF, and then saving it to SavedModel.
Then we prepare for the MNIST example; we show how to use TF DataSets to
load the MNIST training data, and preprocess it with tf.data (["Get
MNIST data from TensorFlow DataSets"](#scrollTo=lc3QJa3NVx4B)). In ["MNIST in pure JAX"](#scrollTo=BjB03X9pzblu) we
define and train an MNIST model using pure JAX (for the reader who prefers fewer abstractions).
In ["MNIST in Flax"](#scrollTo=ALKaq_cL8fTj) we show how to define and
train an MNIST model using Flax, obtaining again a predictor and a set
of parameters.
All the cells up to this point are independent of JAX2TF. In order to
set the stage for JAX2TF conversion and saving to SavedModel, we
express the trained model, whether in pure JAX or Flax, as a pair:
* **func**: a function with signature:
```(params: Parameters, images: BatchedImages) -> Predictions```
* **params**: of type ```Parameters```, the model parameters as a list
or tuple or dictionaries of arrays. We expose the parameters
like this because when we prepare the SavedModel, we will want to
process them with ```tf.nest.map_structure``` to create
```tf.Variable```s.
The more interesting part starts in
["Export to SavedModel"](#scrollTo=Og3FPMFNXRd9) where we show how to
export the trained models to TF so that we can save it in a SavedModel.
All you need here is a pair of a predictor and the parameters,
independent of how you wrote those with JAX or Flax.
In ["Reuse with Keras of the MNIST feature extractor"](#scrollTo=Fhm2kxL_gIF5)
we show how to reuse only the feature extractor (all but the last layer)
of the JAX-trained model, in a Keras model with its own
classification layer, trained in Keras.
**Credits**: the model code is inspired by (go/mnist-jax-colab).
# Getting started with JAX2TF
Connect this Colab to a runtime that includes for JAX and TF, e.g.,
the public Colab hosted runtime.
We have tested with CPU/GPU/TPU runtimes (for the TPU runtime
the `with tf.device` context managers are important.)
```
import time
from typing import Any, Callable, Optional, Sequence, Tuple
import jax
import jax.numpy as jnp
from jax.experimental import jax2tf
import numpy as np
import tensorflow as tf
# A simple JAX function, using jit and grad and a couple of jax.numpy functions
hello_jax = jax.jit(jax.grad(lambda x: jnp.log(jnp.cos(x))))
x = 0.42
print(f"hello_jax(x) = {hello_jax(x)}")
```
We apply the ```jax2tf.convert``` wrapper to ```demo_jax``` to obtain a
function that executes **exactly as if it were written entirely with TF
ops**. This is what will enable us to use the resulting function in
a TF environment, e.g., to execute it eagerly, in graph mode, and even
with the XLA compiler, and to save it in a SavedModel.
```
hello_tf = jax2tf.convert(hello_jax)
print(f"Execute with TF eager: hello_tf(x) = {hello_tf(x)}")
# It is best to turn of autograph to avoid some warnings.
hello_tf_graph = tf.function(hello_tf, autograph=False)
print(f"Execute with TF graph: hello_tf_graph(x) = {hello_tf_graph(x)}")
hello_tf_graph_compiled = tf.function(hello_tf, autograph=False, experimental_compile=True)
print(f"Execute with TF graph: hello_tf_graph_compiled(x) = {hello_tf_graph_compiled(x)}")
```
You can inspect the TF graph and see that it contains a bunch of TF ops:
```
graph_def = hello_tf_graph.get_concrete_function(x).graph.as_graph_def()
#TODO: colab.tfgraph.display(graph=graph_def)
print(graph_def)
```
We can even differentiate the converted function, and the result is
guaranteed to be the same as if we differentiated it in JAX, and this
even if we had JAX custom gradients defined. (This is achieved by using
[tf.custom_gradient](https://www.tensorflow.org/api_docs/python/tf/custom_gradient)
to call back into the JAX autodiff machinery and convert to TF
the JAX gradient function.)
```
print(f"hello_jax_grad(x) = {jax.grad(hello_jax)(x)}")
x_v = tf.Variable(x)
with tf.GradientTape() as tape:
tape.watch(x_v)
y = hello_tf(x_v)
print(f"hello_tf_grad(x) = {tape.gradient(y, x_v)}")
```
Since ```hello_tf``` behaves like any TF function, we can put it
into a SavedModel, using **standard** TF
[tools](https://www.tensorflow.org/guide/saved_model):
```
hello_model = tf.Module()
hello_model.f = tf.function(hello_tf,
autograph=False, # Avoid warnings
input_signature=[tf.TensorSpec([], tf.float32)])
hello_dir = '/tmp/jax2tf/hello'
tf.saved_model.save(hello_model, hello_dir)
# Restoring (note: the restored model does *not* require JAX to run, just XLA).
restored_model = tf.saved_model.load(hello_dir)
print(f"restored_model(x) = {restored_model.f(x)}")
```
# Define and train MNIST
## Get MNIST data from TensorFlow DataSets
```
from matplotlib import pyplot as plt
import tensorflow_datasets as tfds
def load_mnist(split: tfds.Split, batch_size: int,
one_hot_label: bool, drop_remainder=False):
"""Loads either training or test MNIST data.
Returns:
an iterator with pairs (images, labels). The images have shape
(B, 28, 28, 1) and the labels have shape (B, 10), where B is the batch_size.
"""
# TODO: drop the one_hot_label parameter, so that the shapes are indeed as
# documented.
ds = tfds.load('mnist', split=split)
def _prepare_example(x):
image = tf.cast(x['image'], tf.float32) / 255.0
label = tf.cast(x['label'], tf.int32)
if one_hot_label:
label = tf.one_hot(x['label'], 10)
return (image, label)
ds = ds.map(_prepare_example)
ds = ds.cache().shuffle(1000).batch(batch_size, drop_remainder=drop_remainder)
return ds
# For fun, let's use different batch sizes for training and for evaluation.
train_batch_size = 128
eval_batch_size = 16
train_ds = load_mnist(tfds.Split.TRAIN, one_hot_label=True,
batch_size=train_batch_size)
test_ds = load_mnist(tfds.Split.TEST, one_hot_label=True,
batch_size=eval_batch_size)
def plot_images(ds, nr_rows: int, nr_cols: int, is_predicted: bool = True):
"""Plots a grid of images with their predictions"""
count = nr_rows * nr_cols
fig = plt.figure(figsize=(8., 4.))
for batch in tfds.as_numpy(train_ds.take(1)):
images, labels = batch
for i, image in enumerate(images[:count]):
one = fig.add_subplot(nr_rows, nr_cols, i+1)
one.set_title(f"{'pred' if is_predicted else 'label'}={np.argmax(labels[i])}")
plt.imshow((np.reshape(image, (28, 28)) * 255).astype(np.uint8),
interpolation='nearest')
plt.show()
plot_images(train_ds, 1, 5, is_predicted=False)
# Define common parameters for both the JAX and the Flax models.
input_shape = (28, 28, 1) # Excluding batch_size
layer_sizes = [784, 512, 512, 10] # 10 is the number of classes
param_scale = 0.1
step_size = 0.001
num_epochs = 3
```
## MNIST in pure JAX
This is an example that uses just JAX, without any high-level
libraries for readers who prefer fewer moving parts, at the expense
of code size. See [below](#scrollTo=ALKaq_cL8fTj) a shorter example
using Flax.
We define MNIST in two parts, the feature extractor and the classifier.
We plan to share the feature extractor as a SavedModel and allow
reusing it in Keras with a different classifier (see
[below](#scrollTo=Fhm2kxL_gIF5)).
```
class PureJaxMNIST:
"""Encapsulates the pure JAX MNIST model and training."""
@staticmethod
def feature_extractor(extractor_params: Sequence[Tuple[Any, Any]],
inputs):
# The feature extraction parts of MNIST, without the classifier layer.
# Args:
# extractor_params: for each layer, the pair of weights and biases
# inputs: the batch of images (B, 28, 28, 1)
# Returns:
# features: of shape (B, 512)
x = inputs.reshape((inputs.shape[0], -1)) # flatten to f32[B, 784]
for w, b in extractor_params:
x = jnp.dot(x, w) + b
x = jnp.tanh(x)
return x
@staticmethod
def classifier(classifier_params: Tuple[Any, Any], features):
# Args:
# classifier_params: the pair of weights and biases for the classifier
# features: the extracted features (B, 512)
# Returns:
# the predictions (B, 10)
w, b = classifier_params
logits = jnp.dot(features, w) + b
return logits - jax.scipy.special.logsumexp(logits, axis=1, keepdims=True)
@staticmethod
def predict(params: Sequence[Tuple[Any, Any]], inputs):
# Args:
# params: a list with the extractor_params and the classifier_params (at
# the tail)
# inputs: the batch of images (B, 28, 28, 1)
# Returns:
# the predictions (B, 10)
features = PureJaxMNIST.feature_extractor(params[:-1], inputs)
predictions = PureJaxMNIST.classifier(params[-1], features)
return predictions
@staticmethod
def loss(params, inputs, labels):
predictions = PureJaxMNIST.predict(params, inputs)
return -jnp.mean(jnp.sum(predictions * labels, axis=1))
@staticmethod
def accuracy(predict: Callable, params, dataset):
@jax.jit
def _per_batch(inputs, labels):
target_class = jnp.argmax(labels, axis=1)
predicted_class = jnp.argmax(predict(params, inputs), axis=1)
return jnp.mean(predicted_class == target_class)
batched = [_per_batch(inputs, labels) for inputs, labels in tfds.as_numpy(dataset)]
return jnp.mean(jnp.stack(batched))
@staticmethod
def update(params, inputs, labels):
grads = jax.grad(PureJaxMNIST.loss)(params, inputs, labels)
return [(w - step_size * dw, b - step_size * db)
for (w, b), (dw, db) in zip(params, grads)]
@staticmethod
def train():
"""Trains a pure JAX MNIST predictor.
Returns:
a tuple with four elements:
- a predictor function with signature "(Params, ImagesBatch) -> Predictions"
- the parameters "Params" for the predictor function
- a feature extractor function with signature
"(ExtractorParams, ImagesBatch) -> Features"
- the parameters "ExtractorParams" for the feature extractor function
"""
rng = jax.random.PRNGKey(0)
params = [
(param_scale * jax.random.normal(rng, (m, n)),
param_scale * jax.random.normal(rng, (n,)))
for m, n, in zip(layer_sizes[:-1], layer_sizes[1:])]
for epoch in range(num_epochs):
start_time = time.time()
for inputs, labels in tfds.as_numpy(train_ds):
params = jax.jit(PureJaxMNIST.update)(params, inputs, labels)
epoch_time = time.time() - start_time
train_acc = PureJaxMNIST.accuracy(PureJaxMNIST.predict, params, train_ds)
test_acc = PureJaxMNIST.accuracy(PureJaxMNIST.predict, params, test_ds)
print("Epoch {} in {:0.2f} sec".format(epoch, epoch_time))
print("Training set accuracy {}".format(train_acc))
print("Test set accuracy {}".format(test_acc))
return (PureJaxMNIST.predict, params,
PureJaxMNIST.feature_extractor, params[:-1])
(pure_predict, pure_params,
pure_feature_extractor, pure_extractor_params) = PureJaxMNIST.train()
# Plot a few predictions for the first batch of the test set
plot_images([(images, pure_predict(pure_params, images))
for images, _ in tfds.as_numpy(test_ds.take(1))],
1, 5, is_predicted=True)
```
## MNIST in Flax
This follows the structure of the
[MNIST Flax (Linen) example](https://github.com/google/flax/blob/master/linen_examples/mnist/mnist_lib.py).
```
!pip install flax
import flax
from flax import linen as nn
class FlaxMNIST:
"""Encapsulates the Flax MNIST model and training."""
class FeatureExtractorModule(nn.Module):
"""A simple CNN model for MNIST, with only the feature extraction parts."""
@nn.compact
def __call__(self, x):
x = nn.Conv(features=32, kernel_size=(3, 3))(x)
x = nn.relu(x)
x = nn.avg_pool(x, window_shape=(2, 2), strides=(2, 2))
x = nn.Conv(features=64, kernel_size=(3, 3))(x)
x = nn.relu(x)
x = nn.avg_pool(x, window_shape=(2, 2), strides=(2, 2))
x = x.reshape((x.shape[0], -1)) # flatten
x = nn.Dense(features=256)(x)
x = nn.relu(x)
return x
@staticmethod
def feature_extractor(extractor_params, inputs):
"""A functional interface to the trained FeatureExtractorModule."""
return FlaxMNIST.FeatureExtractorModule().apply({'params': extractor_params},
inputs)
class Module(nn.Module):
"""The whole model."""
def setup(self):
self.feature_extractor = FlaxMNIST.FeatureExtractorModule()
@nn.compact
def __call__(self, x):
x = self.feature_extractor(x)
x = nn.Dense(features=10)(x)
x = nn.log_softmax(x)
return x
@staticmethod
def predict(params, inputs):
"""A functional interface to the trained Module."""
return FlaxMNIST.Module().apply({'params': params}, inputs)
@staticmethod
def loss(params, inputs, labels): # Same as the pure JAX example
predictions = FlaxMNIST.predict(params, inputs)
return -jnp.mean(jnp.sum(predictions * labels, axis=1))
@staticmethod
def update(optimizer, inputs, labels):
grad = jax.grad(FlaxMNIST.loss)(optimizer.target, inputs, labels)
optimizer = optimizer.apply_gradient(grad)
return optimizer
@staticmethod
def train():
"""Trains a pure JAX MNIST predictor.
Returns:
a tuple with four elements:
- a predictor function with signature "(Params, ImagesBatch) -> Predictions"
- the parameters "Params" for the predictor function
- a feature extractor function with signature
"(ExtractorParams, ImagesBatch) -> Features"
- the parameters "ExtractorParams" for the feature extractor function
"""
rng = jax.random.PRNGKey(0)
momentum_mass = 0.9
init_shape = jnp.ones((1,) + input_shape, jnp.float32)
initial_params = FlaxMNIST.Module().init(rng, init_shape)["params"]
optimizer_def = flax.optim.Momentum(learning_rate=step_size, beta=momentum_mass)
optimizer = optimizer_def.create(initial_params)
for epoch in range(num_epochs):
start_time = time.time()
for inputs, labels in tfds.as_numpy(train_ds):
optimizer = jax.jit(FlaxMNIST.update)(optimizer, inputs, labels)
epoch_time = time.time() - start_time
# Same accuracy function as for the pure JAX example
train_acc = PureJaxMNIST.accuracy(FlaxMNIST.predict, optimizer.target, train_ds)
test_acc = PureJaxMNIST.accuracy(FlaxMNIST.predict, optimizer.target, test_ds)
print("Epoch {} in {:0.2f} sec".format(epoch, epoch_time))
print("Training set accuracy {}".format(train_acc))
print("Test set accuracy {}".format(test_acc))
return (FlaxMNIST.predict, optimizer.target,
FlaxMNIST.feature_extractor, optimizer.target["feature_extractor"])
(flax_predict, flax_params,
flax_feature_extractor, flax_extractor_params) = FlaxMNIST.train()
# Plot predictions for the first batch of the test set
plot_images([(images, flax_predict(flax_params, images))
for images, _ in tfds.as_numpy(test_ds.take(1))],
1, 5, is_predicted=True)
```
# Export to SavedModel
Follow [reusable SavedModel guidelines](https://www.tensorflow.org/hub/reusable_saved_models).
This wrapper class adapts between the Reusable SavedModel API
and the style in which a JAX model is built. Going forward,
there can probably be a generic adapter class for each modeling
library (such as Flax).
```
class ExportWrapper(tf.train.Checkpoint):
def __init__(self, fn: Callable, params,
input_shape: Sequence[int],
batch_sizes: Sequence[int]):
"""
Args:
fn: a function taking two arguments, the parameters and the batch of
images.
params: the parameters, as a list/tuple/dictionary of np.ndarray, to be
used as first argument for `fn`.
input_shape: the shape of the second argument of `fn` (except the batch size)
batch_sizes: a sequence of batch sizes for which to save the function.
"""
super().__init__()
# Convert fn from JAX to TF.
with_gradient = False # Avoid b/123499169.
self._fn = jax2tf.convert(fn, with_gradient=with_gradient)
# Create tf.Variables for the parameters.
self._params = tf.nest.map_structure(
# If with_gradient=False, we mark the variables behind as non-trainable,
# or else the Keras model below fails for trying to access them
# (even with hub.KerasLayer(..., trainable=False), surprisingly).
lambda param: tf.Variable(param, trainable=with_gradient),
params)
self._signatures = {}
# Implement the interface from https://www.tensorflow.org/hub/reusable_saved_models
self.variables = tf.nest.flatten(self._params)
self.trainable_variables = [v for v in self.variables if v.trainable]
for training in (True, False):
# TODO: batch_size should be None, and nothing else.
for batch_size in batch_sizes:
input_spec = tf.TensorSpec([batch_size] + list(input_shape), tf.float32)
cf = self.__call__.get_concrete_function(input_spec, training=training)
# If you intend to prescribe regularization terms for users of the model,
# add them as @tf.functions with no inputs to this list. Else drop this.
self.regularization_losses = []
@tf.function(autograph=False)
def __call__(self, inputs, training=False):
del training # Unused for now.
# Future directions:
# - If _fn depends on mode (training or inference), pass on `training`.
# - If _fn depens on numeric hyperparameters (e.g., dropout rate),
# add them as kwargs that have a Python constant as default but
# get traced with tf.TensorSpec([], ...).
# - If _fn needs to execute update ops during training, e.g., to update
# batch norm's aggregate stats, make them happen as control dependencies
# on outputs if training is true.
outputs = self._fn(self._params, inputs)
return outputs
def save_model(fn: Callable, params,
model_dir: str, *, batch_sizes: Optional[Sequence[int]] = None):
"""Saves the SavedModel for a function"""
batch_sizes = batch_sizes or [1, eval_batch_size, train_batch_size]
wrapper = ExportWrapper(
fn, params, input_shape,
batch_sizes=batch_sizes)
print(f"Saving the model to {model_dir}")
tf.saved_model.save(wrapper, model_dir)
# Export the full trained model (pure JAX).
pure_predict_model_dir = "/tmp/jax2tf/pure_mnist_full_model"
save_model(pure_predict, pure_params, pure_predict_model_dir)
# Export the feature extractor only (pure JAX).
pure_feature_extractor_model_dir = "/tmp/jax2tf/pure_mnist_features"
save_model(pure_feature_extractor, pure_extractor_params, pure_feature_extractor_model_dir)
# Export the full trained model (Flax)
flax_predict_model_dir = "/tmp/jax2tf/flax_mnist_full_model"
save_model(flax_predict, flax_params, flax_predict_model_dir)
# Export the feature extractor only (Flax)
flax_feature_extractor_model_dir = "/tmp/jax2tf/flax_mnist_features"
save_model(flax_feature_extractor, flax_extractor_params, flax_feature_extractor_model_dir)
```
Congrats!
Reusable SavedModels like these can be shared with TensorFlow users on
the filesystem or by [ publishing on TF Hub ]( https://www.tensorflow.org/hub/exporting_tf2_saved_model )
.
## Import and run the SavedModels
Those SavedModels can now be imported into TensorFlow.
TensorFlow sometimes requires an explicit `with tf.device(tf_accelerator): ...` context to use the same accelerator as JAX, esp. for TPUs. We pick the best we can find in the colab runtime.
```
tf_accelerator = (tf.config.list_logical_devices("TPU") +
tf.config.list_logical_devices("GPU") +
tf.config.list_logical_devices("CPU"))[0]
print(f"Using tf_accelerator = {tf_accelerator}")
```
When comparing models between JAX and TF, we observed varying numerical tolerances depending on device type.
```
if tf_accelerator.device_type == "TPU":
tolerances = dict(atol=0, rtol=0) # Wow! Worked Sep '20. May need loosening.
elif tf_accelerator.device_type == "GPU":
tolerances = dict(atol=1e-6, rtol=1e-4)
elif tf_accelerator.device_type == "CPU":
tolerances = dict(atol=1e-5, rtol=1e-5)
print("Using", tolerances)
```
The following code block shows how to load the full JAX model in low-level TF,
and tests that it behaves the same as in JAX.
NOTE: You can replace tf.saved_model.load() by hub.load()
to make it work on TF Hub handles in addition to ordinary filesystem paths.
```
with tf.device(tf_accelerator):
pure_restored_full_model = tf.saved_model.load(pure_predict_model_dir)
test_input = np.ones([eval_batch_size] + list(input_shape), dtype=np.float32)
np.testing.assert_allclose(pure_restored_full_model(tf.convert_to_tensor(test_input)),
pure_predict(pure_params, test_input),
**tolerances)
# Plot predictions for the first batch of the test set
plot_images([(images, pure_restored_full_model(tf.convert_to_tensor(images)))
for images, _ in tfds.as_numpy(test_ds.take(1))],
1, 5, is_predicted=True)
```
Now the same thing for the Flax model.
```
with tf.device(tf_accelerator):
flax_restored_full_model = tf.saved_model.load(flax_predict_model_dir)
test_input = np.ones([eval_batch_size] + list(input_shape), dtype=np.float32)
np.testing.assert_allclose(flax_restored_full_model(tf.convert_to_tensor(test_input)),
flax_predict(flax_params, test_input),
**tolerances)
# Plot predictions for the first batch of the test set
plot_images([(images, flax_restored_full_model(tf.convert_to_tensor(images)))
for images, _ in tfds.as_numpy(test_ds.take(1))],
1, 5, is_predicted=True)
```
# Reuse in Keras of the MNIST feature extractor
The feature extractor model can be imported in TensorFlow
to train a new classifier on top of it.
For ease of training, we show this with the high-level Keras API,
but it should also be possible in low-level TensorFlow (using the
restored_features under a tf.GradientTape and doing gradient updates
manually).
With Keras, we use the `tf.distribute.OneDeviceStrategy`
as the high-level analogue of the `tf.device(...)` placement seen above.
It works on CPU, GPU and TPU.
Actual high-performance training would use the appropriatey replicated
[TF Distribution Strategy](https://www.tensorflow.org/guide/distributed_training).
```
#@title Choose the model {form-width: "25%"}
import tensorflow_hub as hub
model_choice = "Flax" #@param["Flax", "Pure JAX"]
if model_choice == "Pure JAX":
feature_extractor_model_dir = pure_feature_extractor_model_dir
feature_extractor = pure_feature_extractor
feature_extractor_params = pure_extractor_params
else:
feature_extractor_model_dir = flax_feature_extractor_model_dir
feature_extractor = flax_feature_extractor
feature_extractor_params = flax_extractor_params
strategy = tf.distribute.OneDeviceStrategy(tf_accelerator)
with strategy.scope():
images = tf.keras.layers.Input(input_shape, batch_size=128)
keras_feature_extractor = hub.KerasLayer(feature_extractor_model_dir, trainable=False)
features = keras_feature_extractor(images)
predictor = tf.keras.layers.Dense(10, activation='softmax')
predictions = predictor(features)
keras_model = tf.keras.Model(images, predictions)
```
The imported feature_extractor behaves the same as the JAX original.
```
with tf.device(tf_accelerator):
np.testing.assert_allclose(keras_feature_extractor(tf.convert_to_tensor(test_input)),
feature_extractor(feature_extractor_params, test_input),
**tolerances)
```
Now train the new classifier on top.
```
print(f"Using feature extractor: {model_choice}")
keras_model.compile(loss=tf.keras.losses.categorical_crossentropy,
optimizer=tf.keras.optimizers.SGD(learning_rate=0.01),
metrics=['accuracy'])
print(keras_model.summary())
train_ds = load_mnist(tfds.Split.TRAIN, one_hot_label=True,
batch_size=train_batch_size, drop_remainder=True)
test_ds = load_mnist(tfds.Split.TEST, one_hot_label=True,
batch_size=eval_batch_size, drop_remainder=True)
keras_model.fit(train_ds, epochs=3,
validation_data=test_ds)
# Plot predictions for the first batch of the test set
plot_images([(images, keras_model(tf.convert_to_tensor(images)))
for images, _ in tfds.as_numpy(test_ds.take(1))],
1, 5, is_predicted=True)
```
The imported feature_extractor behaves the same as the JAX original.
```
with tf.device(tf_accelerator):
np.testing.assert_allclose(keras_feature_extractor(tf.convert_to_tensor(test_input)),
feature_extractor(feature_extractor_params, test_input),
**tolerances)
```
|
github_jupyter
|
* **params**: of type ```Parameters```, the model parameters as a list
or tuple or dictionaries of arrays. We expose the parameters
like this because when we prepare the SavedModel, we will want to
process them with ```tf.nest.map_structure``` to create
```tf.Variable```s.
The more interesting part starts in
["Export to SavedModel"](#scrollTo=Og3FPMFNXRd9) where we show how to
export the trained models to TF so that we can save it in a SavedModel.
All you need here is a pair of a predictor and the parameters,
independent of how you wrote those with JAX or Flax.
In ["Reuse with Keras of the MNIST feature extractor"](#scrollTo=Fhm2kxL_gIF5)
we show how to reuse only the feature extractor (all but the last layer)
of the JAX-trained model, in a Keras model with its own
classification layer, trained in Keras.
**Credits**: the model code is inspired by (go/mnist-jax-colab).
# Getting started with JAX2TF
Connect this Colab to a runtime that includes for JAX and TF, e.g.,
the public Colab hosted runtime.
We have tested with CPU/GPU/TPU runtimes (for the TPU runtime
the `with tf.device` context managers are important.)
We apply the ```jax2tf.convert``` wrapper to ```demo_jax``` to obtain a
function that executes **exactly as if it were written entirely with TF
ops**. This is what will enable us to use the resulting function in
a TF environment, e.g., to execute it eagerly, in graph mode, and even
with the XLA compiler, and to save it in a SavedModel.
You can inspect the TF graph and see that it contains a bunch of TF ops:
We can even differentiate the converted function, and the result is
guaranteed to be the same as if we differentiated it in JAX, and this
even if we had JAX custom gradients defined. (This is achieved by using
[tf.custom_gradient](https://www.tensorflow.org/api_docs/python/tf/custom_gradient)
to call back into the JAX autodiff machinery and convert to TF
the JAX gradient function.)
Since ```hello_tf``` behaves like any TF function, we can put it
into a SavedModel, using **standard** TF
[tools](https://www.tensorflow.org/guide/saved_model):
# Define and train MNIST
## Get MNIST data from TensorFlow DataSets
## MNIST in pure JAX
This is an example that uses just JAX, without any high-level
libraries for readers who prefer fewer moving parts, at the expense
of code size. See [below](#scrollTo=ALKaq_cL8fTj) a shorter example
using Flax.
We define MNIST in two parts, the feature extractor and the classifier.
We plan to share the feature extractor as a SavedModel and allow
reusing it in Keras with a different classifier (see
[below](#scrollTo=Fhm2kxL_gIF5)).
## MNIST in Flax
This follows the structure of the
[MNIST Flax (Linen) example](https://github.com/google/flax/blob/master/linen_examples/mnist/mnist_lib.py).
# Export to SavedModel
Follow [reusable SavedModel guidelines](https://www.tensorflow.org/hub/reusable_saved_models).
This wrapper class adapts between the Reusable SavedModel API
and the style in which a JAX model is built. Going forward,
there can probably be a generic adapter class for each modeling
library (such as Flax).
Congrats!
Reusable SavedModels like these can be shared with TensorFlow users on
the filesystem or by [ publishing on TF Hub ]( https://www.tensorflow.org/hub/exporting_tf2_saved_model )
.
## Import and run the SavedModels
Those SavedModels can now be imported into TensorFlow.
TensorFlow sometimes requires an explicit `with tf.device(tf_accelerator): ...` context to use the same accelerator as JAX, esp. for TPUs. We pick the best we can find in the colab runtime.
When comparing models between JAX and TF, we observed varying numerical tolerances depending on device type.
The following code block shows how to load the full JAX model in low-level TF,
and tests that it behaves the same as in JAX.
NOTE: You can replace tf.saved_model.load() by hub.load()
to make it work on TF Hub handles in addition to ordinary filesystem paths.
Now the same thing for the Flax model.
# Reuse in Keras of the MNIST feature extractor
The feature extractor model can be imported in TensorFlow
to train a new classifier on top of it.
For ease of training, we show this with the high-level Keras API,
but it should also be possible in low-level TensorFlow (using the
restored_features under a tf.GradientTape and doing gradient updates
manually).
With Keras, we use the `tf.distribute.OneDeviceStrategy`
as the high-level analogue of the `tf.device(...)` placement seen above.
It works on CPU, GPU and TPU.
Actual high-performance training would use the appropriatey replicated
[TF Distribution Strategy](https://www.tensorflow.org/guide/distributed_training).
The imported feature_extractor behaves the same as the JAX original.
Now train the new classifier on top.
The imported feature_extractor behaves the same as the JAX original.
| 0.89801 | 0.987484 |
# Edafa on ImageNet dataset
This notebook shows an example on how to use Edafa to obtain better results on **classification task**. We use [ImageNet](http://www.image-net.org/) dataset which has **1000 classes**. We use *Keras* and pretrained weights of VGG16. At the end we compare results of the same model with and without augmentations.
#### Import dependencies
```
%load_ext autoreload
%autoreload 2
# add our package directory to the path
import sys
sys.path.append('../../')
sys.path.append('../')
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input,decode_predictions
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```
#### Constants
```
# Filename to use for comparison (3 sample files are given in 'data' folder)
FILE = '000559'
# Input size of the deeplab model
IN_SIZE = 224
```
#### Now we build our model (using pretrained weights)
```
model = VGG16(weights='imagenet', include_top=True)
```
#### Read and preprocess image
```
img_path = '../data/images/%s.jpg'%FILE
img = image.load_img(img_path, target_size=(IN_SIZE, IN_SIZE))
plt.imshow(img)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
```
### Exp1: Predict image without augmentation
```
preds_without = model.predict(x)
```
### Exp2: Using same model with Edafa
#### step 1: import base class `ClassPredictor`
```
from edafa import ClassPredictor
```
#### step 2: inherit `ClassPredictor` and implement the main virtual functions: predict_patches()
```
class myPredictor(ClassPredictor):
def __init__(self,vgg16,*args,**kwargs):
super().__init__(*args,**kwargs)
self.model = vgg16
def predict_patches(self,patches):
return self.model.predict(patches)
```
#### step 3: make an instance of your class with the correct parameters
```
p = myPredictor(model,"../../conf/imagenet.json")
```
#### step 4: call predict_images()
```
preds_with = p.predict_images(x)
## Compare results of Exp1 and Exp2
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted without augmentation:', decode_predictions(preds_without, top=2)[0])
print('Predicted with augmentation:', decode_predictions(preds_with, top=2)[0])
```
We can clearly see from the object image that it's a **desktop computer**.
With *no augmentation* the top prediction is **television**.
With *augmentation* the top prediction is **desktop computer**
### Conclusion
Results showed that with the exact same model and by applying Edafa we can obtain better results!
|
github_jupyter
|
%load_ext autoreload
%autoreload 2
# add our package directory to the path
import sys
sys.path.append('../../')
sys.path.append('../')
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input,decode_predictions
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Filename to use for comparison (3 sample files are given in 'data' folder)
FILE = '000559'
# Input size of the deeplab model
IN_SIZE = 224
model = VGG16(weights='imagenet', include_top=True)
img_path = '../data/images/%s.jpg'%FILE
img = image.load_img(img_path, target_size=(IN_SIZE, IN_SIZE))
plt.imshow(img)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds_without = model.predict(x)
from edafa import ClassPredictor
class myPredictor(ClassPredictor):
def __init__(self,vgg16,*args,**kwargs):
super().__init__(*args,**kwargs)
self.model = vgg16
def predict_patches(self,patches):
return self.model.predict(patches)
p = myPredictor(model,"../../conf/imagenet.json")
preds_with = p.predict_images(x)
## Compare results of Exp1 and Exp2
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted without augmentation:', decode_predictions(preds_without, top=2)[0])
print('Predicted with augmentation:', decode_predictions(preds_with, top=2)[0])
| 0.470007 | 0.928603 |
```
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
from tensorflow.python.framework import ops
ops.reset_default_graph()
sess = tf.Session()
data_dir = 'temp'
mnist = read_data_sets(data_dir)
train_xdata = np.array([np.reshape(x, (28,28)) for x in mnist.train.images])
test_xdata = np.array([np.reshape(x, (28,28)) for x in mnist.test.images])
train_labels = mnist.train.labels
test_labels = mnist.test.labels
batch_size = 100
learning_rate = 0.005
evaluation_size = 100
image_width = train_xdata[0].shape[0]
image_height = train_xdata[0].shape[1]
target_size = max(train_labels) + 1
num_channels = 1
generations = 100
eval_every = 5
conv1_features = 25
conv2_features = 50
max_pool_size1 = 2
max_pool_size2 = 2
fully_connected_size1 = 100
dropout_prob = 0.75
x_input_shape = (batch_size, image_width, image_height, num_channels)
x_input = tf.placeholder(tf.float32, shape=x_input_shape)
y_target = tf.placeholder(tf.int32, shape=(batch_size))
eval_input_shape = (evaluation_size, image_width, image_height, num_channels)
eval_input = tf.placeholder(tf.float32, shape=eval_input_shape)
eval_target = tf.placeholder(tf.int32, shape=(evaluation_size))
dropout = tf.placeholder(tf.float32, shape=())
conv1_weight = tf.Variable(tf.truncated_normal([4, 4, num_channels, conv1_features],
stddev=0.1, dtype=tf.float32))
conv1_bias = tf.Variable(tf.zeros([conv1_features], dtype=tf.float32))
conv2_weight = tf.Variable(tf.truncated_normal([4, 4, conv1_features, conv2_features],
stddev=0.1, dtype=tf.float32))
conv2_bias = tf.Variable(tf.zeros([conv2_features], dtype=tf.float32))
resulting_width = image_width // (max_pool_size1 * max_pool_size2)
resulting_height = image_height // (max_pool_size1 * max_pool_size2)
full1_input_size = resulting_width * resulting_height * conv2_features
full1_weight = tf.Variable(tf.truncated_normal([full1_input_size, fully_connected_size1],
stddev=0.1, dtype=tf.float32))
full1_bias = tf.Variable(tf.truncated_normal([fully_connected_size1], stddev=0.1, dtype=tf.float32))
full2_weight = tf.Variable(tf.truncated_normal([fully_connected_size1, target_size],
stddev=0.1, dtype=tf.float32))
full2_bias = tf.Variable(tf.truncated_normal([target_size], stddev=0.1, dtype=tf.float32))
def my_conv_net(input_data):
conv1 = tf.nn.conv2d(input_data, conv1_weight, strides=[1, 1, 1, 1], padding='SAME')
relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_bias))
max_pool1 = tf.nn.max_pool(relu1, ksize=[1, max_pool_size1, max_pool_size1, 1],
strides=[1, max_pool_size1, max_pool_size1, 1], padding='SAME')
conv2 = tf.nn.conv2d(max_pool1, conv2_weight, strides=[1, 1, 1, 1], padding='SAME')
relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_bias))
max_pool2 = tf.nn.max_pool(relu2, ksize=[1, max_pool_size2, max_pool_size2, 1],
strides=[1, max_pool_size2, max_pool_size2, 1], padding='SAME')
final_conv_shape = max_pool2.get_shape().as_list()
final_shape = final_conv_shape[1] * final_conv_shape[2] * final_conv_shape[3]
flat_output = tf.reshape(max_pool2, [final_conv_shape[0], final_shape])
fully_connected1 = tf.nn.relu(tf.add(tf.matmul(flat_output, full1_weight), full1_bias))
final_model_output = tf.add(tf.matmul(fully_connected1, full2_weight), full2_bias)
final_model_output = tf.nn.dropout(final_model_output, dropout)
return(final_model_output)
model_output = my_conv_net(x_input)
test_model_output = my_conv_net(eval_input)
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=model_output, labels=y_target))
prediction = tf.nn.softmax(model_output)
test_prediction = tf.nn.softmax(test_model_output)
def get_accuracy(logits, targets):
batch_predictions = np.argmax(logits, axis=1)
num_correct = np.sum(np.equal(batch_predictions, targets))
return(100. * num_correct/batch_predictions.shape[0])
my_optimizer = tf.train.MomentumOptimizer(learning_rate, 0.9)
train_step = my_optimizer.minimize(loss)
init = tf.global_variables_initializer()
sess.run(init)
class drop_out_test(tf.test.TestCase):
def dropout_greaterthan(self):
with self.test_session():
self.assertGreater(dropout.eval(), 0.25)
class accuracy_test(tf.test.TestCase):
def accuracy_exact_test(self):
with self.test_session():
test_preds = [[0.9, 0.1],[0.01, 0.99]]
test_targets = [0, 1]
test_acc = get_accuracy(test_preds, test_targets)
self.assertEqual(test_acc.eval(), 100.)
class shape_test(tf.test.TestCase):
def output_shape_test(self):
with self.test_session():
numpy_array = np.ones([batch_size, target_size])
self.assertShapeEqual(numpy_array, model_output)
#tf.test.main()
train_loss = []
train_acc = []
test_acc = []
for i in range(generations):
rand_index = np.random.choice(len(train_xdata), size=batch_size)
rand_x = train_xdata[rand_index]
rand_x = np.expand_dims(rand_x, 3)
rand_y = train_labels[rand_index]
train_dict = {x_input: rand_x, y_target: rand_y, dropout: dropout_prob}
sess.run(train_step, feed_dict=train_dict)
temp_train_loss, temp_train_preds = sess.run([loss, prediction], feed_dict=train_dict)
temp_train_acc = get_accuracy(temp_train_preds, rand_y)
if (i+1) % eval_every == 0:
eval_index = np.random.choice(len(test_xdata), size=evaluation_size)
eval_x = test_xdata[eval_index]
eval_x = np.expand_dims(eval_x, 3)
eval_y = test_labels[eval_index]
test_dict = {eval_input: eval_x, eval_target: eval_y, dropout: 1.0}
test_preds = sess.run(test_prediction, feed_dict=test_dict)
temp_test_acc = get_accuracy(test_preds, eval_y)
train_loss.append(temp_train_loss)
train_acc.append(temp_train_acc)
test_acc.append(temp_test_acc)
acc_and_loss = [(i+1), temp_train_loss, temp_train_acc, temp_test_acc]
acc_and_loss = [np.round(x,2) for x in acc_and_loss]
print('Generation # {}. Train Loss: {:.2f}. Train Acc (Test Acc): {:.2f} ({:.2f})'.format(*acc_and_loss))
```
|
github_jupyter
|
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
from tensorflow.python.framework import ops
ops.reset_default_graph()
sess = tf.Session()
data_dir = 'temp'
mnist = read_data_sets(data_dir)
train_xdata = np.array([np.reshape(x, (28,28)) for x in mnist.train.images])
test_xdata = np.array([np.reshape(x, (28,28)) for x in mnist.test.images])
train_labels = mnist.train.labels
test_labels = mnist.test.labels
batch_size = 100
learning_rate = 0.005
evaluation_size = 100
image_width = train_xdata[0].shape[0]
image_height = train_xdata[0].shape[1]
target_size = max(train_labels) + 1
num_channels = 1
generations = 100
eval_every = 5
conv1_features = 25
conv2_features = 50
max_pool_size1 = 2
max_pool_size2 = 2
fully_connected_size1 = 100
dropout_prob = 0.75
x_input_shape = (batch_size, image_width, image_height, num_channels)
x_input = tf.placeholder(tf.float32, shape=x_input_shape)
y_target = tf.placeholder(tf.int32, shape=(batch_size))
eval_input_shape = (evaluation_size, image_width, image_height, num_channels)
eval_input = tf.placeholder(tf.float32, shape=eval_input_shape)
eval_target = tf.placeholder(tf.int32, shape=(evaluation_size))
dropout = tf.placeholder(tf.float32, shape=())
conv1_weight = tf.Variable(tf.truncated_normal([4, 4, num_channels, conv1_features],
stddev=0.1, dtype=tf.float32))
conv1_bias = tf.Variable(tf.zeros([conv1_features], dtype=tf.float32))
conv2_weight = tf.Variable(tf.truncated_normal([4, 4, conv1_features, conv2_features],
stddev=0.1, dtype=tf.float32))
conv2_bias = tf.Variable(tf.zeros([conv2_features], dtype=tf.float32))
resulting_width = image_width // (max_pool_size1 * max_pool_size2)
resulting_height = image_height // (max_pool_size1 * max_pool_size2)
full1_input_size = resulting_width * resulting_height * conv2_features
full1_weight = tf.Variable(tf.truncated_normal([full1_input_size, fully_connected_size1],
stddev=0.1, dtype=tf.float32))
full1_bias = tf.Variable(tf.truncated_normal([fully_connected_size1], stddev=0.1, dtype=tf.float32))
full2_weight = tf.Variable(tf.truncated_normal([fully_connected_size1, target_size],
stddev=0.1, dtype=tf.float32))
full2_bias = tf.Variable(tf.truncated_normal([target_size], stddev=0.1, dtype=tf.float32))
def my_conv_net(input_data):
conv1 = tf.nn.conv2d(input_data, conv1_weight, strides=[1, 1, 1, 1], padding='SAME')
relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_bias))
max_pool1 = tf.nn.max_pool(relu1, ksize=[1, max_pool_size1, max_pool_size1, 1],
strides=[1, max_pool_size1, max_pool_size1, 1], padding='SAME')
conv2 = tf.nn.conv2d(max_pool1, conv2_weight, strides=[1, 1, 1, 1], padding='SAME')
relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_bias))
max_pool2 = tf.nn.max_pool(relu2, ksize=[1, max_pool_size2, max_pool_size2, 1],
strides=[1, max_pool_size2, max_pool_size2, 1], padding='SAME')
final_conv_shape = max_pool2.get_shape().as_list()
final_shape = final_conv_shape[1] * final_conv_shape[2] * final_conv_shape[3]
flat_output = tf.reshape(max_pool2, [final_conv_shape[0], final_shape])
fully_connected1 = tf.nn.relu(tf.add(tf.matmul(flat_output, full1_weight), full1_bias))
final_model_output = tf.add(tf.matmul(fully_connected1, full2_weight), full2_bias)
final_model_output = tf.nn.dropout(final_model_output, dropout)
return(final_model_output)
model_output = my_conv_net(x_input)
test_model_output = my_conv_net(eval_input)
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=model_output, labels=y_target))
prediction = tf.nn.softmax(model_output)
test_prediction = tf.nn.softmax(test_model_output)
def get_accuracy(logits, targets):
batch_predictions = np.argmax(logits, axis=1)
num_correct = np.sum(np.equal(batch_predictions, targets))
return(100. * num_correct/batch_predictions.shape[0])
my_optimizer = tf.train.MomentumOptimizer(learning_rate, 0.9)
train_step = my_optimizer.minimize(loss)
init = tf.global_variables_initializer()
sess.run(init)
class drop_out_test(tf.test.TestCase):
def dropout_greaterthan(self):
with self.test_session():
self.assertGreater(dropout.eval(), 0.25)
class accuracy_test(tf.test.TestCase):
def accuracy_exact_test(self):
with self.test_session():
test_preds = [[0.9, 0.1],[0.01, 0.99]]
test_targets = [0, 1]
test_acc = get_accuracy(test_preds, test_targets)
self.assertEqual(test_acc.eval(), 100.)
class shape_test(tf.test.TestCase):
def output_shape_test(self):
with self.test_session():
numpy_array = np.ones([batch_size, target_size])
self.assertShapeEqual(numpy_array, model_output)
#tf.test.main()
train_loss = []
train_acc = []
test_acc = []
for i in range(generations):
rand_index = np.random.choice(len(train_xdata), size=batch_size)
rand_x = train_xdata[rand_index]
rand_x = np.expand_dims(rand_x, 3)
rand_y = train_labels[rand_index]
train_dict = {x_input: rand_x, y_target: rand_y, dropout: dropout_prob}
sess.run(train_step, feed_dict=train_dict)
temp_train_loss, temp_train_preds = sess.run([loss, prediction], feed_dict=train_dict)
temp_train_acc = get_accuracy(temp_train_preds, rand_y)
if (i+1) % eval_every == 0:
eval_index = np.random.choice(len(test_xdata), size=evaluation_size)
eval_x = test_xdata[eval_index]
eval_x = np.expand_dims(eval_x, 3)
eval_y = test_labels[eval_index]
test_dict = {eval_input: eval_x, eval_target: eval_y, dropout: 1.0}
test_preds = sess.run(test_prediction, feed_dict=test_dict)
temp_test_acc = get_accuracy(test_preds, eval_y)
train_loss.append(temp_train_loss)
train_acc.append(temp_train_acc)
test_acc.append(temp_test_acc)
acc_and_loss = [(i+1), temp_train_loss, temp_train_acc, temp_test_acc]
acc_and_loss = [np.round(x,2) for x in acc_and_loss]
print('Generation # {}. Train Loss: {:.2f}. Train Acc (Test Acc): {:.2f} ({:.2f})'.format(*acc_and_loss))
| 0.72662 | 0.625552 |
```
import numpy as np
import os
import matplotlib.pyplot as plt
import pandas as pd
import torch
import torch.nn as nn
import torchvision
from torch.utils.data.dataset import Dataset
from torchvision import transforms
import time
from PIL import Image
def loadModel():
model = torch.load(os.path.join(os.getcwd(),'cardtop.pt'))
model.avgpool = nn.AvgPool2d(kernel_size=7,stride=1,padding=0)
return model
def loadData(imgPATH):
dfs = pd.read_excel("cardLaberlling.xlsx")
dfs = dfs.drop(np.arange(2500,5000,1))
distinctNames = np.unique(np.array(dfs['card name']).astype(str))
imgArr = np.array(Image.open(imgPATH).convert('RGB'))
return np.array([imgArr]),distinctNames
class CustomDatasetFrom(Dataset): # input np arrays
def __init__(self,nparray,nblabels,transform=None):
self.data = nparray
self.nlabels = nblabels
self.transforms = transform
def __getitem__(self,index):
img_as_np = self.data[index]
img_as_img = Image.fromarray(img_as_np)
if self.transforms is not None:
img_as_tensor = self.transforms(img_as_img)
return img_as_tensor
def __len__(self):
return self.data.shape[0]
def runmodel(model,dataloaders,device):
was_training = model.training
model.eval()
labs = []; total = 0; correct = 0
with torch.no_grad():
for i, (inputs) in enumerate(dataloaders):
inputs = inputs.to(device)
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
for j in range(inputs.size()[0]):
tmp = preds[j].cpu().numpy()
labs.append(tmp)
return np.array(labs)
def img2label(imgPATH):
imgArr,classNames = loadData(imgDIR)
model = loadModel()
transformations = transforms.Compose([
transforms.Resize((224,224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
nb_labels = len(classNames)
custom_data = CustomDatasetFrom(imgArr,nb_labels,transformations)
dataloaders = torch.utils.data.DataLoader(custom_data, batch_size=1,
shuffle=False, num_workers=0)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
pred = runmodel(model,dataloaders,device)
return pred,imgArr,classNames
imgDIR = '2935card.png'
# 2928-2935 examples
start = time.time()
pred,imgArr,classNames = img2label(imgDIR)
end = time.time()
print(end-start)
plt.imshow(imgArr[0])
plt.title(classNames[pred[0]])
```
|
github_jupyter
|
import numpy as np
import os
import matplotlib.pyplot as plt
import pandas as pd
import torch
import torch.nn as nn
import torchvision
from torch.utils.data.dataset import Dataset
from torchvision import transforms
import time
from PIL import Image
def loadModel():
model = torch.load(os.path.join(os.getcwd(),'cardtop.pt'))
model.avgpool = nn.AvgPool2d(kernel_size=7,stride=1,padding=0)
return model
def loadData(imgPATH):
dfs = pd.read_excel("cardLaberlling.xlsx")
dfs = dfs.drop(np.arange(2500,5000,1))
distinctNames = np.unique(np.array(dfs['card name']).astype(str))
imgArr = np.array(Image.open(imgPATH).convert('RGB'))
return np.array([imgArr]),distinctNames
class CustomDatasetFrom(Dataset): # input np arrays
def __init__(self,nparray,nblabels,transform=None):
self.data = nparray
self.nlabels = nblabels
self.transforms = transform
def __getitem__(self,index):
img_as_np = self.data[index]
img_as_img = Image.fromarray(img_as_np)
if self.transforms is not None:
img_as_tensor = self.transforms(img_as_img)
return img_as_tensor
def __len__(self):
return self.data.shape[0]
def runmodel(model,dataloaders,device):
was_training = model.training
model.eval()
labs = []; total = 0; correct = 0
with torch.no_grad():
for i, (inputs) in enumerate(dataloaders):
inputs = inputs.to(device)
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
for j in range(inputs.size()[0]):
tmp = preds[j].cpu().numpy()
labs.append(tmp)
return np.array(labs)
def img2label(imgPATH):
imgArr,classNames = loadData(imgDIR)
model = loadModel()
transformations = transforms.Compose([
transforms.Resize((224,224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
nb_labels = len(classNames)
custom_data = CustomDatasetFrom(imgArr,nb_labels,transformations)
dataloaders = torch.utils.data.DataLoader(custom_data, batch_size=1,
shuffle=False, num_workers=0)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
pred = runmodel(model,dataloaders,device)
return pred,imgArr,classNames
imgDIR = '2935card.png'
# 2928-2935 examples
start = time.time()
pred,imgArr,classNames = img2label(imgDIR)
end = time.time()
print(end-start)
plt.imshow(imgArr[0])
plt.title(classNames[pred[0]])
| 0.717111 | 0.431704 |
# Evolutionary Machi Koro: Analysis
To start, let's create a set of organisms with random chromosomes.
```
from embark.evolution import Organism, make_random_chromosome
from embark.parameters import GENERATION_SIZE
generation = {Organism(make_random_chromosome()) for _ in range(GENERATION_SIZE)}
```
Next, we'll simulate 100 rounds of evolution.
```
from embark.evolution import iterate
generations = []
for index in range(100):
generation = set(iterate(generation))
generations.append(generation)
```
## Elo Rating System
Elo is a rating system that describes a player's skill relative to the rest of the field.
Let's define some functions to calculate Elo ratings.
```
K_FACTOR = 32
STARTING_RATING = 1200
def find_expected_score(rating, opponent_rating):
"""Calculate the win probability for a pairing."""
return 1 / (1 + 10**((opponent_rating - rating) / 400))
def update_elo(rating, opponent_rating, won):
"""Determine the new rating a player gets from a single result."""
score = 1 if won else 0
return rating + K_FACTOR * (score - find_expected_score(rating, opponent_rating))
```
The world's best chess player, Magnus Carlsen, has an Elo rating of 2843. The average club player is about 1500. What's the probability that the club player beats Carlsen?
```
find_expected_score(1500, 2843)
```
Oof. Not looking good for the club player. If (when) Magnus wins, his rating only slightly improves.
```
update_elo(2843, 1500, True)
```
The opposite result has a much larger point swing.
```
update_elo(1500, 2843, True)
```
## Machi Koro Elo
Now, let's apply the Elo rating system to our Machi Koro algorithm. This will help us determine how much the strength of the computer player increases.
First, let's find the winning organism of each generation of evolution.
```
winners = [max(generation, key=lambda organism: organism.wins) for generation in generations]
```
Next, let's set the default rating on every organism.
```
for winner in winners:
winner.rating = STARTING_RATING
```
Finally, let's simulate a large number of games. After each game, we'll update the player's Elo ratings.
```
from itertools import combinations
from embark.machi_koro import Game
for _ in range(10):
for player1, player2 in combinations(reversed(winners), 2):
game = Game(player1, player2)
game.simulate()
player1.rating = update_elo(player1.rating, player2.rating, game.winner == player1)
player2.rating = update_elo(player2.rating, player1.rating, game.winner == player2)
```
Here's a graph of our Elo scores per round:
```
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot([winner.rating for winner in winners])
plt.ylabel('Elo Rating')
plt.xlabel('Generation')
plt.show()
```
Looking good! The ratings mostly increase as the genetic algorithm improves the fitness of the population.
What's the probability that the winner of the hundredth generation beats the winner of the first generation?
```
find_expected_score(winners[-1].rating, winners[0].rating)
```
This means that the 100th winner should win about 84% of games against the 1st winner.
All Elo ratings are on the low end. Even the good strategies seem to lose frequently. Machi Koro's random element (dice rolls) likely contribute here.
## Best and Worst Cards
Which card did the genetic algorithm find most useful? How soon did EMbArK discover this card?
Let's visualize card probabilities over time. We'll plot one line per card. Each point will be the average gene probability for one generation.
```
from itertools import cycle
from embark.machi_koro import ALL_CARDS
COLORS = cycle(["#9467bd", "#17becf", "#7f7f7f", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b",
"#e377c2", "#bcbd22", "#1f77b4"])
plt.figure(figsize=(15, 10))
# Remove chart border.
ax = plt.subplot()
for border in ["top", "bottom", "right", "left"]:
ax.spines[border].set_visible(False)
for card, color in zip(ALL_CARDS, cycle(COLORS)):
line = [sum(organism[card] for organism in generation) / len(generation)
for generation in generations]
plt.plot(line, color=color)
plt.text(len(generations), line[-1], card.__name__, color=color)
plt.ylabel('Average Probability')
plt.xlabel('Generation')
plt.show()
```
At the end of the genetic algorithm the five cheapest cards are in the top seven most useful genes. EMbArK's strategy seems to embody frequent purchases of low-cost cards. Organisms do not save money. The algorithm buys cheap cards to create a snowball effect; income increases exponentially.
The algorithm also favors the *Wheat Field* and the *Fruit and Vegetable Market*. These cards combo; the amount of reward from the Fruit and Vegetable Market depends on the number of Wheat Fields the player owns. EMbArK cleverly places a similar high probability on these two cards.
The Cafe seems to be the best card in the game. EMbArK makes a great choice here. It's cheap (two coins) and steals money from the opponent.
All four *landmark* cards are required to win the game. These are the *Train Station*, *Amusement Park*, *Shopping Mall*, and *RadioTower*. The algorithm places a surprisingly low weight on the Train Station. This card makes the player roll two dice instead of one. At first glance these seems like a mistake. Why wouldn't EMbArK place a high probability on a winning card?
Closer examination reveals brilliance. As mentioned above, EMbArK gives high probability to cheap cards. These cheap cards generally have low activation numbers (1, 2, 2-3, 3, and 4). The activation number defines which dice roll gives a reward. The top chromosomes intelligently delay purchasing the Train Station in order to keep dice rolls low.
|
github_jupyter
|
from embark.evolution import Organism, make_random_chromosome
from embark.parameters import GENERATION_SIZE
generation = {Organism(make_random_chromosome()) for _ in range(GENERATION_SIZE)}
from embark.evolution import iterate
generations = []
for index in range(100):
generation = set(iterate(generation))
generations.append(generation)
K_FACTOR = 32
STARTING_RATING = 1200
def find_expected_score(rating, opponent_rating):
"""Calculate the win probability for a pairing."""
return 1 / (1 + 10**((opponent_rating - rating) / 400))
def update_elo(rating, opponent_rating, won):
"""Determine the new rating a player gets from a single result."""
score = 1 if won else 0
return rating + K_FACTOR * (score - find_expected_score(rating, opponent_rating))
find_expected_score(1500, 2843)
update_elo(2843, 1500, True)
update_elo(1500, 2843, True)
winners = [max(generation, key=lambda organism: organism.wins) for generation in generations]
for winner in winners:
winner.rating = STARTING_RATING
from itertools import combinations
from embark.machi_koro import Game
for _ in range(10):
for player1, player2 in combinations(reversed(winners), 2):
game = Game(player1, player2)
game.simulate()
player1.rating = update_elo(player1.rating, player2.rating, game.winner == player1)
player2.rating = update_elo(player2.rating, player1.rating, game.winner == player2)
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot([winner.rating for winner in winners])
plt.ylabel('Elo Rating')
plt.xlabel('Generation')
plt.show()
find_expected_score(winners[-1].rating, winners[0].rating)
from itertools import cycle
from embark.machi_koro import ALL_CARDS
COLORS = cycle(["#9467bd", "#17becf", "#7f7f7f", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b",
"#e377c2", "#bcbd22", "#1f77b4"])
plt.figure(figsize=(15, 10))
# Remove chart border.
ax = plt.subplot()
for border in ["top", "bottom", "right", "left"]:
ax.spines[border].set_visible(False)
for card, color in zip(ALL_CARDS, cycle(COLORS)):
line = [sum(organism[card] for organism in generation) / len(generation)
for generation in generations]
plt.plot(line, color=color)
plt.text(len(generations), line[-1], card.__name__, color=color)
plt.ylabel('Average Probability')
plt.xlabel('Generation')
plt.show()
| 0.664431 | 0.987117 |
# 1. Common data problems
**In this chapter, you'll learn how to overcome some of the most common dirty data problems. You'll convert data types, apply range constraints to remove future data points, and remove duplicated data points to avoid double-counting.**
## Data type constraints
### Why do we need to clean data?
In a typical data science workflow, we usually access our raw data, explore and process it, develop insights using visualizations or predictive models, and finally report these insights with dashboards or reports.
Dirty data can appear because of duplicate values, mis-spellings, data type parsing errors and legacy systems.
Without making sure that data is properly cleaned in the exploration and processing phase, we will surely compromise the insights and reports subsequently generated. As the old adage says, garbage in garbage out.
### Data type constraints
When working with data, there are various types that we may encounter along the way. We could be working with text data, integers, decimals, dates, zip codes, and others.
Luckily, Python has specific data type objects for various data types that you're probably familiar with by now. This makes it much easier to manipulate these various data types in Python. As such, before preparing to analyze and extract insights from our data, we need to make sure our variables have the correct data types, other wise we risk compromising our analysis.
### Example: Strings to Intergers
Here's the head of a DataFrame containing revenue generated and quantity of items sold for a sales order. We want to calculate the total revenue generated by all sales orders.
```python
# Import CSV fil and output header
sales = pd.read_csv('sales.csv')
sales.head(2)
```
```
SalesOrderID Revenue Quantity
0 43659 23153$ 12
1 43668 1457$ 2
```
As you can see, the Revenue column has the dollar sign on the right hand side.
```python
# Get data types of columns
sales.dtypes
```
```
SalesOrderID int64
Revenue object
Quantity int64
dtype: object
```
A close inspection of the DataFrame column's data types using the `.dtypes` attribute returns object for the Revenue column, which is what pandas uses to store strings.
Also check the data types as well as the number of missing values per column in a DataFrame, by using the `.info()` method.
```python
# Get DataFrame information
sales.info()
```
```
<class 'pandas.core'frame.DataFram'>
RangeIndex: 31456 entries, 0 to 31464
Data columns (total 3 columns):
SalesOrderID 31465 non-null int64
Revenue 31465 non-null object
Quantity 31465 non-null int64
dtype: int64(2) object(1)
memory usage: 737.5+ KB
```
Since the Revenue column is a string, summing across all sales orders returns one large concatenated string containing each row's string.
```python
# Print sum of all Revenue column
sales['Revenue'].sum()
```
```
23153$1457$36865$34252$4453$...
```
To fix this, we need to first remove the dollar sign from the string so that pandas is able to convert the strings into numbers without error. We do this with the `.str.strip()` method, while specifying the string we want to strip as an argument, which is in this case the dollar sign. Since our dollar values do not contain decimals, we then convert the Revenue column to an integer by using the `.astype()` method, specifying the desired data type as argument. Had our revenue values been decimal, we would have converted the Revenue column to float.
```python
# Remove dollar sign from revenue column
sales['Revenue'] = sales['Revenue'].str.strip('$')
sales['Revenue'] = sales['Revenue'].astype('int')
```
We can make sure that the Revenue column is now an integer by using the assert statement, which takes in a condition as input, as returns nothing if that condition is met, and an error if it is not.
```python
assert sales['Revenue'].dtype == 'int'
```
### Example: Numeric or categorical?
A common type of data seems numeric but actually represents categories with a finite set of possible categories. This is called categorical data.
Here we have a marriage status column, which is represented by 0 for never married, 1 for married, 2 for separated, and 3 for divorced.
```
... marriage_status ...
... 1 ...
... 3 ...
... 0 ...
```
`0` = Never married `1` = Married `2` = Separated `3` = Divorced
However it will be imported of type integer, which could lead to misleading results when trying to extract some statistical summaries.
```python
df['marriage_status'].describe()
```
```
marriage_status
...
mean 1.4
std 0.20
min 0.00
50% 1.8 ...
```
We can solve this by using the same `.astype()` method seen earlier, but this time specifying the category data type.
```python
# Convert to categorical
df['marriage_status'] = df['marriage_status'].astype('category')
df.describe()
```
```
marriage_status
count 241
unique 4
top 1
freq 120
```
When applying the describe again, we see that the summary statistics are much more aligned with that of a categorical variable, discussing the number of observations, number of unique values, most frequent category instead of mean and standard deviation.
## Common data types
Manipulating and analyzing data with incorrect data types could lead to compromised analysis as you go along the data science workflow.
When working with new data, you should always check the data types of your columns using the `.dtypes` attribute or the `.info()` method which you'll see in the next exercise. Often times, you'll run into columns that should be converted to different data types before starting any analysis.
## Numeric data or ... ?
You'll be working with bicycle ride sharing data in San Francisco called `ride_sharing`.
```
import pandas as pd
ride_sharing = pd.read_csv('ride_sharing.csv')
display(ride_sharing.head(2))
```
It contains information on the start and end stations, the trip duration, and some user information for a bike sharing service.
The `user_type` column contains information on whether a user is taking a free ride and takes on the following values:
- `1` for free riders.
- `2` for pay per ride.
- `3` for monthly subscribers.
In this instance, you will print the information of `ride_sharing` using `.info()` and see a firsthand example of how an incorrect data type can flaw your analysis of the dataset.
- Print the information of `ride_sharing`.
```
# Print the information of ride_sharing
print(ride_sharing.info())
```
- Use `.describe()` to print the summary statistics of the `user_type` column from `ride_sharing`.
```
# Print summary statistics of user_type column
print(ride_sharing['user_type'].describe())
```
The `user_type` column has an finite set of possible values that represent groupings of data, it should be converted to `category`.
- Convert `user_type` into categorical by assigning it the `'category'` data type and store it in the `user_type_cat column`.
- Make sure you converted `user_type_cat` correctly by using an `assert` statement.
```
# Convert user_type from integer to category
ride_sharing['user_type_cat'] = ride_sharing['user_type'].astype('category')
# Write an assert statement confirming the change
assert ride_sharing['user_type_cat'].dtype == 'category'
# Print new summary statistics
print(ride_sharing['user_type_cat'].describe())
```
*Take a look at the new summary statistics, it seems that most users are pay per ride users.*
```
import matplotlib.pyplot as plt
import seaborn as sns
x_label = ['Free riders', 'Pay per ride users', 'Monthly subscribers']
ax = sns.countplot(data=ride_sharing, x='user_type')
ax.set_xticklabels(x_label)
ax.set_xlabel('User type')
plt.show()
```
## Summing strings and concatenating numbers
In the previous exercise, you were able to identify that `category` is the correct data type for `user_type` and convert it in order to extract relevant statistical summaries that shed light on the distribution of `user_type`.
Another common data type problem is importing what should be numerical values as strings, as mathematical operations such as summing and multiplication lead to string concatenation, not numerical outputs.
In this exercise, you'll be converting the string column `duration` to the type `int`. Before that however, you will need to make sure to strip `"minutes"` from the column in order to make sure `pandas` reads it as numerical.
- Use the `.strip()` method to strip `duration` of `"minutes"` and store it in the `duration_trim` column.
- Convert `duration_trim` to `int` and store it in the `duration_time` column.
- Write an `assert` statement that checks if `duration_time`'s **data type** is now an `int`.
- Print the average ride duration.
```
# Strip duration of minutes
ride_sharing['duration_trim'] = ride_sharing['duration'].str.strip('minutes')
# Convert duration to integer
ride_sharing['duration_time'] = ride_sharing['duration_trim'].astype('int')
# Write an assert statement making sure of conversion
assert ride_sharing['duration_time'].dtype == 'int'
# View formed columns
display(ride_sharing[['duration', 'duration_trim', 'duration_time']])
# Calculate average ride duration
print(ride_sharing['duration_time'].mean())
```
*11 minutes seems really not bad for an average ride duration in a city like San-Francisco.*
```
fig, ax = plt.subplots()
sns.histplot(ride_sharing['duration_time'], ax=ax)
ax.set(xlabel='Duration Time (minutes)', xlim=(0,80))
ax.axvline(x=ride_sharing['duration_time'].mean(), color='m', label='Mean', linestyle='--')
ax.legend()
plt.show()
```
---
## Data range constraints
### How to deal with out of range data?
- Dropping data:
- The simplest option is to drop the data. *However*, depending on the size of your out of range data, you could be losing out on essential information. As a rule of thumb, only drop data when a small proportion of your dataset is affected by out of range values, but you really need to understand your dataset before deciding to drop values.
- Setting custome minimums and maximums
- Treat as missing and impute
- Setting custom value depending on business assumptions
### Movie example
Let's take a look at the movies example. We first isolate the movies with ratings higher than 5.
```python
import pandas as pd
# Output Movies with rating > 5
movies[movies['avg_rating'] > 5]
```
```
movie_name avg_rating
23 A Beautiful Mind 6
65 La Vita e Bella 6
77 Amelie 6
```
Now if these values are affect a small set of our data, we can drop them.
We can drop them in two ways:
1. we can either create a new filtered movies DataFrame where we only keep values of `avg_rating` lower or equal than to 5.
```python
# Drop values using filtering
movies = movies[movies['avg_rating'] <= 5]
```
2. Or drop the values by using the drop method. The drop method takes in as argument the row indices of movies for which the `avg_rating` is higher than 5. We set the `inplace` argument to `True` so that values are dropped in place and we don't have to create a new column.
```python
# Drop values using .drop()
movies.drop(movies[movies['avg_rating'] > 5].index, inplace = True)
```
We can make sure this is set in place using an `assert` statement that checks if the maximum of `avg_rating` is lower or equal than to 5.
```python
# Assert results
assert movies['avg_rating'].max() <= 5
```
Depending on the assumptions behind our data, we can also change the out of range values to a hard limit. For example, here we're setting any value of the `avg_rating` column in to 5 if it goes beyond it. We can do this using the `.loc` method, which returns all cells that fit a custom row and column index.
```python
# Convert avg_rating > 5 to 5
movies.loc[movies['avg_rating'] > 5, 'avg_rating'] = 5
```
It takes as first argument the row index, or here all instances of `avg_rating` above 5 and as second argument the column index, which is here the `avg_rating` column. Again, we can make sure that this change was done using an `assert` statement
```python
# Assert results
assert movies['avg_rating'].max() <= 5
```
### Date range example
Let's take another at the date range example, where we had subscriptions happening in the future.
We first look at the datatypes of the column with the `.dtypes` attribute.
```python
import datetime as dt
import pandas as pd
# Output data types
user_sugnups.dtype
```
```
subscription_date object
user_name object
Country object
dtype: object
```
We can confirm that the `subscription_date` column is an object and not a `datetime` object. Datetime objects allow much easier manipulation of date data, so let's convert it to that.
We do so with the `to_datetime` function from `pandas`, which takes in as argument the column we want to convert.
```python
# Convert to DateTime
user_signups['subscription_date'] = pd.to_datetime(user_signups['subscription_date'])
```
We can then test the data type conversion by asserting that the subscription date's column is equal to `datetime64[ns]`, which is how the data type is represented in pandas.
```python
# Assert that conversion happened
assert user_signups['subscription_date'].dtype == 'datetime64[ns]'
```
Now that the column is in `datetime`, we can treat it in a variety of ways. We first create a `today_date` variable using the datetime function `date.today`, which allows us to store today's date.
```python
today_date = dt.date.today()
```
We can then either drop the rows with exceeding dates similar to how we did in the average rating example,
```python
# Drop values using filtering
user_signups = user_signups[user_signups['subscription_date'] < today_date]
# Drop values using .drop()
user_signups.drop(user_signups[user_signups['subscription_date'] > todat_date].index, inplace = True)
```
or replace exceeding values with today's date.
```python
# Drop values using filtering
user_signups.loc[user_signups['subscription_date'] > today_date, 'subscription_date'] = today_date
```
In both cases we can use the `assert` statement to verify our treatment went well, by comparing the maximum value in the subscription_date column. However, make sure to chain it with the `.date()` method to return a datetime object instead of a timestamp.
```python
# Assert is true
assert user_signups.subscription_date.max().date() <= today_date
```
## Tire size constraints
In this lesson, you're going to build on top of the work you've been doing with the `ride_sharing` DataFrame. You'll be working with the `tire_sizes` column which contains data on each bike's tire size.
Bicycle tire sizes could be either 26″, 27″ or 29″ and are here correctly stored as a categorical value. In an effort to cut maintenance costs, the ride sharing provider decided to set the maximum tire size to be 27″.
In this exercise, you will make sure the `tire_sizes` column has the correct range by first converting it to an integer, then setting and testing the new upper limit of 27″ for tire sizes.
- Convert the `tire_sizes` column from `category` to `'int'`.
- Use `.loc[]` to set all values of `tire_sizes` above 27 to 27.
- Reconvert back `tire_sizes` to `'category'` from `int`.
- Print the description of the `tire_sizes`.
```python
# Convert tire_sizes to integer
ride_sharing['tire_sizes'] = ride_sharing['tire_sizes'].astype('int')
# Set all values above 27 to 27
ride_sharing.loc[ride_sharing['tire_sizes'] > 27, 'tire_sizes'] = 27
# Reconvert tire_sizes back to categorical
ride_sharing['tire_sizes'] = ride_sharing['tire_sizes'].astype('category')
# Print tire size description
print(ride_sharing['tire_sizes'].describe())
```
```
count 25760
unique 2
top 27
freq 13274
Name: tire_sizes, dtype: int64
```
## Back to the future
A new update to the data pipeline feeding into the `ride_sharing` DataFrame has been updated to register each ride's date. This information is stored in the `ride_date` column of the type `object`, which represents strings in `pandas`.
A bug was discovered which was relaying rides taken today as taken next year. To fix this, you will find all instances of the `ride_date` column that occur anytime in the future, and set the maximum possible value of this column to today's date. Before doing so, you would need to convert `ride_date` to a `datetime` object.
The `datetime` package has been imported as `dt`, alongside all the packages you've been using till now.
- Convert `ride_date` to a `datetime` object and store it in `ride_dt` column using `to_datetime()`.
- Create the variable `today`, which stores today's date by using the `dt.date.today()` function.
- For all instances of `ride_dt` in the future, set them to today's date.
- Print the maximum date in the `ride_dt` column.
```python
# Convert ride_date to datetime
ride_sharing['ride_dt'] = pd.to_datetime(ride_sharing['ride_date'])
# Save today's date
today = dt.date.today()
# Set all in the future to today's date
ride_sharing.loc[ride_sharing['ride_dt'] > today, 'ride_dt'] = today
# Print maximum of ride_dt column
print(ride_sharing['ride_dt'].max())
```
```
2021-07-22 00:00:00
```
---
## Uniqueness constraints
### What are duplicate values?
Duplicate values can be diagnosed when we have the same exact information repeated across multiple rows, for a some or all columns in our DataFrame.
### Why do they happen?
Apart from data entry and human errors alluded to in the previous slide, duplicate data can also arise because of bugs and design errors whether in business processes or data pipelines. However they oftenmost arise from the necessary act of joining and consolidating data from various resources, which could retain duplicate values.
### How to find duplicate values?
We can find duplicates in a DataFrame by using the `.duplicated()` method.
```python
# Get duplicates across all columns
duplicates = height_weight.duplicated()
print(duplicates)
```
```
1 False
... ...
22 True
23 False
... ...
```
It returns a Series of boolean values that are `True` for duplicate values, and `False` for non-duplicated values.
We can see exactly which rows are affected by using brackets as such.
```python
# Get duplicate rows
duplicates = height_weight.duplicated()
height_weight[duplicated]
```
However, using `.duplicated()` without playing around with the arguments of the method can lead to misleading results, as all the columns are required to have duplicate values by default, with all duplicate values being marked as `True` except for the first occurrence. This limits our ability to properly diagnose what type of duplication we have, and how to effectively treat it.
To properly calibrate how we go about finding duplicates, we will use 2 arguments from the `.duplicated()` method. The subset argument lets us set a list of column names to check for duplication.
**The `.duplicated()` method**
- `subset`: List of column names to check for duplication.
- `keep`: Whether to keep **first**(`'first'`), **last**(`'last'`) or **all**(`False`) duplicate values.
For example, it allows us to find duplicates for the first and last name columns only. The keep argument lets us keep the first occurrence of a duplicate value by setting it to the string first, the last occurrence of a duplicate value by setting it the string last, or keep all occurrences of duplicate values by setting it to `False`.
```python
# Columns names to check for duplication
column_names = ['first_name', 'last_name', 'address']
duplicates = height_weight.duplicated(subset = column_names, keep = False)
```
In this example, we're checking for duplicates across the `first name`, `last name`, and `address` variables, and we're choosing to keep all duplicates.
We sort the duplicate rows using the `.sort_values` method, choosing `first_name` to sort by.
```python
# Output duplicate values
height_weight[duplicates].sort_values(by = 'first_name')
```
### How to treat duplicate values?
The complete duplicates can be treated easily. All that is required is to keep one of them only and discard the others.
This can be done with the `.drop_duplicates()` method, which also takes in the same `subset` and `keep` arguments as in the `.duplicated()` method, as well as the `inplace` argument which drops the duplicated values directly inside the `height_weight` DataFrame.
**The `.duplicated()` method**
- `subset`: List of column names to check for duplication.
- `keep`: Whether to keep **first**(`'first'`), **last**(`'last'`) or **all**(`False`) duplicate values.
- `inplace`: Drop duplicated rows directly inside DataFrame without creating new object(`True`).
Here we are dropping complete duplicates only, so it's not necessary nor advisable to set a subset, and since the keep argument takes in first as default, we can keep it as such.
```python
# Drop duplicates
height_weight.drop_duplicates(inplace = True)
```
Note that we can also set it as last, but not as `False` as it would keep all duplicates.
```python
# Output duplicate values
column_names = ['first_name', 'last_name', 'address']
duplicates = height_weight.duplicated(subset = column_names, keep = False)
height_weight[duplicates].sort_values(by = 'first_name')
```
This leaves us with the other 2 sets of duplicates discussed earlier, which are the same for `first_name`, `last_name` and `address`, but contain discrepancies in height and weight. Apart from dropping rows with really small discrepancies, we can use a statistical measure to combine each set of duplicated values.
```
first_name last_name height weight
28 Desirae Shannon 195 83
103 Desirae Shannon 196 83
1 Ivor Pierce 168 66
101 Ivor Pierce 168 88
```
We can do this easily using the groupby method, which when chained with the agg method, lets you group by a set of common columns and return statistical values for specific columns when the aggregation is being performed.
**The `.groupby()` and `.agg()` methods**
For example here, we created a dictionary called summaries, which instructs groupby to return the maximum of duplicated rows for the height column, and the mean duplicated rows for the weight column.
```python
# Group by column names and produce statistical summaries
column_names = ['first_name', 'last_name', 'address']
summaries = {'height': 'max', 'weight': 'mean'}
height_weight = height_weight.groupby(by = column_names).agg(summaries).reset_index()
```
We then group `height_weight` by the column names defined earlier, and chained it with the agg method, which takes in the summaries dictionary we created. We chain this entire line with the `.reset_index()` method, so that we can have numbered indices in the final output.
```python
# Make sure aggregation is done
duplicates = height_weight.duplicated(subset = column_names, keep = False)
height_weight[duplicates].sort_values(by = 'first_name')
```
We can verify that there are no more duplicate values by running the duplicated method again, and use brackets to output duplicate rows.
## How big is your subset?
You have the following `loans` DataFrame which contains loan and credit score data for consumers, and some metadata such as their first and last names. You want to find both complete and incomplete duplicates using `.duplicated()`.
first_name | last_name | credit_score | has_loan
:---|:---|:---|:---
Justin | Saddlemeyer | 600 | 1
Hadrien | Lacroix | 450 | 0
Choose the **correct** usage of `.duplicated()` below:
1. ~~`loans.duplicated()`: Because the default method returns both complete and incomplete duplicates.~~
2. ~~`loans.duplicated(subset = 'first_name')`: Because constraining the duplicate rows to the first name lets me find incomplete duplicates as well.~~
3. `loans.duplicated(subset = ['first_name', 'last_name'], keep = False)` : Because subsetting on consumer metadata and not discarding any duplicate returns all duplicated rows.
4. ~~`loans.duplicated(subset = ['first_name', 'last_name'], keep = 'first')`: Because this drops all duplicates.~~
**Answer: 3**
Subsetting on metadata and keeping all duplicate records gives you a better bird-eye's view over your data and how to duplicate it. You can even subset the `loans` DataFrame using bracketing and sort the values so you can properly identify the duplicates.
## Finding duplicates
A new update to the data pipeline feeding into `ride_sharing` has added the `ride_id` column, which represents a unique identifier for each ride.
The update however coincided with radically shorter average ride duration times and irregular user birth dates set in the future. Most importantly, the number of rides taken has increased by 20% overnight, leading you to think there might be both complete and incomplete duplicates in the `ride_sharing` DataFrame.
In this exercise, you will confirm this suspicion by finding those duplicates.
- Find duplicated rows of `ride_id` in the `ride_sharing` DataFrame while setting `keep` to `False`.
- Subset `ride_sharing` on `duplicates` and sort by `ride_id` and assign the results to `duplicated_rides`.
- Print the `ride_id`, `duration` and `user_birth_year` columns of `duplicated_rides` in that order.
```python
# Find duplicates
duplicates = ride_sharing.duplicated(subset=['ride_id'], keep=False)
# Sort your duplicated rides
duplicated_rides = ride_sharing[duplicates].sort_values('ride_id')
# Print relevant columns of duplicated_rides
print(duplicated_rides[['ride_id','duration','user_birth_year']])
```
```
ride_id duration user_birth_year
22 33 10 1979
39 33 2 1979
53 55 9 1985
65 55 9 1985
74 71 11 1997
75 71 11 1997
76 89 9 1986
77 89 9 2060
```
*Notice that rides 33 and 89 are incomplete duplicates, whereas the remaining are complete.*
## Treating duplicates
In the last exercise, you were able to verify that the new update feeding into `ride_sharing` contains a bug generating both complete and incomplete duplicated rows for some values of the `ride_id` column, with occasional discrepant values for the `user_birth_year` and `duration` columns.
In this exercise, you will be treating those duplicated rows by first dropping complete duplicates, and then merging the incomplete duplicate rows into one while keeping the average `duration`, and the minimum `user_birth_year` for each set of incomplete duplicate rows.
- Drop complete duplicates in `ride_sharing` and store the results in `ride_dup`.
- Create the `statistics` dictionary which holds **minimum** aggregation for `user_birth_year` and **mean** aggregation for `duration`.
- Drop incomplete duplicates by grouping by `ride_id` and applying the aggregation in `statistics`.
- Find duplicates again and run the `assert` statement to verify de-duplication.
```python
# Drop complete duplicates from ride_sharing
ride_dup = ride_sharing.drop_duplicates()
# Create statistics dictionary for aggregation function
statistics = {'user_birth_year': 'min', 'duration': 'mean'}
# Group by ride_id and compute new statistics
ride_unique = ride_dup.groupby(by = 'ride_id').agg(statistics).reset_index()
# Find duplicated values again
duplicates = ride_unique.duplicated(subset = 'ride_id', keep = False)
duplicated_rides = ride_unique[duplicates == True]
# Assert duplicates are processed
assert duplicated_rides.shape[0] == 0
```
*You can bet after this fix that ride sharing KPIs will come back to normal.*
|
github_jupyter
|
# Import CSV fil and output header
sales = pd.read_csv('sales.csv')
sales.head(2)
SalesOrderID Revenue Quantity
0 43659 23153$ 12
1 43668 1457$ 2
# Get data types of columns
sales.dtypes
SalesOrderID int64
Revenue object
Quantity int64
dtype: object
# Get DataFrame information
sales.info()
<class 'pandas.core'frame.DataFram'>
RangeIndex: 31456 entries, 0 to 31464
Data columns (total 3 columns):
SalesOrderID 31465 non-null int64
Revenue 31465 non-null object
Quantity 31465 non-null int64
dtype: int64(2) object(1)
memory usage: 737.5+ KB
# Print sum of all Revenue column
sales['Revenue'].sum()
23153$1457$36865$34252$4453$...
# Remove dollar sign from revenue column
sales['Revenue'] = sales['Revenue'].str.strip('$')
sales['Revenue'] = sales['Revenue'].astype('int')
assert sales['Revenue'].dtype == 'int'
... marriage_status ...
... 1 ...
... 3 ...
... 0 ...
df['marriage_status'].describe()
marriage_status
...
mean 1.4
std 0.20
min 0.00
50% 1.8 ...
# Convert to categorical
df['marriage_status'] = df['marriage_status'].astype('category')
df.describe()
marriage_status
count 241
unique 4
top 1
freq 120
import pandas as pd
ride_sharing = pd.read_csv('ride_sharing.csv')
display(ride_sharing.head(2))
# Print the information of ride_sharing
print(ride_sharing.info())
# Print summary statistics of user_type column
print(ride_sharing['user_type'].describe())
# Convert user_type from integer to category
ride_sharing['user_type_cat'] = ride_sharing['user_type'].astype('category')
# Write an assert statement confirming the change
assert ride_sharing['user_type_cat'].dtype == 'category'
# Print new summary statistics
print(ride_sharing['user_type_cat'].describe())
import matplotlib.pyplot as plt
import seaborn as sns
x_label = ['Free riders', 'Pay per ride users', 'Monthly subscribers']
ax = sns.countplot(data=ride_sharing, x='user_type')
ax.set_xticklabels(x_label)
ax.set_xlabel('User type')
plt.show()
# Strip duration of minutes
ride_sharing['duration_trim'] = ride_sharing['duration'].str.strip('minutes')
# Convert duration to integer
ride_sharing['duration_time'] = ride_sharing['duration_trim'].astype('int')
# Write an assert statement making sure of conversion
assert ride_sharing['duration_time'].dtype == 'int'
# View formed columns
display(ride_sharing[['duration', 'duration_trim', 'duration_time']])
# Calculate average ride duration
print(ride_sharing['duration_time'].mean())
fig, ax = plt.subplots()
sns.histplot(ride_sharing['duration_time'], ax=ax)
ax.set(xlabel='Duration Time (minutes)', xlim=(0,80))
ax.axvline(x=ride_sharing['duration_time'].mean(), color='m', label='Mean', linestyle='--')
ax.legend()
plt.show()
import pandas as pd
# Output Movies with rating > 5
movies[movies['avg_rating'] > 5]
movie_name avg_rating
23 A Beautiful Mind 6
65 La Vita e Bella 6
77 Amelie 6
# Drop values using filtering
movies = movies[movies['avg_rating'] <= 5]
# Drop values using .drop()
movies.drop(movies[movies['avg_rating'] > 5].index, inplace = True)
# Assert results
assert movies['avg_rating'].max() <= 5
# Convert avg_rating > 5 to 5
movies.loc[movies['avg_rating'] > 5, 'avg_rating'] = 5
# Assert results
assert movies['avg_rating'].max() <= 5
import datetime as dt
import pandas as pd
# Output data types
user_sugnups.dtype
subscription_date object
user_name object
Country object
dtype: object
# Convert to DateTime
user_signups['subscription_date'] = pd.to_datetime(user_signups['subscription_date'])
# Assert that conversion happened
assert user_signups['subscription_date'].dtype == 'datetime64[ns]'
today_date = dt.date.today()
# Drop values using filtering
user_signups = user_signups[user_signups['subscription_date'] < today_date]
# Drop values using .drop()
user_signups.drop(user_signups[user_signups['subscription_date'] > todat_date].index, inplace = True)
# Drop values using filtering
user_signups.loc[user_signups['subscription_date'] > today_date, 'subscription_date'] = today_date
# Assert is true
assert user_signups.subscription_date.max().date() <= today_date
# Convert tire_sizes to integer
ride_sharing['tire_sizes'] = ride_sharing['tire_sizes'].astype('int')
# Set all values above 27 to 27
ride_sharing.loc[ride_sharing['tire_sizes'] > 27, 'tire_sizes'] = 27
# Reconvert tire_sizes back to categorical
ride_sharing['tire_sizes'] = ride_sharing['tire_sizes'].astype('category')
# Print tire size description
print(ride_sharing['tire_sizes'].describe())
count 25760
unique 2
top 27
freq 13274
Name: tire_sizes, dtype: int64
# Convert ride_date to datetime
ride_sharing['ride_dt'] = pd.to_datetime(ride_sharing['ride_date'])
# Save today's date
today = dt.date.today()
# Set all in the future to today's date
ride_sharing.loc[ride_sharing['ride_dt'] > today, 'ride_dt'] = today
# Print maximum of ride_dt column
print(ride_sharing['ride_dt'].max())
2021-07-22 00:00:00
# Get duplicates across all columns
duplicates = height_weight.duplicated()
print(duplicates)
1 False
... ...
22 True
23 False
... ...
# Get duplicate rows
duplicates = height_weight.duplicated()
height_weight[duplicated]
# Columns names to check for duplication
column_names = ['first_name', 'last_name', 'address']
duplicates = height_weight.duplicated(subset = column_names, keep = False)
# Output duplicate values
height_weight[duplicates].sort_values(by = 'first_name')
# Drop duplicates
height_weight.drop_duplicates(inplace = True)
# Output duplicate values
column_names = ['first_name', 'last_name', 'address']
duplicates = height_weight.duplicated(subset = column_names, keep = False)
height_weight[duplicates].sort_values(by = 'first_name')
first_name last_name height weight
28 Desirae Shannon 195 83
103 Desirae Shannon 196 83
1 Ivor Pierce 168 66
101 Ivor Pierce 168 88
# Group by column names and produce statistical summaries
column_names = ['first_name', 'last_name', 'address']
summaries = {'height': 'max', 'weight': 'mean'}
height_weight = height_weight.groupby(by = column_names).agg(summaries).reset_index()
# Make sure aggregation is done
duplicates = height_weight.duplicated(subset = column_names, keep = False)
height_weight[duplicates].sort_values(by = 'first_name')
# Find duplicates
duplicates = ride_sharing.duplicated(subset=['ride_id'], keep=False)
# Sort your duplicated rides
duplicated_rides = ride_sharing[duplicates].sort_values('ride_id')
# Print relevant columns of duplicated_rides
print(duplicated_rides[['ride_id','duration','user_birth_year']])
ride_id duration user_birth_year
22 33 10 1979
39 33 2 1979
53 55 9 1985
65 55 9 1985
74 71 11 1997
75 71 11 1997
76 89 9 1986
77 89 9 2060
# Drop complete duplicates from ride_sharing
ride_dup = ride_sharing.drop_duplicates()
# Create statistics dictionary for aggregation function
statistics = {'user_birth_year': 'min', 'duration': 'mean'}
# Group by ride_id and compute new statistics
ride_unique = ride_dup.groupby(by = 'ride_id').agg(statistics).reset_index()
# Find duplicated values again
duplicates = ride_unique.duplicated(subset = 'ride_id', keep = False)
duplicated_rides = ride_unique[duplicates == True]
# Assert duplicates are processed
assert duplicated_rides.shape[0] == 0
| 0.624064 | 0.990954 |
# Simulate Artificial Physiological Signals
Neurokit's core signal processing functions surround electrocardiogram (ECG), respiratory (RSP), electrodermal activity (EDA), and electromyography (EMG) data. Hence, this example shows how to use Neurokit to simulate these physiological signals with customized parametric control.
```
# Load NeuroKit and other useful packages
import neurokit2 as nk
import numpy as np
import pandas as pd
import seaborn as sns
sns.set_style('darkgrid')
%matplotlib inline
plt.rcParams['figure.figsize'] = [8, 5] # Bigger images
```
## Cardiac Activity (ECG)
With `ecg_simulate()`, you can generate an artificial ECG signal of a desired length (in this case here, `duration=10`), noise, and heart rate. As you can see in the plot below, *ecg50* has about half the number of heart beats than *ecg100*, and *ecg50* also has more noise in the signal than the latter.
```
# Alternate heart rate and noise levels
ecg50 = nk.ecg_simulate(duration=10, noise=0.05, heart_rate=50)
ecg100 = nk.ecg_simulate(duration=10, noise=0.01, heart_rate=100)
# Visualize
pd.DataFrame({"ECG_100": ecg100,
"ECG_50": ecg50}).plot()
```
You can also choose to generate the default, simple simulation based on Daubechies wavelets, which roughly approximates one cardiac cycle, or a more complex one by specifiying `method="ecgsyn"`.
```
# Alternate methods
ecg_sim = nk.ecg_simulate(duration=10, method="simple")
ecg_com = nk.ecg_simulate(duration=10, method="ecgsyn")
# Visualize
pd.DataFrame({"ECG_Simple": ecg_sim,
"ECG_Complex": ecg_com}).plot(subplots=True)
```
## Respiration (RSP)
To simulate a synthetic respiratory signal, you can use `rsp_simulate()` and choose a specific duration and breathing rate. In this example below, you can see that *rsp7* has a lower breathing rate than *rsp15*. You can also decide which model you want to generate the signal. The *simple rsp15* signal incorporates `method = "sinusoidal"` which approximates a respiratory cycle based on the trigonometric sine wave. On the other hand, the *complex rsp15* signal specifies `method = "breathmetrics"` which uses a more advanced model by interpolating inhalation and exhalation pauses between each respiratory cycle.
```
# Simulate
rsp15_sim = nk.rsp_simulate(duration=20, respiratory_rate=15, method="sinusoidal")
rsp15_com = nk.rsp_simulate(duration=20, respiratory_rate=15, method="breathmetrics")
rsp7 = nk.rsp_simulate(duration=20, respiratory_rate=7, method="breathmetrics")
# Visualize respiration rate
pd.DataFrame({"RSP7": rsp7,
"RSP15_simple": rsp15_sim,
"RSP15_complex": rsp15_com}).plot(subplots=True)
```
## Electromyography (EMG)
Now, we come to generating an artificial EMG signal using `emg_simulate()`. Here, you can specify the number of bursts of muscular activity (`n_bursts`) in the signal as well as the duration of the bursts (`duration_bursts`). As you can see the active muscle periods in *EMG2_Longer* are greater in duration than that of *EMG2*, and *EMG5* contains more bursts than the former two.
```
# Simulate
emg2 = nk.emg_simulate(duration=10, n_bursts=2, duration_bursts=1.0)
emg2_long = nk.emg_simulate(duration=10, n_bursts=2, duration_bursts=1.5)
emg5 = nk.emg_simulate(duration=10, n_bursts=5, duration_bursts=1.0)
# Visualize
pd.DataFrame({"EMG2": emg2,
"EMG2_Longer": emg2_long,
"EMG5": emg5}).plot(subplots=True)
```
## Electrodermal Activity (EDA)
Finally, `eda_simulate()` can be used to generate a synthetic EDA signal of a given duration, specifying the number of skin conductance responses or activity 'peaks' (`n_scr`) and the `drift` of the signal. You can also modify the noise level of the signal.
```
# Simulate
eda1 = nk.eda_simulate(duration=10, n_scr=1, drift=-0.01, noise=0.05)
eda3 = nk.eda_simulate(duration=10, n_scr=3, drift=-0.01, noise=0.01)
eda3_long = nk.eda_simulate(duration=10, n_scr=3, drift=-0.1, noise=0.01)
# Visualize
pd.DataFrame({"EDA1": eda1,
"EDA3": eda3,
"EDA3_Longer": eda3_long}).plot(subplots=True)
```
|
github_jupyter
|
# Load NeuroKit and other useful packages
import neurokit2 as nk
import numpy as np
import pandas as pd
import seaborn as sns
sns.set_style('darkgrid')
%matplotlib inline
plt.rcParams['figure.figsize'] = [8, 5] # Bigger images
# Alternate heart rate and noise levels
ecg50 = nk.ecg_simulate(duration=10, noise=0.05, heart_rate=50)
ecg100 = nk.ecg_simulate(duration=10, noise=0.01, heart_rate=100)
# Visualize
pd.DataFrame({"ECG_100": ecg100,
"ECG_50": ecg50}).plot()
# Alternate methods
ecg_sim = nk.ecg_simulate(duration=10, method="simple")
ecg_com = nk.ecg_simulate(duration=10, method="ecgsyn")
# Visualize
pd.DataFrame({"ECG_Simple": ecg_sim,
"ECG_Complex": ecg_com}).plot(subplots=True)
# Simulate
rsp15_sim = nk.rsp_simulate(duration=20, respiratory_rate=15, method="sinusoidal")
rsp15_com = nk.rsp_simulate(duration=20, respiratory_rate=15, method="breathmetrics")
rsp7 = nk.rsp_simulate(duration=20, respiratory_rate=7, method="breathmetrics")
# Visualize respiration rate
pd.DataFrame({"RSP7": rsp7,
"RSP15_simple": rsp15_sim,
"RSP15_complex": rsp15_com}).plot(subplots=True)
# Simulate
emg2 = nk.emg_simulate(duration=10, n_bursts=2, duration_bursts=1.0)
emg2_long = nk.emg_simulate(duration=10, n_bursts=2, duration_bursts=1.5)
emg5 = nk.emg_simulate(duration=10, n_bursts=5, duration_bursts=1.0)
# Visualize
pd.DataFrame({"EMG2": emg2,
"EMG2_Longer": emg2_long,
"EMG5": emg5}).plot(subplots=True)
# Simulate
eda1 = nk.eda_simulate(duration=10, n_scr=1, drift=-0.01, noise=0.05)
eda3 = nk.eda_simulate(duration=10, n_scr=3, drift=-0.01, noise=0.01)
eda3_long = nk.eda_simulate(duration=10, n_scr=3, drift=-0.1, noise=0.01)
# Visualize
pd.DataFrame({"EDA1": eda1,
"EDA3": eda3,
"EDA3_Longer": eda3_long}).plot(subplots=True)
| 0.664976 | 0.983738 |
```
import jarvis
jarvis.setNotebookName('JarvisParameterTuning.ipynb')
ex = jarvis.Experiment('JarvisParameterTuning')
ex.groundClient('ground')
import sklearn.linear_model as linear_model
import sklearn
import seaborn as sns
import pandas as pd
import numpy as np
```
# Data Loading
Here I am using built-in data to make a quick example. In practice I would probably want to download the data from some external source
```
@jarvis.func
def crawl():
return sns.load_dataset('titanic')
doCrawl = ex.action(crawl)
titanic_data = ex.artifact('titanic.pkl', doCrawl)
titanic_data.peek()
```
# Data Processing
I need to extract some binary features
```
@jarvis.func
def featurize(df):
return pd.get_dummies(df)
doFeaturize = ex.action(featurize, [titanic_data])
ft_titanic_data = ex.artifact('ft_titanic.pkl', doFeaturize)
ft_titanic_data.peek(func=lambda x: x.head())
```
# Make the training matrices
```
@jarvis.func
def separateLabels(df):
data = df.dropna()
Y = data['survived'].values
X = data.drop(['survived'], axis=1).values.astype('float')
return X, Y
doSepLabels = ex.action(separateLabels, [ft_titanic_data])
X_ft_titanic_data = ex.artifact('x_ft_titanic.pkl', doSepLabels)
Y_ft_titanic_data = ex.artifact('y_ft_titanic.pkl', doSepLabels)
```
# Train Test Split
```
@jarvis.func
def trainTestSplit(X, Y, test_size, random_state):
from sklearn.model_selection import train_test_split
(X_tr, X_te, Y_tr, Y_te) = train_test_split(X, Y, test_size = test_size, random_state=random_state)
return (X_tr, X_te, Y_tr, Y_te)
doTrTeSplit = ex.action(trainTestSplit, [X_ft_titanic_data, Y_ft_titanic_data, ex.literal(0.1), ex.literal(42)])
X_tr = ex.artifact('tr_x_ft_titanic.pkl', doTrTeSplit)
X_te = ex.artifact('te_x_ft_titanic.pkl', doTrTeSplit)
Y_tr = ex.artifact('tr_y_ft_titanic.pkl', doTrTeSplit)
Y_te = ex.artifact('te_y_ft_titanic.pkl', doTrTeSplit)
```
# Model Development
First cut at model development
```
@jarvis.func
def trainModel(X_tr, Y_tr, n_estimators, min_samples_split):
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=n_estimators, min_samples_split=min_samples_split)
model.fit(X_tr, Y_tr)
return model
doTrainModel = ex.action(trainModel, [X_tr, Y_tr, ex.literal(10), ex.literal(2)])
model = ex.artifact('model.pkl', doTrainModel)
@jarvis.func
def scoreModel(model, X_tr, X_te, Y_tr, Y_te):
tr_acc = "Train Accuracy: {}".format(model.score(X_tr, Y_tr))
te_acc = "Test Accuracy: {}".format(model.score(X_te, Y_te))
return (tr_acc + '\n' + te_acc, )
doScoreModel = ex.action(scoreModel, [model, X_tr, X_te, Y_tr, Y_te])
output = ex.artifact('output.txt', doScoreModel)
output.peek(func=lambda x: print(''.join(x)))
```
**Error!!!**
The accuracy is too high! We must have a feature that contains the label
```
ft_titanic_data.peek(func=lambda x: x.dropna().columns)
```
Notice the **alive_no** and **alive_yes** columns appear to have same data as survived. Need to drop these columns
# Re-make the training matrices
```
@jarvis.func
def separateLabels(df):
data = df.dropna()
Y = data['survived'].values
X = data.drop(['survived', 'alive_no', 'alive_yes'], axis=1).values.astype('float')
return X, Y
doSepLabels = ex.action(separateLabels, [ft_titanic_data])
X_ft_titanic_data = ex.artifact('x_ft_titanic.pkl', doSepLabels)
Y_ft_titanic_data = ex.artifact('y_ft_titanic.pkl', doSepLabels)
```
# Train Test Split (Again)
```
doTrTeSplit = ex.action(trainTestSplit, [X_ft_titanic_data, Y_ft_titanic_data, ex.literal(0.1), ex.literal(42)])
X_tr = ex.artifact('tr_x_ft_titanic.pkl', doTrTeSplit)
X_te = ex.artifact('te_x_ft_titanic.pkl', doTrTeSplit)
Y_tr = ex.artifact('tr_y_ft_titanic.pkl', doTrTeSplit)
Y_te = ex.artifact('te_y_ft_titanic.pkl', doTrTeSplit)
```
# Model Development (Again)
First cut at model development
```
doTrainModel = ex.action(trainModel, [X_tr, Y_tr, ex.literal(10), ex.literal(2)])
model = ex.artifact('model.pkl', doTrainModel)
doScoreModel = ex.action(scoreModel, [model, X_tr, X_te, Y_tr, Y_te])
output = ex.artifact('output.txt', doScoreModel)
output.peek(func=lambda x: print(''.join(x)))
output.pull()
```
# Model selection through search
**To be continued after Aggregation is implemented ...**
|
github_jupyter
|
import jarvis
jarvis.setNotebookName('JarvisParameterTuning.ipynb')
ex = jarvis.Experiment('JarvisParameterTuning')
ex.groundClient('ground')
import sklearn.linear_model as linear_model
import sklearn
import seaborn as sns
import pandas as pd
import numpy as np
@jarvis.func
def crawl():
return sns.load_dataset('titanic')
doCrawl = ex.action(crawl)
titanic_data = ex.artifact('titanic.pkl', doCrawl)
titanic_data.peek()
@jarvis.func
def featurize(df):
return pd.get_dummies(df)
doFeaturize = ex.action(featurize, [titanic_data])
ft_titanic_data = ex.artifact('ft_titanic.pkl', doFeaturize)
ft_titanic_data.peek(func=lambda x: x.head())
@jarvis.func
def separateLabels(df):
data = df.dropna()
Y = data['survived'].values
X = data.drop(['survived'], axis=1).values.astype('float')
return X, Y
doSepLabels = ex.action(separateLabels, [ft_titanic_data])
X_ft_titanic_data = ex.artifact('x_ft_titanic.pkl', doSepLabels)
Y_ft_titanic_data = ex.artifact('y_ft_titanic.pkl', doSepLabels)
@jarvis.func
def trainTestSplit(X, Y, test_size, random_state):
from sklearn.model_selection import train_test_split
(X_tr, X_te, Y_tr, Y_te) = train_test_split(X, Y, test_size = test_size, random_state=random_state)
return (X_tr, X_te, Y_tr, Y_te)
doTrTeSplit = ex.action(trainTestSplit, [X_ft_titanic_data, Y_ft_titanic_data, ex.literal(0.1), ex.literal(42)])
X_tr = ex.artifact('tr_x_ft_titanic.pkl', doTrTeSplit)
X_te = ex.artifact('te_x_ft_titanic.pkl', doTrTeSplit)
Y_tr = ex.artifact('tr_y_ft_titanic.pkl', doTrTeSplit)
Y_te = ex.artifact('te_y_ft_titanic.pkl', doTrTeSplit)
@jarvis.func
def trainModel(X_tr, Y_tr, n_estimators, min_samples_split):
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=n_estimators, min_samples_split=min_samples_split)
model.fit(X_tr, Y_tr)
return model
doTrainModel = ex.action(trainModel, [X_tr, Y_tr, ex.literal(10), ex.literal(2)])
model = ex.artifact('model.pkl', doTrainModel)
@jarvis.func
def scoreModel(model, X_tr, X_te, Y_tr, Y_te):
tr_acc = "Train Accuracy: {}".format(model.score(X_tr, Y_tr))
te_acc = "Test Accuracy: {}".format(model.score(X_te, Y_te))
return (tr_acc + '\n' + te_acc, )
doScoreModel = ex.action(scoreModel, [model, X_tr, X_te, Y_tr, Y_te])
output = ex.artifact('output.txt', doScoreModel)
output.peek(func=lambda x: print(''.join(x)))
ft_titanic_data.peek(func=lambda x: x.dropna().columns)
@jarvis.func
def separateLabels(df):
data = df.dropna()
Y = data['survived'].values
X = data.drop(['survived', 'alive_no', 'alive_yes'], axis=1).values.astype('float')
return X, Y
doSepLabels = ex.action(separateLabels, [ft_titanic_data])
X_ft_titanic_data = ex.artifact('x_ft_titanic.pkl', doSepLabels)
Y_ft_titanic_data = ex.artifact('y_ft_titanic.pkl', doSepLabels)
doTrTeSplit = ex.action(trainTestSplit, [X_ft_titanic_data, Y_ft_titanic_data, ex.literal(0.1), ex.literal(42)])
X_tr = ex.artifact('tr_x_ft_titanic.pkl', doTrTeSplit)
X_te = ex.artifact('te_x_ft_titanic.pkl', doTrTeSplit)
Y_tr = ex.artifact('tr_y_ft_titanic.pkl', doTrTeSplit)
Y_te = ex.artifact('te_y_ft_titanic.pkl', doTrTeSplit)
doTrainModel = ex.action(trainModel, [X_tr, Y_tr, ex.literal(10), ex.literal(2)])
model = ex.artifact('model.pkl', doTrainModel)
doScoreModel = ex.action(scoreModel, [model, X_tr, X_te, Y_tr, Y_te])
output = ex.artifact('output.txt', doScoreModel)
output.peek(func=lambda x: print(''.join(x)))
output.pull()
| 0.448668 | 0.758756 |
```
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 14:41:19 2019
@author: karm2204
"""
"""
References:
"""
#%%
# https://github.com/pytorch/examples/blob/master/dcgan/main.py
# https://discuss.pytorch.org/t/gradient-penalty-with-respect-to-the-network-parameters/11944/2
# https://pytorch.org/tutorials/beginner/pytorch_with_examples.html
# https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
#%%
import torch
import torchvision
from torch import nn
import torchvision.transforms as transforms
from torch.utils.data import dataset
#%%
def get_data_loader(dataset_location, batch_size):
trainvalid = torchvision.datasets.SVHN(
dataset_location, split='train',
download=True,
transform=image_transform
)
trainset_size = int(len(trainvalid) * 0.9)
trainset, validset = dataset.random_split(
trainvalid,
[trainset_size, len(trainvalid) - trainset_size]
)
train = torch.utils.data.DataLoader(
trainset,
batch_size=batch_size,
shuffle=True,
num_workers=2
)
valid = torch.utils.data.DataLoader(
validset,
batch_size=batch_size,
)
test = torch.utils.data.DataLoader(
torchvision.datasets.SVHN(
dataset_location, split='test',
download=True,
transform=image_transform
),
batch_size=batch_size,
)
return train, valid, test
image_transform = transforms.Compose([
transforms.ToTensor()
])
#%%
class Generator(nn.Module):
""" Generator. Input is noise and latent variables, output is a generated
image.
"""
def __init__(self):
super(Generator, self).__init__()
self.main = nn.Sequential(
nn.ConvTranspose2d(100, 512, kernel_size = 4, stride = 1, padding = 0, bias = False),
nn.BatchNorm2d(512),
nn.ELU(),
nn.ConvTranspose2d(512, 256, kernel_size = 4, stride = 2, padding = 1, bias = False),
nn.BatchNorm2d(256),
nn.ELU(),
nn.ConvTranspose2d(256, 128, kernel_size = 4, stride = 2, padding = 1, bias = False),
nn.BatchNorm2d(64 * 2),
nn.ELU(),
nn.ConvTranspose2d(128, 3, kernel_size = 4, stride = 2, padding = 1, bias = False)
)
self.activation = nn.Sigmoid()
def forward(self, input_):
input_ = input_.view(input_.size(0), -1, 1, 1)
input_ = self.main(input_)
input_ = self.activation(input_)
return input_
#%%
class Discriminator(nn.Module):
""" Discriminator. Input is an image (real or generated), output is
P(generated), continuous latent variables, discrete latent variables.
"""
def __init__(self):
super(Discriminator, self).__init__()
self.main = nn.Sequential(
nn.Conv2d(3, 128, kernel_size = 4, stride = 2, padding = 1, bias = False),
nn.LeakyReLU(),
nn.Conv2d(128, 256, kernel_size = 4, stride = 2, padding = 1, bias = False),
nn.BatchNorm2d(256),
nn.LeakyReLU(),
nn.Conv2d(256, 512, kernel_size = 4, stride = 2, padding = 1, bias = False),
nn.BatchNorm2d(512),
nn.LeakyReLU(),
nn.Conv2d(512, 1, kernel_size = 4, stride = 1, padding = 0, bias = False),
)
def forward(self, image: torch.Tensor) -> torch.Tensor:
input_ = self.main(image)
input_ = input_.view(-1, 1).squeeze(1)
return input_
#%%
class GAN(nn.Module):
def __init__(self):
super().__init__()
self.latent_dim = 100
self.generator = Generator()
self.discriminator = Discriminator()
self.lambda_gp = 10.0
#%%
def compute_gradient_penalty(x, y, gan):
'''
Random weight term for interpolation between real and fake samples
Get random interpolation between real x and fake y samples
'''
alpha = torch.rand((x.size(0), 1, 1, 1), device = x.device)
lin_interpol = alpha * x + (1-alpha) * y
lin_interpol.requires_grad_(True)
# need a fake grad output
output = gan.discriminator(lin_interpol)
# Get gradient w.r.t. interpolates
gradients = torch.autograd.grad(
outputs=output,
inputs=lin_interpol,
grad_outputs=torch.ones_like(output),
create_graph=True,
retain_graph=True,
only_inputs=True,
)
gradients = gradients[0]
gradient = gradients.view(gradients.size(0), -1)
norm_2 = gradient.norm(p=2, dim=1)
gradient_penalty = ((norm_2 - 1).pow(2)).mean()
return gradient_penalty
#%%
# https://pytorch.org/tutorials/beginner/pytorch_with_examples.html
def visual_samples(gan, dimensions, device, svhn_loader, step=0):
# Generate new images
z = torch.randn(64, dimensions, device=device)
generated = gan.generator(z)
#debug
torchvision.utils.save_image(generated, 'images/gan/3.1gan-generated.png', normalize=False)
#torchvision.utils.save_image(generated, f"images/gan/3_1gan-generated-{step}.png", normalize=False)
def disentangled_representation(gan, dimensions, device, epsilon = 3):
#Sample from prior p(z) which is a Std Normal
z = torch.randn(dimensions, device=device)
#Copy this tensor times its number of dimensions and make perturbations on each dimension
#The first element is the original sample
z = z.repeat(dimensions+1, 1)
for i, sample in enumerate(z[1:]):
sample[i] += epsilon
generated = gan.generator(z)
torchvision.utils.save_image(generated, 'images/gan/3_2positive_eps.png', normalize=False)
#Do the same with the negative epsilon
epsilon = -2*epsilon
for i, sample in enumerate(z[1:]):
sample[i] += epsilon
#Make a batch of the pertubations and pass it through the generator
generated = gan.generator(z)
torchvision.utils.save_image(generated, 'images/gan/3_2negative_eps.png', normalize=False)
#%%
def interpolation(gan, dimensions, device):
# Interpolate in the latent space between z_0 and z_1
z_0 = torch.randn(1,dimensions, device=device)
z_1 = torch.randn(1,dimensions, device=device)
z_a = torch.zeros([11,dimensions], device=device)
for i in range(11):
a = i/10
z_a[i] = a*z_0 + (1-a)*z_1
generated = gan.generator(z_a)
torchvision.utils.save_image(generated, 'images/gan/3_3latent.png', normalize = False)
# Interpolate in the data space between x_0 and x_1
x_0 = gan.generator(z_0)
x_1 = gan.generator(z_1)
x_a = torch.zeros(11,x_0.size()[1],x_0.size()[2],x_0.size()[3], device = device)
for i in range(11):
a = i/10
x_a[i] = torch.lerp(x_0, x_1, a)
torchvision.utils.save_image(x_a, 'images/gan/3_3data.png', normalize = False)
def save_images(img_dir: str):
import os
gan = GAN()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
gan.load_state_dict(torch.load('GAN_q3_save.pth', map_location = device))
gan = gan.to(device)
gan.eval()
for p in gan.parameters():
p.requires_grad = False
for i in range(10):
print(i)
latents = torch.randn(100, 100, device=device)
images = gan.generator(latents)
os.makedirs(f"{img_dir}/img/", exist_ok=True)
for j, image in enumerate(images):
filename = f"{img_dir}/img/{i * 100 + j:03d}.png"
torchvision.utils.save_image(image, filename, normalize=False)
#%%
if __name__ == '__main__':
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"Running on {device}")
gan = GAN()
gan = gan.to(device)
gan.train()
gen_step = 5
D_optimizer = torch.optim.Adam(gan.discriminator.parameters(), lr=1e-4, betas=(0.5, 0.999))
G_optimizer = torch.optim.Adam(gan.generator.parameters(), lr=1e-4, betas=(0.5, 0.999))
train, valid, test = get_data_loader("svhn", 64)
try:
gan.load_state_dict(torch.load('GAN_q3_save.pth', map_location=device))
print('----Using saved model----')
except FileNotFoundError:
for epoch in range(5):
print(f"------- EPOCH {epoch} --------")
running_loss_d = 0
running_loss_g = 0
for i, (img, _) in enumerate(train):
gan.train()
# Training the discriminator
D_optimizer.zero_grad()
img = img.to(device)
latents = torch.randn([img.shape[0], gan.latent_dim], device=device)
fakes = gan.generator(latents).detach()
fakes_score = gan.discriminator(fakes)
fakes_score_mean = fakes_score.mean()
fakes_score_mean.backward()
reals_score = gan.discriminator(img)
reals_score_mean = -reals_score.mean()
reals_score_mean.backward()
loss = fakes_score_mean + reals_score_mean
grad_penalty = gan.lambda_gp * compute_gradient_penalty(img, fakes, gan)
grad_penalty.backward()
loss += grad_penalty
D_optimizer.step()
running_loss_d += loss
# training the generator
if i % gen_step == 0:
G_optimizer.zero_grad()
latents = torch.randn([img.shape[0], gan.latent_dim], device=device)
fakes = gan.generator(latents)
fakes_score = gan.discriminator(fakes)
fakes_score_mean = -fakes_score.mean()
fakes_score_mean.backward()
G_optimizer.step()
running_loss_g += fakes_score_mean
if(i%10 == 0):
visual_samples(gan, 100, device, test)
if i % 100 == 0:
print(f"Training example {i} / {len(train)}. DiscLoss: {running_loss_d:.2f}, GenLoss: {running_loss_g:.2f}")
running_loss_d = 0
running_loss_g = 0
torch.save(gan.state_dict(), 'GAN_q3_save.pth')
dimensions = 100
gan.eval()
#3_1 Visual samples
visual_samples(gan, dimensions, device, test)
#3_2 Disentangled representation
disentangled_representation(gan, dimensions, device, epsilon=10)
#3_3 Interpolation
interpolation(gan, dimensions, device)
img_dir = "images/gan/fid"
save_images(img_dir)
```
|
github_jupyter
|
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 14:41:19 2019
@author: karm2204
"""
"""
References:
"""
#%%
# https://github.com/pytorch/examples/blob/master/dcgan/main.py
# https://discuss.pytorch.org/t/gradient-penalty-with-respect-to-the-network-parameters/11944/2
# https://pytorch.org/tutorials/beginner/pytorch_with_examples.html
# https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
#%%
import torch
import torchvision
from torch import nn
import torchvision.transforms as transforms
from torch.utils.data import dataset
#%%
def get_data_loader(dataset_location, batch_size):
trainvalid = torchvision.datasets.SVHN(
dataset_location, split='train',
download=True,
transform=image_transform
)
trainset_size = int(len(trainvalid) * 0.9)
trainset, validset = dataset.random_split(
trainvalid,
[trainset_size, len(trainvalid) - trainset_size]
)
train = torch.utils.data.DataLoader(
trainset,
batch_size=batch_size,
shuffle=True,
num_workers=2
)
valid = torch.utils.data.DataLoader(
validset,
batch_size=batch_size,
)
test = torch.utils.data.DataLoader(
torchvision.datasets.SVHN(
dataset_location, split='test',
download=True,
transform=image_transform
),
batch_size=batch_size,
)
return train, valid, test
image_transform = transforms.Compose([
transforms.ToTensor()
])
#%%
class Generator(nn.Module):
""" Generator. Input is noise and latent variables, output is a generated
image.
"""
def __init__(self):
super(Generator, self).__init__()
self.main = nn.Sequential(
nn.ConvTranspose2d(100, 512, kernel_size = 4, stride = 1, padding = 0, bias = False),
nn.BatchNorm2d(512),
nn.ELU(),
nn.ConvTranspose2d(512, 256, kernel_size = 4, stride = 2, padding = 1, bias = False),
nn.BatchNorm2d(256),
nn.ELU(),
nn.ConvTranspose2d(256, 128, kernel_size = 4, stride = 2, padding = 1, bias = False),
nn.BatchNorm2d(64 * 2),
nn.ELU(),
nn.ConvTranspose2d(128, 3, kernel_size = 4, stride = 2, padding = 1, bias = False)
)
self.activation = nn.Sigmoid()
def forward(self, input_):
input_ = input_.view(input_.size(0), -1, 1, 1)
input_ = self.main(input_)
input_ = self.activation(input_)
return input_
#%%
class Discriminator(nn.Module):
""" Discriminator. Input is an image (real or generated), output is
P(generated), continuous latent variables, discrete latent variables.
"""
def __init__(self):
super(Discriminator, self).__init__()
self.main = nn.Sequential(
nn.Conv2d(3, 128, kernel_size = 4, stride = 2, padding = 1, bias = False),
nn.LeakyReLU(),
nn.Conv2d(128, 256, kernel_size = 4, stride = 2, padding = 1, bias = False),
nn.BatchNorm2d(256),
nn.LeakyReLU(),
nn.Conv2d(256, 512, kernel_size = 4, stride = 2, padding = 1, bias = False),
nn.BatchNorm2d(512),
nn.LeakyReLU(),
nn.Conv2d(512, 1, kernel_size = 4, stride = 1, padding = 0, bias = False),
)
def forward(self, image: torch.Tensor) -> torch.Tensor:
input_ = self.main(image)
input_ = input_.view(-1, 1).squeeze(1)
return input_
#%%
class GAN(nn.Module):
def __init__(self):
super().__init__()
self.latent_dim = 100
self.generator = Generator()
self.discriminator = Discriminator()
self.lambda_gp = 10.0
#%%
def compute_gradient_penalty(x, y, gan):
'''
Random weight term for interpolation between real and fake samples
Get random interpolation between real x and fake y samples
'''
alpha = torch.rand((x.size(0), 1, 1, 1), device = x.device)
lin_interpol = alpha * x + (1-alpha) * y
lin_interpol.requires_grad_(True)
# need a fake grad output
output = gan.discriminator(lin_interpol)
# Get gradient w.r.t. interpolates
gradients = torch.autograd.grad(
outputs=output,
inputs=lin_interpol,
grad_outputs=torch.ones_like(output),
create_graph=True,
retain_graph=True,
only_inputs=True,
)
gradients = gradients[0]
gradient = gradients.view(gradients.size(0), -1)
norm_2 = gradient.norm(p=2, dim=1)
gradient_penalty = ((norm_2 - 1).pow(2)).mean()
return gradient_penalty
#%%
# https://pytorch.org/tutorials/beginner/pytorch_with_examples.html
def visual_samples(gan, dimensions, device, svhn_loader, step=0):
# Generate new images
z = torch.randn(64, dimensions, device=device)
generated = gan.generator(z)
#debug
torchvision.utils.save_image(generated, 'images/gan/3.1gan-generated.png', normalize=False)
#torchvision.utils.save_image(generated, f"images/gan/3_1gan-generated-{step}.png", normalize=False)
def disentangled_representation(gan, dimensions, device, epsilon = 3):
#Sample from prior p(z) which is a Std Normal
z = torch.randn(dimensions, device=device)
#Copy this tensor times its number of dimensions and make perturbations on each dimension
#The first element is the original sample
z = z.repeat(dimensions+1, 1)
for i, sample in enumerate(z[1:]):
sample[i] += epsilon
generated = gan.generator(z)
torchvision.utils.save_image(generated, 'images/gan/3_2positive_eps.png', normalize=False)
#Do the same with the negative epsilon
epsilon = -2*epsilon
for i, sample in enumerate(z[1:]):
sample[i] += epsilon
#Make a batch of the pertubations and pass it through the generator
generated = gan.generator(z)
torchvision.utils.save_image(generated, 'images/gan/3_2negative_eps.png', normalize=False)
#%%
def interpolation(gan, dimensions, device):
# Interpolate in the latent space between z_0 and z_1
z_0 = torch.randn(1,dimensions, device=device)
z_1 = torch.randn(1,dimensions, device=device)
z_a = torch.zeros([11,dimensions], device=device)
for i in range(11):
a = i/10
z_a[i] = a*z_0 + (1-a)*z_1
generated = gan.generator(z_a)
torchvision.utils.save_image(generated, 'images/gan/3_3latent.png', normalize = False)
# Interpolate in the data space between x_0 and x_1
x_0 = gan.generator(z_0)
x_1 = gan.generator(z_1)
x_a = torch.zeros(11,x_0.size()[1],x_0.size()[2],x_0.size()[3], device = device)
for i in range(11):
a = i/10
x_a[i] = torch.lerp(x_0, x_1, a)
torchvision.utils.save_image(x_a, 'images/gan/3_3data.png', normalize = False)
def save_images(img_dir: str):
import os
gan = GAN()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
gan.load_state_dict(torch.load('GAN_q3_save.pth', map_location = device))
gan = gan.to(device)
gan.eval()
for p in gan.parameters():
p.requires_grad = False
for i in range(10):
print(i)
latents = torch.randn(100, 100, device=device)
images = gan.generator(latents)
os.makedirs(f"{img_dir}/img/", exist_ok=True)
for j, image in enumerate(images):
filename = f"{img_dir}/img/{i * 100 + j:03d}.png"
torchvision.utils.save_image(image, filename, normalize=False)
#%%
if __name__ == '__main__':
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"Running on {device}")
gan = GAN()
gan = gan.to(device)
gan.train()
gen_step = 5
D_optimizer = torch.optim.Adam(gan.discriminator.parameters(), lr=1e-4, betas=(0.5, 0.999))
G_optimizer = torch.optim.Adam(gan.generator.parameters(), lr=1e-4, betas=(0.5, 0.999))
train, valid, test = get_data_loader("svhn", 64)
try:
gan.load_state_dict(torch.load('GAN_q3_save.pth', map_location=device))
print('----Using saved model----')
except FileNotFoundError:
for epoch in range(5):
print(f"------- EPOCH {epoch} --------")
running_loss_d = 0
running_loss_g = 0
for i, (img, _) in enumerate(train):
gan.train()
# Training the discriminator
D_optimizer.zero_grad()
img = img.to(device)
latents = torch.randn([img.shape[0], gan.latent_dim], device=device)
fakes = gan.generator(latents).detach()
fakes_score = gan.discriminator(fakes)
fakes_score_mean = fakes_score.mean()
fakes_score_mean.backward()
reals_score = gan.discriminator(img)
reals_score_mean = -reals_score.mean()
reals_score_mean.backward()
loss = fakes_score_mean + reals_score_mean
grad_penalty = gan.lambda_gp * compute_gradient_penalty(img, fakes, gan)
grad_penalty.backward()
loss += grad_penalty
D_optimizer.step()
running_loss_d += loss
# training the generator
if i % gen_step == 0:
G_optimizer.zero_grad()
latents = torch.randn([img.shape[0], gan.latent_dim], device=device)
fakes = gan.generator(latents)
fakes_score = gan.discriminator(fakes)
fakes_score_mean = -fakes_score.mean()
fakes_score_mean.backward()
G_optimizer.step()
running_loss_g += fakes_score_mean
if(i%10 == 0):
visual_samples(gan, 100, device, test)
if i % 100 == 0:
print(f"Training example {i} / {len(train)}. DiscLoss: {running_loss_d:.2f}, GenLoss: {running_loss_g:.2f}")
running_loss_d = 0
running_loss_g = 0
torch.save(gan.state_dict(), 'GAN_q3_save.pth')
dimensions = 100
gan.eval()
#3_1 Visual samples
visual_samples(gan, dimensions, device, test)
#3_2 Disentangled representation
disentangled_representation(gan, dimensions, device, epsilon=10)
#3_3 Interpolation
interpolation(gan, dimensions, device)
img_dir = "images/gan/fid"
save_images(img_dir)
| 0.797399 | 0.667355 |
### Task 1: **Supervised Learning**
### Name: Bharat Raghunathan
**Problem Statement:** Predict the percentage of marks that a student is expected to score based on the number of hours they studied.
**Solution Approach:** This is a regression task since the output variable, **score**, is continuous.
```
# Importing all libraries required in this notebook
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import metrics
from sklearn.linear_model import LinearRegression
sns.set_style("darkgrid")
%matplotlib inline
# Reading data from remote link
url = "http://bit.ly/w-data"
student = pd.read_csv(url)
student.head()
```
### Exploratory Data Analysis
Let us try to analyze a sample of our dataset:
1. Explore the distributions of the *feature* and *target* variables
2. Find out whether there is any pattern or relationship between the *feature* and the *target* variable
```
# Plotting the distribution of target variable
sns.distplot(student["Scores"])
sns.distplot(student.drop("Scores", axis=1))
#Since features is a single column here, check for any correlations first
sns.scatterplot(student["Hours"], student["Scores"])
```
The above does seem to be **positively correlated** and in fact, maybe a **linear relationship**. Let's try a linear plot.
```
sns.lmplot("Hours", "Scores", data=student)
```
**From the graph above** (and the narrow 95% confidence band), **we can clearly see that there is a positive linear relation between the number of hours studied and percentage of score.**
### Prepare the Data
Separate the given dataset into `features` and `target` variables
```
# Separate the given dataset into its features and target variables
features = student.drop("Scores", axis=1)
target = student["Scores"]
X = features
y = target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2, random_state=42)
```
### **Training the Model**
We have split our data into training and testing sets, and now is finally the time to train our model.
```
regressor = LinearRegression()
regressor.fit(X_train, y_train)
print("Training complete.")
# Plotting the regression line on the entire data
line = regressor.coef_ * X + regressor.intercept_
# Plotting for the entire data
plt.scatter(X, y)
plt.plot(X, line);
plt.show()
```
### **Making Predictions**
Now that we have trained our algorithm, it's time to make some predictions.
```
print(X_test) # Testing data - In Hours
y_pred = regressor.predict(X_test) # Predicting the scores
# Comparing Actual vs Predicted
df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
df
```
#### Task Question
What is the expected % of marks for a student who studied for `9.25` hours?
```
# Testing with sample data.
hours = 9.25
own_pred = regressor.predict([[hours]])
print("No of Hours = {}".format(hours))
print("Predicted Score = {}".format(own_pred[0]))
```
### Interpretation of Model Output
This means that if a student studied for `9.25` hours, they are expected to score `92.38` marks, which seems sensible.
### **Evaluating the model**
The final step is to evaluate the performance of algorithm. This step is particularly important to compare how well different algorithms perform on a particular dataset. Since this is a regression task, we have chosen:
1. Mean Absolute Error (MAE): $\frac{1}{n}\sum_{i=1}^{n}\lvert{y_i - \hat{y_i}}\rvert$
2. Root Mean Squared Error (RMSE): $\sqrt{\frac{1}{n}\sum_{i=1}^{n}{{(y_i - \hat{y_i})}^2}}$
where n -> Number of data points
```
print(f'Mean Absolute Error: {metrics.mean_absolute_error(y_test, y_pred)}')
print(f'Root Mean Squared Error: {metrics.mean_squared_error(y_test, y_pred, squared=False)}')
```
|
github_jupyter
|
# Importing all libraries required in this notebook
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import metrics
from sklearn.linear_model import LinearRegression
sns.set_style("darkgrid")
%matplotlib inline
# Reading data from remote link
url = "http://bit.ly/w-data"
student = pd.read_csv(url)
student.head()
# Plotting the distribution of target variable
sns.distplot(student["Scores"])
sns.distplot(student.drop("Scores", axis=1))
#Since features is a single column here, check for any correlations first
sns.scatterplot(student["Hours"], student["Scores"])
sns.lmplot("Hours", "Scores", data=student)
# Separate the given dataset into its features and target variables
features = student.drop("Scores", axis=1)
target = student["Scores"]
X = features
y = target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2, random_state=42)
regressor = LinearRegression()
regressor.fit(X_train, y_train)
print("Training complete.")
# Plotting the regression line on the entire data
line = regressor.coef_ * X + regressor.intercept_
# Plotting for the entire data
plt.scatter(X, y)
plt.plot(X, line);
plt.show()
print(X_test) # Testing data - In Hours
y_pred = regressor.predict(X_test) # Predicting the scores
# Comparing Actual vs Predicted
df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
df
# Testing with sample data.
hours = 9.25
own_pred = regressor.predict([[hours]])
print("No of Hours = {}".format(hours))
print("Predicted Score = {}".format(own_pred[0]))
print(f'Mean Absolute Error: {metrics.mean_absolute_error(y_test, y_pred)}')
print(f'Root Mean Squared Error: {metrics.mean_squared_error(y_test, y_pred, squared=False)}')
| 0.82251 | 0.990542 |
# Intro to TensorFlow
This notebook covers the basics of TF and shows you an animation with gradient descent trajectory.
<img src="images/gradient_descent.png" style="width:50%">
# TensorBoard
**Plase note that if you are running on the Coursera platform, you won't be able to access the tensorboard instance due to the network setup there.**
Run `tensorboard --logdir=./tensorboard_logs --port=7007` in bash.
If you run the notebook locally, you should be able to access TensorBoard on http://127.0.0.1:7007/
```
# Load the TensorBoard notebook extension
%load_ext tensorboard
import tensorflow as tf
import sys
sys.path.append("../..")
print("We're using TF", tf.__version__)
# Clear any logs from previous runs
!rm -rf ./tensorboard_logs/
```
# Warming up
For starters, let's implement a python function that computes the sum of squares of numbers from 0 to N-1.
```
import numpy as np
def sum_python(N):
return np.sum(np.arange(N)**2)
%%time
sum_python(10**5)
```
# Tensoflow teaser
Doing the very same thing
```
%%time
# An integer parameter
def reduce_sum(N):
return tf.reduce_sum(tf.range(N, dtype='float32')**2)
N = 10**5
reduce_sum(N).numpy()
# logger for tensorboard
writer = tf.summary.create_file_writer("tensorboard_logs")
```
# How does it work?
1. Define placeholders where you'll send inputs
2. Make a symbolic graph: a recipe for mathematical transformation of those placeholders
3. Compute outputs of your graph with particular values for each placeholder
* `output.eval({placeholder: value})`
* `s.run(output, {placeholder: value})`
So far there are two main entities: "placeholder" and "transformation" (operation output)
* Both can be numbers, vectors, matrices, tensors, etc.
* Both can be int32/64, floats, booleans (uint8) of various size.
* You can define new transformations as an arbitrary operation on placeholders and other transformations
* `tf.reduce_sum(tf.arange(N)**2)` are 3 sequential transformations of placeholder `N`
* There's a tensorflow symbolic version for every numpy function
* `a+b, a/b, a**b, ...` behave just like in numpy
* `np.mean` -> `tf.reduce_mean`
* `np.arange` -> `tf.range`
* `np.cumsum` -> `tf.cumsum`
* If you can't find the operation you need, see the [docs](https://www.tensorflow.org/versions/r1.3/api_docs/python).
`tf.contrib` has many high-level features, may be worth a look.
```
with tf.name_scope("Placeholders_examples"):
# Default placeholder that can be arbitrary float32
# scalar, vertor, matrix, etc.
arbitrary_input = tf.keras.backend.placeholder(dtype = 'float32')
# Input vector of arbitrary length
input_vector = tf.keras.backend.placeholder(dtype = 'float32', shape=(None,))
# Input vector that _must_ have 10 elements and integer type
fixed_vector = tf.keras.backend.placeholder(dtype = 'int32', shape=(10,))
# Matrix of arbitrary n_rows and 15 columns
# (e.g. a minibatch of your data table)
input_matrix = tf.keras.backend.placeholder(dtype = 'float32', shape=(None, 15))
# You can generally use None whenever you don't need a specific shape
input1 = tf.keras.backend.placeholder(dtype = 'float64', shape=(None, 100, None))
input2 = tf.keras.backend.placeholder(dtype = 'int32', shape=(None, None, 3, 224, 224))
# elementwise multiplication
double_the_vector = input_vector*2
# elementwise cosine
elementwise_cosine = tf.cos(input_vector)
# difference between squared vector and vector itself plus one
vector_squares = input_vector**2 - input_vector + 1
def transformation(vector1, vector2):
return vector1 * vector2 / (tf.sin(vector1) + 1)
my_vector = tf.keras.backend.placeholder(dtype = 'float32', shape=(None,), name="VECTOR_1")
dummy = np.arange(5).astype('float32')
print(dummy)
my_vector = transformation(dummy, dummy[::-1])
print(my_vector)
with writer.as_default():
for step in range(100):
# other model code would go here
tf.summary.scalar("my_metric", 0.5, step=step)
writer.flush()
```
TensorBoard allows writing scalars, images, audio, histogram. You can read more on tensorboard usage [here](https://www.tensorflow.org/get_started/graph_viz).
# Summary
* Tensorflow is based on computation graphs
* A graph consists of placeholders and transformations
# Loss function: Mean Squared Error
Loss function must be a part of the graph as well, so that we can do backpropagation.
```
@tf.function
def compute_mse(y_true, y_predicted):
y_true = tf.dtypes.cast(y_true, tf.float32)
y_predicted = tf.dtypes.cast(y_predicted, tf.float32)
return tf.cast(tf.reduce_mean(tf.square(y_true - y_predicted)), dtype = 'float32', name='MSE')
with writer.as_default():
for step in range(100):
# other model code would go here
tf.summary.scalar("my_metric", 0.5, step=step)
writer.flush()
# Rigorous local testing of MSE implementation
import sklearn.metrics
for n in [1, 5, 10, 10**3]:
elems = [np.arange(n), np.arange(n, 0, -1), np.zeros(n),
np.ones(n), np.random.random(n), np.random.randint(100, size=n)]
for el in elems:
for el_2 in elems:
true_mse = np.array(sklearn.metrics.mean_squared_error(el, el_2))
my_mse = compute_mse(el, el_2)
if not np.allclose(true_mse, my_mse):
print('mse(%s,%s)' % (el, el_2))
print("should be: %f, but your function returned %f" % (true_mse, my_mse))
raise ValueError('Wrong result')
```
# Variables
Placeholder and transformation values are not stored in the graph once the execution is finished. This isn't too comfortable if you want your model to have parameters (e.g. network weights) that are always present, but can change their value over time.
Tensorflow solves this with `tf.Variable` objects.
* You can assign variable a value at any time in your graph
* Unlike placeholders, there's no need to explicitly pass values to variables when `s.run(...)`-ing
* You can use variables the same way you use transformations
```
# Creating a shared variable
shared_vector_1 = tf.Variable(initial_value=np.ones(5),
name="example_variable")
print("Initial value", shared_vector_1.numpy())
# Setting a new value
shared_vector_1.assign(np.arange(5))
# Getting that new value
print("New value", shared_vector_1.numpy())
```
# tf.gradients - why graphs matter
* Tensorflow can compute derivatives and gradients automatically using the computation graph
* True to its name it can manage matrix derivatives
* Gradients are computed as a product of elementary derivatives via the chain rule:
$$ {\partial f(g(x)) \over \partial x} = {\partial f(g(x)) \over \partial g(x)}\cdot {\partial g(x) \over \partial x} $$
It can get you the derivative of any graph as long as it knows how to differentiate elementary operations
```
def gradientScalar(my_scalar):
with tf.GradientTape() as g:
g.watch(my_scalar)
scalar_squared = my_scalar**2
# A derivative of scalar_squared by my_scalar
return g.gradient(scalar_squared, [my_scalar, ])
import matplotlib.pyplot as plt
%matplotlib inline
x = tf.linspace(-3.0, 3.0, 100)
x_squared, x_squared_der = [x**2, gradientScalar(x)[0]]
plt.plot(x, x_squared,label="$x^2$")
plt.plot(x, x_squared_der, label=r"$\frac{dx^2}{dx}$")
plt.legend();
```
# Why that rocks
```
def gradientScalar(my_scalar, my_vector):
with tf.GradientTape(persistent=True) as g:
g.watch(my_scalar)
weird_psychotic_function = tf.reduce_mean(
(my_vector + my_scalar)**(1 + tf.nn.moments(my_vector,[0])[1]) +
1./ tf.atan(my_scalar))/(my_scalar**2 + 1) + 0.01*tf.sin(
2*my_scalar**1.5)*(tf.reduce_sum(my_vector)* my_scalar**2
)*tf.exp((my_scalar-4)**2)/(
1+tf.exp((my_scalar-4)**2))*(1.-(tf.exp(-(my_scalar-4)**2)
)/(1+tf.exp(-(my_scalar-4)**2)))**2
return g.gradient(weird_psychotic_function, my_scalar), weird_psychotic_function
def gradientVector(my_scalar, my_vector):
with tf.GradientTape() as g:
g.watch(my_vector)
weird_psychotic_function = tf.reduce_mean(
(my_vector + my_scalar)**(1 + tf.nn.moments(my_vector,[0])[1]) +
1./ tf.atan(my_scalar))/(my_scalar**2 + 1) + 0.01*tf.sin(
2*my_scalar**1.5)*(tf.reduce_sum(my_vector)* my_scalar**2
)*tf.exp((my_scalar-4)**2)/(
1+tf.exp((my_scalar-4)**2))*(1.-(tf.exp(-(my_scalar-4)**2)
)/(1+tf.exp(-(my_scalar-4)**2)))**2
return g.gradient(weird_psychotic_function, my_vector), weird_psychotic_function
# Plotting the derivative
scalar_space = tf.linspace(1.0, 7.0, 100)
my_vector = tf.constant([1.0, 2.0, 3.0])
y_der_by_scalar = []
func = []
for x in scalar_space:
df_dy, y = gradientScalar(x, my_vector)
y_der_by_scalar.append(df_dy)
func.append(y)
y_der_by_scalar = tf.stack(y_der_by_scalar)
func = tf.stack(func)
plt.plot(scalar_space, func, label='function')
plt.plot(scalar_space, y_der_by_scalar, label='derivative')
plt.grid()
plt.legend();
```
# Almost done - optimizers
While you can perform gradient descent by hand with automatic gradients from above, tensorflow also has some optimization methods implemented for you. Recall momentum & rmsprop?
```
y_guess = tf.Variable(np.zeros(2, dtype='float32'))
y_true = tf.range(1, 3, dtype='float32')
loss = lambda: tf.reduce_mean((y_guess - y_true + 0.5*tf.random.normal([2]))**2)
def step():
tf.keras.optimizers.SGD(learning_rate=0.03, momentum=0.5).minimize(loss, var_list=y_guess)
```
Let's draw a trajectory of a gradient descent in 2D
```
from matplotlib import animation, rc
import matplotlib_utils
from IPython.display import HTML, display_html
# nice figure settings
fig, ax = plt.subplots()
y_true_value = y_true
level_x = np.arange(0, 2, 0.02)
level_y = np.arange(0, 3, 0.02)
X, Y = np.meshgrid(level_x, level_y)
Z = (X - y_true_value[0])**2 + (Y - y_true_value[1])**2
ax.set_xlim(-0.02, 2)
ax.set_ylim(-0.02, 3)
ax.scatter(*y_true, c='red')
contour = ax.contour(X, Y, Z, 10)
ax.clabel(contour, inline=1, fontsize=10)
line, = ax.plot([], [], lw=2)
# start animation with empty trajectory
def init():
line.set_data([], [])
return (line,)
trajectory = [y_guess.numpy()]
# one animation step (make one GD step)
def animate(i):
step()
trajectory.append(y_guess.numpy())
line.set_data(*zip(*trajectory))
return (line,)
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)
try:
display_html(HTML(anim.to_html5_video()))
except (RuntimeError, KeyError):
# In case the build-in renderers are unaviable, fall back to
# a custom one, that doesn't require external libraries
anim.save(None, writer=matplotlib_utils.SimpleMovieWriter(0.001))
```
|
github_jupyter
|
# Load the TensorBoard notebook extension
%load_ext tensorboard
import tensorflow as tf
import sys
sys.path.append("../..")
print("We're using TF", tf.__version__)
# Clear any logs from previous runs
!rm -rf ./tensorboard_logs/
import numpy as np
def sum_python(N):
return np.sum(np.arange(N)**2)
%%time
sum_python(10**5)
%%time
# An integer parameter
def reduce_sum(N):
return tf.reduce_sum(tf.range(N, dtype='float32')**2)
N = 10**5
reduce_sum(N).numpy()
# logger for tensorboard
writer = tf.summary.create_file_writer("tensorboard_logs")
with tf.name_scope("Placeholders_examples"):
# Default placeholder that can be arbitrary float32
# scalar, vertor, matrix, etc.
arbitrary_input = tf.keras.backend.placeholder(dtype = 'float32')
# Input vector of arbitrary length
input_vector = tf.keras.backend.placeholder(dtype = 'float32', shape=(None,))
# Input vector that _must_ have 10 elements and integer type
fixed_vector = tf.keras.backend.placeholder(dtype = 'int32', shape=(10,))
# Matrix of arbitrary n_rows and 15 columns
# (e.g. a minibatch of your data table)
input_matrix = tf.keras.backend.placeholder(dtype = 'float32', shape=(None, 15))
# You can generally use None whenever you don't need a specific shape
input1 = tf.keras.backend.placeholder(dtype = 'float64', shape=(None, 100, None))
input2 = tf.keras.backend.placeholder(dtype = 'int32', shape=(None, None, 3, 224, 224))
# elementwise multiplication
double_the_vector = input_vector*2
# elementwise cosine
elementwise_cosine = tf.cos(input_vector)
# difference between squared vector and vector itself plus one
vector_squares = input_vector**2 - input_vector + 1
def transformation(vector1, vector2):
return vector1 * vector2 / (tf.sin(vector1) + 1)
my_vector = tf.keras.backend.placeholder(dtype = 'float32', shape=(None,), name="VECTOR_1")
dummy = np.arange(5).astype('float32')
print(dummy)
my_vector = transformation(dummy, dummy[::-1])
print(my_vector)
with writer.as_default():
for step in range(100):
# other model code would go here
tf.summary.scalar("my_metric", 0.5, step=step)
writer.flush()
@tf.function
def compute_mse(y_true, y_predicted):
y_true = tf.dtypes.cast(y_true, tf.float32)
y_predicted = tf.dtypes.cast(y_predicted, tf.float32)
return tf.cast(tf.reduce_mean(tf.square(y_true - y_predicted)), dtype = 'float32', name='MSE')
with writer.as_default():
for step in range(100):
# other model code would go here
tf.summary.scalar("my_metric", 0.5, step=step)
writer.flush()
# Rigorous local testing of MSE implementation
import sklearn.metrics
for n in [1, 5, 10, 10**3]:
elems = [np.arange(n), np.arange(n, 0, -1), np.zeros(n),
np.ones(n), np.random.random(n), np.random.randint(100, size=n)]
for el in elems:
for el_2 in elems:
true_mse = np.array(sklearn.metrics.mean_squared_error(el, el_2))
my_mse = compute_mse(el, el_2)
if not np.allclose(true_mse, my_mse):
print('mse(%s,%s)' % (el, el_2))
print("should be: %f, but your function returned %f" % (true_mse, my_mse))
raise ValueError('Wrong result')
# Creating a shared variable
shared_vector_1 = tf.Variable(initial_value=np.ones(5),
name="example_variable")
print("Initial value", shared_vector_1.numpy())
# Setting a new value
shared_vector_1.assign(np.arange(5))
# Getting that new value
print("New value", shared_vector_1.numpy())
def gradientScalar(my_scalar):
with tf.GradientTape() as g:
g.watch(my_scalar)
scalar_squared = my_scalar**2
# A derivative of scalar_squared by my_scalar
return g.gradient(scalar_squared, [my_scalar, ])
import matplotlib.pyplot as plt
%matplotlib inline
x = tf.linspace(-3.0, 3.0, 100)
x_squared, x_squared_der = [x**2, gradientScalar(x)[0]]
plt.plot(x, x_squared,label="$x^2$")
plt.plot(x, x_squared_der, label=r"$\frac{dx^2}{dx}$")
plt.legend();
def gradientScalar(my_scalar, my_vector):
with tf.GradientTape(persistent=True) as g:
g.watch(my_scalar)
weird_psychotic_function = tf.reduce_mean(
(my_vector + my_scalar)**(1 + tf.nn.moments(my_vector,[0])[1]) +
1./ tf.atan(my_scalar))/(my_scalar**2 + 1) + 0.01*tf.sin(
2*my_scalar**1.5)*(tf.reduce_sum(my_vector)* my_scalar**2
)*tf.exp((my_scalar-4)**2)/(
1+tf.exp((my_scalar-4)**2))*(1.-(tf.exp(-(my_scalar-4)**2)
)/(1+tf.exp(-(my_scalar-4)**2)))**2
return g.gradient(weird_psychotic_function, my_scalar), weird_psychotic_function
def gradientVector(my_scalar, my_vector):
with tf.GradientTape() as g:
g.watch(my_vector)
weird_psychotic_function = tf.reduce_mean(
(my_vector + my_scalar)**(1 + tf.nn.moments(my_vector,[0])[1]) +
1./ tf.atan(my_scalar))/(my_scalar**2 + 1) + 0.01*tf.sin(
2*my_scalar**1.5)*(tf.reduce_sum(my_vector)* my_scalar**2
)*tf.exp((my_scalar-4)**2)/(
1+tf.exp((my_scalar-4)**2))*(1.-(tf.exp(-(my_scalar-4)**2)
)/(1+tf.exp(-(my_scalar-4)**2)))**2
return g.gradient(weird_psychotic_function, my_vector), weird_psychotic_function
# Plotting the derivative
scalar_space = tf.linspace(1.0, 7.0, 100)
my_vector = tf.constant([1.0, 2.0, 3.0])
y_der_by_scalar = []
func = []
for x in scalar_space:
df_dy, y = gradientScalar(x, my_vector)
y_der_by_scalar.append(df_dy)
func.append(y)
y_der_by_scalar = tf.stack(y_der_by_scalar)
func = tf.stack(func)
plt.plot(scalar_space, func, label='function')
plt.plot(scalar_space, y_der_by_scalar, label='derivative')
plt.grid()
plt.legend();
y_guess = tf.Variable(np.zeros(2, dtype='float32'))
y_true = tf.range(1, 3, dtype='float32')
loss = lambda: tf.reduce_mean((y_guess - y_true + 0.5*tf.random.normal([2]))**2)
def step():
tf.keras.optimizers.SGD(learning_rate=0.03, momentum=0.5).minimize(loss, var_list=y_guess)
from matplotlib import animation, rc
import matplotlib_utils
from IPython.display import HTML, display_html
# nice figure settings
fig, ax = plt.subplots()
y_true_value = y_true
level_x = np.arange(0, 2, 0.02)
level_y = np.arange(0, 3, 0.02)
X, Y = np.meshgrid(level_x, level_y)
Z = (X - y_true_value[0])**2 + (Y - y_true_value[1])**2
ax.set_xlim(-0.02, 2)
ax.set_ylim(-0.02, 3)
ax.scatter(*y_true, c='red')
contour = ax.contour(X, Y, Z, 10)
ax.clabel(contour, inline=1, fontsize=10)
line, = ax.plot([], [], lw=2)
# start animation with empty trajectory
def init():
line.set_data([], [])
return (line,)
trajectory = [y_guess.numpy()]
# one animation step (make one GD step)
def animate(i):
step()
trajectory.append(y_guess.numpy())
line.set_data(*zip(*trajectory))
return (line,)
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)
try:
display_html(HTML(anim.to_html5_video()))
except (RuntimeError, KeyError):
# In case the build-in renderers are unaviable, fall back to
# a custom one, that doesn't require external libraries
anim.save(None, writer=matplotlib_utils.SimpleMovieWriter(0.001))
| 0.734596 | 0.971725 |
# About: Hivemall - Ready! on Hive
----
すでにHiveがインストールされた環境にHivemallをインストールします。
## *Operation Note*
*This is a cell for your own recording. ここに経緯を記述*
# 操作対象クラスタの設定
起動したい対象のクラスタ名を設定する。
```
target_group = 'hadoop_all_testcluster'
```
対象クラスタにAnsibleでpingできることを確認する。
```
!ansible -m ping {target_group}
```
インストール対象は、 `hadoop_client` というグループに所属しているものとする。
```
!ansible -m ping hadoop_hive -l {target_group}
```
# 設定の定義
インストール対象パスなど、設定を定義する。
```
hivemall_install_path = '/usr/local/lib'
```
インストールするhivemallのバージョンを定義する。
https://github.com/myui/hivemall
```
hivemall_version = 'v0.4.0-2'
```
Playbookなど定義するための一時ディレクトリを定義しておく。
```
import os
import tempfile
work_dir = tempfile.mkdtemp()
work_dir
```
# hivemallのインストール
hivemallのjarファイルはGitからcloneしてくる・・・まずは対象ホストにgitをインストールする。
```
!ansible -b -m yum -a 'name=git state=latest' hadoop_hive -l {target_group}
```
リポジトリからcloneしてくる。
```
!ansible -b -m git -a 'repo=https://github.com/myui/hivemall.git dest={ hivemall_install_path }/hivemall-{ hivemall_version } version={ hivemall_version }' \
hadoop_hive -l {target_group}
```
`hivemall-with-dependencies.jar` が作成されていることを確認する。
```
!ansible -a 'ls -la { hivemall_install_path }/hivemall-{ hivemall_version }/target/hivemall-with-dependencies.jar' \
hadoop_hive -l {target_group}
```
`.hiverc` を設定する。
```
with open(os.path.join(work_dir, '.hiverc'), 'w') as f:
f.write('''add jar {hivemall_install_path}/hivemall-{hivemall_version}/target/hivemall-with-dependencies.jar;
source {hivemall_install_path}/hivemall-{hivemall_version}/scripts/ddl/define-all.hive;'''.format(hivemall_install_path=hivemall_install_path,
hivemall_version=hivemall_version))
!cat {work_dir}/.hiverc
```
ユーザに .hiverc を配布する。ここでは、対象マシンの全ユーザに登録してみる。
```
!ansible -m fetch -a 'src=/etc/passwd dest={work_dir}/passwd flat=yes' hadoop_hive -l {target_group}
```
ここでは、shellがbashかつHDPインストール時に登録されたユーザでなければ登録対象とする。
```
home = {}
hdp_sys_user = ['hdfs', 'mapred', 'zookeeper', 'yarn', 'spark', 'hive', 'hbase']
with open(os.path.join(work_dir, 'passwd'), 'r') as file_object:
for line in file_object:
fields = line.strip().split(":")
if fields[-1] == '/bin/bash' and fields[0] not in hdp_sys_user:
home[fields[0]] = fields[-2]
home.items()
```
各ユーザのhomeに.hivercを配布する。
```
for owner, path in home.items():
!ansible -b -m copy -a 'src={work_dir}/.hiverc dest={path}/.hiverc owner={owner} group={owner}' \
hadoop_hive -l {target_group}
```
# 動作確認
Hivemallのバージョンを確認する。
```
!ansible -m shell -a 'echo "SELECT HIVEMALL_VERSION();" | hive' hadoop_hive -l {target_group}
```
# 後始末
一時ディレクトリを削除する。
```
!rm -fr {work_dir}
```
|
github_jupyter
|
target_group = 'hadoop_all_testcluster'
!ansible -m ping {target_group}
!ansible -m ping hadoop_hive -l {target_group}
hivemall_install_path = '/usr/local/lib'
hivemall_version = 'v0.4.0-2'
import os
import tempfile
work_dir = tempfile.mkdtemp()
work_dir
!ansible -b -m yum -a 'name=git state=latest' hadoop_hive -l {target_group}
!ansible -b -m git -a 'repo=https://github.com/myui/hivemall.git dest={ hivemall_install_path }/hivemall-{ hivemall_version } version={ hivemall_version }' \
hadoop_hive -l {target_group}
!ansible -a 'ls -la { hivemall_install_path }/hivemall-{ hivemall_version }/target/hivemall-with-dependencies.jar' \
hadoop_hive -l {target_group}
with open(os.path.join(work_dir, '.hiverc'), 'w') as f:
f.write('''add jar {hivemall_install_path}/hivemall-{hivemall_version}/target/hivemall-with-dependencies.jar;
source {hivemall_install_path}/hivemall-{hivemall_version}/scripts/ddl/define-all.hive;'''.format(hivemall_install_path=hivemall_install_path,
hivemall_version=hivemall_version))
!cat {work_dir}/.hiverc
!ansible -m fetch -a 'src=/etc/passwd dest={work_dir}/passwd flat=yes' hadoop_hive -l {target_group}
home = {}
hdp_sys_user = ['hdfs', 'mapred', 'zookeeper', 'yarn', 'spark', 'hive', 'hbase']
with open(os.path.join(work_dir, 'passwd'), 'r') as file_object:
for line in file_object:
fields = line.strip().split(":")
if fields[-1] == '/bin/bash' and fields[0] not in hdp_sys_user:
home[fields[0]] = fields[-2]
home.items()
for owner, path in home.items():
!ansible -b -m copy -a 'src={work_dir}/.hiverc dest={path}/.hiverc owner={owner} group={owner}' \
hadoop_hive -l {target_group}
!ansible -m shell -a 'echo "SELECT HIVEMALL_VERSION();" | hive' hadoop_hive -l {target_group}
!rm -fr {work_dir}
| 0.169269 | 0.792464 |
# Demo: Simulation of Tyrosine NMR Spectrum
This notebook shows how the **nmrsim** library can be used to compose an entire <sup>1</sup>H NMR spectrum from scratch.
The nmrsim.plt routines are convenient for quick plots, but for entire spectrums their small size and low resolution is noticeable (e.g. misleading signal intensities).
*{TODO: provide ways to customize the plots (e.g. have `plt.mplplot` return the actual matplotlib object for customization, or use the peaklist data in another visualization library).}*
This tutorial is adapted from the [nmrmint](https://nmrmint.readthedocs.io/en/latest/tutorial.html) tutorial.
*(If you're interested in an app for the simulation of a complete NMR spectrum, see the [nmrmit project](https://github.com/sametz/nmrmint).)*
```
import os
import sys
import numpy as np
import matplotlib as mpl
mpl.rcParams['figure.dpi']= 300
%config InlineBackend.figure_format = 'svg' # makes inline plot look less blurry
%matplotlib inline
home_path = os.path.abspath(os.path.join('..', '..', '..'))
if home_path not in sys.path:
sys.path.append(home_path)
tests_path = os.path.abspath(os.path.join('..', '..', '..', 'tests'))
if tests_path not in sys.path:
sys.path.append(tests_path)
```
Here is the data for the spectrum of tyrosine in D<sub>2</sub>O:
1H NMR (500 MHz, Deuterium Oxide) δ 7.18 (d, J = 8.5 Hz, 1H), 6.89 (d, J = 8.5 Hz, 1H), 3.93 (dd, J = 7.7, 5.1 Hz, 1H),
3.19 (dd, J = 14.7, 5.1 Hz, 1H), 3.05 (dd, J = 14.7, 7.8 Hz, 1H).
Data is provided in ppm on a 500 MHz spectrometer. We'll create a function to perform ppm-to-Hz conversions for us:
```
def ppm_to_hz(ppm, spec_freq):
"""Given a chemical shift in ppm and spectrometer frequency in MHz, return the corresponding chemical shift in Hz."""
return [d * spec_freq for d in ppm]
```
The two "doublets" in the aromatic region actually comprise an AA'XX' system. This 4-nuclei spin system can be modeled using the SpinSystem class:
```
from nmrsim import SpinSystem
```
Create a frequency list (in Hz) for the A, A', X, and X' nuclei:
```
v_aaxx = ppm_to_hz([7.18, 7.18, 6.89, 6.89], 500)
v_aaxx
```
For the *J* values, as a first approximation we'll assume J<sub>AX</sub> (an J<sub>A'X'</sub>) are close to the faux-doublet splitting of 8.5 Hz. We'll estimate that J<sub>AA'</sub> and J<sub>XX'</sub> are about 2 Hz, and that the J<sub>AX'</sub> and J<sub>A'X</sub> couplings are about 0 Hz.
```
j_aaxx = [[0, 2, 8.5, 0],
[2, 0, 0, 8.5],
[8.5, 0, 0, 2],
[0, 8.5, 2, 0]]
aaxx = SpinSystem(v_aaxx, j_aaxx)
from nmrsim.plt import mplplot, mplplot_lineshape
mplplot(aaxx.peaklist());
```
Next, we'll create the ABX system for the aliphatic protons. For this exercise, we are assuming that the coupling constants that the first-order analysis provided are close enough.
*(If accuracy is critical, there are methods for solving the ABX system. For example, see https://www.chem.wisc.edu/areas/reich/nmr/05-hmr-12-abx.htm#solving%20ABX )*
```
v_abx = ppm_to_hz([3.93,3.19, 3.05], 500)
j_abx = [[0, 5.1, 7.75],
[5.1, 0, -14.7], # geminal Js should be negative
[7.75, -14.7, 0]]
abx = SpinSystem(v_abx, j_abx)
mplplot(abx.peaklist(), y_max=0.2);
```
These spin systems can be combined into a spectrum:
```
tyr_spectrum = aaxx + abx
mplplot(tyr_spectrum.peaklist(), y_max=0.2)
type(tyr_spectrum)
```
Addition of the two SpinSystem objects returned a Spectrum object.
If peak intensities look off, try using more data points for the lineshape. Here is the same example with ~ 10 data points per Hz:
```
points=int((tyr_spectrum.vmax - tyr_spectrum.vmin) * 10)
print(points)
mplplot(tyr_spectrum.peaklist(), y_max=0.5, points=points);
```
The Spectrum class can also provide lineshape data for the spectrum:
```
mplplot_lineshape(*tyr_spectrum.lineshape(points=points));
```
The Spectrum.linewidth() method has an advantage over the .peaklist() method: it can take into account the linewidths specified by its component Multiplet/SpinSystem objects. The default value is 0.5 Hz, but this can be set to other values.
In D<sub>2</sub>O, the -OH and -NH protons are exchanged for D and are not seen in the spectrum. If we wanted to include these in the spectrum for pedagogical reasons, we could create broad singlets with the Multiplet class:
```
from nmrsim import Multiplet
# frequency in Hz, integration, [empty list for no coupling constants], peakwidth = 20 Hz
nh3 = Multiplet(8.3 * 500, 3, [], 20)
tyr_oh = Multiplet(9.8 * 500, 1, [], 10)
tyr_spectrum2 = tyr_spectrum + nh3 + tyr_oh
```
A Spectrum can have its .vmin and .vmax attributes reset to give a full spectral window (defaults are to provide a 50 Hz margin):
```
tyr_spectrum2.default_limits() # resets limits, and returns vmin, vmax tuple
points2 = int((tyr_spectrum2.vmax - tyr_spectrum2.vmin) * 10)
mplplot_lineshape(*tyr_spectrum2.lineshape(points=points2));
```
What if you want the x axis to be in ppm?
```
# A future version of nmrsim should extend the API to facilitate using ppm in simulations.
# For now, simulations use Hz only, and ppm conversions need to be done manually.
tyr_spectrum2.vmin = -0.5 * 500
tyr_spectrum2.vmax = 10.5 * 500
x, y = tyr_spectrum2.lineshape(points=50000)
x_ppm = x / 500
mplplot_lineshape(x_ppm, y, limits=(-0.5, 10.5));
```
|
github_jupyter
|
import os
import sys
import numpy as np
import matplotlib as mpl
mpl.rcParams['figure.dpi']= 300
%config InlineBackend.figure_format = 'svg' # makes inline plot look less blurry
%matplotlib inline
home_path = os.path.abspath(os.path.join('..', '..', '..'))
if home_path not in sys.path:
sys.path.append(home_path)
tests_path = os.path.abspath(os.path.join('..', '..', '..', 'tests'))
if tests_path not in sys.path:
sys.path.append(tests_path)
def ppm_to_hz(ppm, spec_freq):
"""Given a chemical shift in ppm and spectrometer frequency in MHz, return the corresponding chemical shift in Hz."""
return [d * spec_freq for d in ppm]
from nmrsim import SpinSystem
v_aaxx = ppm_to_hz([7.18, 7.18, 6.89, 6.89], 500)
v_aaxx
j_aaxx = [[0, 2, 8.5, 0],
[2, 0, 0, 8.5],
[8.5, 0, 0, 2],
[0, 8.5, 2, 0]]
aaxx = SpinSystem(v_aaxx, j_aaxx)
from nmrsim.plt import mplplot, mplplot_lineshape
mplplot(aaxx.peaklist());
v_abx = ppm_to_hz([3.93,3.19, 3.05], 500)
j_abx = [[0, 5.1, 7.75],
[5.1, 0, -14.7], # geminal Js should be negative
[7.75, -14.7, 0]]
abx = SpinSystem(v_abx, j_abx)
mplplot(abx.peaklist(), y_max=0.2);
tyr_spectrum = aaxx + abx
mplplot(tyr_spectrum.peaklist(), y_max=0.2)
type(tyr_spectrum)
points=int((tyr_spectrum.vmax - tyr_spectrum.vmin) * 10)
print(points)
mplplot(tyr_spectrum.peaklist(), y_max=0.5, points=points);
mplplot_lineshape(*tyr_spectrum.lineshape(points=points));
from nmrsim import Multiplet
# frequency in Hz, integration, [empty list for no coupling constants], peakwidth = 20 Hz
nh3 = Multiplet(8.3 * 500, 3, [], 20)
tyr_oh = Multiplet(9.8 * 500, 1, [], 10)
tyr_spectrum2 = tyr_spectrum + nh3 + tyr_oh
tyr_spectrum2.default_limits() # resets limits, and returns vmin, vmax tuple
points2 = int((tyr_spectrum2.vmax - tyr_spectrum2.vmin) * 10)
mplplot_lineshape(*tyr_spectrum2.lineshape(points=points2));
# A future version of nmrsim should extend the API to facilitate using ppm in simulations.
# For now, simulations use Hz only, and ppm conversions need to be done manually.
tyr_spectrum2.vmin = -0.5 * 500
tyr_spectrum2.vmax = 10.5 * 500
x, y = tyr_spectrum2.lineshape(points=50000)
x_ppm = x / 500
mplplot_lineshape(x_ppm, y, limits=(-0.5, 10.5));
| 0.439026 | 0.982203 |
```
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import warnings
warnings.filterwarnings("ignore")
Data=pd.read_csv("heart.csv")
Data.describe()
Data.info()
numerical_continuous = []
for column in Data.columns:
if Data[column].dtypes != 'object':
if Data[column].nunique() >= 10:
numerical_continuous.append(column)
numerical_continuous
Data[numerical_continuous].plot(kind = 'box', figsize = (8, 10.5))
threshold = 0.5
zscore = np.abs(stats.zscore(Data[['trestbps']]))
Data[(zscore > threshold).all(axis=1)][numerical_continuous].plot(kind = 'box', figsize = (8, 10.5))
def remove_outlier(col):
q25 = col.quantile(0.25)
q75 = col.quantile(0.75)
iqr = q75 - q25
cutoff = iqr*1.5
lower = q25 - cutoff
upper = q75 + cutoff
return lower, upper
lower, upper = remove_outlier(Data.chol)
Data = Data.loc[(Data.chol > lower) & (Data.chol < upper)]
sns.boxplot(Data.chol)
def remove_outlier(col):
q25 = col.quantile(0.25)
q75 = col.quantile(0.75)
iqr = q75 - q25
cutoff = iqr*1.5
lower = q25 - cutoff
upper = q75 + cutoff
return lower, upper
lower, upper = remove_outlier(Data.trestbps)
Data = Data.loc[(Data.trestbps > lower) & (Data.trestbps < upper)]
sns.boxplot(Data.trestbps)
def remove_outlier(col):
q25 = col.quantile(0.25)
q75 = col.quantile(0.75)
iqr = q75 - q25
cutoff = iqr*1.5
lower = q25 - cutoff
upper = q75 + cutoff
return lower, upper
lower, upper = remove_outlier(Data.thalach)
Data = Data.loc[(Data.thalach > lower) & (Data.thalach < upper)]
sns.boxplot(Data.thalach)
def remove_outlier(col):
q25 = col.quantile(0.25)
q75 = col.quantile(0.75)
iqr = q75 - q25
cutoff = iqr*1.5
lower = q25 - cutoff
upper = q75 + cutoff
return lower, upper
lower, upper = remove_outlier(Data.oldpeak)
Data = Data.loc[(Data.oldpeak > lower) & (Data.oldpeak < upper)]
sns.boxplot(Data.oldpeak)
Data[numerical_continuous].plot(kind = 'box', figsize = (8, 10.5))
#Binned the continuous column values apart from the column ‘oldpeak
Data_a=Data
x_a = Data_a.iloc[:, 1:-1]
y_a = Data_a.iloc[:, -1]
from sklearn.model_selection import train_test_split
x_a_train, x_a_test, y_a_train, y_a_test = train_test_split(x_a, y_a, test_size=0.3, random_state=1)
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, LabelBinarizer
from sklearn.preprocessing import OneHotEncoder
x_a_train['age_binned'] = pd.qcut(x_a_train.age, q=[0, .25, .50, .75, 1])
x_a_train['trestbps_binned'] = pd.qcut(x_a_train.trestbps, q=[0, .25, .50, .75, 1])
x_a_train['chol_binned'] = pd.qcut(x_a_train.chol, q=[0, .25, .50, .75, 1])
x_a_train['thalach_binned'] = pd.qcut(x_a_train.thalach, q=[0, .25, .50, .75, 1])
x_a_train.drop(columns=['age','trestbps','chol','thalach'], inplace=True)
x_a_train['age'] = transform(x_a_train['age_binned'])
x_a_train['trestbps'] = transform(x_a_train['trestbps_binned'])
x_a_train['chol'] = transform(x_a_train['chol_binned'])
x_a_train['thalach'] = transform(x_a_train['thalach_binned'])
x_a_train.drop(columns=['age','trestbps_binned', 'chol_binned', 'thalach'],inplace=True)
x_a_train.head()
```
#Separate the features from the labels and use the most appropriate feature selection
technique(s)
```
X=Data.drop('target', axis=1)
y = Data['target']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train.shape, X_test.shape, y_train.shape, y_test.shape
```
Slice the data and scale the features
```
from sklearn.preprocessing import StandardScaler,RobustScaler, MinMaxScaler
X=Data.iloc[:,1:13]
X
X = pd.Data(RobustScaler().fit_transform(X), columns=X.columns)
```
Identify the data if the data is balanced. If not, sample the data using the most appropriate
method keeping the size of the data in mind
```
pip install -U imbalanced-learn
from imblearn.over_sampling import SMOTE
from collections import Counter
oversample = SMOTE()
```
|
github_jupyter
|
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import warnings
warnings.filterwarnings("ignore")
Data=pd.read_csv("heart.csv")
Data.describe()
Data.info()
numerical_continuous = []
for column in Data.columns:
if Data[column].dtypes != 'object':
if Data[column].nunique() >= 10:
numerical_continuous.append(column)
numerical_continuous
Data[numerical_continuous].plot(kind = 'box', figsize = (8, 10.5))
threshold = 0.5
zscore = np.abs(stats.zscore(Data[['trestbps']]))
Data[(zscore > threshold).all(axis=1)][numerical_continuous].plot(kind = 'box', figsize = (8, 10.5))
def remove_outlier(col):
q25 = col.quantile(0.25)
q75 = col.quantile(0.75)
iqr = q75 - q25
cutoff = iqr*1.5
lower = q25 - cutoff
upper = q75 + cutoff
return lower, upper
lower, upper = remove_outlier(Data.chol)
Data = Data.loc[(Data.chol > lower) & (Data.chol < upper)]
sns.boxplot(Data.chol)
def remove_outlier(col):
q25 = col.quantile(0.25)
q75 = col.quantile(0.75)
iqr = q75 - q25
cutoff = iqr*1.5
lower = q25 - cutoff
upper = q75 + cutoff
return lower, upper
lower, upper = remove_outlier(Data.trestbps)
Data = Data.loc[(Data.trestbps > lower) & (Data.trestbps < upper)]
sns.boxplot(Data.trestbps)
def remove_outlier(col):
q25 = col.quantile(0.25)
q75 = col.quantile(0.75)
iqr = q75 - q25
cutoff = iqr*1.5
lower = q25 - cutoff
upper = q75 + cutoff
return lower, upper
lower, upper = remove_outlier(Data.thalach)
Data = Data.loc[(Data.thalach > lower) & (Data.thalach < upper)]
sns.boxplot(Data.thalach)
def remove_outlier(col):
q25 = col.quantile(0.25)
q75 = col.quantile(0.75)
iqr = q75 - q25
cutoff = iqr*1.5
lower = q25 - cutoff
upper = q75 + cutoff
return lower, upper
lower, upper = remove_outlier(Data.oldpeak)
Data = Data.loc[(Data.oldpeak > lower) & (Data.oldpeak < upper)]
sns.boxplot(Data.oldpeak)
Data[numerical_continuous].plot(kind = 'box', figsize = (8, 10.5))
#Binned the continuous column values apart from the column ‘oldpeak
Data_a=Data
x_a = Data_a.iloc[:, 1:-1]
y_a = Data_a.iloc[:, -1]
from sklearn.model_selection import train_test_split
x_a_train, x_a_test, y_a_train, y_a_test = train_test_split(x_a, y_a, test_size=0.3, random_state=1)
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, LabelBinarizer
from sklearn.preprocessing import OneHotEncoder
x_a_train['age_binned'] = pd.qcut(x_a_train.age, q=[0, .25, .50, .75, 1])
x_a_train['trestbps_binned'] = pd.qcut(x_a_train.trestbps, q=[0, .25, .50, .75, 1])
x_a_train['chol_binned'] = pd.qcut(x_a_train.chol, q=[0, .25, .50, .75, 1])
x_a_train['thalach_binned'] = pd.qcut(x_a_train.thalach, q=[0, .25, .50, .75, 1])
x_a_train.drop(columns=['age','trestbps','chol','thalach'], inplace=True)
x_a_train['age'] = transform(x_a_train['age_binned'])
x_a_train['trestbps'] = transform(x_a_train['trestbps_binned'])
x_a_train['chol'] = transform(x_a_train['chol_binned'])
x_a_train['thalach'] = transform(x_a_train['thalach_binned'])
x_a_train.drop(columns=['age','trestbps_binned', 'chol_binned', 'thalach'],inplace=True)
x_a_train.head()
X=Data.drop('target', axis=1)
y = Data['target']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train.shape, X_test.shape, y_train.shape, y_test.shape
from sklearn.preprocessing import StandardScaler,RobustScaler, MinMaxScaler
X=Data.iloc[:,1:13]
X
X = pd.Data(RobustScaler().fit_transform(X), columns=X.columns)
pip install -U imbalanced-learn
from imblearn.over_sampling import SMOTE
from collections import Counter
oversample = SMOTE()
| 0.617743 | 0.756313 |
# Introduction to Variant Allele Frequency
In the field of cancer research, calling mutations (_a.k.a_ variants) from the next-generation sequencing of the tumor sample is not an exact science. Each variant manifests itself in different ways within the data set and both biological and technical variance can make things challenging for the variant callers. Mutation caller tools provide additional metrics on each variant they call, to make it easier for researchers to investigate or filter variants for different purporses within different contexts.
The additional metrics on variants include but are not limited to: the depth of the sequencing around the variant, the number of reads supporting the reference or the mutated allele, the quality associated with the reads supporting a variant or how confident the tools was making a particular call. In this blog series, we are going to focus on the uses of one of these metrics, namely the **Variant Allele Frequency** (`VAF`).
VAF is a simple metric to describe what fraction of the reads spanning a particular variant region is supporting the variant — in other words, does not agree with the reference sequence. Files following the [Variant Call Format](https://en.wikipedia.org/wiki/Variant_Call_Format) standards report VAF under the `AF` field; but, it is also possible to calculate this value from the other annotation fields. As such, the following VCF annotations are all related to each other:
```
##FORMAT=<ID=AD,Number=.,Type=Integer,Description="Allelic depths for the ref and alt alleles in the order listed">
##FORMAT=<ID=DP,Number=1,Type=Integer,Description="Approximate read depth (reads with MQ=255 or with bad mates are filtered)">
##FORMAT=<ID=FA,Number=A,Type=Float,Description="Allele fraction of the alternate allele with regard to reference">
```
since:
\begin{equation*}
FA = \frac{AD_{alt}}{AD_{alt} + AD_{ref}} = \frac{AD_{alt}}{DP}.
\end{equation*}
As the name suggests, a variant's `VAF` ranges between `0` and `1`, where the former means there is no evidence in the read data supporting a variant and the latter indicates all reads from the sequencing data support the variants. In the tumor sequencing data from real patients, none of these extremes are observed due to the way variant calling algorithms work and the heterogenerity of a tumor sample (more on this later).
It is also worth noting that the stochastic nature of the sequencing technology causes the number of reads (supporting either the reference or the variant allele) to vary for each experiment. Because `VAF` is a ratio of two integers, the shallower the sequencing, the fewer reads fall onto the variant and the less stable the `VAF` becomes.
Despite all these caveats, the distribution of `VAF`s for a sample has a lot to offer in terms of understanding some of clinically relevant properties of a tumor sample; *e.g.* purity or hetetogeneity. Before getting into the details, let's do some simulation to get ourselves familiar with `VAF` distributions. For this, we will be needing a few helper utilities:
```
import pandas as pd
import numpy as np
```
Our goal here is to simulate 1000 variants and their `VAF` measures and investigate this data set from a higher level. Since we are not that interested in the location or the nucleotide change, we will drop these information and only fill in our table with relevant statistics: depth, number of reads supporting the reference and the variant allele, and the VAF:
```
number_of_variants = 1000
average_depth = 100 # 100X
index = range(0, number_of_variants)
columns = ['depth', 'ref', 'alt', 'vaf']
variants = pd.DataFrame(index=index, columns=columns)
```
We are going to estimate the coverage with a `lognormal` and the VAF with a `beta` distribution (since it is a ratio). To make things even easier, let's assume that all of our variants are heterozygous and our sample to have `100%` purity. With that, we expect the `VAF`s to be centered around `50%` (or `0.5`) since a heterozygous mutation means that only one out of the two alleles is altered:
```
from numpy.random import RandomState
rs = RandomState(42) # For reproducibility
lognormal_depths = rs.lognormal(mean=np.log(average_depth),
sigma=average_depth/100.0, # arbitrary sigma
size=number_of_variants)
variants['depth'] = lognormal_depths.astype(int)
beta_vafs = rs.beta(a=average_depth, b=average_depth, size=number_of_variants)
variants['vaf'] = beta_vafs
variants['alt'] = (variants.depth * variants.vaf).astype(int)
variants['ref'] = variants.depth - variants.alt
# Let's save this for future use
variants.to_csv("./data/0-random_variants.csv")
variants.head()
```
This is a good start: we now have 1000 variants with varying sequencing depth and `VAF` with some randomness to it. Let's take a look at how the overall distribution looks:
```
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)
# Get ready for our two panel descriptive plot
f, ax = plt.subplots(1, 2, sharex=False, sharey=False, figsize=(15, 5))
sns.distplot(variants.vaf, ax=ax[0])
ax[0].set_title("VAF distribution")
ax[0].set_xlabel("Variant Allele Frequency")
ax[0].set_ylabel("Number of variants")
ax[0].set_xlim(0, 1.0)
sns.regplot(x=variants.vaf, y=np.log10(variants.depth), ax=ax[1], fit_reg=False)
ax[1].set_title("VAF versus sequencing depth")
ax[1].set_xlabel("Variant Allele Frequency")
ax[1].set_ylabel("Depth (log10)")
ax[1].set_xlim(0, 1.0)
plt.show()
```
This is a pretty neat VAF distribution centered around `50%` as we expected. This is as good as it can get for a sequencing experiment; but, of course, things are far from being ideal in real world and we often see much more complicated `VAF` distributions for tumor samples. Here is a summary figure showing data coming from a lung tumor:

And it does look different compared what we have from our simulated data set! The reason our tumor plot looks different than our simulated one has a lot to do with the biology of the tumor; but, this is going to be the topic of another post where we will go into the details of how different properties of tumor samples can affect these distributions. We will even show that we can use a VCF file from a tumor sequencing experiment and recapitulate some of the properties of the tumor sample.
|
github_jupyter
|
##FORMAT=<ID=AD,Number=.,Type=Integer,Description="Allelic depths for the ref and alt alleles in the order listed">
##FORMAT=<ID=DP,Number=1,Type=Integer,Description="Approximate read depth (reads with MQ=255 or with bad mates are filtered)">
##FORMAT=<ID=FA,Number=A,Type=Float,Description="Allele fraction of the alternate allele with regard to reference">
import pandas as pd
import numpy as np
number_of_variants = 1000
average_depth = 100 # 100X
index = range(0, number_of_variants)
columns = ['depth', 'ref', 'alt', 'vaf']
variants = pd.DataFrame(index=index, columns=columns)
from numpy.random import RandomState
rs = RandomState(42) # For reproducibility
lognormal_depths = rs.lognormal(mean=np.log(average_depth),
sigma=average_depth/100.0, # arbitrary sigma
size=number_of_variants)
variants['depth'] = lognormal_depths.astype(int)
beta_vafs = rs.beta(a=average_depth, b=average_depth, size=number_of_variants)
variants['vaf'] = beta_vafs
variants['alt'] = (variants.depth * variants.vaf).astype(int)
variants['ref'] = variants.depth - variants.alt
# Let's save this for future use
variants.to_csv("./data/0-random_variants.csv")
variants.head()
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)
# Get ready for our two panel descriptive plot
f, ax = plt.subplots(1, 2, sharex=False, sharey=False, figsize=(15, 5))
sns.distplot(variants.vaf, ax=ax[0])
ax[0].set_title("VAF distribution")
ax[0].set_xlabel("Variant Allele Frequency")
ax[0].set_ylabel("Number of variants")
ax[0].set_xlim(0, 1.0)
sns.regplot(x=variants.vaf, y=np.log10(variants.depth), ax=ax[1], fit_reg=False)
ax[1].set_title("VAF versus sequencing depth")
ax[1].set_xlabel("Variant Allele Frequency")
ax[1].set_ylabel("Depth (log10)")
ax[1].set_xlim(0, 1.0)
plt.show()
| 0.635901 | 0.992393 |
<div style=" font-variant: small-caps;
font-weight: normal;
font-size: 30px;
text-align: center;
padding: 15px;
margin: 10px;">Convolutional Neural Network (CNN) for Handwritten Digits Recognition</div>
<div style=" font-variant: small-caps;
font-weight: normal;
font-size: 20px;
text-align: center;
padding: 15px;">Deep Learning</div>
<div style=" float:right;
font-size: 12px;
line-height: 12px;
padding: 10px 15px 8px;">Luca BENEDETTO | Alberto IBARRONDO</div>
<div style=" display: inline-block; font-family: 'Lato', sans-serif; font-size: 12px; font-weight: bold; line-height: 12px; letter-spacing: 1px; padding: 10px 15px 8px; ">29/05/2017</div>
# Summary
In the last notebook, we built a Multilayer Perceptron for recognizing hand-written digits from the MNIST data-set. The best achieved accuracy on testing data was about 97%, but modern implementations of Convolutional Neural Networks whould surpass that mark.
In this notebook, we will build, train and optimize in TensorFlow one of the early Convolutional Neural Networks, **LeNet-5**, and push it beyond 99% accuracy.
# 1. A first NeuralNetwork model in TensorFlow
## 1.1 Import Modules & Load MNIST Data in TensorFlow
```
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.layers import flatten
from __future__ import print_function
from numpy import array
import numpy as np
import time
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
X_train, y_train = mnist.train.images, mnist.train.labels
X_validation, y_validation = mnist.validation.images, mnist.validation.labels
X_test, y_test = mnist.test.images, mnist.test.labels
print("Image Shape: {}".format(X_train[0].shape[0]))
print("Training Set: {} samples".format(len(X_train)))
print("Validation Set: {} samples".format(len(X_validation)))
print("Test Set: {} samples".format(len(X_test)))
```
Before starting with CNN, let's train and test in TensorFlow a simple example :
**y=softmax(Wx+b)**
This model should reach an accuracy of about 92 %.
## 1.2 Coding the Graph and Training
```
#GRAPH DEFINITION
# Parameters
learning_rate = 0.01
training_epochs = 100
batch_size = 128
display_step = 1
logs_path = 'log_files/' # useful for tensorboard
# tf Graph Input: mnist data image of shape 28*28=784
x = tf.placeholder(tf.float32, [None, 784], name='InputData')
# 0-9 digits recognition, 10 classes
y = tf.placeholder(tf.float32, [None, 10], name='LabelData')
# Set model weights
W = tf.Variable(tf.zeros([784, 10]), name='Weights')
b = tf.Variable(tf.zeros([10]), name='Bias')
# Construct model and encapsulating all ops into scopes,
# making Tensorboard's Graph visualization more convenient
with tf.name_scope('Model'):
# Model
pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
with tf.name_scope('Loss'):
# Minimize error using cross entropy
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
with tf.name_scope('SGD'):
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
with tf.name_scope('Accuracy'):
# Accuracy
acc = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
acc = tf.reduce_mean(tf.cast(acc, tf.float32))
# Initializing the variables
init = tf.global_variables_initializer()
# Create a summary to monitor cost tensor
tf.summary.scalar("TrainingLoss", cost)
# Create a summary to monitor accuracy tensor
tf.summary.scalar("TrainingAccuracy", acc)
# Merge all summaries into a single op
merged_summary_op = tf.summary.merge_all()
#TRAINING
# Launch the graph for training
with tf.Session() as sess:
sess.run(init)
# op to write logs to Tensorboard
summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Run optimization op (backprop), cost op (to get loss value)
# and summary nodes
_, c, summary = sess.run([optimizer, cost, merged_summary_op],
feed_dict={x: batch_xs, y: batch_ys})
# Write logs at every iteration
summary_writer.add_summary(summary, epoch * total_batch + i)
# Compute average loss
avg_cost += c / total_batch
# Display logs per epoch step
if (epoch+1) % display_step == 0:
print("Epoch: ", '%02d' % (epoch+1), " =====> Loss=",
"{:.9f}".format(avg_cost))
print("Optimization Finished!")
# Test model
# Calculate accuracy
print("Accuracy:", acc.eval({x: mnist.test.images, y: mnist.test.labels}))
```
## 1.3 Visualization with Tensorboard
Using [Tensorboard](https://www.tensorflow.org/get_started/summaries_and_tensorboard), we can now visualize the created graph, giving us an overview of the architecture and how all of the major components are connected. You can also visalize and analyse the learning curves.
In order to launch tensorBoard we follow these steps:
- Open a Terminal and run the command line **"tensorboard --logdir=log_files/"**, it will generate an http link ,ex http://666.6.6.6:6006,
- Copy this link into a web browser
- Display the images!
<img src="MNIST_99_Challenge_Figures/Screenshot from 2017-05-26 17:53:17.png",width="800" height="600" align="center">
<center><span>Figure 1: Tensorboard visualization </span></center>
# 2. The 99% MNIST Challenge using CNNs
## 2.1 LeNet5 Implementation
Now that we are familiar with familar with **tensorFlow** and **tensorBoard**, we are going to build, train and test the baseline [LeNet-5](http://yann.lecun.com/exdb/lenet/) model for the MNIST digits recognition problem.
Further ahead we will make some optimizations to surpass 99% of accuracy. The best model so far achieved over 99.7% accuracy ([List of Results](http://rodrigob.github.io/are_we_there_yet/build/classification_datasets_results.html))
<img src="lenet.png",width="800" height="600" align="center">
<center><span>Figure 2: Lenet 5 </span></center>
The LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since MNIST images are grayscale, C is 1 in this case.
--------------------------
1. **Layer 1: Convolutional.** The output shape should be 28x28x6 **Activation.** sigmoid **Pooling.** The output shape should be 14x14x6.
-
2. **Layer 2: Convolutional.** The output shape should be 10x10x16. **Activation.** sigmoid **Pooling.** The output shape should be 5x5x16.
3. **Flatten.** Flatten the output shape of the final pooling layer such that it's 1D instead of 3D. You may need to use **flatten* from tensorflow.contrib.layers import flatten
4. **Layer 3: Fully Connected.** This should have 120 outputs. **Activation.** sigmoid
5. **Layer 4: Fully Connected.** This should have 84 outputs. **Activation.** sigmoid
6. **Layer 5: Fully Connected.** This should have 10 outputs. **Activation.** softmax
### 2.1.1 LeNet5 model Implementation [Question 2.1.1]
The implementation draws classes and functions from the [Tensorflow API](https://www.tensorflow.org/api_docs/python/tf/nn).
```
# LeNet5 variables init
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.01)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
These functions are used for weigths and bias initilization. The standard deviation in the weights can be tuned in case we find any strange behaviour in the CNN.
</div>
```
# LeNet5 convolutional and max pool layers
def conv2d(x, W,pad='SAME'):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=pad)
def max_pool_2x2(x,pad='VALID'):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding=pad)
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
The stride of value 1x1 in the convolutional will yield a same size feature map when used with padding 'SAME', which adds padding to ensure that the proportion stays equal after the convolution. <br/><br/>
Using a stride of 2x2 in the max pool ensures reducing the features in half, which is why padding 'VALID' is used (equivalent to no padding).
</div>
```
def LeNet5_Model(data, keep_pr=1, activFunc=tf.nn.sigmoid):
input_data = tf.reshape(data,[-1,28,28,1])
# -------------------------------------------------
# --------------------VARIABLES--------------------
# -------------------------------------------------
# Convolutional layer 1 variables
W_conv1 = weight_variable([5,5,1,6])
b_conv1 = bias_variable([6])
# Convolutional layer 2 variables
W_conv2 = weight_variable([5,5,6,16])
b_conv2 = bias_variable([16])
# Fully connected layer 1 param
W_fc1 = weight_variable([400, 120])
b_fc1 = bias_variable([120])
# Fully connected layer 2 param
W_fc2 = weight_variable([120, 84])
b_fc2 = bias_variable([84])
# Fully connected layer 3 param
W_fc3 = weight_variable([84, 10])
b_fc3 = bias_variable([10])
# ----------------------------------------------------
# --------------------COMPUTATIONS--------------------
# ----------------------------------------------------
# Convolutional layer 1 & max pooling
h_conv1 = activFunc(conv2d(input_data,W_conv1)+ b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
# Convolutional layer 2 & max pooling
h_conv2 = activFunc(conv2d(h_pool1,W_conv2, pad='VALID')+ b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
# Flattening
h_pool2_flat = tf.contrib.layers.flatten(h_pool2)
# Fully connected layer 1, sigmoid activation
h_fc1 = activFunc(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
drop_fc1 = tf.nn.dropout(h_fc1, keep_pr)
# Fully connected layer 2, sigmoid activation
h_fc2 = activFunc(tf.matmul(drop_fc1, W_fc2) + b_fc2)
drop_fc2 = tf.nn.dropout(h_fc2, keep_pr)
# Fully connected layer 3, softmax activation
predicted = tf.nn.softmax(tf.matmul(drop_fc2, W_fc3) + b_fc3)
return predicted
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
First we define all the variables, then we compute all the activations using the functions defined above. We included a dropout in the fully connected layers, but is set off (with keep_p=1) by default.
</div>
### 2.1.2 Number of parameters in LeNet5 [Question 2.1.2]
```
NParameters_LeNet5 = \
2*(5*5*1*6) + \
2*(5*5*6*16) + \
400*120 + \
120 + \
120*84 + \
84 + \
84*10 + \
10
print('Mumber of parameters in LeNet5: %d'%NParameters_LeNet5)
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
<ul>
<li> Weights and biases for convolutional layer 1 = 2 x (5 x 5 x 1 x 6) </li>
<li> Weights and biases for convolutional layer 2 = 2 x (5 x 5 x 6 x 16)</li>
<li> Weights for fully connected layer 1 = 400 x 120</li>
<li> Biases for fully connected layer 1 = 120</li>
<li> Weights for fully connected layer 2 = 120 x 84</li>
<li> Biases for fully connected layer 2 = 84</li>
<li> Weights for fully connected layer 3 = 84 x 10</li>
<li> Biases for fully connected layer 3 = 10</li>
</ul>
TOTAL: 64234
</div>
### 2.1.3 CNNet: Tensorflow graph creation [Question 2.1.3]
The initial training will be using the parameters cited below:
Learning rate =0.1
Loss Function : Cross entropy
Optimisateur: SGD
Number of training iterations= 10000
The batch size =128
```
def CNNet ( modelName,
learning_rate = 0.1,
training_epochs = 100,
batch_size = 128,
display_step = 1,
keep_p = 1,
activationFunc = tf.nn.sigmoid,
optimFunc = tf.train.GradientDescentOptimizer,
X_train=mnist.train.images,
y_train=mnist.train.labels,
X_val=mnist.validation.images,
y_val=mnist.validation.labels,
X_test= mnist.test.images,
y_test=mnist.test.labels,
loadModel=None
):
# ---------- DESCRIPTION OF DATASET ----------
InputSize = X_train[0].shape[0]
OutputSize = y_train[0].shape[0]
TrainingSetSize = len(X_train)
ValidationSetSize = len(X_validation)
TestSetSize = len(X_test)
# ---------- OUTPUT FOLDERS ----------
logsFolder = 'log_files/' # useful for tensorboard
saveFolder = 'Models/' # useful to restore the model
# ---------- RESET GRAPH ----------
tf.reset_default_graph()
# ---------- DEFINE VARIABLES ----------
# tf Graph Input: mnist data image of shape 28*28*1
x = tf.placeholder(tf.float32, [None,InputSize], name='InputData')
# 0-9 digits recognition, 10 classes
y = tf.placeholder(tf.float32, [None,OutputSize], name='LabelData')
# Dropout
keep_prob = tf.placeholder(tf.float32, name='DropoutKeepProbability')
# ---------- DEFINE GRAPH NODES ----------
with tf.name_scope('Model'):
# Model
model = LeNet5_Model(x, keep_prob, activFunc=activationFunc)
with tf.name_scope('Loss'):
# Minimize error using cross entropy
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(model+1e-9), reduction_indices=1))
#cost = tf.nn.softmax_cross_entropy_with_logits(model, tf.one_hot(y, 10))
with tf.name_scope('Optimizer'):
#Optimization, using cost reduction
optimizer = optimFunc(learning_rate).minimize(cost)
with tf.name_scope('Accuracy'):
# Accuracies
acc = CNNetAccuracy(model, y)
# ---------- INITIALIZE VARIABLES ----------
init = tf.global_variables_initializer()
# ---------- TRACK BATCH LOSS AND ACCURACY ----------
# Create a summary to monitor cost tensor
tf.summary.scalar("BatchLoss", cost)
# Create a summary to monitor batch accuracy tensor
tf.summary.scalar("BatchAccuracy", acc)
# Merge all summaries into a single op
merged_summary_op = tf.summary.merge_all()
# ---------- TRAIN MODEL ----------
CNNtrain(model, cost, optimizer, acc,
x, y, keep_prob, TrainingSetSize,
X_train, y_train, X_val, y_val, X_test, y_test,
init, merged_summary_op,
modelName, saveFolder,logsFolder,
learning_rate, training_epochs, batch_size, display_step , keep_p,
loadModel
)
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
The CNNet function creates the whole graph from scratch (Nodes, Variables, Summaries) and calls the function CNNTrain, which will be in charge of creating a session and running the graph.
</div>
### 2.1.4 CNNet: Accuracy [Question 2.1.4]
Here we implement the evaluation function for accuracy computation:
```
def CNNetAccuracy(model, y):
accuracy = tf.reduce_mean(
tf.cast( tf.equal( tf.argmax(model, 1),
tf.argmax(y, 1)), tf.float32))
return accuracy
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
We've opted for defining the computation the way it should be set inside a Tensorflow graph. However, in order to execute it and obtain a value, we need to create the rest of the graph and use a session to perform the computation (it will be called in the training function)
</div>
### 2.1.5 CNNet Training [Question 2.1.5]
Here we implement training pipeline and run the training data through it to train the model. Other steps to consider are:
- Before each epoch, shuffling the training set.
- Printing the loss per mini batch and the training/validation accuracy per epoch. (Display results every 100 epochs)
- Saving the model after training
- Printing after training the final testing accuracy
```
def read_my_file_format(filename_queue):
reader = tf.SomeReader()
key, record_string = reader.read(filename_queue)
example, label = tf.some_decoder(record_string)
processed_example = some_processing(example)
return processed_example, label
def input_pipeline(filenames, batch_size, num_epochs=None):
filename_queue = tf.train.string_input_producer(
filenames, num_epochs=num_epochs, shuffle=True)
example, label = read_my_file_format(filename_queue)
# min_after_dequeue defines how big a buffer we will randomly sample
# from -- bigger means better shuffling but slower start up and more
# memory used.
# capacity must be larger than min_after_dequeue and the amount larger
# determines the maximum we will prefetch. Recommendation:
# min_after_dequeue + (num_threads + a small safety margin) * batch_size
min_after_dequeue = 10000
capacity = min_after_dequeue + 3 * batch_size
example_batch, label_batch = tf.train.shuffle_batch(
[example, label], batch_size=batch_size, capacity=capacity,
min_after_dequeue=min_after_dequeue)
return example_batch, label_batch
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
We import the pipeline functions that come from tensorflow: https://www.tensorflow.org/programmers_guide/reading_data
</div>
```
def CNNtrain(model, cost, optimizer, acc,
x, y, keep_prob, TrainingSetSize,
X_train, y_train, X_val, y_val, X_test, y_test,
init, merged_summary_op,
modelName, saveFolder, logsFolder,
learning_rate, training_epochs, batch_size, display_step, keep_p,
loadModel, dataFileName=None
):
# Initial model print
print("*Model [", modelName,"] {l_r: %.4f; n_iter: %d; batch: %d}"%\
(learning_rate, training_epochs, batch_size))
# Start a tensorflow session
with tf.Session() as sess:
print (" Start Training!")
sess.run(init)
# Load model if the parameter loadModel is not empty
saver = tf.train.Saver()
if(loadModel):
saver.restore(sess=sess,save_path='Models/'+loadModel)
# op to write logs to Tensorboard
summary_writer = tf.summary.FileWriter(logsFolder,
graph=tf.get_default_graph())
# Training cycle
t0 = time.time()
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
# batch_xs, batch_ys = mnist.train.next_batch(batch_size)
batch_xs, batch_ys = input_pipeline(filenames=dataFileName,
batch_size=batch_size,
num_epochs=total_batch):
# Run optimization op (backprop), cost op (to get loss value)
# and summary nodes
_, c, summary = sess.run([optimizer, cost, merged_summary_op],
feed_dict={x: batch_xs,
y: batch_ys,
keep_prob: keep_p})
# Write logs at every iteration
summary_writer.add_summary(summary, epoch * total_batch + i)
# Compute average loss
avg_cost += c / total_batch
# Display logs per epoch step
if (epoch+1) % display_step == 0:
tr_acc = acc.eval({x: X_train, y: y_train, keep_prob: 1})
vl_acc = acc.eval({x: X_val, y: y_val, keep_prob: 1})
print(" Epoch: %02d | Loss=%.9f | TrainAcc=%.3f %% | ValAcc=%.3f %%"%
(epoch+1, avg_cost, tr_acc*100, vl_acc*100));
print (" Training Finished in %.1f seconds."%(time.time()-t0))
# Evaluating model with the accuracies
print (" Final accuracies:")
print (" ~ TrainAcc: %.3f %%"%(100*acc.eval({x: X_train, y: y_train, keep_prob: 1})))
print (" ~ ValAcc: %.3f %%"%(100*acc.eval({x: X_val, y: y_val, keep_prob: 1})))
print (" ~ TestAcc: %.3f %%"%(100*acc.eval({x: X_test, y: y_test, keep_prob: 1})))
# Saving Model
saver.save(sess=sess,save_path=saveFolder+modelName)
print (" Saving model in file: %s"%(saveFolder+modelName))
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
This function implements the session, and using and input pipeline, it fetches batches of data to the graph and runs it in order to obtain results.<br/><br/>
The model is evaluated in the end, and we have added a possibility to load previous models as well as saving it. The training and validation accuracies are calculated on every epoch, while test accuracy is only calculated in the end.<br/><br/>
In order to keep the original version available, we have commented the original batch function from the mnist dataset.
</div>
```
# Training our first model!
CNNet ('lenet5-model',
learning_rate = 0.1,
training_epochs = 100,
batch_size = 128,
)
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
First accuracy obtained is 98.76%! very close to the objective of 99%.
</div>
### 2.1.6 Visualization of results with Tensorboard [Question 2.1.6]
We use tensorBoard to visualise and save the LeNet5 Graph and all learning curves.
The data is then converted into CSV using the GUI drom tensorboard and is then plotted using Excel. The resulting figures are:
<img src="MNIST_99_Challenge_Figures/LeNet5_graph.png",width="800" height="600" align="center">
<center><span>Figure 3: LeNet5 Graph </span></center>
<img src="MNIST_99_Challenge_Figures/TrainingLeNet5.png",width="800" height="600" align="center">
<center><span>Figure 4: LeNet5 Training </span></center>
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
There is an initial step of search for a steep surface in the loss function, and in the epoch 8-9 it starts converging fast, completely stabilizing after epoch 50.
</div>
# 2.2 LeNet5 Optimization
## 2.2.1 Parameter Tuning [Question 2.2.1]
We change the sigmoid function to a Relu and perform the next steps:
- Retrain the network with SGD and AdamOptimizer. Compare them with the best parameters:
| Optimizer | Gradient Descent |AdamOptimizer |
| ------------- |: -------------: | ---------:
| Validation Accuracy | 98.760 % | 99.080 % |
| Testing Accuracy | 98.670 % | 99.110 % |
| Training Time | 8048 s | 2670 s |
- Try with different learning rates for each Optimizer (0.0001 and 0.001 ) and different Batch sizes (50 and 128) for 10000 Epochs.
- For each optimizer, plot (on the same curve) the **testing accuracies** function to **(learning rate, batch size)**
- Did you reach the 99% accuracy ? What are the optimal parametres that gave you the best results?
<img src="MNIST_99_Challenge_Figures/ParameterTuning.png",width="800" height="600" align="center">
<center><span>Figure 5: Parameter Tuning </span></center>
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
Clearly the Adam Optimizer is better than the SGD, and in much less time. <br/><br/>
We tried with several parameters and thebest combination we found is <b>AdamOptimizer, lr=0.001 bs=128</b>.<br/><br/>
Also, we achieved the desired accuracy of 99%!
</div>
```
# Trying parameters with SGD
setOfParams = [ [0.001, 250, 50, 'lenet5-model_relu_lr0001_bs50'],
[0.001, 100, 128, 'lenet5-model_relu_lr0001_bs128'],
[0.0001, 250, 50, 'lenet5-model_relu_lr00001_bs50'],
[0.0001, 100, 128, 'lenet5-model_relu_lr00001_bs128'],
]
for p in setOfParams:
CNNet (modelName=p[3],
learning_rate = p[0],
training_epochs = p[1],
batch_size = p[2],
activationFunc=tf.nn.relu,
)
# Trying parameters with Adam Optimizer
setOfParams = [ [0.001, 250, 50, 'lenet5-model_adam_relu_lr0001_bs50'],
[0.001, 100, 128, 'lenet5-model_adam_relu_lr0001_bs128'],
[0.0001, 250, 50, 'lenet5-model_adam_relu_lr00001_bs50'],
[0.0001, 100, 128, 'lenet5-model_adam_relu_lr00001_bs128'],
]
for p in setOfParams:
CNNet (modelName=p[3],
learning_rate = p[0],
training_epochs = p[1],
batch_size = p[2],
activationFunc=tf.nn.relu,
optimFunc=tf.train.AdamOptimizer
)
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
As seen in the training, the AdamOptimizer gets NaN at a certain point. In order to make it numerically stable, we have included a small value in the logarighm of the loss node in the grapl (1e-9), and we have reduced the standard deviation in the weight initialization
</div>
```
# Trying parameters with Adam Optimizer - AFTER CHANGING THE OPTIMIZER!
# (Weight init & safe softmax)
setOfParams = [ [0.001, 100, 50, 'lenet5-model_adam_relu_lr0001_bs50'],
[0.001, 100, 128, 'lenet5-model_adam_relu_lr0001_bs128'],
[0.0001, 100, 50, 'lenet5-model_adam_relu_lr00001_bs50'],
[0.0001, 100, 128, 'lenet5-model_adam_relu_lr00001_bs128'],
]
for p in setOfParams:
CNNet (modelName=p[3],
learning_rate = p[0],
training_epochs = p[1],
batch_size = p[2],
activationFunc=tf.nn.relu,
optimFunc=tf.train.AdamOptimizer
)
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
Other measure that we took was to stop the training when reaching 100% accuracy. Nevertheless, even with 100% accuracy the loss keeps going down, which is why we implemented the model loading and retrained the best model for other 30 epochs:
</div>
```
# Ending the training of the best optimizer
CNNet (modelName='lenet5-model_best',
learning_rate = 0.001,
training_epochs = 30,
batch_size = 128,
activationFunc=tf.nn.relu,
optimFunc=tf.train.AdamOptimizer,
loadModel='lenet5-model_adam_relu_lr0001_bs128'
)
```
### 2.2.2 Dropout layer [Question 2.2.2]
What about applying a dropout layer on the Fully conntected layer and then retraining the model with the best Optimizer and parameters(Learning rate and Batsh size) obtained in the previous section? (probability to keep units=0.75). For this stage we ensure that the keep prob is set to 1.0 to evaluate the performance of the network including all nodes.
```
CNNet ('lenet5-model',
learning_rate = 0.001,
training_epochs = 100,
batch_size = 128,
activationFunc = tf.nn.relu,
optimFunc=tf.train.AdamOptimizer,
keep_p = 0.75
)
```
<div class='alert alert-warning'>
<b>COMMENT:</b><br/>
We had everything implemented in the functions above, we only needed to call it.<br/><br/>
We once again surpass the 99% frontier! In fact, since the validation acuracy is 99.2%, this suggests that further playing with the keep probability could lead to an even better model. However, this is our of the scope of this notebook
</div>
|
github_jupyter
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.layers import flatten
from __future__ import print_function
from numpy import array
import numpy as np
import time
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
X_train, y_train = mnist.train.images, mnist.train.labels
X_validation, y_validation = mnist.validation.images, mnist.validation.labels
X_test, y_test = mnist.test.images, mnist.test.labels
print("Image Shape: {}".format(X_train[0].shape[0]))
print("Training Set: {} samples".format(len(X_train)))
print("Validation Set: {} samples".format(len(X_validation)))
print("Test Set: {} samples".format(len(X_test)))
#GRAPH DEFINITION
# Parameters
learning_rate = 0.01
training_epochs = 100
batch_size = 128
display_step = 1
logs_path = 'log_files/' # useful for tensorboard
# tf Graph Input: mnist data image of shape 28*28=784
x = tf.placeholder(tf.float32, [None, 784], name='InputData')
# 0-9 digits recognition, 10 classes
y = tf.placeholder(tf.float32, [None, 10], name='LabelData')
# Set model weights
W = tf.Variable(tf.zeros([784, 10]), name='Weights')
b = tf.Variable(tf.zeros([10]), name='Bias')
# Construct model and encapsulating all ops into scopes,
# making Tensorboard's Graph visualization more convenient
with tf.name_scope('Model'):
# Model
pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
with tf.name_scope('Loss'):
# Minimize error using cross entropy
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
with tf.name_scope('SGD'):
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
with tf.name_scope('Accuracy'):
# Accuracy
acc = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
acc = tf.reduce_mean(tf.cast(acc, tf.float32))
# Initializing the variables
init = tf.global_variables_initializer()
# Create a summary to monitor cost tensor
tf.summary.scalar("TrainingLoss", cost)
# Create a summary to monitor accuracy tensor
tf.summary.scalar("TrainingAccuracy", acc)
# Merge all summaries into a single op
merged_summary_op = tf.summary.merge_all()
#TRAINING
# Launch the graph for training
with tf.Session() as sess:
sess.run(init)
# op to write logs to Tensorboard
summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Run optimization op (backprop), cost op (to get loss value)
# and summary nodes
_, c, summary = sess.run([optimizer, cost, merged_summary_op],
feed_dict={x: batch_xs, y: batch_ys})
# Write logs at every iteration
summary_writer.add_summary(summary, epoch * total_batch + i)
# Compute average loss
avg_cost += c / total_batch
# Display logs per epoch step
if (epoch+1) % display_step == 0:
print("Epoch: ", '%02d' % (epoch+1), " =====> Loss=",
"{:.9f}".format(avg_cost))
print("Optimization Finished!")
# Test model
# Calculate accuracy
print("Accuracy:", acc.eval({x: mnist.test.images, y: mnist.test.labels}))
# LeNet5 variables init
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.01)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
# LeNet5 convolutional and max pool layers
def conv2d(x, W,pad='SAME'):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=pad)
def max_pool_2x2(x,pad='VALID'):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding=pad)
def LeNet5_Model(data, keep_pr=1, activFunc=tf.nn.sigmoid):
input_data = tf.reshape(data,[-1,28,28,1])
# -------------------------------------------------
# --------------------VARIABLES--------------------
# -------------------------------------------------
# Convolutional layer 1 variables
W_conv1 = weight_variable([5,5,1,6])
b_conv1 = bias_variable([6])
# Convolutional layer 2 variables
W_conv2 = weight_variable([5,5,6,16])
b_conv2 = bias_variable([16])
# Fully connected layer 1 param
W_fc1 = weight_variable([400, 120])
b_fc1 = bias_variable([120])
# Fully connected layer 2 param
W_fc2 = weight_variable([120, 84])
b_fc2 = bias_variable([84])
# Fully connected layer 3 param
W_fc3 = weight_variable([84, 10])
b_fc3 = bias_variable([10])
# ----------------------------------------------------
# --------------------COMPUTATIONS--------------------
# ----------------------------------------------------
# Convolutional layer 1 & max pooling
h_conv1 = activFunc(conv2d(input_data,W_conv1)+ b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
# Convolutional layer 2 & max pooling
h_conv2 = activFunc(conv2d(h_pool1,W_conv2, pad='VALID')+ b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
# Flattening
h_pool2_flat = tf.contrib.layers.flatten(h_pool2)
# Fully connected layer 1, sigmoid activation
h_fc1 = activFunc(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
drop_fc1 = tf.nn.dropout(h_fc1, keep_pr)
# Fully connected layer 2, sigmoid activation
h_fc2 = activFunc(tf.matmul(drop_fc1, W_fc2) + b_fc2)
drop_fc2 = tf.nn.dropout(h_fc2, keep_pr)
# Fully connected layer 3, softmax activation
predicted = tf.nn.softmax(tf.matmul(drop_fc2, W_fc3) + b_fc3)
return predicted
NParameters_LeNet5 = \
2*(5*5*1*6) + \
2*(5*5*6*16) + \
400*120 + \
120 + \
120*84 + \
84 + \
84*10 + \
10
print('Mumber of parameters in LeNet5: %d'%NParameters_LeNet5)
def CNNet ( modelName,
learning_rate = 0.1,
training_epochs = 100,
batch_size = 128,
display_step = 1,
keep_p = 1,
activationFunc = tf.nn.sigmoid,
optimFunc = tf.train.GradientDescentOptimizer,
X_train=mnist.train.images,
y_train=mnist.train.labels,
X_val=mnist.validation.images,
y_val=mnist.validation.labels,
X_test= mnist.test.images,
y_test=mnist.test.labels,
loadModel=None
):
# ---------- DESCRIPTION OF DATASET ----------
InputSize = X_train[0].shape[0]
OutputSize = y_train[0].shape[0]
TrainingSetSize = len(X_train)
ValidationSetSize = len(X_validation)
TestSetSize = len(X_test)
# ---------- OUTPUT FOLDERS ----------
logsFolder = 'log_files/' # useful for tensorboard
saveFolder = 'Models/' # useful to restore the model
# ---------- RESET GRAPH ----------
tf.reset_default_graph()
# ---------- DEFINE VARIABLES ----------
# tf Graph Input: mnist data image of shape 28*28*1
x = tf.placeholder(tf.float32, [None,InputSize], name='InputData')
# 0-9 digits recognition, 10 classes
y = tf.placeholder(tf.float32, [None,OutputSize], name='LabelData')
# Dropout
keep_prob = tf.placeholder(tf.float32, name='DropoutKeepProbability')
# ---------- DEFINE GRAPH NODES ----------
with tf.name_scope('Model'):
# Model
model = LeNet5_Model(x, keep_prob, activFunc=activationFunc)
with tf.name_scope('Loss'):
# Minimize error using cross entropy
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(model+1e-9), reduction_indices=1))
#cost = tf.nn.softmax_cross_entropy_with_logits(model, tf.one_hot(y, 10))
with tf.name_scope('Optimizer'):
#Optimization, using cost reduction
optimizer = optimFunc(learning_rate).minimize(cost)
with tf.name_scope('Accuracy'):
# Accuracies
acc = CNNetAccuracy(model, y)
# ---------- INITIALIZE VARIABLES ----------
init = tf.global_variables_initializer()
# ---------- TRACK BATCH LOSS AND ACCURACY ----------
# Create a summary to monitor cost tensor
tf.summary.scalar("BatchLoss", cost)
# Create a summary to monitor batch accuracy tensor
tf.summary.scalar("BatchAccuracy", acc)
# Merge all summaries into a single op
merged_summary_op = tf.summary.merge_all()
# ---------- TRAIN MODEL ----------
CNNtrain(model, cost, optimizer, acc,
x, y, keep_prob, TrainingSetSize,
X_train, y_train, X_val, y_val, X_test, y_test,
init, merged_summary_op,
modelName, saveFolder,logsFolder,
learning_rate, training_epochs, batch_size, display_step , keep_p,
loadModel
)
def CNNetAccuracy(model, y):
accuracy = tf.reduce_mean(
tf.cast( tf.equal( tf.argmax(model, 1),
tf.argmax(y, 1)), tf.float32))
return accuracy
def read_my_file_format(filename_queue):
reader = tf.SomeReader()
key, record_string = reader.read(filename_queue)
example, label = tf.some_decoder(record_string)
processed_example = some_processing(example)
return processed_example, label
def input_pipeline(filenames, batch_size, num_epochs=None):
filename_queue = tf.train.string_input_producer(
filenames, num_epochs=num_epochs, shuffle=True)
example, label = read_my_file_format(filename_queue)
# min_after_dequeue defines how big a buffer we will randomly sample
# from -- bigger means better shuffling but slower start up and more
# memory used.
# capacity must be larger than min_after_dequeue and the amount larger
# determines the maximum we will prefetch. Recommendation:
# min_after_dequeue + (num_threads + a small safety margin) * batch_size
min_after_dequeue = 10000
capacity = min_after_dequeue + 3 * batch_size
example_batch, label_batch = tf.train.shuffle_batch(
[example, label], batch_size=batch_size, capacity=capacity,
min_after_dequeue=min_after_dequeue)
return example_batch, label_batch
def CNNtrain(model, cost, optimizer, acc,
x, y, keep_prob, TrainingSetSize,
X_train, y_train, X_val, y_val, X_test, y_test,
init, merged_summary_op,
modelName, saveFolder, logsFolder,
learning_rate, training_epochs, batch_size, display_step, keep_p,
loadModel, dataFileName=None
):
# Initial model print
print("*Model [", modelName,"] {l_r: %.4f; n_iter: %d; batch: %d}"%\
(learning_rate, training_epochs, batch_size))
# Start a tensorflow session
with tf.Session() as sess:
print (" Start Training!")
sess.run(init)
# Load model if the parameter loadModel is not empty
saver = tf.train.Saver()
if(loadModel):
saver.restore(sess=sess,save_path='Models/'+loadModel)
# op to write logs to Tensorboard
summary_writer = tf.summary.FileWriter(logsFolder,
graph=tf.get_default_graph())
# Training cycle
t0 = time.time()
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
# batch_xs, batch_ys = mnist.train.next_batch(batch_size)
batch_xs, batch_ys = input_pipeline(filenames=dataFileName,
batch_size=batch_size,
num_epochs=total_batch):
# Run optimization op (backprop), cost op (to get loss value)
# and summary nodes
_, c, summary = sess.run([optimizer, cost, merged_summary_op],
feed_dict={x: batch_xs,
y: batch_ys,
keep_prob: keep_p})
# Write logs at every iteration
summary_writer.add_summary(summary, epoch * total_batch + i)
# Compute average loss
avg_cost += c / total_batch
# Display logs per epoch step
if (epoch+1) % display_step == 0:
tr_acc = acc.eval({x: X_train, y: y_train, keep_prob: 1})
vl_acc = acc.eval({x: X_val, y: y_val, keep_prob: 1})
print(" Epoch: %02d | Loss=%.9f | TrainAcc=%.3f %% | ValAcc=%.3f %%"%
(epoch+1, avg_cost, tr_acc*100, vl_acc*100));
print (" Training Finished in %.1f seconds."%(time.time()-t0))
# Evaluating model with the accuracies
print (" Final accuracies:")
print (" ~ TrainAcc: %.3f %%"%(100*acc.eval({x: X_train, y: y_train, keep_prob: 1})))
print (" ~ ValAcc: %.3f %%"%(100*acc.eval({x: X_val, y: y_val, keep_prob: 1})))
print (" ~ TestAcc: %.3f %%"%(100*acc.eval({x: X_test, y: y_test, keep_prob: 1})))
# Saving Model
saver.save(sess=sess,save_path=saveFolder+modelName)
print (" Saving model in file: %s"%(saveFolder+modelName))
# Training our first model!
CNNet ('lenet5-model',
learning_rate = 0.1,
training_epochs = 100,
batch_size = 128,
)
# Trying parameters with SGD
setOfParams = [ [0.001, 250, 50, 'lenet5-model_relu_lr0001_bs50'],
[0.001, 100, 128, 'lenet5-model_relu_lr0001_bs128'],
[0.0001, 250, 50, 'lenet5-model_relu_lr00001_bs50'],
[0.0001, 100, 128, 'lenet5-model_relu_lr00001_bs128'],
]
for p in setOfParams:
CNNet (modelName=p[3],
learning_rate = p[0],
training_epochs = p[1],
batch_size = p[2],
activationFunc=tf.nn.relu,
)
# Trying parameters with Adam Optimizer
setOfParams = [ [0.001, 250, 50, 'lenet5-model_adam_relu_lr0001_bs50'],
[0.001, 100, 128, 'lenet5-model_adam_relu_lr0001_bs128'],
[0.0001, 250, 50, 'lenet5-model_adam_relu_lr00001_bs50'],
[0.0001, 100, 128, 'lenet5-model_adam_relu_lr00001_bs128'],
]
for p in setOfParams:
CNNet (modelName=p[3],
learning_rate = p[0],
training_epochs = p[1],
batch_size = p[2],
activationFunc=tf.nn.relu,
optimFunc=tf.train.AdamOptimizer
)
# Trying parameters with Adam Optimizer - AFTER CHANGING THE OPTIMIZER!
# (Weight init & safe softmax)
setOfParams = [ [0.001, 100, 50, 'lenet5-model_adam_relu_lr0001_bs50'],
[0.001, 100, 128, 'lenet5-model_adam_relu_lr0001_bs128'],
[0.0001, 100, 50, 'lenet5-model_adam_relu_lr00001_bs50'],
[0.0001, 100, 128, 'lenet5-model_adam_relu_lr00001_bs128'],
]
for p in setOfParams:
CNNet (modelName=p[3],
learning_rate = p[0],
training_epochs = p[1],
batch_size = p[2],
activationFunc=tf.nn.relu,
optimFunc=tf.train.AdamOptimizer
)
# Ending the training of the best optimizer
CNNet (modelName='lenet5-model_best',
learning_rate = 0.001,
training_epochs = 30,
batch_size = 128,
activationFunc=tf.nn.relu,
optimFunc=tf.train.AdamOptimizer,
loadModel='lenet5-model_adam_relu_lr0001_bs128'
)
CNNet ('lenet5-model',
learning_rate = 0.001,
training_epochs = 100,
batch_size = 128,
activationFunc = tf.nn.relu,
optimFunc=tf.train.AdamOptimizer,
keep_p = 0.75
)
| 0.87768 | 0.892281 |
# Hyper-parameters in Action!
## Part 1 - Activation Functions
### This notebook generates the animations I used in my [blog post](https://towardsdatascience.com/hyper-parameters-in-action-a524bf5bf1c).
```
# To run this notebook on Google Colab, you need to run these two commands first
# to install FFMPEG (to generate animations - it may take a while to install!)
# and the actual DeepReplay package
#!apt-get install ffmpeg
#!pip install deepreplay
from keras.layers import Dense
from keras.models import Sequential
from keras.initializers import he_normal, normal
from deepreplay.datasets.parabola import load_data
from deepreplay.callbacks import ReplayData
from deepreplay.replay import Replay
from deepreplay.plot import compose_animations, compose_plots
import matplotlib.pyplot as plt
from IPython.display import HTML
import pandas as pd
from sklearn.preprocessing import StandardScaler
%matplotlib inline
```
## Dataset
### Fetch the dataset from the Data Folder at [UCI Machine Learning Repository: Spambase Data Set](https://archive.ics.uci.edu/ml/datasets/spambase)
```
# Download it using wget (Linux) or manually download it and place on the same folder as this notebook
#!wget https://archive.ics.uci.edu/ml/machine-learning-databases/spambase/spambase.data
```
### Loads data and creates ReplayData callback
```
group_name = 'spam'
# Loads the CSV data
df = pd.read_csv('spambase.data', header=None)
# The first 57 columns are features
# The last column has the correct labels (targets)
X, y = df.iloc[:, :57].values, df.iloc[:, 57].values
# Scale the features, as the original values have wide ranges
X = StandardScaler().fit_transform(X)
replaydata = ReplayData(X, y, filename='spambase_dataset.h5', group_name=group_name)
```
### Builds Keras model
```
he_initializer = he_normal(seed=42)
normal_initializer = normal(seed=42)
model = Sequential()
# Hidden layer with 10 units, taking the 57 features as inputs
model.add(Dense(input_dim=57,
units=10,
kernel_initializer=he_initializer,
activation='tanh'))
# Added layer to allow plotting the feature space
# It has 2 units and uses a LINEAR activation, so the network will also learn the
# mapping from 10-dimensions to 2-dimensions
model.add(Dense(units=2,
kernel_initializer=normal_initializer,
activation='linear',
name='hidden'))
# Typical output layer for binary classification
model.add(Dense(units=1,
kernel_initializer=normal_initializer,
activation='sigmoid',
name='output'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['acc'])
print(model.summary())
```
### Trains the model using ReplayData as a callback to store the information
```
model.fit(X, y, epochs=100, batch_size=16, callbacks=[replaydata])
```
### Builds figure to attach the plots to
```
fig = plt.figure(figsize=(12, 6))
ax_fs = plt.subplot2grid((2, 4), (0, 0), colspan=2, rowspan=2)
ax_ph_neg = plt.subplot2grid((2, 4), (0, 2))
ax_ph_pos = plt.subplot2grid((2, 4), (1, 2))
ax_lm = plt.subplot2grid((2, 4), (0, 3))
ax_lh = plt.subplot2grid((2, 4), (1, 3))
```
### Loads data into Replay and builds the plots
```
replay = Replay(replay_filename='spambase_dataset.h5', group_name=group_name)
fs = replay.build_feature_space(ax_fs, layer_name='hidden', scale_fixed=False)
ph = replay.build_probability_histogram(ax_ph_neg, ax_ph_pos)
lh = replay.build_loss_histogram(ax_lh)
lm = replay.build_loss_and_metric(ax_lm, 'acc')
```
### Plotting the figure for 80th epoch
```
sample_figure = compose_plots([fs, ph, lm, lh], 80)
sample_figure
```
### Animating the plot
```
sample_anim = compose_animations([fs, ph, lm, lh])
HTML(sample_anim.to_html5_video())
```
|
github_jupyter
|
# To run this notebook on Google Colab, you need to run these two commands first
# to install FFMPEG (to generate animations - it may take a while to install!)
# and the actual DeepReplay package
#!apt-get install ffmpeg
#!pip install deepreplay
from keras.layers import Dense
from keras.models import Sequential
from keras.initializers import he_normal, normal
from deepreplay.datasets.parabola import load_data
from deepreplay.callbacks import ReplayData
from deepreplay.replay import Replay
from deepreplay.plot import compose_animations, compose_plots
import matplotlib.pyplot as plt
from IPython.display import HTML
import pandas as pd
from sklearn.preprocessing import StandardScaler
%matplotlib inline
# Download it using wget (Linux) or manually download it and place on the same folder as this notebook
#!wget https://archive.ics.uci.edu/ml/machine-learning-databases/spambase/spambase.data
group_name = 'spam'
# Loads the CSV data
df = pd.read_csv('spambase.data', header=None)
# The first 57 columns are features
# The last column has the correct labels (targets)
X, y = df.iloc[:, :57].values, df.iloc[:, 57].values
# Scale the features, as the original values have wide ranges
X = StandardScaler().fit_transform(X)
replaydata = ReplayData(X, y, filename='spambase_dataset.h5', group_name=group_name)
he_initializer = he_normal(seed=42)
normal_initializer = normal(seed=42)
model = Sequential()
# Hidden layer with 10 units, taking the 57 features as inputs
model.add(Dense(input_dim=57,
units=10,
kernel_initializer=he_initializer,
activation='tanh'))
# Added layer to allow plotting the feature space
# It has 2 units and uses a LINEAR activation, so the network will also learn the
# mapping from 10-dimensions to 2-dimensions
model.add(Dense(units=2,
kernel_initializer=normal_initializer,
activation='linear',
name='hidden'))
# Typical output layer for binary classification
model.add(Dense(units=1,
kernel_initializer=normal_initializer,
activation='sigmoid',
name='output'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['acc'])
print(model.summary())
model.fit(X, y, epochs=100, batch_size=16, callbacks=[replaydata])
fig = plt.figure(figsize=(12, 6))
ax_fs = plt.subplot2grid((2, 4), (0, 0), colspan=2, rowspan=2)
ax_ph_neg = plt.subplot2grid((2, 4), (0, 2))
ax_ph_pos = plt.subplot2grid((2, 4), (1, 2))
ax_lm = plt.subplot2grid((2, 4), (0, 3))
ax_lh = plt.subplot2grid((2, 4), (1, 3))
replay = Replay(replay_filename='spambase_dataset.h5', group_name=group_name)
fs = replay.build_feature_space(ax_fs, layer_name='hidden', scale_fixed=False)
ph = replay.build_probability_histogram(ax_ph_neg, ax_ph_pos)
lh = replay.build_loss_histogram(ax_lh)
lm = replay.build_loss_and_metric(ax_lm, 'acc')
sample_figure = compose_plots([fs, ph, lm, lh], 80)
sample_figure
sample_anim = compose_animations([fs, ph, lm, lh])
HTML(sample_anim.to_html5_video())
| 0.832781 | 0.932269 |
# TextMAP Tokenization
Here we are going to walk through the various transforms available within textmap used in word and document embeddings. In general the process of tokenization is given a string of text (a document), return a sequence of tokens (words or word-like objects). While one would like to assume this is a simple processes of breaking a string on spaces, in general language is much more complex than that - some tokens have non-alpha numeric characters, periods, spaces, etc. or the language may not use the roman alphabet at all. In english, tokens such as "can't", "x-ray", "Ms.", "$5.00", "www\.words\.com", "john\@doe\.edu", "3D", "Las Vegas", ":-D", "20\%", etc., have several 'natural' ways to tokenize them depending on the use case.
TextMAP contains several standard NLP tokenizers all mad eto work within a standard sci-kit learn fit_transformer API. There are several default options available, each of which makes slightly different choices to tokenize a document, though they all have the flexibility for a user to provide their own tokenizer instances. TextMAP also contains a tansformer for bigram and ngram contraction to replace common occuring pairs (or n-tuples more generally) with a single token for the pair (or n-gram), to deal with multi-token terms like "Las Vegas", "ice cream", "without loss of generality", etc. in an unsupervised or semi-supervised fashion.
To demonstrate some of the tokenizers and their usage we'll walk through some examples and explore the options available.
First let's get some data! We'll use 20newgroups and remove documents less than 100 characters long.
```
import sklearn.datasets
import numpy as np
import pandas
import vectorizers
import textmap
import textmap.tokenizers
import textmap.transformers
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
news = sklearn.datasets.fetch_20newsgroups(remove=('headers', 'footers', 'quotes'))
long_enough = [len(t) > 100 for t in news['data']]
data = np.array(news['data'])
data = data[long_enough]
targets = np.array(news.target)
targets = targets[long_enough]
target_names = np.array(news.target_names)
```
### Default Tokenizers:
Let's look at a couple documents and notice all of the awful text in there... numbers, email addresses, hyphens, signatures, special characters, etc... and these are some of the better ones!
```
data[0:3]
```
The SKlearnTokenizer tokenizes the corpus using the same methodology as CountVectorizer.
```
%%time
tokens = textmap.tokenizers.SKLearnTokenizer().fit_transform(data)
```
Looking at the first 3 documents we can see how it performs. Notice that is removes tokes of length 1 only produces 'word-like' tokens
```
tokens[0:3]
```
NLTK's default tokenizer keeps the punctuation and tries to handle special characters more naturally.
```
%%time
tokens = textmap.tokenizers.NLTKTokenizer().fit_transform(data)
tokens[0:3]
```
NLTK's tweet tokenizer tries to tokenize emojis, urls, and email addresses as single tokens as well.
```
%%time
tokens = textmap.tokenizers.NLTKTweetTokenizer().fit_transform(data)
tokens[0:3]
```
SpaCy uses several language processing techniques to make even more refined choices.
```
%%time
tokens = textmap.tokenizers.SpacyTokenizer().fit_transform(data)
tokens[0:3]
```
Stanza uses other custom language processing tools (which we default to English) for tokenization. Because of all of the additional NLP processing, Stanza can be time consuming for large corpora.
```
%%time
tokens = textmap.tokenizers.StanzaTokenizer().fit_transform(data[0:100])
tokens[0:3]
```
## Tokenizer options:
All of the tokenizers can return tokenization by document (default) but also by sentence (returning a sequence per sentence) or by sentence by document (a sequence of token sequences per sentence per document). This is more time consuming as finding sentence breaks presents its own challenges. For example
```
%%time
tokens = textmap.tokenizers.NLTKTokenizer(tokenize_by = "sentence").fit_transform(data)
tokens[0:3]
%%time
tokens = textmap.tokenizers.NLTKTweetTokenizer(tokenize_by = "sentence_by_document").fit_transform(data)
tokens[0:3]
```
All tokenizers lower case by default but this option can be changed as well. For example;
```
tokens = textmap.tokenizers.NLTKTokenizer(lower_case = False).fit_transform(data)
tokens[0:3]
```
If you have a pre-build NLP model (from Spacy, Stanza, or NLTK) you can pass those in to replace the defaults. For example
```
my_nlp = nltk.tokenize.SpaceTokenizer()
tokens = textmap.tokenizers.NLTKTokenizer(nlp = my_nlp).fit_transform(data)
tokens[0:3]
from spacy.lang.fr import French
tokens = textmap.tokenizers.SpacyTokenizer(nlp = French()).fit_transform(data)
tokens[0:3]
```
You can pass any tokenizer an instance of any class that you would like, as long as it has the same basic functionality. For example, the NLTK tokenizer can accept any class that has a tokenize function.
```
class SillyNLP():
def tokenize(self, X):
if len(X) % 5 == 4:
return ["Badger"]*(len(X) // 10 ) + ['aghh', 'Snake', 'A', 'Snake', 'Ooooh', 'Its', 'A', 'Snake']
return ["Badger"]*(len(X) // 10 ) + ['mushroom', 'mushroom']
silly_tokens = textmap.tokenizers.NLTKTokenizer(nlp = SillyNLP()).fit_transform(data)
silly_tokens[0:3]
silly_tokens = textmap.tokenizers.NLTKTokenizer(nlp = SillyNLP(), lower_case = False).fit_transform(data)
silly_tokens[0:3]
```
## Multi-token expressions:
Now we may wish to contract common n-grams into a single token to cature common phrases as a single token. By default this computes the likelihood ratio of the actual number of times a pair of tokens are adjacent over the likelihood under independence (the product of thier frequencies). If a pair of tokens is occurs more then 2^7 times more often together than expected under independence then the occurrences of adjacent pairs are contracted to a single token. It then repeats this process again on the contracted text (default is on more time) to potentially contract larger n-grams.
(This class relies heavily on the NLTK MultiWordExpression infrastructure which is quite excellent)
```
mte = textmap.transformers.MultiTokenExpressionTransformer()
new_tokens = mte.fit_transform(tokens)
```
For reproducibility, the model stores the multi-token expressions as a list of pairs of tokens to contract per iteration.
```
mte.mtes_
```
By default, it will not contract any token that is a non-word (under the regex r"\W+") but this can be easily changed as we will see later on.
The tokens are contracted on first-come-first-serve basis, one round at a time, ultimately producing the new sequence of (multi-)tokens.
```
new_tokens[0:3]
```
Notice that this has a tendency to combine stopwords into stop phrases as stop words tend to occur next to eachother much more often then one would expect by chance. However, it also captures other bigrams you might expect like 'electrical_engineering', which helps distinguish this token from 'electrical' and 'engineering' when they occur seperatately.
Perhaps we want to ignore stop words for example. In this case we can just add them to the ignored tokes.
```
mte = textmap.transformers.MultiTokenExpressionTransformer(ignored_tokens=stopwords.words('english'))
new_tokens = mte.fit_transform(tokens)
new_tokens[0:3]
```
You can also filter the tokens to contract in various ways, including minimum and maximum frequencies (or number of occurrences) or regex expression, or only contract ngrams if the pair occur sufficiently often. You can also set the maximal number of iterations to be larger or small to control the maximal lenght of a contracted n-gram.
```
mte = textmap.transformers.MultiTokenExpressionTransformer(max_token_frequency = 1e-4,
min_token_occurrences = 50,
min_ngram_occurrences = 30,
excluded_token_regex="\W",
max_iterations=1
)
mte.fit(tokens)
mte.mtes_
```
(Yes some one of the tokens is lots of white space in this example... meh... it's just an example)
You can also change the minimal score to merge an n-gram and/or the score function itself to anything that behaves like those found in nltk.metrics.BigramAssocMeasures
```
from nltk.metrics import BigramAssocMeasures
%%time
mte = textmap.transformers.MultiTokenExpressionTransformer(score_function=BigramAssocMeasures.chi_sq,
min_score = 1e5,
max_token_frequency = 1e-4,
min_token_occurrences = 50,
min_ngram_occurrences = 30,
excluded_token_regex="\W",
max_iterations=1
)
mte.fit(tokens)
mte.mtes_
```
|
github_jupyter
|
import sklearn.datasets
import numpy as np
import pandas
import vectorizers
import textmap
import textmap.tokenizers
import textmap.transformers
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
news = sklearn.datasets.fetch_20newsgroups(remove=('headers', 'footers', 'quotes'))
long_enough = [len(t) > 100 for t in news['data']]
data = np.array(news['data'])
data = data[long_enough]
targets = np.array(news.target)
targets = targets[long_enough]
target_names = np.array(news.target_names)
data[0:3]
%%time
tokens = textmap.tokenizers.SKLearnTokenizer().fit_transform(data)
tokens[0:3]
%%time
tokens = textmap.tokenizers.NLTKTokenizer().fit_transform(data)
tokens[0:3]
%%time
tokens = textmap.tokenizers.NLTKTweetTokenizer().fit_transform(data)
tokens[0:3]
%%time
tokens = textmap.tokenizers.SpacyTokenizer().fit_transform(data)
tokens[0:3]
%%time
tokens = textmap.tokenizers.StanzaTokenizer().fit_transform(data[0:100])
tokens[0:3]
%%time
tokens = textmap.tokenizers.NLTKTokenizer(tokenize_by = "sentence").fit_transform(data)
tokens[0:3]
%%time
tokens = textmap.tokenizers.NLTKTweetTokenizer(tokenize_by = "sentence_by_document").fit_transform(data)
tokens[0:3]
tokens = textmap.tokenizers.NLTKTokenizer(lower_case = False).fit_transform(data)
tokens[0:3]
my_nlp = nltk.tokenize.SpaceTokenizer()
tokens = textmap.tokenizers.NLTKTokenizer(nlp = my_nlp).fit_transform(data)
tokens[0:3]
from spacy.lang.fr import French
tokens = textmap.tokenizers.SpacyTokenizer(nlp = French()).fit_transform(data)
tokens[0:3]
class SillyNLP():
def tokenize(self, X):
if len(X) % 5 == 4:
return ["Badger"]*(len(X) // 10 ) + ['aghh', 'Snake', 'A', 'Snake', 'Ooooh', 'Its', 'A', 'Snake']
return ["Badger"]*(len(X) // 10 ) + ['mushroom', 'mushroom']
silly_tokens = textmap.tokenizers.NLTKTokenizer(nlp = SillyNLP()).fit_transform(data)
silly_tokens[0:3]
silly_tokens = textmap.tokenizers.NLTKTokenizer(nlp = SillyNLP(), lower_case = False).fit_transform(data)
silly_tokens[0:3]
mte = textmap.transformers.MultiTokenExpressionTransformer()
new_tokens = mte.fit_transform(tokens)
mte.mtes_
new_tokens[0:3]
mte = textmap.transformers.MultiTokenExpressionTransformer(ignored_tokens=stopwords.words('english'))
new_tokens = mte.fit_transform(tokens)
new_tokens[0:3]
mte = textmap.transformers.MultiTokenExpressionTransformer(max_token_frequency = 1e-4,
min_token_occurrences = 50,
min_ngram_occurrences = 30,
excluded_token_regex="\W",
max_iterations=1
)
mte.fit(tokens)
mte.mtes_
from nltk.metrics import BigramAssocMeasures
%%time
mte = textmap.transformers.MultiTokenExpressionTransformer(score_function=BigramAssocMeasures.chi_sq,
min_score = 1e5,
max_token_frequency = 1e-4,
min_token_occurrences = 50,
min_ngram_occurrences = 30,
excluded_token_regex="\W",
max_iterations=1
)
mte.fit(tokens)
mte.mtes_
| 0.465387 | 0.978875 |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#5.-오차역전파법" data-toc-modified-id="5.-오차역전파법-1">5. 오차역전파법</a></span><ul class="toc-item"><li><span><a href="#5.1-계산-그래프" data-toc-modified-id="5.1-계산-그래프-1.1">5.1 계산 그래프</a></span><ul class="toc-item"><li><span><a href="#[계산-그래프로-풀다]" data-toc-modified-id="[계산-그래프로-풀다]-1.1.1">[계산 그래프로 풀다]</a></span></li><li><span><a href="#[국소적-계산]" data-toc-modified-id="[국소적-계산]-1.1.2">[국소적 계산]</a></span></li><li><span><a href="#[왜-계산-그래프로-푸는가?]" data-toc-modified-id="[왜-계산-그래프로-푸는가?]-1.1.3">[왜 계산 그래프로 푸는가?]</a></span></li></ul></li><li><span><a href="#5.2-연쇄법칙" data-toc-modified-id="5.2-연쇄법칙-1.2">5.2 연쇄법칙</a></span><ul class="toc-item"><li><span><a href="#[계산-그래프의-역전파]" data-toc-modified-id="[계산-그래프의-역전파]-1.2.1">[계산 그래프의 역전파]</a></span></li><li><span><a href="#[연쇄법칙이란?]" data-toc-modified-id="[연쇄법칙이란?]-1.2.2">[연쇄법칙이란?]</a></span></li><li><span><a href="#[연쇄법칙과-계산-그래프]" data-toc-modified-id="[연쇄법칙과-계산-그래프]-1.2.3">[연쇄법칙과 계산 그래프]</a></span></li></ul></li><li><span><a href="#5.3-역전파" data-toc-modified-id="5.3-역전파-1.3">5.3 역전파</a></span><ul class="toc-item"><li><span><a href="#[덧셈-노드의-역전파]" data-toc-modified-id="[덧셈-노드의-역전파]-1.3.1">[덧셈 노드의 역전파]</a></span></li><li><span><a href="#[곱셈-노드의-역전파]" data-toc-modified-id="[곱셈-노드의-역전파]-1.3.2">[곱셈 노드의 역전파]</a></span></li><li><span><a href="#[사과-쇼핑의-예]" data-toc-modified-id="[사과-쇼핑의-예]-1.3.3">[사과 쇼핑의 예]</a></span></li></ul></li><li><span><a href="#5.4-단순한-계층-구현하기" data-toc-modified-id="5.4-단순한-계층-구현하기-1.4">5.4 단순한 계층 구현하기</a></span><ul class="toc-item"><li><span><a href="#[곱셈-계층]" data-toc-modified-id="[곱셈-계층]-1.4.1">[곱셈 계층]</a></span></li><li><span><a href="#[덧셈-계층]" data-toc-modified-id="[덧셈-계층]-1.4.2">[덧셈 계층]</a></span></li></ul></li><li><span><a href="#5.5-활성화-함수-계층-구현하기" data-toc-modified-id="5.5-활성화-함수-계층-구현하기-1.5">5.5 활성화 함수 계층 구현하기</a></span><ul class="toc-item"><li><span><a href="#[ReLU-계층]" data-toc-modified-id="[ReLU-계층]-1.5.1">[ReLU 계층]</a></span></li><li><span><a href="#[Sigmoid-계층]" data-toc-modified-id="[Sigmoid-계층]-1.5.2">[Sigmoid 계층]</a></span><ul class="toc-item"><li><span><a href="#<<Sigmoid-역전파-흐름>>" data-toc-modified-id="<<Sigmoid-역전파-흐름>>-1.5.2.1"><<Sigmoid 역전파 흐름>></a></span></li><li><span><a href="#<<Sigmoid-계층의-계산-그래프-간소화>>" data-toc-modified-id="<<Sigmoid-계층의-계산-그래프-간소화>>-1.5.2.2"><<Sigmoid 계층의 계산 그래프 간소화>></a></span></li></ul></li></ul></li><li><span><a href="#5.6-Affine/Softmax-계층-구현하기" data-toc-modified-id="5.6-Affine/Softmax-계층-구현하기-1.6">5.6 Affine/Softmax 계층 구현하기</a></span><ul class="toc-item"><li><span><a href="#[Affine-계층]" data-toc-modified-id="[Affine-계층]-1.6.1">[Affine 계층]</a></span></li><li><span><a href="#[배치용-Affine-계층]" data-toc-modified-id="[배치용-Affine-계층]-1.6.2">[배치용 Affine 계층]</a></span></li><li><span><a href="#[Softmax-with-Loss-계층]" data-toc-modified-id="[Softmax-with-Loss-계층]-1.6.3">[Softmax-with-Loss 계층]</a></span></li></ul></li><li><span><a href="#5.7-오차역전파법-구현하기" data-toc-modified-id="5.7-오차역전파법-구현하기-1.7">5.7 오차역전파법 구현하기</a></span><ul class="toc-item"><li><span><a href="#[신경망-학습의-전체-순서]" data-toc-modified-id="[신경망-학습의-전체-순서]-1.7.1">[신경망 학습의 전체 순서]</a></span></li><li><span><a href="#[오차역전파법을-적용한-신경망-구현하기]" data-toc-modified-id="[오차역전파법을-적용한-신경망-구현하기]-1.7.2">[오차역전파법을 적용한 신경망 구현하기]</a></span></li><li><span><a href="#[오차역전파법으로-구한-기울기-검증하기]" data-toc-modified-id="[오차역전파법으로-구한-기울기-검증하기]-1.7.3">[오차역전파법으로 구한 기울기 검증하기]</a></span></li><li><span><a href="#[오차역전파법을-사용한-학습-구현하기]" data-toc-modified-id="[오차역전파법을-사용한-학습-구현하기]-1.7.4">[오차역전파법을 사용한 학습 구현하기]</a></span></li></ul></li></ul></li></ul></div>
# 5. 오차역전파법
- 앞 장에서는 신경망의 가중치 매개변수의 기울기(정확히는 가중치 매개변수에 대한 손실함수의 기울기)는 수치 미분을 사용해 구했으나, <br>
수치 미분은 단순하고 구현하기도 쉽지만 계산 시간이 오래 걸리는 단점이 있음
- **오차역전파법(backpropagation, backward propagation of errors)**은 가중치 매개변수에 대한 손실함수의 기울기를 효율적으로 계산하기 위한 방법
- 오차역전파법을 이해하는 방법은 수식을 통한 방법 또는 계산 그래프를 이용한 방법이 있음(이번 장에서는 계산 그래프를 사용해 시각적으로 이해)
## 5.1 계산 그래프
- **계산 그래프(Computational Graph)**는 계산 과정을 그래프로 나타낸 것
- 그래프는 그래프 자료구조로, 복수의 **노드(Node)**와 **에지(Edge)**로 표현(노드 사이의 직선을 '에지'라고 함)
### [계산 그래프로 풀다]
- 계산 그래프는 계산 과정을 노드와 화살표로 표현함
- 노드는 원으로 표기하고, 원 안에 연산 내용을 기술
- 계산 결과를 화살표 위에 적어서 각 노드의 계산 결과가 왼쪽에서 오른쪽으로 전해짐
- 사과 지불 금액 계산 그래프 [그림 5.1]
>
- 사과와 귤의 지불금액 계산 그래프 [그림 5.2]
>
- **계산 그래프를 이용한 문제풀이 흐름**
> 1. 계산 그래프를 구성한다.
> 1. 그래프에서 계산을 왼쪽에서 오른쪽으로 진행한다.
- 계산을 왼쪽에서 오른쪽으로 진행하는 단계를 **순전파(Forward Propagation)** 라고 함
- 반대방향(오른쪽에서 왼쪽)으로 전파가 진행하는 단계를 **역전파(Backward Propagation)** 라고 함
### [국소적 계산]
- 계산 그래프의 특징은 **"국소적 계산"을 전파함으로써 최종 결과를 얻는다**는 점에 있음
- 국소적이란 **"자신과 직접 관계된 작은 범위"**라는 뜻
- 국소적 계산은 결국 전체에서 어떤 일이 벌어지든 상관 없이 자신과 관계된 정보만으로 다음 결과(그 후의 결과)를 출력할 수 있음. <br>
각 노드는 자신과 관련된 계산 외에는 아무것도 신경 쓸 게 없음
### [왜 계산 그래프로 푸는가?]
1. 국소적 계산을 통해 전체가 아무리 복잡해도 각 노드에서는 단순한 계산에 집중하여 문제를 단순화할 수 있음
1. 계산 그래프는 중간 계산 결과를 모두 보관할 수 있음
1. 역전파를 통해 "미분"을 효율적으로 계산할 수 있음
>예로, **"사과 가격이 오르면 최종 금액에 어떤 영향을 끼치는지"**를 알고 싶다면, <br>
이 문제는 **"사과 가격에 대한 지불 금액의 미분"**을 구하는 문제에 해당함. <br>
기호로 나타내면 사과 값을 $x$, 지불 금액을 $L$ 이라 했을 때, $\frac{\delta L}{\delta x}$을 구하는 것. <br>
**이 미분 값은 사과 값이 "아주 조금" 올랐을 때 지불 금액이 얼마나 증가하느냐를 표시한 것 이며,** <br>
**"사과 가격에 대한 지불 금액의 미분" 같은 값은 계산 그래프에서 역전파를 하면 구할 수 있음**
- **역전파에 의한 미분 값의 전달** [그림 5.3]
>
> - 역전파는 순전파와는 반대 방향의 화살표(굵은 선)로 그리며, 국소적 미분 값을 전달하고 그 미분 값은 화살표의 아래에 적음
> - 위의 그림에서, "사과 가격에 대한 지불 금액의 미분" 값은 2.2라 할 수 있으며, <br>
사과 값이 아주 조금 오르면 최종 금액은 그 아주 작은 값의 2.2배 만큼 오른다는 뜻
> - 소비세에 대한 지불 금액의 미분이나, 사과 개수에 대한 지불 금액의 미분도 구할 수 있으며, <br>
이러한 계산 시 중간까지 구한 미분 결과를 공유할 수 있어서 다수의 미분을 효율적으로 계산할 수 있음
## 5.2 연쇄법칙
- 국소적 미분을 전달하는 원리는 **"연쇄법칙(Chain Rule)"**에 따른 것임
- **연쇄법칙은 계산 그래프의 역전파와 같음**
### [계산 그래프의 역전파]
- **$\normalsize y = f(x)$ 계산 그래프의 역전파** [그림 5.4]
>
> - 역전파의 계산 절차는 신호 $E$에 노드의 국소적 미분($\large \frac{\delta y}{\delta x}$)을 곱한 후 다음 노드로 전달 함
> - 국소적 미분은 순전파 때의 y = f(x) 계산의 미분을 구한다는 것이며, 이는 x에 대한 y의 미분($\large \frac{\delta y}{\delta x}$)을 구한다는 뜻
> - 가령, $y = f(x) = x^2$ 이라면, $\large \frac{\delta y}{\delta x}$는 $2x$ 가 되며, 이 국소적인 미분을 상류에서 전달된 값($E$)에 곱해서 앞쪽 노드로 전달 함
> - 이러한 방식을 따르면 목표로 하는 미분 값을 효율적으로 구할 수 있다는 것이 이 전파의 핵심임
### [연쇄법칙이란?]
- 합성 함수란 여러 함수로 구성된 함수로, $\normalsize z = (x + y)^2$ 은 다음 두 개의 식으로 구성됨
> $\large z = t^2 \\
\large t = x + y$ --- \[식 5.1]
- 연쇄법칙은 합성 함수의 미분에 대한 성질이며, <br>
**연쇄법칙의 정의**는 **"합성 함수의 미분은 합성 함수를 구성하는 각 함수의 미분의 곱으로 나타낼 수 있다."** <br><br>
- $\Large \frac{\delta z}{\delta x}$($x$에 대한 $z$의 미분)은 $\Large \frac{\delta z}{\delta t}$($t$에 대한 $z$의 미분)과 $\Large \frac{\delta t}{\delta x}$($x$에 대한 $t$의 미분)의 곱으로 나타낼 수 있음 ---- \[식 5.2]
>$$\large \frac{\delta z}{\delta x} = \frac{\delta z}{\delta t} \frac{\delta t}{\delta x}$$ <br>
- 위 식에서 $\delta t$는 분모와 분자에서 서로 지울 수 있음
>$$\large \frac{\delta z}{\delta x} = \frac{\delta z}{\not \delta t} \frac{\not \delta t}{\delta x}$$ <br>
- \[식 5.1]에서 국소적 미분(편미분)을 구하면 아래와 같음 ---- \[식 5.3]
>$$\large \frac{\delta z}{\delta t} = 2t \\
\large \frac{\delta t}{\delta x} = 1$$ <br>
> - $\large \frac{\delta z}{\delta t}$는 $2t$이고, $\large \frac{\delta t}{\delta x}$는 1 이며, 이는 미분 공식에서 해석적으로 구한 결과임
- 최종적으로 구하고 싶은 $\large \frac{\delta z}{\delta x}$는 [식 5.3]에서 구한 두 미분을 곱해서 계산 함 ---- \[식 5.4]
>$$\large \frac{\delta z}{\delta x} = \frac{\delta z}{\delta t} \frac{\delta t}{\delta x} = 2t \cdot 1 = 2(x + y)$$
### [연쇄법칙과 계산 그래프]
- [식 5.4]의 계산 그래프 : 순전파와 반대 방향으로 국소적 미분을 곱하여 전달 [그림 5.5]
>
- "$**2$" 노드에서의 역전파는 입력이 $\large \frac{\delta z}{\delta z}$이며, 이에 극소적 미분인 $\large \frac{\delta z}{\delta t}$를 곱하고 다음 노드로 넘김 <br>
(순전파 시에는 입력이 $t$이고 출력이 $z$이므로 이 노드에서 국소적 미분은 $\large \frac{\delta z}{\delta t}$)
- 역전파의 첫 신호인 $\large \frac{\delta z}{\delta z}$의 값은 1
- 맨 왼쪽의 역전파는 연쇄법칙에 따르면, 아래 식이 성립되어 "$x$에 대한 $z$의 미분"이 됨
>$$\large \frac{\delta z}{\delta z} \frac{\delta z}{\delta t} \frac{\delta t}{\delta x} = \frac{\delta z}{\delta t} \frac{\delta t}{\delta x} = \frac{\delta z}{\delta x}$$
- 즉, **역전파가 하는 일은 연쇄법칙의 원리와 같다.**
- [그림 5.5]에 [식 5.3]을 대입한 계산 그래프의 역전파 결과
> 
## 5.3 역전파
### [덧셈 노드의 역전파]
- $\normalsize z = x + y$의 미분은 다음과 같이 해석적으로 계산할 수 있음 ---- \[식 5.5]
>$$\large \frac{\delta z}{\delta x} = 1 \\
\large \frac{\delta z}{\delta y} = 1$$
- **덧셈 노드의 역전파**는 $\large \frac{\delta z}{\delta x}$와 $\large \frac{\delta z}{\delta y}$ 모두 1 이이서, **입력 값을 그대로 흘려보냄** [그림 5.6]
>
> - 상류에서 전해진 미분(이 예에서는 $\Large \frac{\delta z}{\delta t}$)에 $\normalsize 1$을 곱하여 하류로 흘림
### [곱셈 노드의 역전파]
- $\normalsize z = x \: y$의 미분은 다음과 같이 해석적으로 계산할 수 있음 ---- [식 5.6]
> $$\large \frac {\delta z}{\delta x} = y \\
\large \frac {\delta z}{\delta y} = x$$
- 곱셈 노드의 역전파 계산 그래프 [그림 5.7]
> 
> - 곱셈 노드의 역전파는 상류의 값에 순전파 때의 입력 신호들을 "서로 바꾼 값"을 곱해서 하류로 보냄
> - "서로 바꾼 값"이란 순전파 때 $x$ 였다면 역전파에서는 $y$, 순전파 때 $y$ 였다면 역전파에서는 $x$로 바꾼다는 의미
> - 곱셈의 역전파는 순방향 입력 신호의 값이 필요하기 때문에 곱셈 노드를 구현할 때는 순전파의 입력 신호를 지유해야 함
### [사과 쇼핑의 예]
- 사과의 가격, 사과의 개수, 소비세라는 세 변수 각각이 최종 금액에 어떻게 영향을 주는지 문제를 풀고자 함
- 이는 "사과 가격에 대한 지불 금액의 미분", "사과 개수에 대한 지불 금액의 미분", "소비세에 대한 지불 금액의 미분"을 구하는 것임
- 사과 쇼핑의 역전파 예 [그림 5.8]
>
> - 곱셈 노드의 역전파에서는 상류의 값에 입력 신호를 서로 바꾼 값을 곱해서 하류로 흘림
- 사과와 귤 쇼핑의 역전파 예 [그림 5.9]
>
## 5.4 단순한 계층 구현하기
- 신경망을 구성하는 층(계층) 각각을 하나의 클래스로 구현(연산을 담당하는 노드를 클래스로 구현)
### [곱셈 계층]
- 모든 계층은 forward()와 backward()라는 공통의 메서드(인터페이스)를 갖도록 구현. forward()는 순전파, backward()는 역전파
```
# 곱셈 계층 계산 그래프 구현
class MultiLayer():
def __init__(self):
self.x = None # 역전파에 사용하기 위해, 순전파 때의 입력 값을 유지하기 위한 변수
self.y = None
def forward(self, x, y):
self.x = x
self.y = y
out = x * y
return out
def backward(self, dout): # dout은 상류층의 순전파의 미분 값
dx = dout * self.y # 상류에서 전달된 값에 x와 y를 바꿔서 곱한다.
dy = dout * self.x
return dx, dy
apple = 100
apple_num = 2
tax = 1.1
# 계층들
mul_apple_layer = MultiLayer()
mul_tax_layer = MultiLayer()
# 순전파
apple_price = mul_apple_layer.forward(apple, apple_num)
price = mul_tax_layer.forward(apple_price, tax)
print("price : {:.2f}".format(price))
# 역전파
dprice = 1
dapple_price, dtax = mul_tax_layer.backward(dprice)
dapple, dapple_num = mul_apple_layer.backward(dapple_price)
print("dapple, dapple_num, dtax : {:.2f}, {:.2f}, {:.2f}".format(
dapple, dapple_num, dtax))
```
- [그림 5.8]의 곱셈의 역전파 그래프와 결과가 동일함
### [덧셈 계층]
```
# 덧셈 계층 계산 그래프 구현
class AddLayer:
def __init__(self):
pass # 덧셈 노드에서는 순전파 때의 입력 값을 유지할 필요 없음(역전파에서 사용하지 않음)
def forward(self, x, y):
out = x + y
return out
def backward(self, dout):
dx = dout * 1 # 상류에서 내려온 미분(dout) 값을 그대로 하류로 흘려 보냄
dy = dout * 1
return dx, dy
# 덧셈 계층과 곱셈 계층을 사용한 사과와 귤의 계산 그래프 구현
apple = 100
apple_num = 2
orange = 150
orange_num = 3
tax = 1.1
# 계층들
mul_apple_layer = MultiLayer()
mul_orange_layer = MultiLayer()
add_apple_orange_layer = AddLayer()
mul_tax_layer = MultiLayer()
# 순전파
apple_price = mul_apple_layer.forward(apple, apple_num)
orange_price = mul_orange_layer.forward(orange, orange_num)
all_price = add_apple_orange_layer.forward(apple_price, orange_price)
price = mul_tax_layer.forward(all_price, tax)
# 역전파
dprice = 1
dall_price, dtax = mul_tax_layer.backward(dprice)
dapple_price, dorange_price = add_apple_orange_layer.backward(dall_price)
dapple, dapple_num = mul_apple_layer.backward(dapple_price)
dorange, dorange_num = mul_orange_layer.backward(dorange_price)
print("price : {:.0f}".format(price))
print("dapple, dapple_num, dorange, dorange_num, dtax: {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}".format(
dapple, dapple_num, dorange, dorange_num, dtax))
```
- 필요한 계층을 만들고 순전파 메서드인 **forward()를 적절한 순서로 호출** (계산 그래프의 순전파 순서 대로 호출)
- **순전파와 반대 순서로 역전파 메서드인 backward()를 호출하면 미분이 계산됨**
- [그림 5.9]의 사과와 귤 쇼핑의 역전파 결과와 동일함
## 5.5 활성화 함수 계층 구현하기
- 신경망을 구성하는 층(계층) 각각을 클래스 하나로 구현
### [ReLU 계층]
- ReLU 수식 ---- \[식 5.7]
> $$\normalsize y = \begin{cases} x \ \ \ \ \ (x > 0) \\
0 \ \ \ \ \ (x \le 0) \end{cases}$$
- $x$에 대한 $y$의 미분 ---- \[식 5.8]
> $$\normalsize \frac{\delta y}{\delta x} = \begin{cases} 1 \ \ \ \ \ (x > 0) \\
0 \ \ \ \ \ (x \le 0) \end{cases}$$
> - [식 5.8]에서와 같이 **순전파 때의 입력인 $x$가 $0$ 보다 크면 역전파는 상류의 값을 그대로 하류로 흘리고 ($1$을 곱해서 하류로 흘리고)**,
> - **순전파 때 $x$가 $0$ 이하이면 역전파 때는 하류에 신호를 보내지 않음 ($0$을 보냄)**
- ReLU 계층의 계산 그래프 [그림 5.10]
> 
```
# ReLU 계층 구현 (forward() 함수와 backward() 함수는 numpy 배열을 인수로 받는 것으로 가정)
class ReLU:
def __init__(self):
# True/False로 구성된 numpy 배열로, 순전파의 입력인 x의 원소 값이 0 이하인 인덱스는 True, 그 외의 인덱스는 False
self.mask = None
def forward(self, x):
self.mask = (x <= 0)
out = x.copy()
out[self.mask] = 0 # self.mask가 True인 인덱스의 값을 0으로 변경
return 0
def backward(self, dout):
# 순전파에서 만든 mask를 써서 mask가 True인 곳은 상류에서 전파된 dout을 0으로 변경
dout[self.mask] = 0
return dout
import numpy as np
x = np.array([[1.0, -0.5], [-2.0, 3.0]])
print(x)
mask = (x <= 0)
print(mask)
```
### [Sigmoid 계층]
- 시그모이드 함수 식 ---- \[식 5.9]
> $$\normalsize y = \frac{1}{1 + exp(-x)}$$
> - $\normalsize exp(-x)$는 지수함수 $\large e^{-x}$를 의미
- Sigmoid 계층의 계산 그래프(순전파) ---- \[그림 5.11]
> 
> - "$\normalsize exp$" 노드는 $\normalsize y = exp(-x)$ 계산을 수행하고,
> - "$\normalsize /$" 노드는 $\normalsize y = \large \frac{1}{x}$ 계산을 수행 ($\normalsize x$는 국소적 미분의 입력값을 의미)
#### <<Sigmoid 역전파 흐름>>
- **1단계**
> - $\normalsize y = \frac{1}{\large x}$ 미분 식은, ---- \[식 5.10]
> $$\normalsize \frac{\delta y}{\delta x} = - \frac{1}{x^2}$$ <br>
> $$\normalsize \ \ \ = - y^2$$ <br>
> - $\normalsize y = \frac{1}{\large x}$의 $x$를 시그모이드 출력의 분모 부분으로 생각하면 시그모이드 출력의 미분에 그대로 적용 가능 <br>
> $$\normalsize y = \frac{1}{1 + exp(-x)}$$ <br>
> $$\normalsize \frac{\delta y}{\delta x} = - \frac{1}{(1 + exp(-x))^2}$$ <br>
> $$\normalsize = - \Big(\frac{1}{1 + exp(-x)} \Big)^2$$ <br>
> $$\normalsize = - y^2$$ <br>
> - **"$\normalsize /$" 노드는 상류의 예측값에 $-y^2$(순전파의 출력을 제곱한 후 마이너스를 붙인 값)을 곱해서 하류로 전달** <br><br>
> $$\normalsize - \frac{\delta L}{\delta y} \ y^2$$ <br>
- **2단계**
> - **"$\normalsize +$" 노드는 상류의 값을 여과 없이 하류로 내보냄** (1단계 출력과 동일함)
- **3단계**
> - **"$\normalsize exp$" 노드는 $\normalsize y = exp(-x)$ 연산을 수행** 하며, 그 미분은 다음과 같음 (밑이 $\normalsize e$인 지수 함수의 도함수는 자기 자신) ---- \[식 5.11] <br><br>
> $$\normalsize \frac{\delta y}{\delta x} = exp(-x)$$ <br>
> - "$\normalsize exp$" 노드의 연산 결과는 상류의 예측값에 위의 값을 곱하여 아래와 같이 하류로 전달 <br><br>
> $$\normalsize - \frac{\delta L}{\delta y} \ y^2 \ exp(-x)$$
- **4단계**
> - **"$\normalsize x$" 노드는 순전파 때의 값을 서로 바꿔 곱함**. 이 예에서는 **-1을 곱 하면 됨** <br><br>
> - 역전파의 최종 출력은,
> $$\normalsize \frac{\delta L}{\delta y} \ y^2 \ exp(-x)$$ <br>
> - 역전파 전체 과정을 포함한 Sigmoid 계층의 계산 그래프(순전파 &역전파) ---- \[그림 5.12] <br>
>  <br>
> - 위의 식 처럼, **$\large \frac{\delta L}{\delta y} \normalsize y^2 exp(-x)$를 순전파의 입력 $x$와 출력 $y$ 만으로 계산할 수 있으며**, <br>
**계산 그래프의 중간 과정을 그룹화 하여 아래와 같이 단순한 "sigmoid" 노드 하나로 대체할 수 있음** ---- \[그림 5.13]
> 
> - \[그림 5.12]와 \[그림 5.13]의 결과는 똑같음. \[그림 5.13]의 간소화 버전이 역전파 과정의 중간 계산들을 생략할 수 있어 더 효율적인 계산이라 말할 수 있음 <br>
> - 노드를 그룹화 하여 sigmoid 계층의 세세한 내용을 노출하지 않고 입력과 출력에만 집중할 수 있다는 것도 중요한 포인트
#### <<Sigmoid 계층의 계산 그래프 간소화>>
- $\large \frac{\delta L}{\delta y} \normalsize y^2 exp(-x)$는 다음처럼 정리해서 쓸 수 있음 ---- \[식 5.12]
> $$\normalsize \frac{\delta L}{\delta y} y^2 exp(-x) = \frac{\delta L}{\delta y} \frac{1}{(1 + exp(-x))^2} exp(-x)$$ <br>
> $$\normalsize = \frac{\delta L}{\delta y} \frac{1}{1 + exp(-x)} \frac{exp(-x)}{1 + exp(-x)}$$ <br>
> $$\normalsize = \frac{\delta L}{\delta y} \ y \ (1 - y)$$ <br>
> - 참고로, $\normalsize (1 - y)$로 축약되는 과정을 역으로 풀면, $\normalsize 1$의 분모와 분자에 동일한 값$\normalsize (1 + exp(-x))$을 곱한 후 분자 끼리 더함 <br><br>
> $$\normalsize (1 - y) = \frac{\not 1 + exp(-x)}{1 + exp(-x)} + \frac{\not -1}{1 + exp(-x)}$$ <br>
> - 결론적으로, **sigmoid 계층의 역전파는 순전파의 출력($\normalsize y$) 만으로 계산할 수 있음**
- **Sigmoid 계층의 계산 그래프 : 순전파의 출력 $\normalsize y$ 만으로 역전파 계산** ---- \[그림 5.14]
> 
```
# Sigmoid 계층 구현하기
class Sigmoid:
def __init__(self):
self.out = None # 역전파 계산을 위한 순전파 출력값을 저장하기 위한 인스턴스 변수
def forward(self, x):
# sigmoid 출력 공식을 그대로 구현 (x는 numpy 배열이라는 전제)
out = 1 / (1 + np.exp(-x))
self.out = out # 역전파 계산을 위해 인스턴스 변수에 저장
return out
def backward(self, dout):
# [식 5.12]와 [그림 5.14]의 역전파 최종 출력 공식
dx = dout * self.out * (1 - self.out)
return dx
```
## 5.6 Affine/Softmax 계층 구현하기
### [Affine 계층]
- 신경망의 순전파에서는 가중치 신호의 총합을 계산하기 때문에 행렬의 내적을 사용함 : np.dot() 메서드 사용
- 행렬의 내적 계산은 대응하는 차원의 원소 수를 일치시키는 게 핵심 ---- \[그림 5.15]
> 
- 신경망의 순전파 때 수행하는 **행렬의 내적**은 기하학에서는 **어파인 변환(Affine Transformation)** 이라고 함
```
X = np.random.rand(2)
W = np.random.rand(2, 3)
B = np.random.rand(3)
print(X.shape)
print(W.shape)
print(B.shape)
Y = np.dot(X, W) + B
print(B)
```
- **Affine 계층의 계산 그래프(순전파)**
> - 행렬의 내적을 계산하는 노드를 "dot"이라 정의
> - Affine 계층 계산 그래프(순전파) : $\matrix Y = np.dot(\matrix X \cdot \matrix W) + \matrix B$의 계산 그래프 (각 변수의 이름 위에 형상도 표기) ---- \[그림 5.16]
> 
> - $\matrix X, W, B$는 행렬 : "(2, )"은 "1행 2열" 짜리 행렬의 Numpy 표현(열 벡터를 행렬로 표현한 것) 이며, N행 2열의 경우 (N, 2) 처럼 표현됨
- **Affine 계층의 계산 그래프(역전파)**
> - 행렬을 사용한 역전파도 행렬의 원소마다 전개해보면 스칼라값을 사용한 지금까지의 계산 그래프와 같은 순서로 생각할 수 있음 <br>
> - **Affine 계층의 역전파 수식** ---- \[식 5.13] <br><br>
> $$\frac{\delta \matrix L}{\delta \matrix X} = \frac{\delta \matrix L}{\delta \matrix Y} \cdot \matrix W^T$$ <br>
> $$\frac{\delta \matrix L}{\delta \matrix W} = \matrix X^T \cdot \frac{\delta \matrix L}{\delta \matrix Y}$$ <br>
> - ["벡터와 행렬에 대한 미분" 참고 자료 1](http://darkpgmr.tistory.com/141), ["벡터와 행렬에 대한 미분" 참고 자료 2](https://nbviewer.jupyter.org/github/metamath1/ml-simple-works/blob/master/fitting/matrix-derivative.ipynb) <br><br>
> - $\matrix W^T$의 T는 전치행렬을 뜻하며, 전치행렬은 $\matrix W$의 $(i, j)$위치의 원소를 $(j, i)$ 위치로 바꾼 것 ---- \[식 5.14] <br><br>
> $$\matrix W = \begin{bmatrix} W_{11} W_{21} W_{31} \\
W_{12} W_{22} W_{32} \end{bmatrix}$$ <br>
> $$\matrix W^T = \begin{bmatrix} W_{11} W_{12} \\
W_{21} W_{22} \\
W_{31} W_{32} \end{bmatrix}$$ <br>
> - **Affine 계층의 역전파 계산 그래프 (변수는 다차원 배열)** ---- \[그림 5.17]
> 
> - **$\matrix X$와 $\large \frac{\delta L}{\delta X}$가 같은 형상이고, $\matrix W$와 $\large \frac{\delta L}{\delta W}$가 같은 형상임** (스칼라 함수인 $L$을 행렬 $\matrix X$와 $\matrix W$의 각 원소 마다 미분하는 형태) ---- \[식 5.15] <br><br>
> $$\large \matrix X = (x_0, x_1, \cdots, x_n)$$ <br>
> $$\large \frac{\delta L}{\delta X} = (\frac{\delta L}{\delta x_0}, \frac{\delta L}{\delta x_1}, \cdots, \frac{\delta L}{\delta x_n})$$ <br>
> - 행렬 내적("dot" 노드)의 역전파는 행렬의 대응하는 차원의 원소 수가 일치하도록 내적을 조립하여 구할 수 있음. <br>
예를들어, $\large \frac{\delta L}{\delta Y}$의 형상이 $(3, )$이고, $\large \frac{\delta L}{\delta X}$의 형상이 $(2, )$가 되도록 하는 $\matrix W$의 형상 $(3, 2)$를 찾아낼 수 있음 ---- \[그림 5.18]
> 
### [배치용 Affine 계층]
- 배치용 Affine 계층은 데이터 $N$개를 묶어 순전파 하는 경우의 Affine 계층으로, 기존 Affine 계층과 다른 부분은 형상이 $(N, 2)$가 된 것 뿐임
- **배치용 Affine 계층 계산 그래프** ---- \[그림 5.19]
> 
> - 순전파 때의 편향 덧셈은 $\matrix X \cdot \matrix W$에 대한 편향 $\matrix B$가 N개의 데이터 각각에 더해짐. <br>
결론적으로, 출력에 B의 N 배 만큼의 영향이 있음
> - **역전파 때는 각 데이터의 역전파 값이 편향의 원소에 모여야 함.** <br>
미분의 정의(입력이 아주 조금 변동될 때 출력의 영향)에 따라 역전파 때는 각 데이터의 미분 값을 모두 더해야 함
> - **편향의 역전파는 그 두 데이터에 대한 미분을 데이터 마다 더해서 구함.** <br>
numpy.sum( )으로 상류에서 전달된 미분값의 0번째 축(데이터를 단위로 하는 축, axis=0)에 대해서 총합을 구하면 됨
```
# 편향의 역전파
dY = np.array([[1, 2, 3], [4, 5, 6]])
print(dY)
dB = np.sum(dY, axis=0)
print(dB)
# 배치용 Affine 계층 구현
class Affine:
def __init__(self, W, b):
self.W = W
self.b = b
self.x = None
self.dW = None
self.db = None
def forward(self, x):
self.x = x
out = np.dot(x, self.W) + self.b
return out
def backward(self, dout):
dx = np.dot(dout, self.W.T)
self.dW = np.dot(self.x.T, dout)
self.db = np.sum(dout, axis=0)
return dx
```
### [Softmax-with-Loss 계층]
- Softmax 계층과 손실함수인 Cross-Entropy-Error 계층을 포함하여 **"Softmax-with-Loss 계층"** 으로 구현
- 춣력층에서 사용하는 **Softmax 함수는 입력 값을 정규화(출력의 합이 1이 되도록 변형) 하여 출력함(출력 결과는 확률로 사용 가능함)**
- 신경망의 학습에는 Softmax 계층이 필요하지만, 추론할 때는 일반적으로 Softmax 함수를 사용하지 않고 마지막 Affine 계층의 출력을 인식 결과로 이용함
- 신경망에서 정규화 하지 않은 출력 결과(Softmax 바로 전의 Affine 계층의 출력)을 **점수**라고 함
- **간소화한 Softmax-with-Loss 계층 계산 그래프** ---- \[그림 5.20]
> 
> - 3클래스 분류로 가정하고, 이전 계층에서 3개의 입력(점수)을 받음. Softmax 계층의 입력은 $\normalsize (a_1, a_2, a_3)$, 출력은 $\normalsize (y_1, y_2, y_3)$
> - Cross Entropy Error 계층은 Softmax 계층의 출력과 정답 레이블 $\normalsize (t_1, t_2, t_3)$을 입력으로 받고, 손실 $\normalsize L$을 출력
> - Softmax-with-Loss 계층의 **순전파의 출력인 손실함수는** $\normalsize L = - \ (t_1 \log {y_1} + t_2 \log {y_2} + \cdots + t_n \log {y_n})$
> - Softmax 계층의 **역전파는 $\normalsize (y_1 - t_1, y_2 - t_2, y_3 - t_3)$ 이며, 이는 Softmax 계층의 출력과 정답 레이블의 차분과 같음.** <br>
신경망의 역전파에서는 이 차이인 오차가 앞 계층에 전해지는 것 임
> - 신경망 학습의 목적은 신경망의 출력(Softmax의 출력)이 정답 레이블과 가까워지도록 가중치 매개변수의 값을 조정하는 것이며, <br>
신경망의 출력과 정답 레이블의 오차를 효율적으로 앞 계층에 전달해야 함. $(y_1 - t_1, y_2 - t_2, y_3 - t_3)$ 라는 결과는 이를 잘 반영하고 있음
```
# Softmax-with-Loss 계층 구현
class SoftmaWithLoss:
def __init__(self):
self.loss = None
self.y = None
self.t = None
def forward(self, x, t):
self.t = t
self.y = softmax(x)
self.loss = cross_entropy_error(self.y, self.t)
return self.loss
def backward(self, dout=1):
batch_size = self.t.shape[0]
dx = (self.y - self.t) / batch_size
return dx
```
- **역전파 구현 시 참고사항**
> - 역전파의 초기값은 가장 오른쪽 역전파의 값으로, $\large \frac{\delta L}{\delta L}$은 $1$ 임
> - "X" 노드의 역전파는 순전파 시의 입력들의 값을 서로 바꿔서 상류의 미분에 곱하고 하류로 전달
> - "+" 노드의 역전파는 상류에서 전해지는 미분을 그대로 출력
> - "log" 노드의 역전파는 다음 식에 따름
> $$\normalsize y = \log x$$ <br>
> $$\normalsize \frac{\delta y}{\delta x} = \frac{1}{x}$$ <br>
## 5.7 오차역전파법 구현하기
### [신경망 학습의 전체 순서]
- 전제 : 신경망에는 적용 가능한 가중치와 편향이 있고, 이 **가중치와 편향을 훈련 데이터에 적응하도록 조정하는 과정을 "학습"이라 함**
- **1단계(미니배치)** : 훈련 데이터 중 일부를 무작위로 가져옴. 이렇게 선별한 데이터를 미니배치라 하며, 그 미니배치의 손실함수 값을 줄이는 것이 목표
- **2단계(기울기 산출)** : 미니배치의 손실 함수 값을 줄이기 위해 각 가중치 매개변수의 기울기를 구함. <br>
기울기는 손실 함수의 값을 가장 작게 하는 방향을 제시함. **오차역전파법**을 이용하면 느린 수치 미분과 달리 기울기를 효율적이고 빠르게 구할 수 있음
- **3단계(매개변수 갱신)** : 가중치 매개변수를 기울기 방향으로 아주 조금 갱신
- **4단계(반복)** : 1~3단계를 반복
### [오차역전파법을 적용한 신경망 구현하기]
- **TwoLayerNet 클래스의 인스턴스 변수**
> - **params** : 딕셔너리 변수로 신경망의 **매개변수($W1, b1, W2, b2$)를 보관**
> - **layers** : 순서가 있는 딕셔너리 변수로, 신경망의 계층을 보관. **각 계층을 순서대로 유지**(OrderedDict 클래스로 객체 생성)
> - **lastLayer** : 신경망의 마지막 계층(**SoftmaxWithLoss 계층**)
- **TwoLayerNet 클래스의 메서드**
> - **__init__(self, input_size, hidden_size, output_size, weight_init_std)** : 초기화 수행 (weight_init_std는 가중치 초기화 시 정규분포의 스케일)
> - **predict(self, x)** : 예측(추론)을 수행. x는 이미지 데이터
> - **loss(self, x, t)** : 손실 함수의 값을 구함. x는 이미지 데이터, t는 정답 레이블
> - **accuracy(self, x, t)** : 정확도를 구함
> - **numerical_gradient(self, x, t)** : 가중치 매개변수의 기울기를 수치 미분 방식으로 구함
> - **gradient(self, x, t)** : 가중치 매개변수의 기울기를 오차역전파법으로 구함
```
# 오차역전파법을 적용한 2층 신경망 구현
import sys
import os
sys.path.append(os.pardir)
from collections import OrderedDict
from common.gradient import numerical_gradient
from common.layers import *
import numpy as np
class TwoLayerNet:
def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
# 가중치 초기화
self.params = {}
self.params['W1'] = weight_init_std * \
np.random.randn(input_size, hidden_size)
self.params['b1'] = np.zeros(hidden_size)
self.params['W2'] = weight_init_std * \
np.random.randn(hidden_size, output_size)
self.params['b2'] = np.zeros(output_size)
# 계층 생성
self.layers = OrderedDict()
self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1'])
self.layers['Relu1'] = Relu()
self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2'])
self.lastLayer = SoftmaxWithLoss()
def predict(self, x):
for layer in self.layers.values():
x = layer.forward(x)
return x
def loss(self, x, t): # x는 입력 데이터, t는 정답 레이블
y = self.predict(x)
return self.lastLayer.forward(y, t)
def accuracy(self, x, t):
y = self.predict(x)
y = np.argmax(y, axis=1)
if t.ndim != 1:
t = np.argmax(t, axis=1)
accuracy = np.sum(y == t) / float(x.shape[0])
return accuracy
def numerical_gradient(self, x, t):
def loss_W(W): return self.loss(x, t)
grads = {}
grads['W1'] = numerical_gradient(loss_W, self.params['W1'])
grads['b1'] = numerical_gradient(loss_W, self.params['b1'])
grads['W2'] = numerical_gradient(loss_W, self.params['W2'])
grads['b2'] = numerical_gradient(loss_W, self.params['b2'])
return grads
def gradient(self, x, t):
# 순전파
self.loss(x, t)
# 역전파
dout = 1
dout = self.lastLayer.backward(dout)
layers = list(self.layers.values())
layers.reverse()
for layer in layers:
dout = layer.backward(dout)
# 결과 저장
grads = {}
grads['W1'] = self.layers['Affine1'].dW
grads['b1'] = self.layers['Affine1'].db
grads['W2'] = self.layers['Affine2'].dW
grads['b2'] = self.layers['Affine2'].db
return grads
```
- **신경망의 계층을 OrderedDict 객체(순서가 있는 딕셔너리)에 보관**
> - **순전파 때는 각 계층을 추가한 순서대로 forward() 메서드를 호출** 하기만 하면 처리가 완료됨
> - **역전파 때는 계층을 추가한 반대 순서로 호출** 하기만 하면 됨
> - Affine 계층과 ReLU 계층이 각자의 내부에서 순전파와 역전파를 처리하고 있기 때문에, 각 계층을 올바른 순서로 연결한 다음 호출해주기만 하면 됨
- 신경망의 구성 요소를 "계층"으로 구현("계층"으로 모듈화) 한 덕분에 **더 깊은 층을 구현하고 싶다면, 단순히 필요한 만큼 계층을 추가 만 하면 됨**
### [오차역전파법으로 구한 기울기 검증하기]
- 기울기를 구할 때, 오차역전파법을 이용해 해석적으로 구하는 방법은 매개변수가 많아도 효율적으로 계산할 수 있으나, 수치 미분 방식은 느린 반면 구현하기 쉬움
- 수치 미분 방식은 구현하기 쉬워서 버그가 숨어 있기 어려운 반면, 오차역전파법은 구현하기 복잡해서 종종 실수를 할 수 있음
- **기울기 검증(gradient check)** : 수치 미분 방식의 결과와 오차역전파법의 결과를 비교하여 오차역전파법을 제대로 구현 했는지 검증하는 작업
```
# 오차역전파법 기울기 검증
# 위에서 작성한 코드(오차역전파법을 적용한 2층 신경망 구현)를 two_layer_net.py로 저장해야 함
import sys
import os
sys.path.append(os.pardir)
from two_layer_net import TwoLayerNet
from dataset.mnist import load_mnist
import numpy as np
# 데이터 읽기
(x_train, t_train), (x_test, t_test) = load_mnist(
normalize=True, one_hot_label=True)
network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
x_batch = x_train[:100]
t_batch = t_train[:100]
grad_numerical = network.numerical_gradient(x_batch, t_batch)
grad_backprop = network.gradient(x_batch, t_batch)
# 각 가중치의 절대 오차의 평균을 구한다.
for key in grad_numerical.keys():
diff = np.average(np.abs(grad_backprop[key] - grad_numerical[key]))
print(key + ": " + str(diff))
```
### [오차역전파법을 사용한 학습 구현하기]
```
# 오차역전파법을 사용한 신경망 학습 구현
import sys
import os
sys.path.append(os.pardir)
from two_layer_net import TwoLayerNet
from dataset.mnist import load_mnist
import numpy as np
# 데이터 읽기
(x_train, t_train), (x_test, t_test) = load_mnist(
normalize=True, one_hot_label=True)
network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1
train_loss_list = []
train_acc_list = []
test_acc_list = []
iter_per_epoch = max(train_size / batch_size, 1)
for i in range(iters_num):
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
# 오차역전파법으로 기울기를 구한다.
grads = network.gradient(x_batch, t_batch)
# 갱신
for key in ('W1', 'b1', 'W2', 'b2'):
network.params[key] -= learning_rate * grads[key]
# 손실함수 계산 및 진행경과 저장
loss = network.loss(x_batch, t_batch)
train_loss_list.append(loss)
# 학습 진행 경과 저장 및 출력
if (i % iter_per_epoch == 0) or (i == (iters_num - 1)):
train_acc = network.accuracy(x_train, t_train)
test_acc = network.accuracy(x_test, t_test)
train_acc_list.append(train_acc)
test_acc_list.append(test_acc)
print("{:.0f} 번째 학습 loss, train_acc, test_acc : {:.3f}, {:.3f}, {:.3f}".format(i, loss, train_acc, test_acc))
# 손실함수 변화 추이 그래프
import matplotlib.pyplot as plt
%matplotlib inline
fig, axes = plt.subplots(1, 2, figsize=(15,4))
for iters_num, ax in zip([10000, 1000], axes):
ax.plot(train_loss_list[:iters_num])
ax.set_title("{}-Iterations Loss".format(iters_num))
ax.set_xlabel("Iterations")
ax.set_ylabel("Loss")
ax.set_ylim(0, 5)
ax.set_xlim(0, iters_num)
# 훈련 데이터와 시험 데이터에 대한 정확도 추이
fig, ax = plt.subplots(figsize=(15,4))
ax.plot(train_acc_list, c="b")
ax.plot(test_acc_list, "--", c="r") # 시험 데이터에 대한 정확도는 점선으로 표시(Red 색상)
ax.set_title("훈련 데이터와 학습 데이터 정확도 추이")
ax.set_xlabel("Accuracy")
ax.set_ylabel("Epochs")
ax.set_ylim(0.0, 1.0)
ax.set_xlim(0, len(train_acc_list))
```
|
github_jupyter
|
# 곱셈 계층 계산 그래프 구현
class MultiLayer():
def __init__(self):
self.x = None # 역전파에 사용하기 위해, 순전파 때의 입력 값을 유지하기 위한 변수
self.y = None
def forward(self, x, y):
self.x = x
self.y = y
out = x * y
return out
def backward(self, dout): # dout은 상류층의 순전파의 미분 값
dx = dout * self.y # 상류에서 전달된 값에 x와 y를 바꿔서 곱한다.
dy = dout * self.x
return dx, dy
apple = 100
apple_num = 2
tax = 1.1
# 계층들
mul_apple_layer = MultiLayer()
mul_tax_layer = MultiLayer()
# 순전파
apple_price = mul_apple_layer.forward(apple, apple_num)
price = mul_tax_layer.forward(apple_price, tax)
print("price : {:.2f}".format(price))
# 역전파
dprice = 1
dapple_price, dtax = mul_tax_layer.backward(dprice)
dapple, dapple_num = mul_apple_layer.backward(dapple_price)
print("dapple, dapple_num, dtax : {:.2f}, {:.2f}, {:.2f}".format(
dapple, dapple_num, dtax))
# 덧셈 계층 계산 그래프 구현
class AddLayer:
def __init__(self):
pass # 덧셈 노드에서는 순전파 때의 입력 값을 유지할 필요 없음(역전파에서 사용하지 않음)
def forward(self, x, y):
out = x + y
return out
def backward(self, dout):
dx = dout * 1 # 상류에서 내려온 미분(dout) 값을 그대로 하류로 흘려 보냄
dy = dout * 1
return dx, dy
# 덧셈 계층과 곱셈 계층을 사용한 사과와 귤의 계산 그래프 구현
apple = 100
apple_num = 2
orange = 150
orange_num = 3
tax = 1.1
# 계층들
mul_apple_layer = MultiLayer()
mul_orange_layer = MultiLayer()
add_apple_orange_layer = AddLayer()
mul_tax_layer = MultiLayer()
# 순전파
apple_price = mul_apple_layer.forward(apple, apple_num)
orange_price = mul_orange_layer.forward(orange, orange_num)
all_price = add_apple_orange_layer.forward(apple_price, orange_price)
price = mul_tax_layer.forward(all_price, tax)
# 역전파
dprice = 1
dall_price, dtax = mul_tax_layer.backward(dprice)
dapple_price, dorange_price = add_apple_orange_layer.backward(dall_price)
dapple, dapple_num = mul_apple_layer.backward(dapple_price)
dorange, dorange_num = mul_orange_layer.backward(dorange_price)
print("price : {:.0f}".format(price))
print("dapple, dapple_num, dorange, dorange_num, dtax: {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}".format(
dapple, dapple_num, dorange, dorange_num, dtax))
# ReLU 계층 구현 (forward() 함수와 backward() 함수는 numpy 배열을 인수로 받는 것으로 가정)
class ReLU:
def __init__(self):
# True/False로 구성된 numpy 배열로, 순전파의 입력인 x의 원소 값이 0 이하인 인덱스는 True, 그 외의 인덱스는 False
self.mask = None
def forward(self, x):
self.mask = (x <= 0)
out = x.copy()
out[self.mask] = 0 # self.mask가 True인 인덱스의 값을 0으로 변경
return 0
def backward(self, dout):
# 순전파에서 만든 mask를 써서 mask가 True인 곳은 상류에서 전파된 dout을 0으로 변경
dout[self.mask] = 0
return dout
import numpy as np
x = np.array([[1.0, -0.5], [-2.0, 3.0]])
print(x)
mask = (x <= 0)
print(mask)
# Sigmoid 계층 구현하기
class Sigmoid:
def __init__(self):
self.out = None # 역전파 계산을 위한 순전파 출력값을 저장하기 위한 인스턴스 변수
def forward(self, x):
# sigmoid 출력 공식을 그대로 구현 (x는 numpy 배열이라는 전제)
out = 1 / (1 + np.exp(-x))
self.out = out # 역전파 계산을 위해 인스턴스 변수에 저장
return out
def backward(self, dout):
# [식 5.12]와 [그림 5.14]의 역전파 최종 출력 공식
dx = dout * self.out * (1 - self.out)
return dx
X = np.random.rand(2)
W = np.random.rand(2, 3)
B = np.random.rand(3)
print(X.shape)
print(W.shape)
print(B.shape)
Y = np.dot(X, W) + B
print(B)
# 편향의 역전파
dY = np.array([[1, 2, 3], [4, 5, 6]])
print(dY)
dB = np.sum(dY, axis=0)
print(dB)
# 배치용 Affine 계층 구현
class Affine:
def __init__(self, W, b):
self.W = W
self.b = b
self.x = None
self.dW = None
self.db = None
def forward(self, x):
self.x = x
out = np.dot(x, self.W) + self.b
return out
def backward(self, dout):
dx = np.dot(dout, self.W.T)
self.dW = np.dot(self.x.T, dout)
self.db = np.sum(dout, axis=0)
return dx
# Softmax-with-Loss 계층 구현
class SoftmaWithLoss:
def __init__(self):
self.loss = None
self.y = None
self.t = None
def forward(self, x, t):
self.t = t
self.y = softmax(x)
self.loss = cross_entropy_error(self.y, self.t)
return self.loss
def backward(self, dout=1):
batch_size = self.t.shape[0]
dx = (self.y - self.t) / batch_size
return dx
# 오차역전파법을 적용한 2층 신경망 구현
import sys
import os
sys.path.append(os.pardir)
from collections import OrderedDict
from common.gradient import numerical_gradient
from common.layers import *
import numpy as np
class TwoLayerNet:
def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
# 가중치 초기화
self.params = {}
self.params['W1'] = weight_init_std * \
np.random.randn(input_size, hidden_size)
self.params['b1'] = np.zeros(hidden_size)
self.params['W2'] = weight_init_std * \
np.random.randn(hidden_size, output_size)
self.params['b2'] = np.zeros(output_size)
# 계층 생성
self.layers = OrderedDict()
self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1'])
self.layers['Relu1'] = Relu()
self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2'])
self.lastLayer = SoftmaxWithLoss()
def predict(self, x):
for layer in self.layers.values():
x = layer.forward(x)
return x
def loss(self, x, t): # x는 입력 데이터, t는 정답 레이블
y = self.predict(x)
return self.lastLayer.forward(y, t)
def accuracy(self, x, t):
y = self.predict(x)
y = np.argmax(y, axis=1)
if t.ndim != 1:
t = np.argmax(t, axis=1)
accuracy = np.sum(y == t) / float(x.shape[0])
return accuracy
def numerical_gradient(self, x, t):
def loss_W(W): return self.loss(x, t)
grads = {}
grads['W1'] = numerical_gradient(loss_W, self.params['W1'])
grads['b1'] = numerical_gradient(loss_W, self.params['b1'])
grads['W2'] = numerical_gradient(loss_W, self.params['W2'])
grads['b2'] = numerical_gradient(loss_W, self.params['b2'])
return grads
def gradient(self, x, t):
# 순전파
self.loss(x, t)
# 역전파
dout = 1
dout = self.lastLayer.backward(dout)
layers = list(self.layers.values())
layers.reverse()
for layer in layers:
dout = layer.backward(dout)
# 결과 저장
grads = {}
grads['W1'] = self.layers['Affine1'].dW
grads['b1'] = self.layers['Affine1'].db
grads['W2'] = self.layers['Affine2'].dW
grads['b2'] = self.layers['Affine2'].db
return grads
# 오차역전파법 기울기 검증
# 위에서 작성한 코드(오차역전파법을 적용한 2층 신경망 구현)를 two_layer_net.py로 저장해야 함
import sys
import os
sys.path.append(os.pardir)
from two_layer_net import TwoLayerNet
from dataset.mnist import load_mnist
import numpy as np
# 데이터 읽기
(x_train, t_train), (x_test, t_test) = load_mnist(
normalize=True, one_hot_label=True)
network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
x_batch = x_train[:100]
t_batch = t_train[:100]
grad_numerical = network.numerical_gradient(x_batch, t_batch)
grad_backprop = network.gradient(x_batch, t_batch)
# 각 가중치의 절대 오차의 평균을 구한다.
for key in grad_numerical.keys():
diff = np.average(np.abs(grad_backprop[key] - grad_numerical[key]))
print(key + ": " + str(diff))
# 오차역전파법을 사용한 신경망 학습 구현
import sys
import os
sys.path.append(os.pardir)
from two_layer_net import TwoLayerNet
from dataset.mnist import load_mnist
import numpy as np
# 데이터 읽기
(x_train, t_train), (x_test, t_test) = load_mnist(
normalize=True, one_hot_label=True)
network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1
train_loss_list = []
train_acc_list = []
test_acc_list = []
iter_per_epoch = max(train_size / batch_size, 1)
for i in range(iters_num):
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
# 오차역전파법으로 기울기를 구한다.
grads = network.gradient(x_batch, t_batch)
# 갱신
for key in ('W1', 'b1', 'W2', 'b2'):
network.params[key] -= learning_rate * grads[key]
# 손실함수 계산 및 진행경과 저장
loss = network.loss(x_batch, t_batch)
train_loss_list.append(loss)
# 학습 진행 경과 저장 및 출력
if (i % iter_per_epoch == 0) or (i == (iters_num - 1)):
train_acc = network.accuracy(x_train, t_train)
test_acc = network.accuracy(x_test, t_test)
train_acc_list.append(train_acc)
test_acc_list.append(test_acc)
print("{:.0f} 번째 학습 loss, train_acc, test_acc : {:.3f}, {:.3f}, {:.3f}".format(i, loss, train_acc, test_acc))
# 손실함수 변화 추이 그래프
import matplotlib.pyplot as plt
%matplotlib inline
fig, axes = plt.subplots(1, 2, figsize=(15,4))
for iters_num, ax in zip([10000, 1000], axes):
ax.plot(train_loss_list[:iters_num])
ax.set_title("{}-Iterations Loss".format(iters_num))
ax.set_xlabel("Iterations")
ax.set_ylabel("Loss")
ax.set_ylim(0, 5)
ax.set_xlim(0, iters_num)
# 훈련 데이터와 시험 데이터에 대한 정확도 추이
fig, ax = plt.subplots(figsize=(15,4))
ax.plot(train_acc_list, c="b")
ax.plot(test_acc_list, "--", c="r") # 시험 데이터에 대한 정확도는 점선으로 표시(Red 색상)
ax.set_title("훈련 데이터와 학습 데이터 정확도 추이")
ax.set_xlabel("Accuracy")
ax.set_ylabel("Epochs")
ax.set_ylim(0.0, 1.0)
ax.set_xlim(0, len(train_acc_list))
| 0.625209 | 0.950041 |
<a href="https://colab.research.google.com/github/salu133445/flows/blob/main/realnvp_toy.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# RealNVP on Toy Dataset
Code adapted from https://github.com/tensorchiefs/dl_book.
## RealNVP Example
__Goal__: This notebook shows how to wrap learnable flows into Keras _subclassing_ `tf.keras.models.Model`.
__Usage__: Try to understand the provided code.
__Dataset__: Two dimnesional artifical data.
__Content__:
- Generation of the 2 dimensional artificial data set
- Creating a RealVNP-Flow subclassing Keras
- Fitting the flow to the 2-dimensional data
```
!pip install --upgrade tensorflow tensorflow_probability
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
np.random.seed(1)
tf.random.set_seed(1)
```
### Learning Flows with TF 2.0
Let's create a flow using parameters, which can be learned. We use masked Autoregressive flows for that.
```
def sample(num):
return np.array(np.random.uniform(-1,1,(num,2)), dtype='float32') #A real hard problem
# Adapted from: https://blog.evjang.com/2018/01/nf1.html
def sample_2(batch_size=500):
x2_dist = tfd.Normal(loc=0., scale=4.)
x2_samples = x2_dist.sample(batch_size)
x1 = tfd.Normal(loc=.25 * tf.square(x2_samples),
scale=tf.ones(batch_size, dtype=tf.float32))
x1_samples = x1.sample()
x_samples = tf.stack([x1_samples, x2_samples], axis=1)
return x_samples.numpy()/40.0
X = sample_2(1500)
xlim, ylim = [-2, 2], [-2, 2]
plt.scatter(X[:, 0], X[:, 1], s=10, color='red')
plt.xlim(-0.1,1)
plt.ylim(-0.35,0.35)
plt.show()
```
### Makeing a Keras model
#### Subclassing a Keras model
We build our own model. As suggested in: https://www.tensorflow.org/beta/tutorials/quickstart/advanced we wrap the model into a Keras model class, by subclassing `tf.keras.models.Model`. Having the variables in a model. Keras takes care of holding the variables.
#### Listing 6.7: The simple example of realNVPn TFP
Note that the listing in the book just shows the inner part.
```
# See also https://github.com/tensorflow/probability/blob/master/tensorflow_probability/python/bijectors/real_nvp.py
import time
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
tfb = tfp.bijectors
tfd = tfp.distributions
class RealNVP(tf.keras.models.Model):
def __init__(self, *, output_dim, num_masked, **kwargs):
super().__init__(**kwargs)
self.output_dim = output_dim
self.nets=[]
# We need to keep track of the nets
bijectors=[]
num_blocks = 5
h = 32
for i in range(num_blocks):
net = tfb.real_nvp_default_template([h, h])
bijectors.append(
tfb.RealNVP(shift_and_log_scale_fn=net,
num_masked=num_masked))
bijectors.append(tfb.Permute([1,0]))
self.nets.append(net)
bijector = tfb.Chain(list(reversed(bijectors[:-1])))
self.flow = tfd.TransformedDistribution(
distribution=tfd.MultivariateNormalDiag(loc=[0., 0.]),
bijector=bijector)
def call(self, *inputs):
return self.flow.bijector.forward(*inputs)
model = RealNVP(output_dim=2, num_masked=1)
_ = model(X) # The model needs called before it is build.
model.summary()
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
# Needs to be called other-wise @tf.function has problem
-tf.reduce_mean(model.flow.log_prob(X))
@tf.function
def train_step(X):
with tf.GradientTape() as tape:
loss = -tf.reduce_mean(model.flow.log_prob(X))
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
return loss
start = time.time()
for i in range(1001):
# Xs = sample(1000) #Creat new training data
loss = train_step(X)
if (i % 100 == 0):
print(i, " ",loss.numpy(), (time.time()-start))
start = time.time()
# XF = model.flow.sample(5000)
Z = np.random.normal(0,1,(5000,2))
cols = []
for i in range(5000):
if (Z[i,0] > 0 and Z[i,1] > 0):
cols.append('r')
elif (Z[i,0] < 0 and Z[i,1] > 0):
cols.append('b')
elif (Z[i,0] < 0 and Z[i,1] < 0):
cols.append('y')
else:
cols.append('g')
plt.figure(figsize=(14,6))
plt.subplot(1,2,1)
plt.scatter(Z[:, 0], Z[:, 1], s=5,c=cols)
plt.title('$Z \sim N(0,1)$')
plt.xlabel('$z_1$')
plt.ylabel('$z_2$')
Xs = model(Z)
plt.subplot(1,2,2)
plt.title('Transformed distribution')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.scatter(Xs[:,0], Xs[:, 1], s=5, c=cols)
plt.xlim(-0.1,1)
plt.ylim(-0.35,0.35)
plt.show()
```
### Understanding the mixture
We redo the morphing between two point in the x-space. In our high dimensional examples, we went from Beyonce to DiCaprio. We now redo this morphing with the two dimensional example to understand the principle.
```
X1 = np.array((0.6, 0.25), dtype=np.float32)
X2 = np.array((0.6, -0.25), dtype=np.float32)
Z1 = model.flow.bijector.inverse(X1) # np.array((-1.5,-1.5), dtype=float32)
Z2 = model.flow.bijector.inverse(X2) # np.array((1.5,1.5), dtype=float32)
nums = 500
Z_mixs = np.zeros((nums,2),dtype=np.float32)
for i,m in enumerate(np.linspace(0,1,nums)):
Z_mixs[i] = (Z2*m+Z1*(1.-m))
plt.figure(figsize=(14,6))
plt.subplot(1,2,1)
plt.scatter(Z[:, 0], Z[:, 1], s=5,c='lightgray')
plt.plot(Z_mixs[:,0],Z_mixs[:,1],c='blue', linewidth=2)
plt.scatter(Z_mixs[0,0],Z_mixs[0,1],c='red', s=120,marker='*')
plt.scatter(Z_mixs[nums-1,0],Z_mixs[nums-1,1],c='green', s=120,marker='*')
plt.title('$Z \sim N(0,1)$')
plt.xlabel('$z_1$')
plt.ylabel('$z_2$')
plt.subplot(1,2,2)
plt.title('X-Space')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.scatter(Xs[:,0], Xs[:, 1], s=5,c='lightgray')
plt.xlim(-0.1,1)
plt.ylim(-0.35,0.35)
plt.scatter(X1[0], X1[1], s=10)
plt.scatter(X2[0], X2[1], s=10)
X_mix = model.flow.bijector.forward(Z_mixs)
plt.plot(X_mix[:,0],X_mix[:,1],c='blue',linewidth=2)
plt.scatter(X1[0],X1[1],c='red', s=120,marker='*')
plt.scatter(X2[0],X2[1],c='green', s=120,marker='*')
X_mixs = np.zeros((nums,2), dtype=np.float32)
for i,m in enumerate(np.linspace(0,1,nums)):
X_mixs[i] = (X2*m+X1*(1.-m))
plt.plot(X_mixs[:,0],X_mixs[:,1],'--',c='black', linewidth=1.)
plt.show()
```
|
github_jupyter
|
!pip install --upgrade tensorflow tensorflow_probability
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
np.random.seed(1)
tf.random.set_seed(1)
def sample(num):
return np.array(np.random.uniform(-1,1,(num,2)), dtype='float32') #A real hard problem
# Adapted from: https://blog.evjang.com/2018/01/nf1.html
def sample_2(batch_size=500):
x2_dist = tfd.Normal(loc=0., scale=4.)
x2_samples = x2_dist.sample(batch_size)
x1 = tfd.Normal(loc=.25 * tf.square(x2_samples),
scale=tf.ones(batch_size, dtype=tf.float32))
x1_samples = x1.sample()
x_samples = tf.stack([x1_samples, x2_samples], axis=1)
return x_samples.numpy()/40.0
X = sample_2(1500)
xlim, ylim = [-2, 2], [-2, 2]
plt.scatter(X[:, 0], X[:, 1], s=10, color='red')
plt.xlim(-0.1,1)
plt.ylim(-0.35,0.35)
plt.show()
# See also https://github.com/tensorflow/probability/blob/master/tensorflow_probability/python/bijectors/real_nvp.py
import time
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
tfb = tfp.bijectors
tfd = tfp.distributions
class RealNVP(tf.keras.models.Model):
def __init__(self, *, output_dim, num_masked, **kwargs):
super().__init__(**kwargs)
self.output_dim = output_dim
self.nets=[]
# We need to keep track of the nets
bijectors=[]
num_blocks = 5
h = 32
for i in range(num_blocks):
net = tfb.real_nvp_default_template([h, h])
bijectors.append(
tfb.RealNVP(shift_and_log_scale_fn=net,
num_masked=num_masked))
bijectors.append(tfb.Permute([1,0]))
self.nets.append(net)
bijector = tfb.Chain(list(reversed(bijectors[:-1])))
self.flow = tfd.TransformedDistribution(
distribution=tfd.MultivariateNormalDiag(loc=[0., 0.]),
bijector=bijector)
def call(self, *inputs):
return self.flow.bijector.forward(*inputs)
model = RealNVP(output_dim=2, num_masked=1)
_ = model(X) # The model needs called before it is build.
model.summary()
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
# Needs to be called other-wise @tf.function has problem
-tf.reduce_mean(model.flow.log_prob(X))
@tf.function
def train_step(X):
with tf.GradientTape() as tape:
loss = -tf.reduce_mean(model.flow.log_prob(X))
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
return loss
start = time.time()
for i in range(1001):
# Xs = sample(1000) #Creat new training data
loss = train_step(X)
if (i % 100 == 0):
print(i, " ",loss.numpy(), (time.time()-start))
start = time.time()
# XF = model.flow.sample(5000)
Z = np.random.normal(0,1,(5000,2))
cols = []
for i in range(5000):
if (Z[i,0] > 0 and Z[i,1] > 0):
cols.append('r')
elif (Z[i,0] < 0 and Z[i,1] > 0):
cols.append('b')
elif (Z[i,0] < 0 and Z[i,1] < 0):
cols.append('y')
else:
cols.append('g')
plt.figure(figsize=(14,6))
plt.subplot(1,2,1)
plt.scatter(Z[:, 0], Z[:, 1], s=5,c=cols)
plt.title('$Z \sim N(0,1)$')
plt.xlabel('$z_1$')
plt.ylabel('$z_2$')
Xs = model(Z)
plt.subplot(1,2,2)
plt.title('Transformed distribution')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.scatter(Xs[:,0], Xs[:, 1], s=5, c=cols)
plt.xlim(-0.1,1)
plt.ylim(-0.35,0.35)
plt.show()
X1 = np.array((0.6, 0.25), dtype=np.float32)
X2 = np.array((0.6, -0.25), dtype=np.float32)
Z1 = model.flow.bijector.inverse(X1) # np.array((-1.5,-1.5), dtype=float32)
Z2 = model.flow.bijector.inverse(X2) # np.array((1.5,1.5), dtype=float32)
nums = 500
Z_mixs = np.zeros((nums,2),dtype=np.float32)
for i,m in enumerate(np.linspace(0,1,nums)):
Z_mixs[i] = (Z2*m+Z1*(1.-m))
plt.figure(figsize=(14,6))
plt.subplot(1,2,1)
plt.scatter(Z[:, 0], Z[:, 1], s=5,c='lightgray')
plt.plot(Z_mixs[:,0],Z_mixs[:,1],c='blue', linewidth=2)
plt.scatter(Z_mixs[0,0],Z_mixs[0,1],c='red', s=120,marker='*')
plt.scatter(Z_mixs[nums-1,0],Z_mixs[nums-1,1],c='green', s=120,marker='*')
plt.title('$Z \sim N(0,1)$')
plt.xlabel('$z_1$')
plt.ylabel('$z_2$')
plt.subplot(1,2,2)
plt.title('X-Space')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.scatter(Xs[:,0], Xs[:, 1], s=5,c='lightgray')
plt.xlim(-0.1,1)
plt.ylim(-0.35,0.35)
plt.scatter(X1[0], X1[1], s=10)
plt.scatter(X2[0], X2[1], s=10)
X_mix = model.flow.bijector.forward(Z_mixs)
plt.plot(X_mix[:,0],X_mix[:,1],c='blue',linewidth=2)
plt.scatter(X1[0],X1[1],c='red', s=120,marker='*')
plt.scatter(X2[0],X2[1],c='green', s=120,marker='*')
X_mixs = np.zeros((nums,2), dtype=np.float32)
for i,m in enumerate(np.linspace(0,1,nums)):
X_mixs[i] = (X2*m+X1*(1.-m))
plt.plot(X_mixs[:,0],X_mixs[:,1],'--',c='black', linewidth=1.)
plt.show()
| 0.878991 | 0.98302 |
```
import pandas as pd
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, GridSearchCV, cross_validate
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score
from itertools import permutations
from math import ceil
from matplotlib import pyplot as plt
import seaborn as sns
cfier = MLPClassifier(hidden_layer_sizes=(7,), random_state = 13, solver="lbfgs", verbose=True)
data = pd.read_csv("../Data/95_percent_var_PCs.csv")
def split_pca_data(df, cols=("PC1","PC164"), target="target", test_pct=0.8, rng_seed=0, ):
train_df, test_df = train_test_split(df, train_size=test_pct, random_state=23)
test_lbl = test_df["target"]
train_lbl = train_df["target"]
train = train_df.loc[:,cols[0]:cols[1]]
test = test_df.loc[:,cols[0]:cols[1]]
return train, test, train_lbl, test_lbl
train_data, test_data, train_lbls, test_lbls = split_pca_data(data, rng_seed=23)
# Standardize scale to training data
scaler = StandardScaler().fit(train_data)
train_data = scaler.transform(train_data)
test_data = scaler.transform(test_data)
```
# Bayesian hyperparameter searching using Hyperopt
- The python libary hyperopt has an implementation of a [Tree Parzen Estimator](https://papers.nips.cc/paper/2011/file/86e8f7ab32cfd12577bc2619bc635690-Paper.pdf) based bayesian hyperoptimizer.
Practically speaking the fmin function attempts to optimize the hyperparameter set using the tree parzen estimator (TPE) as a surrogate function for the actual objective function (which involves cross-validating a neural network). This TPE updates its preference for certain paramater values in a bayesian fashion, based on information gained from the last set of hyperparameters chosen and the resulting loss.
```
from hyperopt import hp, Trials, fmin, tpe, space_eval, STATUS_OK, STATUS_FAIL
from timeit import default_timer as timer
from statistics import mean
```
## Experimenting with various search spaces
I think it's wise to keep alpha as a uniform distribution. I'll start with normal distributions for the number now neurons in each layer and see where that takes things.
1. Search space 1: normal distributions with large variance.
- layer 1: ~N(mu = 150 neurons, sigma = 65)
- layer 2: ~N(mu = 75 neurons, sigma = 32)
- alpha: uniform {0.1, 0.01,... 10^-7}
```
# Define the search space. Dictionaries are in key:value where the value is a probabilistic space to
# "randomly" chose from (I believe as TPE algorithm works, it changes updates probabilistic distributions)
search_space = hp.choice("layers", [
{
"type": "two_layer",
"k": hp.quniform("2layers_k",1,7,1), # k is selecting for bias alpha, where alpha = 10^-k [0.1, 0.01, ... 10^-7]
"l1": hp.qnormal("2layers_l1",150, 65, 1), # Discretized normal dist, mu =150, stdev=65
"l2": hp.qnormal("2layers_l2",75, 32, 1), # mu =75, stdev=32
"iters": hp.qnormal("2layers_max_iters", 300, 25, 1)
},
{
"type": "three_layer",
"k": hp.quniform("3layers_k",1,7,1),
"l1": hp.qnormal("3layers_l1",150, 65, 1), # Discretized normal dist, mu =150, stdev=65
"l2": hp.qnormal("3layers_l2",75, 32, 1), # mu =75, stdev=32
"l3": hp.qnormal("3layers_l3",40, 20, 1), # Discretized normal dist, mu =75, stdev=32
"iters": hp.qnormal("3layers_max_iters", 300, 35, 1)
}
])
# Define the optimization function (Costly as it implies fitting a MLP classifier via CV)
def objective(architecture):
""" The objective function to optimize is the 5-fold cross-validation fitting of a 2 hidden layer NN classifier.
The hyperoptimizer operates as a minimizer, so the returned loss will be the negative of the avg of
mean accuracy.
"""
# Determine classifer hyperparams from architecture dictionary given
if "l3" in architecture:
shape = (2, int(architecture["l1"]), int(architecture["l2"]), int(architecture["l3"]))
else:
shape = (2, int(architecture["l1"]), int(architecture["l2"]))
k = architecture["k"]
iters = architecture["iters"]
# Make a new MLP Classifier
cfier = MLPClassifier(max_iter=iters, hidden_layer_sizes=shape, solver= "lbfgs", alpha = pow(10, -k),
random_state=25)
# Cross Validatae
results = cross_validate(cfier, X=train_data, y=train_lbls, cv=5, n_jobs=-1)
# Results must contain a "loss" value for hyperopt to minimize, and the status
results["loss"] = -1 * mean(results["test_score"])
del results["test_score"]
# For brevity report means
results["fit_time"] = mean(results["fit_time"])
results["score_time"] = mean(results["score_time"])
results["status"] = STATUS_OK
return results
# Create a trials Hyperopt Object which stores data regarding the results of our hyperparameter search
trials = Trials()
# Run the hyperparam search. We'll let the hyperopt lib suggest the tpe to use
best_performer = fmin(fn=objective, space=search_space, algo=tpe.suggest, trials=trials, max_evals=100,
rstate= np.random.RandomState(29))
```
## Hyperparameter optimization performance
```
# Analyze Hyperopt Progress
layers = best_performer["layers"] + 2
alpha = pow(10, -1 * best_performer[f"{layers}layers_k"])
iters = best_performer[f"{layers}layers_max_iters"]
l1_neurons = best_performer[f"{layers}layers_l1"]
l2_neurons = best_performer[f"{layers}layers_l2"]
print(f"Best performing architecture")
print(f"\tlayers: {layers}")
print(f"\talpha: {alpha}")
print(f"\tTraining Iterations: {iters}")
print(f"\titerations: {iters}")
print(f"\tl1 neurons: {l1_neurons}")
print(f"\tl2 neurons: {l2_neurons}")
if 3 == layers:
l3_neurons = best_performer[f"{layers}layers_l3"]
print(f"\tl3 neurons: {l3_neurons}")
# Plot mean accuracy versus iteration, and train time versus iteration
mean_acc = [abs(res["loss"]) for res in trials.results]
fit_time = [abs(res["fit_time"]) for res in trials.results]
fig, axs = plt.subplots(2, 1, constrained_layout=True)
mean_acc_nafiltered = pd.Series(mean_acc).fillna(value=0) # Replace NaNs with 0's
axs[0].plot(mean_acc_nafiltered, c="cyan")
axs[0].set_title(f"164 PC features: mean acc vs iteration")
axs[0].set_xlabel("Iteration")
axs[0].set_ylabel("Mean Accuracy (%)")
axs[1].plot(fit_time, c="red")
axs[1].set_title(f"164 PC features: mean fit time vs iteration")
axs[1].set_xlabel("Iteration")
axs[1].set_ylabel("Mean fit time (s)")
fig.set_figwidth(12)
fig.set_figheight(10)
```
## Training and Testing Optimal Architecture Performance
```
from print_conf_mat import *
if 3 == layers:
shape = (3,int(l1_neurons),int(l2_neurons),int(l3_neurons))
else:
shape = (2,int(l1_neurons),int(l2_neurons))
cfier = MLPClassifier(max_iter=iters, hidden_layer_sizes=shape, solver="lbfgs", alpha=alpha,
random_state=25)
cfier.fit(train_data, train_lbls)
predictions = cfier.predict(test_data)
c_mat = confusion_matrix(test_lbls, predictions)
report = classification_report(test_lbls, predictions)
print(f"Classification Report for 164 PC feature MLP classifier\n {report}")
fig = print_confusion_matrix(c_mat, ["AD", "ND"], figsize=(10,8), fontsize=20,
title="164 Principle Component MLP Classifier")
# y-axis annotation alignment goofs up on some versions of matplitlib.
# If this is the case, comment/uncomment the following line
fig.gca().set_ylim([0,2])
```
|
github_jupyter
|
import pandas as pd
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, GridSearchCV, cross_validate
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score
from itertools import permutations
from math import ceil
from matplotlib import pyplot as plt
import seaborn as sns
cfier = MLPClassifier(hidden_layer_sizes=(7,), random_state = 13, solver="lbfgs", verbose=True)
data = pd.read_csv("../Data/95_percent_var_PCs.csv")
def split_pca_data(df, cols=("PC1","PC164"), target="target", test_pct=0.8, rng_seed=0, ):
train_df, test_df = train_test_split(df, train_size=test_pct, random_state=23)
test_lbl = test_df["target"]
train_lbl = train_df["target"]
train = train_df.loc[:,cols[0]:cols[1]]
test = test_df.loc[:,cols[0]:cols[1]]
return train, test, train_lbl, test_lbl
train_data, test_data, train_lbls, test_lbls = split_pca_data(data, rng_seed=23)
# Standardize scale to training data
scaler = StandardScaler().fit(train_data)
train_data = scaler.transform(train_data)
test_data = scaler.transform(test_data)
from hyperopt import hp, Trials, fmin, tpe, space_eval, STATUS_OK, STATUS_FAIL
from timeit import default_timer as timer
from statistics import mean
# Define the search space. Dictionaries are in key:value where the value is a probabilistic space to
# "randomly" chose from (I believe as TPE algorithm works, it changes updates probabilistic distributions)
search_space = hp.choice("layers", [
{
"type": "two_layer",
"k": hp.quniform("2layers_k",1,7,1), # k is selecting for bias alpha, where alpha = 10^-k [0.1, 0.01, ... 10^-7]
"l1": hp.qnormal("2layers_l1",150, 65, 1), # Discretized normal dist, mu =150, stdev=65
"l2": hp.qnormal("2layers_l2",75, 32, 1), # mu =75, stdev=32
"iters": hp.qnormal("2layers_max_iters", 300, 25, 1)
},
{
"type": "three_layer",
"k": hp.quniform("3layers_k",1,7,1),
"l1": hp.qnormal("3layers_l1",150, 65, 1), # Discretized normal dist, mu =150, stdev=65
"l2": hp.qnormal("3layers_l2",75, 32, 1), # mu =75, stdev=32
"l3": hp.qnormal("3layers_l3",40, 20, 1), # Discretized normal dist, mu =75, stdev=32
"iters": hp.qnormal("3layers_max_iters", 300, 35, 1)
}
])
# Define the optimization function (Costly as it implies fitting a MLP classifier via CV)
def objective(architecture):
""" The objective function to optimize is the 5-fold cross-validation fitting of a 2 hidden layer NN classifier.
The hyperoptimizer operates as a minimizer, so the returned loss will be the negative of the avg of
mean accuracy.
"""
# Determine classifer hyperparams from architecture dictionary given
if "l3" in architecture:
shape = (2, int(architecture["l1"]), int(architecture["l2"]), int(architecture["l3"]))
else:
shape = (2, int(architecture["l1"]), int(architecture["l2"]))
k = architecture["k"]
iters = architecture["iters"]
# Make a new MLP Classifier
cfier = MLPClassifier(max_iter=iters, hidden_layer_sizes=shape, solver= "lbfgs", alpha = pow(10, -k),
random_state=25)
# Cross Validatae
results = cross_validate(cfier, X=train_data, y=train_lbls, cv=5, n_jobs=-1)
# Results must contain a "loss" value for hyperopt to minimize, and the status
results["loss"] = -1 * mean(results["test_score"])
del results["test_score"]
# For brevity report means
results["fit_time"] = mean(results["fit_time"])
results["score_time"] = mean(results["score_time"])
results["status"] = STATUS_OK
return results
# Create a trials Hyperopt Object which stores data regarding the results of our hyperparameter search
trials = Trials()
# Run the hyperparam search. We'll let the hyperopt lib suggest the tpe to use
best_performer = fmin(fn=objective, space=search_space, algo=tpe.suggest, trials=trials, max_evals=100,
rstate= np.random.RandomState(29))
# Analyze Hyperopt Progress
layers = best_performer["layers"] + 2
alpha = pow(10, -1 * best_performer[f"{layers}layers_k"])
iters = best_performer[f"{layers}layers_max_iters"]
l1_neurons = best_performer[f"{layers}layers_l1"]
l2_neurons = best_performer[f"{layers}layers_l2"]
print(f"Best performing architecture")
print(f"\tlayers: {layers}")
print(f"\talpha: {alpha}")
print(f"\tTraining Iterations: {iters}")
print(f"\titerations: {iters}")
print(f"\tl1 neurons: {l1_neurons}")
print(f"\tl2 neurons: {l2_neurons}")
if 3 == layers:
l3_neurons = best_performer[f"{layers}layers_l3"]
print(f"\tl3 neurons: {l3_neurons}")
# Plot mean accuracy versus iteration, and train time versus iteration
mean_acc = [abs(res["loss"]) for res in trials.results]
fit_time = [abs(res["fit_time"]) for res in trials.results]
fig, axs = plt.subplots(2, 1, constrained_layout=True)
mean_acc_nafiltered = pd.Series(mean_acc).fillna(value=0) # Replace NaNs with 0's
axs[0].plot(mean_acc_nafiltered, c="cyan")
axs[0].set_title(f"164 PC features: mean acc vs iteration")
axs[0].set_xlabel("Iteration")
axs[0].set_ylabel("Mean Accuracy (%)")
axs[1].plot(fit_time, c="red")
axs[1].set_title(f"164 PC features: mean fit time vs iteration")
axs[1].set_xlabel("Iteration")
axs[1].set_ylabel("Mean fit time (s)")
fig.set_figwidth(12)
fig.set_figheight(10)
from print_conf_mat import *
if 3 == layers:
shape = (3,int(l1_neurons),int(l2_neurons),int(l3_neurons))
else:
shape = (2,int(l1_neurons),int(l2_neurons))
cfier = MLPClassifier(max_iter=iters, hidden_layer_sizes=shape, solver="lbfgs", alpha=alpha,
random_state=25)
cfier.fit(train_data, train_lbls)
predictions = cfier.predict(test_data)
c_mat = confusion_matrix(test_lbls, predictions)
report = classification_report(test_lbls, predictions)
print(f"Classification Report for 164 PC feature MLP classifier\n {report}")
fig = print_confusion_matrix(c_mat, ["AD", "ND"], figsize=(10,8), fontsize=20,
title="164 Principle Component MLP Classifier")
# y-axis annotation alignment goofs up on some versions of matplitlib.
# If this is the case, comment/uncomment the following line
fig.gca().set_ylim([0,2])
| 0.790934 | 0.790934 |
<img src="https://drive.google.com/uc?id=1v7YY_rNBU2OMaPnbUGmzaBj3PUeddxrw" alt="ITI MCIT EPITA" style="width: 750px;"/>
___
# Data Preparation & Exploration
**By**: Mohamed Fouad Fakhruldeen, [email protected]
____
## Session 02
#### Topics:
* Download and open PostgreSQL
* Quick overview of DDL
* Quick overview of DML
* Integration of the Northwind database
* Query and extractions on that database
* Integration of the results in Orange
#### Postgresql installation
https://www.postgresql.org/
https://www.postgresql.org/download/
https://www.tecmint.com/install-postgresql-and-pgadmin-in-ubuntu/
https://www.microfocus.com/documentation/idol/IDOL_12_0/MediaServer/Guides/html/English/Content/Getting_Started/Configure/_TRN_Set_up_PostgreSQL.htm
https://www.postgresqltutorial.com/install-postgresql/
#### Crow's Foot Notation
Cardinality:
zero or many
one or many
one and only one
zero or one
Relationship degrees make them readable as :
One-to-one
One-to-many
Many-to-many
#### List of tables in the hospital database:
physician
department
affiliated_with
procedure
trained_in
patient
nurse
appointment
medication
prescribes
block
room
on_call
stay
undergoes
### DDL Data Definition Language
#### DML (Data Manipulation Language)
##### inner join
##### left join
##### Right Join
##### full outer join
#### import csv to postgresql
check persons.csv in files directory session02
#### export from postgresql to csv
### Exercise
1. Write a query to get Product name and quantity/unit. Solution
2. Write a query to get current Product list (Product ID and name). Solution
3. Write a query to get most expense and least expensive Product list (name and unit price). Solution
4. Write a query to get Product list (id, name, unit price) where current products cost less than 20.
5. Write a query to get Product list (id, name, unit price) where products cost between 15 and 25.
6. Write a query to get Product list (name, unit price) of above average price.
7. Write a query to get Product list (name, unit price) of ten most expensive products.
8. Make a list of categories and suppliers who supply products within those categories.
9. Make a complete list of customers, the OrderID and date of any orders they have made. Include customers who have not placed any orders.
10. Make a complete list of customers along with the number of orders they have placed.
11. Create a parameterized query that has the user enter a city and then list the customers or suppliers from that city.
#### connect to jupyterbook
To load ipython-sql, use the following magic command:
```
%load_ext sql
from sqlalchemy import create_engine
#%sql postgresql://username:password@host:port/databasename
%sql postgresql://mohamed:fakhrulde3n@localhost/dataprep
```
```
# Example format
#engine = create_engine('postgresql://username:password@host:port/databasename')
%%sql
DROP TABLE IF EXISTS links;
CREATE TABLE links (
id serial PRIMARY KEY,
url varchar(255) NOT NULL,
name varchar(255) NOT NULL,
description varchar(255),
rel varchar(10),
last_update date DEFAULT now()
);
INSERT INTO
links
VALUES
('1', 'https://www.ekb.eg', 'EKB', 'Egyptian Knowledge Bank', 'follow', '2020-06-02'),
('2', 'http://www.oreilly.com', 'O''Reilly Media', 'O''Reilly Media', 'nofollow', '2013-06-02'),
('3', 'http://www.google.com', 'Google', 'Google', 'nofollow', '2013-06-02'),
('4', 'http://www.yahoo.com', 'Yahoo', 'Yahoo', 'nofollow', '2013-06-02'),
('5', 'http://www.bing.com', 'Bing', 'Bing', 'nofollow', '2013-06-02'),
('6', 'http://www.facebook.com', 'Facebook', 'Facebook', 'nofollow', '2013-06-01'),
('7', 'https://www.twitter.com/', 'twitter', 'twitter', 'nofollow', '2013-06-02'),
('8', 'http://www.postgresql.org', 'PostgreSQL', 'PostgreSQL', 'nofollow', '2013-06-02');
%%sql
SELECT url, name FROM links;
```
|
github_jupyter
|
%load_ext sql
from sqlalchemy import create_engine
#%sql postgresql://username:password@host:port/databasename
%sql postgresql://mohamed:fakhrulde3n@localhost/dataprep
# Example format
#engine = create_engine('postgresql://username:password@host:port/databasename')
%%sql
DROP TABLE IF EXISTS links;
CREATE TABLE links (
id serial PRIMARY KEY,
url varchar(255) NOT NULL,
name varchar(255) NOT NULL,
description varchar(255),
rel varchar(10),
last_update date DEFAULT now()
);
INSERT INTO
links
VALUES
('1', 'https://www.ekb.eg', 'EKB', 'Egyptian Knowledge Bank', 'follow', '2020-06-02'),
('2', 'http://www.oreilly.com', 'O''Reilly Media', 'O''Reilly Media', 'nofollow', '2013-06-02'),
('3', 'http://www.google.com', 'Google', 'Google', 'nofollow', '2013-06-02'),
('4', 'http://www.yahoo.com', 'Yahoo', 'Yahoo', 'nofollow', '2013-06-02'),
('5', 'http://www.bing.com', 'Bing', 'Bing', 'nofollow', '2013-06-02'),
('6', 'http://www.facebook.com', 'Facebook', 'Facebook', 'nofollow', '2013-06-01'),
('7', 'https://www.twitter.com/', 'twitter', 'twitter', 'nofollow', '2013-06-02'),
('8', 'http://www.postgresql.org', 'PostgreSQL', 'PostgreSQL', 'nofollow', '2013-06-02');
%%sql
SELECT url, name FROM links;
| 0.315947 | 0.817392 |
# Programming with Python
## Episode 3 - Storing Multiple Values in Lists
Teaching: 30 min,
Exercises: 30 min
## Objectives
- Explain what a list is.
- Create and index lists of simple values.
- Change the values of individual elements
- Append values to an existing list
- Reorder and slice list elements
- Create and manipulate nested lists
#### How can I store many values together?
Just as a `for loop` is a way to do operations many times, a list is a way to store many values. Unlike NumPy arrays, lists are built into the language (so we don't have to load a library to use them). We create a list by putting values inside square brackets and separating the values with commas:
```
odds = [1, 3, 5, 7]
print('odds are:', odds)
```
```
odds = [1, 3, 5, 7]
print('odds are:', odds)
```
We can access elements of a list using indices – numbered positions of elements in the list. These positions are numbered starting at 0, so the first element has an index of 0.
```
print('first element:', odds[0])
print('last element:', odds[3])
print('"-1" element:', odds[-1])
```
```
print('first element:', odds[0])
print('last element:', odds[3])
print('"-1" element:', odds[-1])
```
Yes, we can use negative numbers as indices in Python. When we do so, the index `-1` gives us the last element in the list, `-2` the second to last, and so on.
Because of this, `odds[3]` and `odds[-1]` point to the same element here.
If we loop over a list, the loop variable is assigned elements one at a time:
for number in odds:
print(number)
```
for number in odds:
print(number)
```
There is one important difference between lists and strings: we can change the values in a list, but we cannot change individual characters in a string. For example:
```
names = ['Curie', 'Darwing', 'Turing'] # typo in Darwin's name
print('names is originally:', names)
names[1] = 'Darwin' # correct the name
print('final value of names:', names)
```
```
names = ['Curie', 'Darwing', 'Turing'] # typo in Darwin's name
print('names is originally:', names)
names[1] = 'Darwin' # correct the name
print('final value of names:', names)
```
works, but:
```
name = 'Darwin'
name[0] = 'd'
```
doesn't.
```
name = 'Darwin'
name[0] = 'd'
```
### Ch-Ch-Ch-Ch-Changes
Data which can be modified in place is called *mutable*, while data which cannot be modified is called *immutable*. Strings and numbers are immutable. This does not mean that variables with string or number values are constants, but when we want to change the value of a string or number variable, we can only replace the old value with a completely new value.
Lists and arrays, on the other hand, are mutable: we can modify them after they have been created. We can change individual elements, append new elements, or reorder the whole list. For some operations, like sorting, we can choose whether to use a function that modifies the data in-place or a function that returns a modified copy and leaves the original unchanged.
Be careful when modifying data in-place. If two variables refer to the same list, and you modify the list value, it will change for both variables!
```
salsa = ['peppers', 'onions', 'cilantro', 'tomatoes']
my_salsa = salsa # <-- my_salsa and salsa point to the *same* list data in memory
salsa[0] = 'hot peppers'
print('Ingredients in salsa:', salsa)
print('Ingredients in my salsa:', my_salsa)
```
If you want variables with mutable values to be independent, you must make a copy of the value when you assign it.
```
salsa = ['peppers', 'onions', 'cilantro', 'tomatoes']
my_salsa = list(salsa) # <-- makes a *copy* of the list
salsa[0] = 'hot peppers'
print('Ingredients in salsa:', salsa)
print('Ingredients in my salsa:', my_salsa)
```
Because of pitfalls like this, code which modifies data in place can be more difficult to understand. However, it is often far more efficient to modify a large data structure in place than to create a modified copy for every small change. You should consider both of these aspects when writing your code.
```
salsa = ['peppers', 'onions', 'cilantro', 'tomatoes']
my_salsa = salsa # <-- my_salsa and salsa point to the *same* list data in memory
salsa[0] = 'hot peppers'
print('Ingredients in salsa:', salsa)
print('Ingredients in my salsa:', my_salsa)
```
### Nested Lists
Since lists can contain any Python variable type, it can even contain other lists.
For example, we could represent the products in the shelves of a small grocery shop:
```
shop = [['pepper', 'zucchini', 'onion'],
['cabbage', 'lettuce', 'garlic'],
['apple', 'pear', 'banana']]
```
```
shop = [['pepper', 'zucchini', 'onion'],
['cabbage', 'lettuce', 'garlic'],
['apple', 'pear', 'banana']] #list within a list
```
Here is an example of how indexing a list of lists works:
The first element of our list is another list representing the first shelf:
```
print(shop[0])
```
```
print(shop[0])
```
to reference a particular item on a particular shelf (e.g. the third item on the second shelf - i.e. the `garlic`) we'd use extra `[` `]`'s
```
print(shop[1][2])
```
don't forget the zero index thing ...
```
print(shop[0])
print(shop[1:])
```
### Heterogeneous Lists
Lists in Python can contain elements of different types. Example:
```
sample_ages = [10, 12.5, 'Unknown']
```
```
sample_ages = [10, 12.5, 'Unknown']
print(sample_ages)
```
There are many ways to change the contents of lists besides assigning new values to individual elements:
```
odds.append(11)
print('odds after adding a value:', odds)
del odds[0]
print('odds after removing the first element:', odds)
odds.reverse()
print('odds after reversing:', odds)
```
```
odds.append(11)
print('odds after adding a value:', odds)
del odds[0]
print('odds after removing the first element:', odds)
odds.reverse()
print('odds after reversing:', odds)
```
While modifying in place, it is useful to remember that Python treats lists in a slightly counter-intuitive way.
If we make a list and (attempt to) copy it then modify in place, we can cause all sorts of trouble:
```
odds = [1, 3, 5, 7]
primes = odds
primes.append(2)
print('primes:', primes)
print('odds:', odds)
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7, 2]
```
```
odds.reverse()
print('odds after reversing:', odds)
odds = [1, 3, 5, 7]
primes = odds
primes.append(2)
print('primes:', primes)
print('odds:', odds)
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7, 2]
```
This is because Python stores a list in memory, and then can use multiple names to refer to the same list. If all we want to do is copy a (simple) list, we can use the list function, so we do not modify a list we did not mean to:
```
odds = [1, 3, 5, 7]
primes = list(odds)
primes.append(2)
print('primes:', primes)
print('odds:', odds)
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7]
```
```
odds = [1, 3, 5, 7]
primes = list(odds)
primes.append(2)
print('primes:', primes)
print('odds:', odds)
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7]
```
### Turn a String Into a List
Use a `for loop` to convert the string "hello" into a list of letters: `["h", "e", "l", "l", "o"]`
Hint: You can create an empty list like this:
my_list = []
```
my_list = []
for char in 'hello':
my_list.append(char)
print(my_list)
print(my_list)
```
Subsets of lists and strings can be accessed by specifying ranges of values in brackets, similar to how we accessed ranges of positions in a NumPy array. This is commonly referred to as *slicing* the list/string.
```
binomial_name = "Drosophila melanogaster"
group = binomial_name[0:10]
print("group:", group)
species = binomial_name[11:24]
print("species:", species)
chromosomes = ["X", "Y", "2", "3", "4"]
autosomes = chromosomes[2:5]
print("autosomes:", autosomes)
last = chromosomes[-1]
print("last:", last)
```
```
binomial_name = "Drosophila melanogaster"
group = binomial_name[0:10]
print("group:", group)
species = binomial_name[11:24]
print("species:", species)
chromosomes = ["X", "Y", "2", "3", "4"]
autosomes = chromosomes[2:5]
print("autosomes:", autosomes)
last = chromosomes[-1]
print("last:", last)
```
### Slicing From the End
Use slicing to access only the last four characters of a string or entries of a list.
```
string_for_slicing = "Observation date: 02-Feb-2013"
list_for_slicing = [["fluorine", "F"],
["chlorine", "Cl"],
["bromine", "Br"],
["iodine", "I"],
["astatine", "At"]]
```
Would your solution work regardless of whether you knew beforehand the length of the string or list (e.g. if you wanted to apply the solution to a set of lists of different lengths)? If not, try to change your approach to make it more robust.
Hint: Remember that indices can be negative as well as positive
```
string_for_slicing = "Observation date: 02-Feb-2013"
list_for_slicing = [["fluorine", "F"],
["chlorine", "Cl"],
["bromine", "Br"],
["iodine", "I"],
["astatine", "At"]]
print("last 4 items from string_for_slicing:", string_for_slicing[-4:])
print("last 4 items from list_for_slicing:", list_for_slicing[-4:])
```
### Non-Continuous Slices
So far we've seen how to use slicing to take single blocks of successive entries from a sequence. But what if we want to take a subset of entries that aren't next to each other in the sequence?
You can achieve this by providing a third argument to the range within the brackets, called the step size. The example below shows how you can take every third entry in a list:
```
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
subset = primes[0:12:3]
print("subset", subset)
```
```
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
subset = primes[0:12:3]
print("subset", subset)
```
Notice that the slice taken begins with the first entry in the range, followed by entries taken at equally-spaced intervals (the steps) thereafter. If you wanted to begin the subset with the third entry, you would need to specify that as the starting point of the sliced range:
```
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
subset = primes[2:12:3]
print("subset", subset)
```
```
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
subset = primes[2:12:3]
print("subset", subset)
```
Use the step size argument to create a new string that contains only every second character in the string "In an octopus's garden in the shade"
Start with:
```
beatles = "In an octopus's garden in the shade"
```
and print:
```
I notpssgre ntesae
```
```
beatles = "In an octopus's garden in the shade"
subset = beatles[0:35:2]
print("subset", subset)
```
If you want to take a slice from the beginning of a sequence, you can omit the first index in the range:
```
date = "Monday 4 January 2016"
day = date[0:6]
print("Using 0 to begin range:", day)
day = date[:6]
print("Omitting beginning index:", day)
```
```
date = "Monday 4 January 2016"
day = date[0:6]
print("Using 0 to begin range:", day)
day = date[:6]
print("Omitting beginning index:", day)
```
And similarly, you can omit the ending index in the range to take a slice to the end of the sequence:
```
months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
q4 = months[8:12]
print("With specified start and end position:", q4)
q4 = months[8:len(months)]
print("Using len() to get last entry:", q4)
q4 = months[8:]
print("Omitting ending index:", q4)
```
```
months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
q4 = months[8:12]
print("With specified start and end position:", q4)
q4 = months[8:len(months)]
print("Using len() to get last entry:", q4)
q4 = months[8:]
print("Omitting ending index:", q4)
```
### Overloading
`+` usually means addition, but when used on strings or lists, it means "concatenate". Given that, what do you think the multiplication operator * does on lists? In particular, what will be the output of the following code?
```
counts = [2, 4, 6, 8, 10]
repeats = counts * 2
print(repeats)
```
The technical term for this is operator overloading. A single operator, like `+` or `*`, can do different things depending on what it's applied to.
```
counts = [2, 4, 6, 8, 10]
repeats = counts * 2
print(repeats)
```
is this the same as:
```
counts + counts
```
and what might:
```
counts / 2
```
mean ?
```
counts = [2, 4, 6, 8, 10]
repeats = counts + counts
print(repeats)
```
## Key Points
- [value1, value2, value3, ...] creates a list.
- Lists can contain any Python object, including lists (i.e., list of lists).
- Lists are indexed and sliced with square brackets (e.g., list[0] and list[2:9]), in the same way as strings and arrays.
- Lists are mutable (i.e., their values can be changed in place).
- Strings are immutable (i.e., the characters in them cannot be changed).
### Save, and version control your changes
- save your work: `File -> Save`
- add all your changes to your local repository: `Terminal -> git add .`
- commit your updates a new Git version: `Terminal -> git commit -m "End of Episode 3"`
- push your latest commits to GitHub: `Terminal -> git push`
|
github_jupyter
|
odds = [1, 3, 5, 7]
print('odds are:', odds)
odds = [1, 3, 5, 7]
print('odds are:', odds)
print('first element:', odds[0])
print('last element:', odds[3])
print('"-1" element:', odds[-1])
print('first element:', odds[0])
print('last element:', odds[3])
print('"-1" element:', odds[-1])
for number in odds:
print(number)
names = ['Curie', 'Darwing', 'Turing'] # typo in Darwin's name
print('names is originally:', names)
names[1] = 'Darwin' # correct the name
print('final value of names:', names)
names = ['Curie', 'Darwing', 'Turing'] # typo in Darwin's name
print('names is originally:', names)
names[1] = 'Darwin' # correct the name
print('final value of names:', names)
name = 'Darwin'
name[0] = 'd'
name = 'Darwin'
name[0] = 'd'
salsa = ['peppers', 'onions', 'cilantro', 'tomatoes']
my_salsa = salsa # <-- my_salsa and salsa point to the *same* list data in memory
salsa[0] = 'hot peppers'
print('Ingredients in salsa:', salsa)
print('Ingredients in my salsa:', my_salsa)
salsa = ['peppers', 'onions', 'cilantro', 'tomatoes']
my_salsa = list(salsa) # <-- makes a *copy* of the list
salsa[0] = 'hot peppers'
print('Ingredients in salsa:', salsa)
print('Ingredients in my salsa:', my_salsa)
salsa = ['peppers', 'onions', 'cilantro', 'tomatoes']
my_salsa = salsa # <-- my_salsa and salsa point to the *same* list data in memory
salsa[0] = 'hot peppers'
print('Ingredients in salsa:', salsa)
print('Ingredients in my salsa:', my_salsa)
shop = [['pepper', 'zucchini', 'onion'],
['cabbage', 'lettuce', 'garlic'],
['apple', 'pear', 'banana']]
shop = [['pepper', 'zucchini', 'onion'],
['cabbage', 'lettuce', 'garlic'],
['apple', 'pear', 'banana']] #list within a list
print(shop[0])
print(shop[0])
print(shop[1][2])
print(shop[0])
print(shop[1:])
sample_ages = [10, 12.5, 'Unknown']
sample_ages = [10, 12.5, 'Unknown']
print(sample_ages)
odds.append(11)
print('odds after adding a value:', odds)
del odds[0]
print('odds after removing the first element:', odds)
odds.reverse()
print('odds after reversing:', odds)
odds.append(11)
print('odds after adding a value:', odds)
del odds[0]
print('odds after removing the first element:', odds)
odds.reverse()
print('odds after reversing:', odds)
odds = [1, 3, 5, 7]
primes = odds
primes.append(2)
print('primes:', primes)
print('odds:', odds)
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7, 2]
odds.reverse()
print('odds after reversing:', odds)
odds = [1, 3, 5, 7]
primes = odds
primes.append(2)
print('primes:', primes)
print('odds:', odds)
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7, 2]
odds = [1, 3, 5, 7]
primes = list(odds)
primes.append(2)
print('primes:', primes)
print('odds:', odds)
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7]
odds = [1, 3, 5, 7]
primes = list(odds)
primes.append(2)
print('primes:', primes)
print('odds:', odds)
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7]
my_list = []
for char in 'hello':
my_list.append(char)
print(my_list)
print(my_list)
binomial_name = "Drosophila melanogaster"
group = binomial_name[0:10]
print("group:", group)
species = binomial_name[11:24]
print("species:", species)
chromosomes = ["X", "Y", "2", "3", "4"]
autosomes = chromosomes[2:5]
print("autosomes:", autosomes)
last = chromosomes[-1]
print("last:", last)
binomial_name = "Drosophila melanogaster"
group = binomial_name[0:10]
print("group:", group)
species = binomial_name[11:24]
print("species:", species)
chromosomes = ["X", "Y", "2", "3", "4"]
autosomes = chromosomes[2:5]
print("autosomes:", autosomes)
last = chromosomes[-1]
print("last:", last)
string_for_slicing = "Observation date: 02-Feb-2013"
list_for_slicing = [["fluorine", "F"],
["chlorine", "Cl"],
["bromine", "Br"],
["iodine", "I"],
["astatine", "At"]]
string_for_slicing = "Observation date: 02-Feb-2013"
list_for_slicing = [["fluorine", "F"],
["chlorine", "Cl"],
["bromine", "Br"],
["iodine", "I"],
["astatine", "At"]]
print("last 4 items from string_for_slicing:", string_for_slicing[-4:])
print("last 4 items from list_for_slicing:", list_for_slicing[-4:])
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
subset = primes[0:12:3]
print("subset", subset)
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
subset = primes[0:12:3]
print("subset", subset)
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
subset = primes[2:12:3]
print("subset", subset)
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
subset = primes[2:12:3]
print("subset", subset)
beatles = "In an octopus's garden in the shade"
I notpssgre ntesae
beatles = "In an octopus's garden in the shade"
subset = beatles[0:35:2]
print("subset", subset)
date = "Monday 4 January 2016"
day = date[0:6]
print("Using 0 to begin range:", day)
day = date[:6]
print("Omitting beginning index:", day)
date = "Monday 4 January 2016"
day = date[0:6]
print("Using 0 to begin range:", day)
day = date[:6]
print("Omitting beginning index:", day)
months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
q4 = months[8:12]
print("With specified start and end position:", q4)
q4 = months[8:len(months)]
print("Using len() to get last entry:", q4)
q4 = months[8:]
print("Omitting ending index:", q4)
months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
q4 = months[8:12]
print("With specified start and end position:", q4)
q4 = months[8:len(months)]
print("Using len() to get last entry:", q4)
q4 = months[8:]
print("Omitting ending index:", q4)
counts = [2, 4, 6, 8, 10]
repeats = counts * 2
print(repeats)
counts = [2, 4, 6, 8, 10]
repeats = counts * 2
print(repeats)
counts + counts
counts / 2
counts = [2, 4, 6, 8, 10]
repeats = counts + counts
print(repeats)
| 0.314893 | 0.985158 |
```
import os
import numpy as np
import matplotlib.pyplot as plt
import floris.tools as wfct
import floris.tools.visualization as vis
from floris.tools.optimization.scipy.yaw import YawOptimization
print("Running FLORIS with no yaw...")
# Instantiate the FLORIS object
file_dir = os.path.dirname(os.path.abspath('..'))
fi = wfct.floris_interface.FlorisInterface(
os.path.join(file_dir, "examples/example_input.json")
)
# Set turbine locations to 3 turbines in a row
D = fi.floris.farm.turbines[0].rotor_diameter
layout_x = [0, 7 * D, 14 * D, 21 * D, 28 * D] * 5
layout_y = list(np.array([i * 3 * D for i in range(5)]).repeat(5, axis=0))
fi.reinitialize_flow_field(layout_array=(layout_x, layout_y),
wind_direction=270.0,
)
fi.calculate_wake()
# Initial power output
power_initial = fi.get_farm_power()
power_initial
axis_visible = True
# =============================================================================
print("Plotting the FLORIS flowfield...")
# =============================================================================
# Initialize the horizontal cut
hor_plane = fi.get_hor_plane(x_resolution=400,
y_resolution=300,
# x_bounds=[-150.0, 150.0],
# y_bounds=[-200.0, 200.0],
)
# Plot and show
fig, ax = plt.subplots(figsize=(15, 10), dpi=300)
D = fi.floris.farm.turbine_map.turbines[0].rotor_diameter # m
# hor_plane = wfct.cut_plane.rescale_axis(hor_plane, x1_factor=D, x2_factor=D)
wfct.visualization.visualize_cut_plane(hor_plane, ax=ax, cmap="hot")
vis.plot_turbines(
ax,
fi.layout_x,
fi.layout_y,
fi.get_yaw_angles(),
D,
)
if not axis_visible:
ax.set_title("Baseline Case for U = 8 m/s, Wind Direction = 270$^\\circ$")
ax.set_xticks([i * 7 * D for i in range(5)])
ax.set_xticklabels([str(i * 7) for i in range(5)])
ax.set_yticks([-1.0 * D, 0.0, 1.0 * D])
ax.set_yticklabels(["-1.0", "0", "1.0"])
else:
ax.set_xticks([])
ax.set_yticks([])
plt.axis('off')
# =============================================================================
print("Finding optimal yaw angles in FLORIS...")
# =============================================================================
# Set bounds for allowable wake steering
min_yaw = 0.0
max_yaw = 30.0
# options = None
options = {'maxiter': 20,
'disp': True,
'iprint': 2,
'ftol': 1e-5,
'eps': 0.01}
# Instantiate the Optimization object
yaw_opt = YawOptimization(fi,
minimum_yaw_angle=min_yaw,
maximum_yaw_angle=max_yaw,
opt_method="SLSQP",
opt_options=options,
)
# Perform optimization
yaw_angles = yaw_opt.optimize()
print("==========================================")
print("yaw angles = ")
for i in range(len(yaw_angles)):
print("Turbine ", i, "=", yaw_angles[i], " deg")
# Assign yaw angles to turbines and calculate wake
fi.calculate_wake(yaw_angles=yaw_angles)
power_opt = fi.get_farm_power()
print("==========================================")
print(
"Total Power Gain = %.1f%%" % (100.0 * (power_opt - power_initial) / power_initial)
)
print("==========================================")
axis_visible = True
# =============================================================================
print("Plotting the FLORIS flowfield with yaw...")
# =============================================================================
# Initialize the horizontal cut
hor_plane = fi.get_hor_plane(x_resolution=400,
y_resolution=300,
# x_bounds=[-150.0, 150.0],
# y_bounds=[-200.0, 200.0],
)
# Plot and show
fig, ax = plt.subplots(figsize=(15, 10), dpi=300)
D = fi.floris.farm.turbine_map.turbines[0].rotor_diameter # m
# hor_plane = wfct.cut_plane.rescale_axis(hor_plane, x1_factor=D, x2_factor=D)
wfct.visualization.visualize_cut_plane(hor_plane, ax=ax, cmap="hot")
vis.plot_turbines(
ax,
fi.layout_x,
fi.layout_y,
fi.get_yaw_angles(),
fi.floris.farm.turbine_map.turbines[0].rotor_diameter,
)
if not axis_visible:
ax.set_title("Optimal Yawed Wake for U = 8 m/s, Wind Direction = 270$^\\circ$")
ax.set_xticks([i * 7 * D for i in range(5)])
ax.set_xticklabels([str(i * 7) for i in range(5)])
ax.set_yticks([-1.0 * D, 0.0, 1.0 * D])
ax.set_yticklabels(["-1.0", "0", "1.0"])
else:
ax.set_xticks([])
ax.set_yticks([])
plt.axis('off')
# plt.savefig("opt_yawed.png", format='png', bbox_inches='tight', dpi=150)
# plt.show()
```
|
github_jupyter
|
import os
import numpy as np
import matplotlib.pyplot as plt
import floris.tools as wfct
import floris.tools.visualization as vis
from floris.tools.optimization.scipy.yaw import YawOptimization
print("Running FLORIS with no yaw...")
# Instantiate the FLORIS object
file_dir = os.path.dirname(os.path.abspath('..'))
fi = wfct.floris_interface.FlorisInterface(
os.path.join(file_dir, "examples/example_input.json")
)
# Set turbine locations to 3 turbines in a row
D = fi.floris.farm.turbines[0].rotor_diameter
layout_x = [0, 7 * D, 14 * D, 21 * D, 28 * D] * 5
layout_y = list(np.array([i * 3 * D for i in range(5)]).repeat(5, axis=0))
fi.reinitialize_flow_field(layout_array=(layout_x, layout_y),
wind_direction=270.0,
)
fi.calculate_wake()
# Initial power output
power_initial = fi.get_farm_power()
power_initial
axis_visible = True
# =============================================================================
print("Plotting the FLORIS flowfield...")
# =============================================================================
# Initialize the horizontal cut
hor_plane = fi.get_hor_plane(x_resolution=400,
y_resolution=300,
# x_bounds=[-150.0, 150.0],
# y_bounds=[-200.0, 200.0],
)
# Plot and show
fig, ax = plt.subplots(figsize=(15, 10), dpi=300)
D = fi.floris.farm.turbine_map.turbines[0].rotor_diameter # m
# hor_plane = wfct.cut_plane.rescale_axis(hor_plane, x1_factor=D, x2_factor=D)
wfct.visualization.visualize_cut_plane(hor_plane, ax=ax, cmap="hot")
vis.plot_turbines(
ax,
fi.layout_x,
fi.layout_y,
fi.get_yaw_angles(),
D,
)
if not axis_visible:
ax.set_title("Baseline Case for U = 8 m/s, Wind Direction = 270$^\\circ$")
ax.set_xticks([i * 7 * D for i in range(5)])
ax.set_xticklabels([str(i * 7) for i in range(5)])
ax.set_yticks([-1.0 * D, 0.0, 1.0 * D])
ax.set_yticklabels(["-1.0", "0", "1.0"])
else:
ax.set_xticks([])
ax.set_yticks([])
plt.axis('off')
# =============================================================================
print("Finding optimal yaw angles in FLORIS...")
# =============================================================================
# Set bounds for allowable wake steering
min_yaw = 0.0
max_yaw = 30.0
# options = None
options = {'maxiter': 20,
'disp': True,
'iprint': 2,
'ftol': 1e-5,
'eps': 0.01}
# Instantiate the Optimization object
yaw_opt = YawOptimization(fi,
minimum_yaw_angle=min_yaw,
maximum_yaw_angle=max_yaw,
opt_method="SLSQP",
opt_options=options,
)
# Perform optimization
yaw_angles = yaw_opt.optimize()
print("==========================================")
print("yaw angles = ")
for i in range(len(yaw_angles)):
print("Turbine ", i, "=", yaw_angles[i], " deg")
# Assign yaw angles to turbines and calculate wake
fi.calculate_wake(yaw_angles=yaw_angles)
power_opt = fi.get_farm_power()
print("==========================================")
print(
"Total Power Gain = %.1f%%" % (100.0 * (power_opt - power_initial) / power_initial)
)
print("==========================================")
axis_visible = True
# =============================================================================
print("Plotting the FLORIS flowfield with yaw...")
# =============================================================================
# Initialize the horizontal cut
hor_plane = fi.get_hor_plane(x_resolution=400,
y_resolution=300,
# x_bounds=[-150.0, 150.0],
# y_bounds=[-200.0, 200.0],
)
# Plot and show
fig, ax = plt.subplots(figsize=(15, 10), dpi=300)
D = fi.floris.farm.turbine_map.turbines[0].rotor_diameter # m
# hor_plane = wfct.cut_plane.rescale_axis(hor_plane, x1_factor=D, x2_factor=D)
wfct.visualization.visualize_cut_plane(hor_plane, ax=ax, cmap="hot")
vis.plot_turbines(
ax,
fi.layout_x,
fi.layout_y,
fi.get_yaw_angles(),
fi.floris.farm.turbine_map.turbines[0].rotor_diameter,
)
if not axis_visible:
ax.set_title("Optimal Yawed Wake for U = 8 m/s, Wind Direction = 270$^\\circ$")
ax.set_xticks([i * 7 * D for i in range(5)])
ax.set_xticklabels([str(i * 7) for i in range(5)])
ax.set_yticks([-1.0 * D, 0.0, 1.0 * D])
ax.set_yticklabels(["-1.0", "0", "1.0"])
else:
ax.set_xticks([])
ax.set_yticks([])
plt.axis('off')
# plt.savefig("opt_yawed.png", format='png', bbox_inches='tight', dpi=150)
# plt.show()
| 0.611498 | 0.560012 |
```
# Notebook imports and packages
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
import sys
sys.path.insert(0,"/content/drive/MyDrive/Stuff/Online Courses/Udemy/DS&ML Course/Section_04/Example_01-03_(01-04)/")
from gd_fun import gradient_descent # Implemented in Example 02
```
# Understanding Learning Rates
$$h(x)=x^5-2x^4+2$$
$$\mathfrak{d}h(x)=5x^4-8x^3$$
```
x_2 = np.linspace(-2, 2, 1001)
def g(x):
return x**4-4*x**2+5
def dg(x):
return 4*x**3-8*x
```
## Too high learning rate may never converge or even cause values to diverge.
```
local_min, x_list, deriv_list = gradient_descent(dg, .2, multiplier=.25, max_iter=500)
fig, axs = plt.subplots(1, 2, figsize=(12,4), dpi=200)
# Cost function chart:
axs[0].plot(x_2, g(x_2), color="blue", linewidth=3, alpha=.8)
axs[0].set_title("Cost function:")
axs[0].set_xlim([-2, 2])
# axs[0, 0].set_ylim(0,13)
axs[0].grid()
axs[0].set_ylabel("g(x)", fontsize=16)
axs[0].scatter(x_list, g(x_list), color='red', s=50, alpha=.3)
# Derivative chart:
axs[1].set_title("Derivative:")
axs[1].plot(x_2, dg(x_2), color='skyblue', linewidth=5, alpha=.8)
axs[1].set_xlabel("x", fontsize=16)
axs[1].set_ylabel("dg(x)", fontsize=16)
axs[1].set_xlim([-2, 2])
axs[1].grid()
axs[1].scatter(x_list, deriv_list, color='red', s=50, alpha=.3)
plt.show()
```
## Too low learning rate may take an eternity to converge.
```
from os import pread
n=100
iter_list = list(range(1,n+1))
_, low_gamma, _ = gradient_descent(dg, 2.2, multiplier=.0001, max_iter=n)
_, mid_gamma, _ = gradient_descent(dg, 2.2, multiplier=.0005, max_iter=n)
_, high_gamma, _ = gradient_descent(dg, 2.2, multiplier=.002, max_iter=n)
_, bad_gamma, _ = gradient_descent(dg, 1.9, multiplier=.25, precision=0.0000001, max_iter=n)
fig, axs = plt.subplots(1, 3, figsize=(17,5), dpi=200)
# Low
axs[0].set_title("Low learning-rate:")
axs[0].set_xlim([1, n])
axs[0].set_xlabel("Steps (iterations)", fontsize=10)
axs[0].set_ylabel("Cost", fontsize=16)
axs[0].plot(iter_list, g(low_gamma), color="lightgreen", linewidth=1)
axs[0].scatter(iter_list, g(low_gamma), color='lightgreen', s=10)
# Mid
axs[1].set_title("Mid learning-rate:")
axs[1].set_xlim([1, n])
axs[1].set_xlabel("Steps (iterations)", fontsize=10)
axs[1].plot(iter_list, g(mid_gamma), color="yellow", linewidth=1)
axs[1].scatter(iter_list, g(mid_gamma), color='yellow', s=10)
# High
axs[2].set_title("High learning-rate:")
axs[2].set_xlim([1, n])
axs[2].set_xlabel("Steps (iterations)", fontsize=10)
axs[2].plot(iter_list, g(high_gamma), color="lightblue", linewidth=1)
axs[2].scatter(iter_list, g(high_gamma), color='lightblue', s=10)
plt.show()
plt.figure(figsize=(14, 8), dpi=250)
plt.title("Effect of learning rate on cost per iteration")
plt.xlabel("Steps (iterations)")
plt.ylabel("Cost")
plt.plot(iter_list, g(low_gamma), color="lightgreen", linewidth=1, label="Low Gamma (0.0001)")
plt.scatter(iter_list, g(low_gamma), color='lightgreen', s=13)
plt.plot(iter_list, g(mid_gamma), color="yellow", linewidth=1, label="Mid Gamma (0.0005)")
plt.scatter(iter_list, g(mid_gamma), color='yellow', s=13)
plt.plot(iter_list, g(high_gamma), color="lightblue", linewidth=1, label="High Gamma (0.002)")
plt.scatter(iter_list, g(high_gamma), color='lightblue', s=13)
plt.plot(iter_list, g(bad_gamma), color="red", linewidth=1, alpha=.2, label="Too high Gamma (0.25)")
plt.scatter(iter_list, g(bad_gamma), color='red', s=8, alpha=.4)
plt.legend()
plt.show()
```
|
github_jupyter
|
# Notebook imports and packages
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
import sys
sys.path.insert(0,"/content/drive/MyDrive/Stuff/Online Courses/Udemy/DS&ML Course/Section_04/Example_01-03_(01-04)/")
from gd_fun import gradient_descent # Implemented in Example 02
x_2 = np.linspace(-2, 2, 1001)
def g(x):
return x**4-4*x**2+5
def dg(x):
return 4*x**3-8*x
local_min, x_list, deriv_list = gradient_descent(dg, .2, multiplier=.25, max_iter=500)
fig, axs = plt.subplots(1, 2, figsize=(12,4), dpi=200)
# Cost function chart:
axs[0].plot(x_2, g(x_2), color="blue", linewidth=3, alpha=.8)
axs[0].set_title("Cost function:")
axs[0].set_xlim([-2, 2])
# axs[0, 0].set_ylim(0,13)
axs[0].grid()
axs[0].set_ylabel("g(x)", fontsize=16)
axs[0].scatter(x_list, g(x_list), color='red', s=50, alpha=.3)
# Derivative chart:
axs[1].set_title("Derivative:")
axs[1].plot(x_2, dg(x_2), color='skyblue', linewidth=5, alpha=.8)
axs[1].set_xlabel("x", fontsize=16)
axs[1].set_ylabel("dg(x)", fontsize=16)
axs[1].set_xlim([-2, 2])
axs[1].grid()
axs[1].scatter(x_list, deriv_list, color='red', s=50, alpha=.3)
plt.show()
from os import pread
n=100
iter_list = list(range(1,n+1))
_, low_gamma, _ = gradient_descent(dg, 2.2, multiplier=.0001, max_iter=n)
_, mid_gamma, _ = gradient_descent(dg, 2.2, multiplier=.0005, max_iter=n)
_, high_gamma, _ = gradient_descent(dg, 2.2, multiplier=.002, max_iter=n)
_, bad_gamma, _ = gradient_descent(dg, 1.9, multiplier=.25, precision=0.0000001, max_iter=n)
fig, axs = plt.subplots(1, 3, figsize=(17,5), dpi=200)
# Low
axs[0].set_title("Low learning-rate:")
axs[0].set_xlim([1, n])
axs[0].set_xlabel("Steps (iterations)", fontsize=10)
axs[0].set_ylabel("Cost", fontsize=16)
axs[0].plot(iter_list, g(low_gamma), color="lightgreen", linewidth=1)
axs[0].scatter(iter_list, g(low_gamma), color='lightgreen', s=10)
# Mid
axs[1].set_title("Mid learning-rate:")
axs[1].set_xlim([1, n])
axs[1].set_xlabel("Steps (iterations)", fontsize=10)
axs[1].plot(iter_list, g(mid_gamma), color="yellow", linewidth=1)
axs[1].scatter(iter_list, g(mid_gamma), color='yellow', s=10)
# High
axs[2].set_title("High learning-rate:")
axs[2].set_xlim([1, n])
axs[2].set_xlabel("Steps (iterations)", fontsize=10)
axs[2].plot(iter_list, g(high_gamma), color="lightblue", linewidth=1)
axs[2].scatter(iter_list, g(high_gamma), color='lightblue', s=10)
plt.show()
plt.figure(figsize=(14, 8), dpi=250)
plt.title("Effect of learning rate on cost per iteration")
plt.xlabel("Steps (iterations)")
plt.ylabel("Cost")
plt.plot(iter_list, g(low_gamma), color="lightgreen", linewidth=1, label="Low Gamma (0.0001)")
plt.scatter(iter_list, g(low_gamma), color='lightgreen', s=13)
plt.plot(iter_list, g(mid_gamma), color="yellow", linewidth=1, label="Mid Gamma (0.0005)")
plt.scatter(iter_list, g(mid_gamma), color='yellow', s=13)
plt.plot(iter_list, g(high_gamma), color="lightblue", linewidth=1, label="High Gamma (0.002)")
plt.scatter(iter_list, g(high_gamma), color='lightblue', s=13)
plt.plot(iter_list, g(bad_gamma), color="red", linewidth=1, alpha=.2, label="Too high Gamma (0.25)")
plt.scatter(iter_list, g(bad_gamma), color='red', s=8, alpha=.4)
plt.legend()
plt.show()
| 0.512937 | 0.863737 |
```
from collections import deque
class Node:
def __init__(self):
self.children = {}
self.isEnd = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = Node()
node = node.children[c]
node.isEnd = True
class StreamChecker:
def __init__(self, words: List[str]):
self.letters = deque()
self.trie = Trie()
for w in words:
self.trie.insert(w[::-1])
self.max_len = max([len(x) for x in words])
def query(self, letter: str) -> bool:
self.letters.appendleft(letter)
if len(self.letters) > self.max_len:
self.letters.pop()
node = self.trie.root
for c in self.letters:
if c not in node.children:
return False
node = node.children[c]
if node.isEnd:
return True
return node.isEnd
from functools import lru_cache
class Node:
def __init__(self):
self.children = {}
self.isEnd = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = Node()
node = node.children[c]
node.isEnd = True
class StreamChecker:
def __init__(self, words):
self.trie = Trie()
for w in words:
self.trie.insert(w)
self.pre = set() # 存放在单词列表中,但不是单词结尾的字母
self.seen = {}
@lru_cache(None)
def check(self, s):
node = self.trie.root
for c in s:
if c not in node.children:
return False
node = node.children[c]
return node.isEnd
def query(self, letter: str) -> bool:
node = self.trie.root
if not self.pre:
if letter in node.children:
self.pre.add(letter)
else:
new = {letter}
for v in self.pre:
new.add(v + letter)
self.pre = new
for s in self.pre:
print(s, s[-1] == letter)
if s[-1] == letter:
if self.check(s):
return True
return False
from functools import lru_cache
from collections import deque
class Node:
def __init__(self):
self.children = {}
self.isEnd = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = Node()
node = node.children[c]
node.isEnd = True
class StreamChecker:
def __init__(self, words):
self.letters = deque()
self.trie = Trie()
self.maxLen = max(map(len, words)) # 单词的最大长度
for w in words:
self.trie.insert(w[::-1])
def query(self, letter: str) -> bool:
self.letters.appendleft(letter)
if len(self.letters) > self.maxLen: # 最长单词拼接的长度,肯定不会超过words中最长的一个单词
self.letters.pop()
node = self.trie.root
for c in self.letters:
if node.isEnd:
return True
if c not in node.children:
return False
node = node.children[c]
return node.isEnd
obj = StreamChecker(["ab","ba","aaab","abab","baa"])
for i in ["a"],["a"],["a"],["a"],["a"],["b"],["a"],["b"],["a"],["b"],["b"]:
print(obj.query(i[0]))
["StreamChecker","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query"]
[[["ab","ba","aaab","abab","baa"]],["a"],["a"],["a"],["a"],["a"],["b"],["a"],["b"],["a"],["b"],["b"],["b"],["a"],["b"],["a"],["b"],["b"],["b"],["b"],["a"],["b"],["a"],["b"],["a"],["a"],["a"],["b"],["a"],["a"],["a"]]
# if letter in node.children and letter not in self.pre:
# if node.isEnd:
# return True
# self.pre.add(letter)
```
|
github_jupyter
|
from collections import deque
class Node:
def __init__(self):
self.children = {}
self.isEnd = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = Node()
node = node.children[c]
node.isEnd = True
class StreamChecker:
def __init__(self, words: List[str]):
self.letters = deque()
self.trie = Trie()
for w in words:
self.trie.insert(w[::-1])
self.max_len = max([len(x) for x in words])
def query(self, letter: str) -> bool:
self.letters.appendleft(letter)
if len(self.letters) > self.max_len:
self.letters.pop()
node = self.trie.root
for c in self.letters:
if c not in node.children:
return False
node = node.children[c]
if node.isEnd:
return True
return node.isEnd
from functools import lru_cache
class Node:
def __init__(self):
self.children = {}
self.isEnd = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = Node()
node = node.children[c]
node.isEnd = True
class StreamChecker:
def __init__(self, words):
self.trie = Trie()
for w in words:
self.trie.insert(w)
self.pre = set() # 存放在单词列表中,但不是单词结尾的字母
self.seen = {}
@lru_cache(None)
def check(self, s):
node = self.trie.root
for c in s:
if c not in node.children:
return False
node = node.children[c]
return node.isEnd
def query(self, letter: str) -> bool:
node = self.trie.root
if not self.pre:
if letter in node.children:
self.pre.add(letter)
else:
new = {letter}
for v in self.pre:
new.add(v + letter)
self.pre = new
for s in self.pre:
print(s, s[-1] == letter)
if s[-1] == letter:
if self.check(s):
return True
return False
from functools import lru_cache
from collections import deque
class Node:
def __init__(self):
self.children = {}
self.isEnd = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = Node()
node = node.children[c]
node.isEnd = True
class StreamChecker:
def __init__(self, words):
self.letters = deque()
self.trie = Trie()
self.maxLen = max(map(len, words)) # 单词的最大长度
for w in words:
self.trie.insert(w[::-1])
def query(self, letter: str) -> bool:
self.letters.appendleft(letter)
if len(self.letters) > self.maxLen: # 最长单词拼接的长度,肯定不会超过words中最长的一个单词
self.letters.pop()
node = self.trie.root
for c in self.letters:
if node.isEnd:
return True
if c not in node.children:
return False
node = node.children[c]
return node.isEnd
obj = StreamChecker(["ab","ba","aaab","abab","baa"])
for i in ["a"],["a"],["a"],["a"],["a"],["b"],["a"],["b"],["a"],["b"],["b"]:
print(obj.query(i[0]))
["StreamChecker","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query","query"]
[[["ab","ba","aaab","abab","baa"]],["a"],["a"],["a"],["a"],["a"],["b"],["a"],["b"],["a"],["b"],["b"],["b"],["a"],["b"],["a"],["b"],["b"],["b"],["b"],["a"],["b"],["a"],["b"],["a"],["a"],["a"],["b"],["a"],["a"],["a"]]
# if letter in node.children and letter not in self.pre:
# if node.isEnd:
# return True
# self.pre.add(letter)
| 0.441553 | 0.232724 |
```
import pandas as pd
import numpy as np
import os
raw_data_path = os.path.join(os.path.pardir, 'data', 'raw')
train_file_path = os.path.join(raw_data_path, 'train.csv')
test_file_path = os.path.join(raw_data_path, 'test.csv')
train_df = pd.read_csv(train_file_path, index_col='PassengerId')
test_df = pd.read_csv(test_file_path, index_col='PassengerId')
type(test_df)
test_df.info()
test_df['Survived'] = 888
df = pd.concat((train_df, test_df))
df.info()
df.head()
df.head(10)
df.tail(15)
df.Name
df[['Name', 'Age']]
df.loc[5:20,'Name' : 'Age']
df.loc[5:10, ['Name', 'Age']]
df.iloc[5:10, 3:8]
male = df.loc[df.Sex == 'male',:]
print(len(male))
male_first_sur = df.loc[((df.Sex == 'male') & (df.Pclass ==1) & (df.Survived ==1)),:]
print(len(male_first_sur))
fmale_first = df.loc[((df.Sex == 'female') & (df.Pclass == 1)),:]
print(len(fmale_first))
fmale_first_sur = df.loc[((df.Sex == 'female') & (df.Pclass == 1) & (df.Survived == 1)),:]
print(len(fmale_first_sur))
```
<h4>Summary</h4>
```
df.describe()
df.Fare.plot(kind='box')
df.describe(include='all')
df.Sex.value_counts()
df.Sex.value_counts(normalize=True)
df[df.Survived != 888].Survived.value_counts()
df.Pclass.value_counts()
df.Pclass.value_counts().plot(kind='bar')
df.Pclass.value_counts(normalize=True)
df.Pclass.value_counts().plot(kind='bar', rot=0, title='class wise passengers', color='c');
```
<h4>Distributions</h4>
```
df.Age.plot(kind='hist', title='Histogram for Age', color='c', bins=20)
df.Age.plot(kind='kde', title='Desity for Age', color='c')
df.Fare.plot(kind='hist', title='Fare Histogram', color='c')
print('skeness of age: {0:.2f}'.format(df.Age.skew()))
print('skeness of fare: {0:.2f}'.format(df.Fare.skew()))
df.plot.scatter(x='Age', y='Fare', color='c', title='Scatter Plot Age vs Fare', alpha=0.1)
df.plot.scatter(x='Pclass', y='Fare', color='c', title='Scatter Plot Class vs Fare', alpha=0.15)
```
<h4>Grouping<h4>
```
df.groupby('Sex').Age.median()
df.groupby(['Pclass']).Fare.median()
df.groupby(['Pclass']).Age.median()
df.groupby(['Pclass'])['Fare', 'Age'].median()
df.groupby(['Pclass']).agg({'Fare': 'mean', 'Age': 'median'})
# more complicated aggregations
aggregations = {
'Fare': { # work on the "Fare" column
'mean_Fare': 'mean', # get the mean fare
'median_Fare': 'median', # get median fare
'max_Fare': max,
'min_Fare': np.min
},
'Age': { # work on the "Age" column
'median_Age': 'median', # Find the max, call the result "max_date"
'min_Age': min,
'max_Age': max,
'range_Age': lambda x: max(x) - min(x) # Calculate the age range per group
}
}
df.groupby(['Pclass', 'Embarked']).Fare.median()
```
## Crosstabs
```
pd.crosstab(df.Sex, df.Pclass)
pd.crosstab(df.Sex, df.Pclass).plot(kind='bar')
```
## Pivot
```
df.pivot_table(index='Sex', columns='Pclass', values='Age', aggfunc='mean')
df.groupby(['Sex', 'Pclass']).Age.mean()
df.groupby(['Sex', 'Pclass']).Age.mean().unstack()
```
## Missing Values
```
df.info()
df[df.Embarked.isnull()]
df.Embarked.value_counts()
pd.crosstab(df[df.Survived != 888].Survived, df[df.Survived != 888].Embarked)
df.loc[df.Embarked.isnull(), 'Embarked'] = 'S'
df.groupby(['Pclass', 'Embarked']).Fare.median()
df[df.Embarked.isnull()]
df.info()
df[df.Fare.isnull()]
print(df.loc[((df.Pclass == 3) & (df.Embarked == 'S') & (df.SibSp == 0) & (df.Parch == 0)), :])
median_fare = df.loc[(df.Pclass == 3) & (df.Embarked == 'S'), 'Fare'].median()
df.Fare.fillna(median_fare, inplace=True)
df.info()
```
## Age Feature
```
df[df.Age.isnull()]
df.Age.plot(kind='hist', bins=20, color='c')
df.Age.mean()
pclass_age_median = df.groupby('Pclass').Age.transform('median')
df.Age.fillna(pclass_age_median , inplace=True)
df.groupby('Sex').Age.median()
df[df.Age.notnull()].boxplot('Age', 'Sex')
df[df.Age.notnull()].boxplot('Age', 'Pclass')
df.Name
def GetTitle(name):
first_name_with_title = name.split(',')[1]
title = first_name_with_title.split('.')[0]
title = title.strip().lower()
return title
df.Name.map(lambda x: GetTitle(x))
df.Name.map(lambda x: GetTitle(x)).unique()
def GetTitle(name):
title_group = {
'mr': 'Mr',
'mrs': 'Mrs',
'miss': 'Miss',
'master': 'Master',
'don': 'Sir',
'rev': 'Sir',
'dr': 'Officer',
'mme': 'Mrs',
'ms': 'Mrs',
'major': 'Officer',
'lady': 'Lady',
'sir': 'Sir',
'mlle': 'Miss',
'col': 'Officer',
'capt': 'Officer',
'the countess': 'Lady',
'jonkheer': 'Sir',
'dona': 'Lady'
}
first_name_with_title = name.split(',')[1]
title = first_name_with_title.split('.')[0]
title = title.strip().lower()
return title_group[title]
df['Title'] = df.Name.map(lambda x: GetTitle(x))
df.head()
df[df.Age.notnull()].boxplot('Age', 'Title')
title_age_median = df.groupby('Title').Age.transform('median')
print(title_age_median)
df[df.Age.isnull()]
df.info()
```
## Outliers
```
df.Age.plot(kind='hist', bins=20, color='c')
df.loc[df.Age > 70]
df.Fare.plot(kind='hist', bins=20, color='c')
df.Fare.plot(kind='box')
df.loc[df.Fare == df.Fare.max()]
LogFare = np.log(df.Fare + 1.0)
LogFare.plot(kind='hist')
pd.qcut(df.Fare, 4)
pd.qcut(df.Fare, 4, labels=['very low', 'low', 'high', 'very high'])
pd.qcut(df.Fare, 4, labels=['very low', 'low', 'high', 'very high']).value_counts().plot(kind='bar', color='c')
df['Fare_Bin'] = pd.qcut(df.Fare, 4, labels=['very low', 'low', 'high', 'very high'])
```
## Feature Engineering
### Feature: Age Stage
```
df['AgeState'] = np.where(df['Age'] >= 18, 'Adult', 'Child')
df['AgeState'].value_counts()
pd.crosstab(df[df.Survived.notnull()].Survived, df[df.Survived.notnull()].AgeState)
```
### Feature: FamilySize
```
df['FamilySize'] = df.Parch + df.SibSp + 1
df['FamilySize'].plot(kind='hist', color='c')
df['FamilySize']
df.loc[df.FamilySize == df.FamilySize.max()]
pd.crosstab(df[df.Survived.notnull()].Survived, df[df.Survived.notnull()].FamilySize)
```
### Feature: IsMother
```
df['IsMonther'] = np.where(((df.Sex == 'female') & (df.Parch > 0) & (df.Age > 18) & (df.Title == 'Miss')), 1, 0)
df.describe()
pd.crosstab(df[df.Survived.notnull()].Survived, df[df.Survived.notnull()].IsMonther)
```
### Deck
```
df.Cabin
df.Cabin.unique()
df.loc[df.Cabin == 'T']
df.loc[df.Cabin == 'T', 'Cabin'] = np.NaN
df.Cabin.unique()
def GetDeck(cabin):
return np.where(pd.notnull(cabin), str(cabin)[0].upper(), 'Z')
df['Deck'] = df['Cabin'].map(lambda x: GetDeck(x))
df.Deck.value_counts()
pd.crosstab(df[df.Survived.notnull()].Survived, df[df.Survived.notnull()].Deck)
df.info()
```
### Categorical Feature Encoding
```
df['IsMale'] = np.where(df.Sex == 'Male', 1, 0)
df = pd.get_dummies(df, columns=['Deck', 'Pclass', 'Title', 'Embarked', 'AgeState'])
df.info
df.drop(['Cabin','Name','Ticket','Parch', 'SibSp', 'Sex'], axis=1, inplace=True)
columns = [column for column in df.columns if column != 'Survived']
columns = ['Survived'] + columns
df = df[columns]
df.info()
```
### Save to File
```
processed_data_path = os.path.join(os.path.pardir, 'data', 'processed')
write_train_path = os.path.join(processed_data_path, 'train.csv')
write_test_path = os.path.join(processed_data_path, 'test.csv')
df.loc[(df.Survived != 888)].to_csv(write_train_path)
columns = [column for column in df.columns if column != 'Survived']
df.loc[df.Survived == 888].to_csv(test_train_path)
```
### Building the data processing scripts
```
get_processed_data_script_file = os.path.join(os.path.pardir,'src','data','get_processed_data.py')
%%writefile $get_processed_data_script_file
import numpy as np
import pandas as pd
import os
def read_data():
# set the path of the raw data
raw_data_path = os.path.join(os.path.pardir,'data','raw')
train_file_path = os.path.join(raw_data_path, 'train.csv')
test_file_path = os.path.join(raw_data_path, 'test.csv')
# read the data with all default parameters
train_df = pd.read_csv(train_file_path, index_col='PassengerId')
test_df = pd.read_csv(test_file_path, index_col='PassengerId')
test_df['Survived'] = -888
df = pd.concat((train_df, test_df), axis=0)
return df
def process_data(df):
# using the method chaining concept
return (df
# create title attribute - then add this
.assign(Title = lambda x: x.Name.map(get_title))
# working missing values - start with this
.pipe(fill_missing_values)
# create fare bin feature
.assign(Fare_Bin = lambda x: pd.qcut(x.Fare, 4, labels=['very_low','low','high','very_high']))
# create age state
.assign(AgeState = lambda x : np.where(x.Age >= 18, 'Adult','Child'))
.assign(FamilySize = lambda x : x.Parch + x.SibSp + 1)
.assign(IsMother = lambda x : np.where(((x.Sex == 'female') & (x.Parch > 0) & (x.Age > 18) & (x.Title != 'Miss')), 1, 0))
# create deck feature
.assign(Cabin = lambda x: np.where(x.Cabin == 'T', np.nan, x.Cabin))
.assign(Deck = lambda x : x.Cabin.map(get_deck))
# feature encoding
.assign(IsMale = lambda x : np.where(x.Sex == 'male', 1,0))
.pipe(pd.get_dummies, columns=['Deck', 'Pclass','Title', 'Fare_Bin', 'Embarked','AgeState'])
# add code to drop unnecessary columns
.drop(['Cabin','Name','Ticket','Parch','SibSp','Sex'], axis=1)
# reorder columns
.pipe(reorder_columns)
)
def get_title(name):
title_group = {'mr' : 'Mr',
'mrs' : 'Mrs',
'miss' : 'Miss',
'master' : 'Master',
'don' : 'Sir',
'rev' : 'Sir',
'dr' : 'Officer',
'mme' : 'Mrs',
'ms' : 'Mrs',
'major' : 'Officer',
'lady' : 'Lady',
'sir' : 'Sir',
'mlle' : 'Miss',
'col' : 'Officer',
'capt' : 'Officer',
'the countess' : 'Lady',
'jonkheer' : 'Sir',
'dona' : 'Lady'
}
first_name_with_title = name.split(',')[1]
title = first_name_with_title.split('.')[0]
title = title.strip().lower()
return title_group[title]
def get_deck(cabin):
return np.where(pd.notnull(cabin),str(cabin)[0].upper(),'Z')
def fill_missing_values(df):
# embarked
df.Embarked.fillna('C', inplace=True)
# fare
median_fare = df[(df.Pclass == 3) & (df.Embarked == 'S')]['Fare'].median()
df.Fare.fillna(median_fare, inplace=True)
# age
title_age_median = df.groupby('Title').Age.transform('median')
df.Age.fillna(title_age_median , inplace=True)
return df
def reorder_columns(df):
columns = [column for column in df.columns if column != 'Survived']
columns = ['Survived'] + columns
df = df[columns]
return df
def write_data(df):
processed_data_path = os.path.join(os.path.pardir,'data','processed')
write_train_path = os.path.join(processed_data_path, 'train.csv')
write_test_path = os.path.join(processed_data_path, 'test.csv')
# train data
df[df.Survived != -888].to_csv(write_train_path)
# test data
columns = [column for column in df.columns if column != 'Survived']
df[df.Survived == -888][columns].to_csv(write_test_path)
if __name__ == '__main__':
df = read_data()
df = process_data(df)
write_data(df)
!python $get_processed_data_script_file
train_df = pd.read_csv(write_train_path)
train_df.info()
test_df = pd.read_csv(write_test_path)
test_df.info()
```
### Advanced visualization using MatPlotlib
```
import matplotlib.pyplot as plt
%matplotlib inline
plt.hist(df.Age)
plt.hist(df.Age, bins=20, color='c')
plt.show()
plt.hist(df.Age, bins=20, color='c')
plt.title('Histogram: age')
plt.xlabel('Bins')
plt.ylabel('Count')
plt.show()
f , ax = plt.subplots()
ax.hist(df.Age, bins=20, color='c')
ax.set_title('Histogram : Age')
ax.set_xlabel('Bins')
ax.set_ylabel('Counts')
plt.show()
# Add subplots
f , (ax1, ax2) = plt.subplots(1, 2 , figsize=(14,3))
ax1.hist(df.Fare, bins=20, color='c')
ax1.set_title('Histogram : Fare')
ax1.set_xlabel('Bins')
ax1.set_ylabel('Counts')
ax2.hist(df.Age, bins=20, color='tomato')
ax2.set_title('Histogram : Age')
ax2.set_xlabel('Bins')
ax2.set_ylabel('Counts')
plt.show()
# Adding subplots
f , ax_arr = plt.subplots(3 , 2 , figsize=(14,7))
# Plot 1
ax_arr[0,0].hist(df.Fare, bins=20, color='c')
ax_arr[0,0].set_title('Histogram : Fare')
ax_arr[0,0].set_xlabel('Bins')
ax_arr[0,0].set_ylabel('Counts')
# Plot 2
ax_arr[0,1].hist(df.Age, bins=20, color='c')
ax_arr[0,1].set_title('Histogram : Age')
ax_arr[0,1].set_xlabel('Bins')
ax_arr[0,1].set_ylabel('Counts')
# Plot 3
ax_arr[1,0].boxplot(df.Fare.values)
ax_arr[1,0].set_title('Boxplot : Age')
ax_arr[1,0].set_xlabel('Fare')
ax_arr[1,0].set_ylabel('Fare')
# Plot 4
ax_arr[1,1].boxplot(df.Age.values)
ax_arr[1,1].set_title('Boxplot : Age')
ax_arr[1,1].set_xlabel('Age')
ax_arr[1,1].set_ylabel('Age')
# Plot 5
ax_arr[2,0].scatter(df.Age, df.Fare, color='c', alpha=0.15)
ax_arr[2,0].set_title('Scatter Plot : Age vs Fare')
ax_arr[2,0].set_xlabel('Age')
ax_arr[2,0].set_ylabel('Fare')
ax_arr[2,1].axis('off')
plt.tight_layout()
plt.show()
```
|
github_jupyter
|
import pandas as pd
import numpy as np
import os
raw_data_path = os.path.join(os.path.pardir, 'data', 'raw')
train_file_path = os.path.join(raw_data_path, 'train.csv')
test_file_path = os.path.join(raw_data_path, 'test.csv')
train_df = pd.read_csv(train_file_path, index_col='PassengerId')
test_df = pd.read_csv(test_file_path, index_col='PassengerId')
type(test_df)
test_df.info()
test_df['Survived'] = 888
df = pd.concat((train_df, test_df))
df.info()
df.head()
df.head(10)
df.tail(15)
df.Name
df[['Name', 'Age']]
df.loc[5:20,'Name' : 'Age']
df.loc[5:10, ['Name', 'Age']]
df.iloc[5:10, 3:8]
male = df.loc[df.Sex == 'male',:]
print(len(male))
male_first_sur = df.loc[((df.Sex == 'male') & (df.Pclass ==1) & (df.Survived ==1)),:]
print(len(male_first_sur))
fmale_first = df.loc[((df.Sex == 'female') & (df.Pclass == 1)),:]
print(len(fmale_first))
fmale_first_sur = df.loc[((df.Sex == 'female') & (df.Pclass == 1) & (df.Survived == 1)),:]
print(len(fmale_first_sur))
df.describe()
df.Fare.plot(kind='box')
df.describe(include='all')
df.Sex.value_counts()
df.Sex.value_counts(normalize=True)
df[df.Survived != 888].Survived.value_counts()
df.Pclass.value_counts()
df.Pclass.value_counts().plot(kind='bar')
df.Pclass.value_counts(normalize=True)
df.Pclass.value_counts().plot(kind='bar', rot=0, title='class wise passengers', color='c');
df.Age.plot(kind='hist', title='Histogram for Age', color='c', bins=20)
df.Age.plot(kind='kde', title='Desity for Age', color='c')
df.Fare.plot(kind='hist', title='Fare Histogram', color='c')
print('skeness of age: {0:.2f}'.format(df.Age.skew()))
print('skeness of fare: {0:.2f}'.format(df.Fare.skew()))
df.plot.scatter(x='Age', y='Fare', color='c', title='Scatter Plot Age vs Fare', alpha=0.1)
df.plot.scatter(x='Pclass', y='Fare', color='c', title='Scatter Plot Class vs Fare', alpha=0.15)
df.groupby('Sex').Age.median()
df.groupby(['Pclass']).Fare.median()
df.groupby(['Pclass']).Age.median()
df.groupby(['Pclass'])['Fare', 'Age'].median()
df.groupby(['Pclass']).agg({'Fare': 'mean', 'Age': 'median'})
# more complicated aggregations
aggregations = {
'Fare': { # work on the "Fare" column
'mean_Fare': 'mean', # get the mean fare
'median_Fare': 'median', # get median fare
'max_Fare': max,
'min_Fare': np.min
},
'Age': { # work on the "Age" column
'median_Age': 'median', # Find the max, call the result "max_date"
'min_Age': min,
'max_Age': max,
'range_Age': lambda x: max(x) - min(x) # Calculate the age range per group
}
}
df.groupby(['Pclass', 'Embarked']).Fare.median()
pd.crosstab(df.Sex, df.Pclass)
pd.crosstab(df.Sex, df.Pclass).plot(kind='bar')
df.pivot_table(index='Sex', columns='Pclass', values='Age', aggfunc='mean')
df.groupby(['Sex', 'Pclass']).Age.mean()
df.groupby(['Sex', 'Pclass']).Age.mean().unstack()
df.info()
df[df.Embarked.isnull()]
df.Embarked.value_counts()
pd.crosstab(df[df.Survived != 888].Survived, df[df.Survived != 888].Embarked)
df.loc[df.Embarked.isnull(), 'Embarked'] = 'S'
df.groupby(['Pclass', 'Embarked']).Fare.median()
df[df.Embarked.isnull()]
df.info()
df[df.Fare.isnull()]
print(df.loc[((df.Pclass == 3) & (df.Embarked == 'S') & (df.SibSp == 0) & (df.Parch == 0)), :])
median_fare = df.loc[(df.Pclass == 3) & (df.Embarked == 'S'), 'Fare'].median()
df.Fare.fillna(median_fare, inplace=True)
df.info()
df[df.Age.isnull()]
df.Age.plot(kind='hist', bins=20, color='c')
df.Age.mean()
pclass_age_median = df.groupby('Pclass').Age.transform('median')
df.Age.fillna(pclass_age_median , inplace=True)
df.groupby('Sex').Age.median()
df[df.Age.notnull()].boxplot('Age', 'Sex')
df[df.Age.notnull()].boxplot('Age', 'Pclass')
df.Name
def GetTitle(name):
first_name_with_title = name.split(',')[1]
title = first_name_with_title.split('.')[0]
title = title.strip().lower()
return title
df.Name.map(lambda x: GetTitle(x))
df.Name.map(lambda x: GetTitle(x)).unique()
def GetTitle(name):
title_group = {
'mr': 'Mr',
'mrs': 'Mrs',
'miss': 'Miss',
'master': 'Master',
'don': 'Sir',
'rev': 'Sir',
'dr': 'Officer',
'mme': 'Mrs',
'ms': 'Mrs',
'major': 'Officer',
'lady': 'Lady',
'sir': 'Sir',
'mlle': 'Miss',
'col': 'Officer',
'capt': 'Officer',
'the countess': 'Lady',
'jonkheer': 'Sir',
'dona': 'Lady'
}
first_name_with_title = name.split(',')[1]
title = first_name_with_title.split('.')[0]
title = title.strip().lower()
return title_group[title]
df['Title'] = df.Name.map(lambda x: GetTitle(x))
df.head()
df[df.Age.notnull()].boxplot('Age', 'Title')
title_age_median = df.groupby('Title').Age.transform('median')
print(title_age_median)
df[df.Age.isnull()]
df.info()
df.Age.plot(kind='hist', bins=20, color='c')
df.loc[df.Age > 70]
df.Fare.plot(kind='hist', bins=20, color='c')
df.Fare.plot(kind='box')
df.loc[df.Fare == df.Fare.max()]
LogFare = np.log(df.Fare + 1.0)
LogFare.plot(kind='hist')
pd.qcut(df.Fare, 4)
pd.qcut(df.Fare, 4, labels=['very low', 'low', 'high', 'very high'])
pd.qcut(df.Fare, 4, labels=['very low', 'low', 'high', 'very high']).value_counts().plot(kind='bar', color='c')
df['Fare_Bin'] = pd.qcut(df.Fare, 4, labels=['very low', 'low', 'high', 'very high'])
df['AgeState'] = np.where(df['Age'] >= 18, 'Adult', 'Child')
df['AgeState'].value_counts()
pd.crosstab(df[df.Survived.notnull()].Survived, df[df.Survived.notnull()].AgeState)
df['FamilySize'] = df.Parch + df.SibSp + 1
df['FamilySize'].plot(kind='hist', color='c')
df['FamilySize']
df.loc[df.FamilySize == df.FamilySize.max()]
pd.crosstab(df[df.Survived.notnull()].Survived, df[df.Survived.notnull()].FamilySize)
df['IsMonther'] = np.where(((df.Sex == 'female') & (df.Parch > 0) & (df.Age > 18) & (df.Title == 'Miss')), 1, 0)
df.describe()
pd.crosstab(df[df.Survived.notnull()].Survived, df[df.Survived.notnull()].IsMonther)
df.Cabin
df.Cabin.unique()
df.loc[df.Cabin == 'T']
df.loc[df.Cabin == 'T', 'Cabin'] = np.NaN
df.Cabin.unique()
def GetDeck(cabin):
return np.where(pd.notnull(cabin), str(cabin)[0].upper(), 'Z')
df['Deck'] = df['Cabin'].map(lambda x: GetDeck(x))
df.Deck.value_counts()
pd.crosstab(df[df.Survived.notnull()].Survived, df[df.Survived.notnull()].Deck)
df.info()
df['IsMale'] = np.where(df.Sex == 'Male', 1, 0)
df = pd.get_dummies(df, columns=['Deck', 'Pclass', 'Title', 'Embarked', 'AgeState'])
df.info
df.drop(['Cabin','Name','Ticket','Parch', 'SibSp', 'Sex'], axis=1, inplace=True)
columns = [column for column in df.columns if column != 'Survived']
columns = ['Survived'] + columns
df = df[columns]
df.info()
processed_data_path = os.path.join(os.path.pardir, 'data', 'processed')
write_train_path = os.path.join(processed_data_path, 'train.csv')
write_test_path = os.path.join(processed_data_path, 'test.csv')
df.loc[(df.Survived != 888)].to_csv(write_train_path)
columns = [column for column in df.columns if column != 'Survived']
df.loc[df.Survived == 888].to_csv(test_train_path)
get_processed_data_script_file = os.path.join(os.path.pardir,'src','data','get_processed_data.py')
%%writefile $get_processed_data_script_file
import numpy as np
import pandas as pd
import os
def read_data():
# set the path of the raw data
raw_data_path = os.path.join(os.path.pardir,'data','raw')
train_file_path = os.path.join(raw_data_path, 'train.csv')
test_file_path = os.path.join(raw_data_path, 'test.csv')
# read the data with all default parameters
train_df = pd.read_csv(train_file_path, index_col='PassengerId')
test_df = pd.read_csv(test_file_path, index_col='PassengerId')
test_df['Survived'] = -888
df = pd.concat((train_df, test_df), axis=0)
return df
def process_data(df):
# using the method chaining concept
return (df
# create title attribute - then add this
.assign(Title = lambda x: x.Name.map(get_title))
# working missing values - start with this
.pipe(fill_missing_values)
# create fare bin feature
.assign(Fare_Bin = lambda x: pd.qcut(x.Fare, 4, labels=['very_low','low','high','very_high']))
# create age state
.assign(AgeState = lambda x : np.where(x.Age >= 18, 'Adult','Child'))
.assign(FamilySize = lambda x : x.Parch + x.SibSp + 1)
.assign(IsMother = lambda x : np.where(((x.Sex == 'female') & (x.Parch > 0) & (x.Age > 18) & (x.Title != 'Miss')), 1, 0))
# create deck feature
.assign(Cabin = lambda x: np.where(x.Cabin == 'T', np.nan, x.Cabin))
.assign(Deck = lambda x : x.Cabin.map(get_deck))
# feature encoding
.assign(IsMale = lambda x : np.where(x.Sex == 'male', 1,0))
.pipe(pd.get_dummies, columns=['Deck', 'Pclass','Title', 'Fare_Bin', 'Embarked','AgeState'])
# add code to drop unnecessary columns
.drop(['Cabin','Name','Ticket','Parch','SibSp','Sex'], axis=1)
# reorder columns
.pipe(reorder_columns)
)
def get_title(name):
title_group = {'mr' : 'Mr',
'mrs' : 'Mrs',
'miss' : 'Miss',
'master' : 'Master',
'don' : 'Sir',
'rev' : 'Sir',
'dr' : 'Officer',
'mme' : 'Mrs',
'ms' : 'Mrs',
'major' : 'Officer',
'lady' : 'Lady',
'sir' : 'Sir',
'mlle' : 'Miss',
'col' : 'Officer',
'capt' : 'Officer',
'the countess' : 'Lady',
'jonkheer' : 'Sir',
'dona' : 'Lady'
}
first_name_with_title = name.split(',')[1]
title = first_name_with_title.split('.')[0]
title = title.strip().lower()
return title_group[title]
def get_deck(cabin):
return np.where(pd.notnull(cabin),str(cabin)[0].upper(),'Z')
def fill_missing_values(df):
# embarked
df.Embarked.fillna('C', inplace=True)
# fare
median_fare = df[(df.Pclass == 3) & (df.Embarked == 'S')]['Fare'].median()
df.Fare.fillna(median_fare, inplace=True)
# age
title_age_median = df.groupby('Title').Age.transform('median')
df.Age.fillna(title_age_median , inplace=True)
return df
def reorder_columns(df):
columns = [column for column in df.columns if column != 'Survived']
columns = ['Survived'] + columns
df = df[columns]
return df
def write_data(df):
processed_data_path = os.path.join(os.path.pardir,'data','processed')
write_train_path = os.path.join(processed_data_path, 'train.csv')
write_test_path = os.path.join(processed_data_path, 'test.csv')
# train data
df[df.Survived != -888].to_csv(write_train_path)
# test data
columns = [column for column in df.columns if column != 'Survived']
df[df.Survived == -888][columns].to_csv(write_test_path)
if __name__ == '__main__':
df = read_data()
df = process_data(df)
write_data(df)
!python $get_processed_data_script_file
train_df = pd.read_csv(write_train_path)
train_df.info()
test_df = pd.read_csv(write_test_path)
test_df.info()
import matplotlib.pyplot as plt
%matplotlib inline
plt.hist(df.Age)
plt.hist(df.Age, bins=20, color='c')
plt.show()
plt.hist(df.Age, bins=20, color='c')
plt.title('Histogram: age')
plt.xlabel('Bins')
plt.ylabel('Count')
plt.show()
f , ax = plt.subplots()
ax.hist(df.Age, bins=20, color='c')
ax.set_title('Histogram : Age')
ax.set_xlabel('Bins')
ax.set_ylabel('Counts')
plt.show()
# Add subplots
f , (ax1, ax2) = plt.subplots(1, 2 , figsize=(14,3))
ax1.hist(df.Fare, bins=20, color='c')
ax1.set_title('Histogram : Fare')
ax1.set_xlabel('Bins')
ax1.set_ylabel('Counts')
ax2.hist(df.Age, bins=20, color='tomato')
ax2.set_title('Histogram : Age')
ax2.set_xlabel('Bins')
ax2.set_ylabel('Counts')
plt.show()
# Adding subplots
f , ax_arr = plt.subplots(3 , 2 , figsize=(14,7))
# Plot 1
ax_arr[0,0].hist(df.Fare, bins=20, color='c')
ax_arr[0,0].set_title('Histogram : Fare')
ax_arr[0,0].set_xlabel('Bins')
ax_arr[0,0].set_ylabel('Counts')
# Plot 2
ax_arr[0,1].hist(df.Age, bins=20, color='c')
ax_arr[0,1].set_title('Histogram : Age')
ax_arr[0,1].set_xlabel('Bins')
ax_arr[0,1].set_ylabel('Counts')
# Plot 3
ax_arr[1,0].boxplot(df.Fare.values)
ax_arr[1,0].set_title('Boxplot : Age')
ax_arr[1,0].set_xlabel('Fare')
ax_arr[1,0].set_ylabel('Fare')
# Plot 4
ax_arr[1,1].boxplot(df.Age.values)
ax_arr[1,1].set_title('Boxplot : Age')
ax_arr[1,1].set_xlabel('Age')
ax_arr[1,1].set_ylabel('Age')
# Plot 5
ax_arr[2,0].scatter(df.Age, df.Fare, color='c', alpha=0.15)
ax_arr[2,0].set_title('Scatter Plot : Age vs Fare')
ax_arr[2,0].set_xlabel('Age')
ax_arr[2,0].set_ylabel('Fare')
ax_arr[2,1].axis('off')
plt.tight_layout()
plt.show()
| 0.379723 | 0.725916 |
# Blackjack game
This notebook was an exercise of a Python course. The task was to program a Blackjack game. It's problably a standard practice for Object-Oriented Programming, but then the teacher is based in Las Vegas. I went a bit beyond the requirements and added more than one player, which made things considerably more messy.
First I import modules and define some list: Card ranks, suits and a dictionary with the values.
```
import random
from IPython.display import clear_output
suits = ['Hearts', 'Spades', 'Diamonds', 'Clubs']
ranks = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace']
values = {'Two':2,'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':10,'Queen':10,'King':10,'Ace':11} # dict
```
Now I define a Card class, pretty straightforward, with suit and rank:
```
class Card():
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
self.value = values[rank]
def __str__(self):
return f"{self.rank} of {self.suit}"
```
Next comes a Deck class, with functions to shuffle and draw one, which gets removed from the deck. I don't want print to print out all cards, just the number, but I defined a separate function to print all out explicitly (mainly for debugging).
```
class Deck():
def __init__(self):
self.all_cards = []
for suit in suits:
for rank in ranks:
self.all_cards.append(Card(suit,rank))
self.num_cards = len(self.all_cards)
def __str__(self):
return f"Deck contains {self.num_cards} cards"
def shuffle(self):
random.shuffle(self.all_cards)
def printall(self):
for card in self.all_cards:
print(card)
def deal_one(self):
return self.all_cards.pop()
```
Next comes the player class. This seems quite overloaded and can probably be done more elegantly. The player has a hand (list) of cards, a number of chips, current bet.
```
class Player():
def __init__(self,name,chips):
self.name = name
self.chips = chips
self.all_cards = []
self.total_value = 0
self.bet = 0
self.out = False
self.bust = False
self.ace_number = 0
#Every time a card is added to the player, the total value of the hand is updated, taking into account aces
def add_card(self,card):
if card.rank == "Ace":
self.ace_number += 1
self.all_cards.append(card)
self.total_value += card.value
while self.total_value > 21 and self.ace_number > 0:
self.ace_number -= 1
self.total_value -= 10
#Betting too much automatically bets all remaining chips. Why not?
def place_bet(self,amount):
if amount > self.chips:
print(f"You only have {self.chips} chips. Maximum amount placed.")
self.chips = 0
self.bet = self.chips
else:
self.chips -= amount
self.bet += amount
def add_chips(self,amount):
self.chips += amount
#This explicitly displays all cards the player currently has
def on_table(self):
print(f"{self.name} has: ")
for card in self.all_cards:
print(f"{card.rank} of {card.suit}")
print("")
#To reset the player: Remove all cards, reset boolean flags
def reset(self):
self.all_cards = []
self.total_value = 0
self.out = False
self.bust = False
self.ace_number = 0
def __str__(self):
return f"{self.name} has {self.chips} chips."
```
I made the dealer a subclass of the player? Smart or stupid?
```
class Dealer(Player):
def __init__(self,hit_until=17):
self.name = "Dealer"
self.chips = 0
self.hit_until = hit_until
self.all_cards = []
self.total_value = 0
#When the dealer's hand is displayed, one card is hidden
def on_table(self):
print(f"{self.name} has: ")
print("1 face-down card")
for card in self.all_cards[1::]:
print(f"{card.rank} of {card.suit}")
print("")
#But later, all cards are revealed
def reveal(self):
print(f"{self.name} has: ")
for card in self.all_cards:
print(f"{card.rank} of {card.suit}")
print("")
def play(self):
while True:
self.reveal()
if self.total_value <= self.hit_until:
print("Dealer hits.")
self.add_card(deck.deal_one())
elif self.total_value <= 21:
print("Dealer stands.")
break
if self.total_value > 21:
print("Dealer busts.")
dealer.bust = True
break
```
Now the players get generated, first ask how many (max. 4 is completely arbitrary), then generate them. By default, all players are named Ollie, after my cat.
```
def numplayers():
numstr = '0'
while numstr not in ('1','2','3','4'):
numstr = input("How many players want to play? (1 - 4)") or '1'
return int(numstr)
def init_players(n_players=1):
players = []
#The or statements below trigger when the user just presses enter, as empty strings count as False in Python
for n in range(n_players):
name = input (f"Enter your name, player {n+1}: ") or f'Ollie {n+1}'
chips = 'A'
while not chips.isdigit():
chips = input (f"How many chips do you have, {name}? ") or '100'
players.append(Player(name,int(chips)))
print("")
return players
```
Now I define some helpful functions that display information about chips, bets, etc.
```
#Show all chips of all players, called at the beginning of each game
def showchips():
global players
for p in players:
if type(p) != Dealer:
print(p)
print()
#Show all bets made by all players
def showbets():
global players
for p in players:
if type(p) != Dealer:
print(f"{p.name} has bet {p.bet} chips.")
print()
#Show all cards on all players
def showcards():
global players
clear_output()
for p in players:
p.on_table()
#This gets called when the game is over, to give an overview of the final situation
def showfinal():
global players
clear_output()
dealer.reveal()
if dealer.total_value > 21:
print(f"Value: {dealer.total_value} :BUSTED!\n\n")
else:
print(f"Value: {dealer.total_value}\n\n")
for p in players[1:]:
p.on_table()
if p.total_value > 21:
print(f"Value: {p.total_value} :BUSTED!\n\n")
else:
print(f"Value: {p.total_value}\n\n")
```
Below is called before the hitting/standing etc. starts, to see if someone has blackjack at the start (and then resolve the game immediately). Not sure if this is the actual rules...
```
def checkbj():
global players
bj = False
#If the dealer has blackjack, everyone loses, unless they also have blackjack
#If you lose, the bet gets removed. The chips do not get removed, because that happens during betting
if dealer.total_value == 21:
bj = True
print("Dealer has blackjack!")
for p in players[1:]:
if p.total_value == 21:
print(f"{p.name} draws.")
p.add_chips(p.bet)
else:
print(f"{p.name} loses {p.bet} chips.")
p.bet = 0
#If the dealer does not have blackjack, check all players
else:
for p in players[1:]:
if p.total_value == 21:
print(f"{p.name} has blackjack!")
print(f"{p.name} wins {3*p.bet//2} chips!")
#The original bet gets returned + 1.5 times the bet is won
p.add_chips(5*p.bet//2)
bj = True
#bj remains False, unless someone had blackjack
return bj
```
The long function below loop through the players asking what they want to do. I did not implement splitting (yet)
```
def player_actions():
global players
global n_out
for p in players[1:]:
#Ask each player what they want to do and then react
if p.out == False:
print(f"{p.name}, what would you like to do?")
action = 'A'
#Surrender and Doubling Down are only allowed in the first round
if round == 1:
while not action[0].upper() in ("H","S","D","U"):
#You can't double down without enough chips
if p.chips >= p.bet:
action = input("(H)it, (S)tand, (D)ouble down or S(U)rrender \n")
else:
action = input("(H)it, (S)tand or S(U)rrender \n")
else:
while not action[0].upper() in ("H","S"):
action = input("(H)it or (S)tand ")
#Hit
if action[0].upper() == 'H':
p.add_card(deck.deal_one())
showcards()
#Stand
elif action[0].upper() == 'S':
p.out = True
n_out += 1
#Double down ends the game for this player, no more cards
elif action[0].upper() == 'D':
p.add_card(deck.deal_one())
p.place_bet(p.bet)
p.out = True
n_out += 1
showcards()
#Surrender: Get half of your bet back, out of the loop
elif action[0].upper() == 'U':
p.add_chips(p.bet//2)
p.bet = p.bet//2
p.out = True
p.bust = True
n_out += 1
#Take all players out of the loop who have busted or reached exactly 21
if p.total_value > 21:
print(f"{p.name} busted!")
p.out = True
n_out += 1
p.bust = True
elif p.total_value == 21:
print(f"{p.name} has 21")
p.out = True
n_out += 1
```
The next function is the roundup to check who wins, in case there was no blackjack
```
def roundup():
global players
for p in players[1:]:
#If the dealer busts, everyone wins, unless they busted too
if dealer.bust:
if not p.bust:
print(f"{p.name} wins {p.bet} chips!")
p.add_chips(2*p.bet)
else:
print(f"{p.name} loses {p.bet} chips!")
else:
#If the dealer does not bust, check each player for win/loss/draw/bust and adjust chips
if not p.bust:
if p.total_value > dealer.total_value:
print(f"{p.name} wins {p.bet} chips!")
p.add_chips(2*p.bet)
elif p.total_value == dealer.total_value:
print(f"Draw between {p.name} and Dealer!")
p.add_chips(p.bet)
else:
print(f"{p.name} loses {p.bet} chips!")
else:
print(f"{p.name} loses {p.bet} chips!")
p.bet = 0
```
The ugly monstrosity below is the game itself. But it works.
```
#Initialize the program, get number, name and chips of players
game = 1
n_players = numplayers()
players = init_players(n_players)
dealer = Dealer(17)
#The dealer is player number 0
players.insert(0,dealer)
#This while true loop runs until all players are bankrupt or the user doesn't want to play anymore
while True:
#Initialize the current game: Get a new deck with all cards
clear_output()
print(f"Dealer must hit until {dealer.hit_until}, then stay.\n")
showchips()
deck = Deck()
deck.shuffle()
#Loop through all players (but not the dealer) to get them to bet
print(f"Game {game}\n")
for p in players[1:]:
bet = 'A'
while not bet.isdigit():
bet = input(f"Place your bet, {p.name}!\n")
p.place_bet(int(bet))
round = 1
showbets()
#Everyone gets two cards from the deck (including the dealer)
for p in players:
p.reset()
p.add_card(deck.deal_one())
p.add_card(deck.deal_one())
p.on_table()
bj = False
n_out = 0
#Now continously loop through all players until all are out (stand, have busted, have surrendered)
while n_out != len(players)-1:
#Check if there is an immediate blackjack. In that case, the game is already over
if round == 1:
bj = checkbj()
if bj:
break
#Each round show the current cards of each player
showcards()
#Now let the players do their stuff
player_actions()
round += 1
#This block comes when all players are finished and nobody had blackjack
if bj == False:
#Unnecessary if (should always be true here), but might help in case of bugs
if n_out == len(players)-1:
clear_output()
print("All players are done. Dealer draws now:")
#The dealer draws now until hitting 17 or bust
dealer.play()
print("Final table:")
showfinal()
#Now round up all values and distribute wins/losses
roundup()
#Below happens after each game
#Automatically remove players with 0 chips from the game
for p in players[1:]:
if p.chips <= 0:
print(f"{p.name} has no chips left and is leaving the game!")
players.remove(p)
#If there are no players left, end the program
if len(players) < 2:
print("No players left, game over")
break
else:
#If there are still players left, ask the user
l = "A"
while not l[0].upper() in ("Y","N"):
l = input("Another game (y/n)?")
if l.upper() == "Y":
game += 1
elif l.upper() == "N":
print("Thank you for playing!")
break
```
|
github_jupyter
|
import random
from IPython.display import clear_output
suits = ['Hearts', 'Spades', 'Diamonds', 'Clubs']
ranks = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace']
values = {'Two':2,'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':10,'Queen':10,'King':10,'Ace':11} # dict
class Card():
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
self.value = values[rank]
def __str__(self):
return f"{self.rank} of {self.suit}"
class Deck():
def __init__(self):
self.all_cards = []
for suit in suits:
for rank in ranks:
self.all_cards.append(Card(suit,rank))
self.num_cards = len(self.all_cards)
def __str__(self):
return f"Deck contains {self.num_cards} cards"
def shuffle(self):
random.shuffle(self.all_cards)
def printall(self):
for card in self.all_cards:
print(card)
def deal_one(self):
return self.all_cards.pop()
class Player():
def __init__(self,name,chips):
self.name = name
self.chips = chips
self.all_cards = []
self.total_value = 0
self.bet = 0
self.out = False
self.bust = False
self.ace_number = 0
#Every time a card is added to the player, the total value of the hand is updated, taking into account aces
def add_card(self,card):
if card.rank == "Ace":
self.ace_number += 1
self.all_cards.append(card)
self.total_value += card.value
while self.total_value > 21 and self.ace_number > 0:
self.ace_number -= 1
self.total_value -= 10
#Betting too much automatically bets all remaining chips. Why not?
def place_bet(self,amount):
if amount > self.chips:
print(f"You only have {self.chips} chips. Maximum amount placed.")
self.chips = 0
self.bet = self.chips
else:
self.chips -= amount
self.bet += amount
def add_chips(self,amount):
self.chips += amount
#This explicitly displays all cards the player currently has
def on_table(self):
print(f"{self.name} has: ")
for card in self.all_cards:
print(f"{card.rank} of {card.suit}")
print("")
#To reset the player: Remove all cards, reset boolean flags
def reset(self):
self.all_cards = []
self.total_value = 0
self.out = False
self.bust = False
self.ace_number = 0
def __str__(self):
return f"{self.name} has {self.chips} chips."
class Dealer(Player):
def __init__(self,hit_until=17):
self.name = "Dealer"
self.chips = 0
self.hit_until = hit_until
self.all_cards = []
self.total_value = 0
#When the dealer's hand is displayed, one card is hidden
def on_table(self):
print(f"{self.name} has: ")
print("1 face-down card")
for card in self.all_cards[1::]:
print(f"{card.rank} of {card.suit}")
print("")
#But later, all cards are revealed
def reveal(self):
print(f"{self.name} has: ")
for card in self.all_cards:
print(f"{card.rank} of {card.suit}")
print("")
def play(self):
while True:
self.reveal()
if self.total_value <= self.hit_until:
print("Dealer hits.")
self.add_card(deck.deal_one())
elif self.total_value <= 21:
print("Dealer stands.")
break
if self.total_value > 21:
print("Dealer busts.")
dealer.bust = True
break
def numplayers():
numstr = '0'
while numstr not in ('1','2','3','4'):
numstr = input("How many players want to play? (1 - 4)") or '1'
return int(numstr)
def init_players(n_players=1):
players = []
#The or statements below trigger when the user just presses enter, as empty strings count as False in Python
for n in range(n_players):
name = input (f"Enter your name, player {n+1}: ") or f'Ollie {n+1}'
chips = 'A'
while not chips.isdigit():
chips = input (f"How many chips do you have, {name}? ") or '100'
players.append(Player(name,int(chips)))
print("")
return players
#Show all chips of all players, called at the beginning of each game
def showchips():
global players
for p in players:
if type(p) != Dealer:
print(p)
print()
#Show all bets made by all players
def showbets():
global players
for p in players:
if type(p) != Dealer:
print(f"{p.name} has bet {p.bet} chips.")
print()
#Show all cards on all players
def showcards():
global players
clear_output()
for p in players:
p.on_table()
#This gets called when the game is over, to give an overview of the final situation
def showfinal():
global players
clear_output()
dealer.reveal()
if dealer.total_value > 21:
print(f"Value: {dealer.total_value} :BUSTED!\n\n")
else:
print(f"Value: {dealer.total_value}\n\n")
for p in players[1:]:
p.on_table()
if p.total_value > 21:
print(f"Value: {p.total_value} :BUSTED!\n\n")
else:
print(f"Value: {p.total_value}\n\n")
def checkbj():
global players
bj = False
#If the dealer has blackjack, everyone loses, unless they also have blackjack
#If you lose, the bet gets removed. The chips do not get removed, because that happens during betting
if dealer.total_value == 21:
bj = True
print("Dealer has blackjack!")
for p in players[1:]:
if p.total_value == 21:
print(f"{p.name} draws.")
p.add_chips(p.bet)
else:
print(f"{p.name} loses {p.bet} chips.")
p.bet = 0
#If the dealer does not have blackjack, check all players
else:
for p in players[1:]:
if p.total_value == 21:
print(f"{p.name} has blackjack!")
print(f"{p.name} wins {3*p.bet//2} chips!")
#The original bet gets returned + 1.5 times the bet is won
p.add_chips(5*p.bet//2)
bj = True
#bj remains False, unless someone had blackjack
return bj
def player_actions():
global players
global n_out
for p in players[1:]:
#Ask each player what they want to do and then react
if p.out == False:
print(f"{p.name}, what would you like to do?")
action = 'A'
#Surrender and Doubling Down are only allowed in the first round
if round == 1:
while not action[0].upper() in ("H","S","D","U"):
#You can't double down without enough chips
if p.chips >= p.bet:
action = input("(H)it, (S)tand, (D)ouble down or S(U)rrender \n")
else:
action = input("(H)it, (S)tand or S(U)rrender \n")
else:
while not action[0].upper() in ("H","S"):
action = input("(H)it or (S)tand ")
#Hit
if action[0].upper() == 'H':
p.add_card(deck.deal_one())
showcards()
#Stand
elif action[0].upper() == 'S':
p.out = True
n_out += 1
#Double down ends the game for this player, no more cards
elif action[0].upper() == 'D':
p.add_card(deck.deal_one())
p.place_bet(p.bet)
p.out = True
n_out += 1
showcards()
#Surrender: Get half of your bet back, out of the loop
elif action[0].upper() == 'U':
p.add_chips(p.bet//2)
p.bet = p.bet//2
p.out = True
p.bust = True
n_out += 1
#Take all players out of the loop who have busted or reached exactly 21
if p.total_value > 21:
print(f"{p.name} busted!")
p.out = True
n_out += 1
p.bust = True
elif p.total_value == 21:
print(f"{p.name} has 21")
p.out = True
n_out += 1
def roundup():
global players
for p in players[1:]:
#If the dealer busts, everyone wins, unless they busted too
if dealer.bust:
if not p.bust:
print(f"{p.name} wins {p.bet} chips!")
p.add_chips(2*p.bet)
else:
print(f"{p.name} loses {p.bet} chips!")
else:
#If the dealer does not bust, check each player for win/loss/draw/bust and adjust chips
if not p.bust:
if p.total_value > dealer.total_value:
print(f"{p.name} wins {p.bet} chips!")
p.add_chips(2*p.bet)
elif p.total_value == dealer.total_value:
print(f"Draw between {p.name} and Dealer!")
p.add_chips(p.bet)
else:
print(f"{p.name} loses {p.bet} chips!")
else:
print(f"{p.name} loses {p.bet} chips!")
p.bet = 0
#Initialize the program, get number, name and chips of players
game = 1
n_players = numplayers()
players = init_players(n_players)
dealer = Dealer(17)
#The dealer is player number 0
players.insert(0,dealer)
#This while true loop runs until all players are bankrupt or the user doesn't want to play anymore
while True:
#Initialize the current game: Get a new deck with all cards
clear_output()
print(f"Dealer must hit until {dealer.hit_until}, then stay.\n")
showchips()
deck = Deck()
deck.shuffle()
#Loop through all players (but not the dealer) to get them to bet
print(f"Game {game}\n")
for p in players[1:]:
bet = 'A'
while not bet.isdigit():
bet = input(f"Place your bet, {p.name}!\n")
p.place_bet(int(bet))
round = 1
showbets()
#Everyone gets two cards from the deck (including the dealer)
for p in players:
p.reset()
p.add_card(deck.deal_one())
p.add_card(deck.deal_one())
p.on_table()
bj = False
n_out = 0
#Now continously loop through all players until all are out (stand, have busted, have surrendered)
while n_out != len(players)-1:
#Check if there is an immediate blackjack. In that case, the game is already over
if round == 1:
bj = checkbj()
if bj:
break
#Each round show the current cards of each player
showcards()
#Now let the players do their stuff
player_actions()
round += 1
#This block comes when all players are finished and nobody had blackjack
if bj == False:
#Unnecessary if (should always be true here), but might help in case of bugs
if n_out == len(players)-1:
clear_output()
print("All players are done. Dealer draws now:")
#The dealer draws now until hitting 17 or bust
dealer.play()
print("Final table:")
showfinal()
#Now round up all values and distribute wins/losses
roundup()
#Below happens after each game
#Automatically remove players with 0 chips from the game
for p in players[1:]:
if p.chips <= 0:
print(f"{p.name} has no chips left and is leaving the game!")
players.remove(p)
#If there are no players left, end the program
if len(players) < 2:
print("No players left, game over")
break
else:
#If there are still players left, ask the user
l = "A"
while not l[0].upper() in ("Y","N"):
l = input("Another game (y/n)?")
if l.upper() == "Y":
game += 1
elif l.upper() == "N":
print("Thank you for playing!")
break
| 0.380759 | 0.835852 |
## Introduction
In this kernel, I'll demonstrate how to use Sohier's [BigQuery helper module](https://github.com/SohierDane/BigQuery_Helper/blob/master/bq_helper.py) to safely query the largest BigQuery dataset we've made available on Kaggle, [GitHub Repos](https://www.kaggle.com/github/github-repos). Weighing in at 3TB total, you can see how it would be easy for me to quickly exhaust my 5TB/30-day quota scanning lots of large tables.
The `bq_helper` module simplifies the common read-only tasks we can do using the BigQuery Python client library on Kaggle and makes it a cinch to manage resource usage. This helper class works only in Kernels because we handle authentication on our side. This means you don't need to worry about anything like managing credentials or entering in credit card information to have fun learning how to work with BigQuery datasets.
You'll learn how to do the following:
1. Create a `BigQueryHelper` object
2. Understand the tables in the dataset
3. Estimate the size of your queries before you make them
4. Query safely, convert to `pandas.dataframe`, and visualize results
By the end of this kernel, you'll not only learn a lot about querying BigQuery datasets safely, but we'll also find out the most popular licenses used by open source projects on GitHub. Let's go!
```
import pandas as pd
# https://github.com/SohierDane/BigQuery_Helper
from bq_helper import BigQueryHelper
```
### Creating a BigQueryHelper object
To start, we use `bq_helper` to create a `BigQueryHelper` object. This requires the project name and dataset name as its two arguments. You can find out the project name and dataset name by clicking on the "Data" tab of this kernel. Select any table and you'll see the first two parts of the address (in the blue BigQuery Table box) separated by `.` correspond to the project and dataset names respectively:
* `bigquery-public-data`
* `github_repos`
Let's create a `BigQueryHelper` object for the GitHub dataset:
```
bq_assistant = BigQueryHelper("bigquery-public-data", "github_repos")
```
If you're following along in your own kernel, click on the "Environment Variables" tab in the console at the bottom of the editor pane. You'll now see a `BigQueryHelper` object in your environment.
### Get to know your data with simple read-only functions
Now that we have our `BigQueryHelper` object for the GitHub dataset, there are a few super simple read-only functions we can use to learn more about the data including:
* Listing tables
* Getting table schema
* Inspecting table rows
Next, the simplest read-only task we can do is list all of the tables in the dataset. You can of course preview the tables by looking at the "Data" tab, too.
```
%%time
bq_assistant.list_tables()
```
Good. We confirm that we see the same 9 tables that are shown in our "Data" tab.
The GitHub BigQuery dataset doesn't have column-level descriptions for any of its tables (otherwise you could also look at them in the "Data" tab file previews), but if it did, looking at table schema using `bq_helper` would show them:
```
%%time
bq_assistant.table_schema("licenses")
```
Finally, while you can preview the first 100 rows in the table previews in the "Data" tab, there's also an efficient way to look at the first few rows using `bq_helper`.
Because `SELECT *` will scan all rows of the columns you specify (and potentially burn lots of quota), it's best practice to avoid using it especially just to explore your data. Here's how you can look at the first few rows using `head` which uses the efficient `list_rows` function [as Sohier notes](https://www.kaggle.com/sohier/introduction-to-the-bq-helper-package). Let's try it out on the `licenses` table:
```
%%time
bq_assistant.head("licenses", num_rows=10)
```
So far, these are the helper functions available in `bq_helper` that will let you get to safely know your data a bit before writing queries. Feel free to let us know if you'd like to see more functionality by opening an issue or submitting a PR to the [GitHub repo](https://github.com/SohierDane/BigQuery_Helper).
### Estimating query size
Now for the really cool part. We're eager to start analyzing the GitHub BigQuery dataset to uncover insights into open source software development, but we should be careful about how much data we scan in our queries. Let's make those free 5TB count!
Fortunately, the `bq_helper` module gives us tools to very easily estimate the size of our queries before we get ahead of ourselves. We simply write a `QUERY` using BigQuery's Standard SQL syntax then call the `estimate_query_size` function which will return the size of the query in GB. Let's give it a try.
[In this kernel](https://www.kaggle.com/mrisdal/github-commit-messages), I wrote a query which `SELECTS` 2000 rather short commit messages from the `commits` table. Let's use `estimate_query_size` to see how much data it scans.
```
QUERY = """
SELECT message
FROM `bigquery-public-data.github_repos.commits`
WHERE LENGTH(message) > 6 AND LENGTH(message) <= 20
LIMIT 2000
"""
%%time
bq_assistant.estimate_query_size(QUERY)
```
The above query would cost me nearly 18GB to run now. Now you can see why it's extremely helpful to know this without needing to actually expend the quota! Note that the query obviously doesn't return an object that's 17.6GB--it's only returning 2000 very short commit messages.
Let's experiment with estimating the size of a query that returns twice as many results:
```
QUERY = """
SELECT message
FROM `bigquery-public-data.github_repos.commits`
WHERE LENGTH(message) > 6 AND LENGTH(message) <= 20
LIMIT 4000 -- twice as many commit messages
"""
%%time
bq_assistant.estimate_query_size(QUERY)
```
Ah hah. See how it returns the same exact size estimate? This illustrates how using `LIMIT` to reduce the amount of data the query returns doesn't actually change how much data the query is scanning. The latter is what really counts against your quota.
Let's do one more experiment. What about the `WHERE` clause that I included? Let's remove that AND `LIMIT` and see if it increases the amount of data my query scans:
```
%%time
QUERY = """
SELECT message
FROM `bigquery-public-data.github_repos.commits`
"""
%%time
bq_assistant.estimate_query_size(QUERY)
```
Again, we're scanning the same 17.6GB which we now clearly know is the full size of the `message` field. The lesson here that I hope you'll take away is that the data you're scanning is NOT equivalent to the data you expect the query to return as its result. I encourage you to [check out BigQuery's best practices docs](https://cloud.google.com/bigquery/docs/best-practices) for more information.
Don't be discouraged by this. There is some good news! When you _do_ make a query request, your results will be cached for some time by default. So as long as you're in the same interactive notebook session, you can run the same cell/query multiple times without expending multiples of the quota cost. Whew! This is especially helpful because when you click "New Snapshot" to save your work, your kernel will be freshly executed from top to bottom.
### Executing queries safely
Now that we're comfortable with the huge amounts of data at our fingertips and know we can confidently estimate the size of our queries, let's actually fetch some data!
The `query_to_pandas_safe` function is another `bq_helper` function that makes the call to execute our query. It has two advantages over using the base BigQuery Python client library:
* By default it won't execute a query with a size estimate over 1GB
* It returns a convenient pandas dataframe
Let's try out `query_to_pandas_safe` on our first query. If it works correctly, the query will fail to execute as we know it scans 17.6GB of data.
```
QUERY = """
SELECT message
FROM `bigquery-public-data.github_repos.commits`
WHERE LENGTH(message) > 6 AND LENGTH(message) <= 20
LIMIT 2000
"""
%%time
df = bq_assistant.query_to_pandas_safe(QUERY)
```
Thanks to `query_to_pandas_safe` we didn't actually execute a query that was larger than 1GB. Relief! If we were comfortable making a larger query, we would simply add an argument `max_gb_scanned`. To successfully execute this query, I would add `max_gb_scanned=18`.
### Putting it all together in four steps
We've come a long way in learning how to safely handle large datasets in BigQuery. Let's see if we can put it all together to make a reasonably sized query, get a pandas dataframe back, and visualize the results. Boom.
Returning to my question at the beginning of this kernel, I want to know the licenses most frequently used by projects on GitHub. After writing my query, I will:
1. Estimate the size of my query to make sure it's not too huge
2. Execute my query using `query_to_pandas_safe` to get my results in a pandas dataframe
3. Explore the results
3. Visualize the results
```
QUERY = """
SELECT license, COUNT(*) AS count
FROM `bigquery-public-data.github_repos.licenses`
GROUP BY license
ORDER BY COUNT(*) DESC
"""
```
#### Step 1. Estimate the size of the query I've written above.
```
%%time
bq_assistant.estimate_query_size(QUERY)
```
Executing this query will only cost me 0.02 GB which I'm comfortable with given my 5TB 30-day quota.
#### Step 2. Use `query_to_pandas_safe` to get the results back as a pandas dataframe:
```
%%time
df = bq_assistant.query_to_pandas_safe(QUERY)
```
Ahh, perfect silence. Because my query scanned less than 1GB of data, it executed without canceling.
#### Step 3. Explore the results of the query
Now that our results are in a pandas dataframe, the data is super easy to manipulate. Let's check out the size of our dataframe and compare to the amount of data we know we scanned (0.02GB):
```
print('Size of dataframe: {} Bytes'.format(int(df.memory_usage(index=True, deep=True).sum())))
```
Much, much smaller! Again, this is to reiterate that the data you scan is much different from the results you get back from your query. This is again because BigQuery is scanning the entire contents of the `license` field in the `licenses` table.
Now we can take a look at the first few rows returned:
```
df.head()
```
It's clear that the MIT license is the most popular among open source projects in the GitHub BigQuery dataset. How many licenses did we return, anyway?
```
df.shape
```
We've got the counts for each of fifteen licenses used in the dataset.
#### Step 4. Visualize the results
The results of our query (and our efforts learning BigQuery) will all become real once we visualize them! I'm going to use `matplotlib` with `seaborn` to create a bar plot showing the count of GitHub projects by type of license.
```
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.style.use('ggplot')
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
f, g = plt.subplots(figsize=(12, 9))
g = sns.barplot(x="license", y="count", data=df, palette="Blues_d")
g.set_xticklabels(g.get_xticklabels(), rotation=30)
plt.title("Popularity of Licenses Used by Open Source Projects on GitHub")
plt.show(g)
```
Beautiful! We already knew that MIT was the most popular license by far, but here we see it in plain contrast to the next most common licenses, Apache 2.0 and GPL 2.0 and 3.0. For the record, this kernel is Apache 2.0-licensed. :)
## Conclusion
I hope you've enjoyed this kernel and learned at least something new. I know I felt confident about exploring this massive 3TB dataset knowing the functions available to me in `bq_helper` would prevent me from accidentally exceeding my quota. Here are some additional resources for working with BigQuery datasets in Kaggle Kernels:
* New to SQL? Learn this practical language by signing up for our [5-day SQL Scavenger Hunt](https://www.kaggle.com/sql-scavenger-hunt) which starts February 15th
* [A collection of all BigQuery resources on Kaggle](https://www.kaggle.com/product-feedback/48573)
* [Learn more about the BigQuery Python client library here](https://www.kaggle.com/sohier/beyond-queries-exploring-the-bigquery-api)
* Explore [all BigQuery datasets available on Kaggle](https://www.kaggle.com/datasets?filetype=bigQuery)--each has its own "starter kernel" for you to fork
|
github_jupyter
|
import pandas as pd
# https://github.com/SohierDane/BigQuery_Helper
from bq_helper import BigQueryHelper
bq_assistant = BigQueryHelper("bigquery-public-data", "github_repos")
%%time
bq_assistant.list_tables()
%%time
bq_assistant.table_schema("licenses")
%%time
bq_assistant.head("licenses", num_rows=10)
QUERY = """
SELECT message
FROM `bigquery-public-data.github_repos.commits`
WHERE LENGTH(message) > 6 AND LENGTH(message) <= 20
LIMIT 2000
"""
%%time
bq_assistant.estimate_query_size(QUERY)
QUERY = """
SELECT message
FROM `bigquery-public-data.github_repos.commits`
WHERE LENGTH(message) > 6 AND LENGTH(message) <= 20
LIMIT 4000 -- twice as many commit messages
"""
%%time
bq_assistant.estimate_query_size(QUERY)
%%time
QUERY = """
SELECT message
FROM `bigquery-public-data.github_repos.commits`
"""
%%time
bq_assistant.estimate_query_size(QUERY)
QUERY = """
SELECT message
FROM `bigquery-public-data.github_repos.commits`
WHERE LENGTH(message) > 6 AND LENGTH(message) <= 20
LIMIT 2000
"""
%%time
df = bq_assistant.query_to_pandas_safe(QUERY)
QUERY = """
SELECT license, COUNT(*) AS count
FROM `bigquery-public-data.github_repos.licenses`
GROUP BY license
ORDER BY COUNT(*) DESC
"""
%%time
bq_assistant.estimate_query_size(QUERY)
%%time
df = bq_assistant.query_to_pandas_safe(QUERY)
print('Size of dataframe: {} Bytes'.format(int(df.memory_usage(index=True, deep=True).sum())))
df.head()
df.shape
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.style.use('ggplot')
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
f, g = plt.subplots(figsize=(12, 9))
g = sns.barplot(x="license", y="count", data=df, palette="Blues_d")
g.set_xticklabels(g.get_xticklabels(), rotation=30)
plt.title("Popularity of Licenses Used by Open Source Projects on GitHub")
plt.show(g)
| 0.442877 | 0.982624 |
# README
Helpful hints to make life easier when using this project.
---
## Get the latest data from Johns Hopkins CSSE
- [Data repository](https://github.com/CSSEGISandData/COVID-19) - GitHub
### Check if data is available in this workspace
```
%sx if (test -d "./COVID-19"); then echo "COVID-19 data already installed - get to work"; else echo "Clone the data repository to the $HOME/work directory"; fi
```
### Clone the COVID-19 directory
```
%sx git clone https://github.com/CSSEGISandData/COVID-19.git
```
Great - now, [GET TO WORK](./COVIDvu.ipynb)
---
## rclone configuration
The `refreshdata` script uses [`rclone`](https://rclone.org/) for moving the JSON data files to the website S3 bucket. It requires a sample configuration file in the same directory. A sample configuration file, `rclone.conf.SAMPLE` is provided. Provide the appropriate AWS keys to gain access to the bucket.
---
## Git branches management
### Remove stale origin/branches
```
%sx git fetch --prune
```
### Remove all local branches except master and active
```
%sx git branch | awk '!/\*/ && !/master/ { system(sprintf("git branch -D %s", $1))}'
```
---
## Improve the command prompt and environment
Update the shell environment with a customizable `.bash_profile`
```
%sx if [[ -e "../.bash_profile" ]]; then echo ".bash_profile already installed in $HOME"; else cp -v "../resources/_bash_profile" "../.bash_profile"; fi
```
Any new terminals will use the .bash_profile configuration. This file isn't under version control, so users are free to customize it at will.
### nbstripout - strips all output from notebooks before a commit
This only needs to run once per repository. The configuration file alread exists in `./work/.pre-commit-config.yaml`, run this command to avoid having to clear all the Notebooks by hand.
```
!! [[ -n $(which pre-commit) ]] && pre-commit install
```
---
## Vim and NERDTree support
A complete command line development environment for Python shipped with this project. Vim is the default programming editor, available in any terminal. (NERDTree)[https://github.com/preservim/nerdtree] will simplify file system operations.
### Check NERDTree availability
```
%sx if (test -d "$HOME/.vim/pack/vendor/start/nerdtree"); then echo "NERDTree is installed and ready"; else echo "NERDTree is NOT installed"; fi
```
### Install NERDTree
```
%sx git clone https://github.com/preservim/nerdtree.git ~/.vim/pack/vendor/start/nerdtree
%sx vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q
```
---
## Virtual environment & package installation
To set up a virtual environment, ensure that python3 and virtualenv are installed and added to your path. Then [create and activate a virtual environment](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/),
On Linux or macOS:
```
python3 -m pip install --user virtualenv
```
On Windows:
```
py -m venv env
```
Then, on Linux or macOS:
```
source env/bin/activate
```
on Windows:
```
.\env\Scripts\activate
```
Once the virtual environment is activated, install the following packages:
```
pip install -r requirements.txt
```
Launch jupyter notebook by entering into your terminal
```
jupyter notebook
```
---
© pr3d4t0r - BSD-3 license - https://github.com/pr3d4t0r/COVIDvu
|
github_jupyter
|
%sx if (test -d "./COVID-19"); then echo "COVID-19 data already installed - get to work"; else echo "Clone the data repository to the $HOME/work directory"; fi
%sx git clone https://github.com/CSSEGISandData/COVID-19.git
%sx git fetch --prune
%sx git branch | awk '!/\*/ && !/master/ { system(sprintf("git branch -D %s", $1))}'
%sx if [[ -e "../.bash_profile" ]]; then echo ".bash_profile already installed in $HOME"; else cp -v "../resources/_bash_profile" "../.bash_profile"; fi
!! [[ -n $(which pre-commit) ]] && pre-commit install
%sx if (test -d "$HOME/.vim/pack/vendor/start/nerdtree"); then echo "NERDTree is installed and ready"; else echo "NERDTree is NOT installed"; fi
%sx git clone https://github.com/preservim/nerdtree.git ~/.vim/pack/vendor/start/nerdtree
%sx vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q
python3 -m pip install --user virtualenv
py -m venv env
source env/bin/activate
.\env\Scripts\activate
pip install -r requirements.txt
jupyter notebook
| 0.134037 | 0.810891 |
<a href="https://colab.research.google.com/github/NataliaDiaz/colab/blob/master/Neural_Networks_MI203_TD3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torch.autograd
import torch.autograd.variable
```
L'objectif de ce tp est de manipuler les objets "convolutions" et "pooling".
Nous ne traiteront pas d'images réelles (car les moyens informatiques à mettre en oeuvre sont complexes). Mais nous observerons l'effet de ces objets sur des tenseurs aléatoires.
EN CAS DE DOUTE CONSULTER LA DOCUMENTATION SUR https://pytorch.org/
N'hésitez pas à regarder sur internet les illustrations sur la convolution/pooling avec ou sans stride et padding (par example : https://github.com/vdumoulin/conv_arithmetic).
Ici, on conservera l'esprit convolution <=> stride 1 // pooling <=> stride 2.
TP Author: Adrien CHAN HON TONG [email protected]
# Les convolutions
```
image = torch.rand((1,3,32,32))
print(image.shape)
conv = nn.Conv2d(3,5,kernel_size = (5))
print(conv.weight.shape)
```
**Q1 : À quoi correspondent les arguments de Conv2d ?** (regardez la doc) https://pytorch.org/docs/stable/nn.html#conv2d
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')
```
imageApresConv = conv(image)
print(imageApresConv.shape)
```
Ici, la convolution n'avait pas de padding, la taille de l'image est modifié... Généralement, on préfère que les convolutions aient du padding pour conserver la taille de l'image
```
convpadding = nn.Conv2d(3,5,kernel_size = (5),padding=2)
print(convpadding.weight.shape)
imageApresConvPadding = convpadding(image)
print(imageApresConvPadding.shape)
```
**Q2 : Comment transformeriez vous une image en 1 seul vecteur à l'aide d'une seule convolution ?**
```
print("TODO")
print(image.shape)
old_channels = 3 # to have image.shape[1]*image.shape[2]*image.shape[3]
convFor1D = nn.Conv2d(image.shape[1], image.shape[1], kernel_size = (1), padding=0, stride=1 )
oneVecImg = convFor1D(image)
print(oneVecImg.shape)
```
**Q3 : Combien de poids a cette convolution (vis à vis de l'image) ? Qu'elle différence avec un neurone classique dans ce cas ?**
Si l'image faisait 64x64 pixel, quelle serait la taille qu'on obtiendrait ?
Pareil si l'image faisait 128x128 pixel ? (vous pouvez coder pour tester si vous n'êtes pas sur)
**Q4 :**
il n'y a aucun intérêt à avoir de si grosse convolution, généralement les convolutions sont petites - 3x3 avec padding - et combiné avec du pooling
**Écrire une convolution 3x3 avec padding qui va donner une valeur très forte au niveau des pixels qui ont des valeurs plus fortes au dessus qu'en dessous (l'entrée est une image 1D la sortie aussi). Tester votre code sur des matrices aléatoires**
```
print("TODO")
```
# Relu
```
image = torch.rand((1,1,6,6))-0.5
print(image)
imagerelu = F.relu(image)
print(imagerelu)
```
**Q5 : Que fait la fonction relu ? Combinez là avec votre convolution "dégradé de couleur vers le haut".**
```
print("TODO")
```
# Les pooling
```
image = torch.rand((1,3,32,32))
print(image.shape)
imagepool = F.max_pool2d(image, kernel_size=2, stride=2)
print(imagepool.shape)
```
**Q6 : Que fait le pooling ?
Quel serait le résultat sur une image 64x64 ou 128x128 ?** (vous pouvez coder pour tester si vous n'êtes pas sur)
**Q7 : Transformer une image 128x128 en une image 1x1 en utilisant uniquement des des convolutions 3x3 avec padding suivi de pooling 2x2 et 1 convolution 4x4 sans padding.**
**Combien de poids à ce réseau ? Calculer le ratio avec 1 convolution 128x128.**
```
print("TODO")
```
# estimation du champs recepteur d'un réseau
**Q8 :**
Le code suivant permet de mesurer la taille du champs recepteur des 13 première couche du réseau VGG 16 (un réseau très classique - regarder sur internet).
**Qu'est ce que vous pensez que ça signifie ?**
```
class EmptyVGG(nn.Module):
def __init__(self):
super(EmptyVGG, self).__init__()
self.conv = nn.Conv2d(1,1,kernel_size = 3,padding=1,bias=False)
self.conv.weight.data = torch.ones(1,1,3,3)
def forward(self,x):
x = self.conv(x)
x = self.conv(x)
x = F.max_pool2d(x, kernel_size=2, stride=2)
x = self.conv(x)
x = self.conv(x)
x = F.max_pool2d(x, kernel_size=2, stride=2)
x = self.conv(x)
x = self.conv(x)
x = self.conv(x)
x = F.max_pool2d(x, kernel_size=2, stride=2)
x = self.conv(x)
x = self.conv(x)
x = self.conv(x)
x = F.max_pool2d(x, kernel_size=2, stride=2)
x = self.conv(x)
x = self.conv(x)
x = self.conv(x)
x = F.upsample(x,scale_factor=16)
return x
def measureReceptivefield(model):
x = torch.torch.zeros(1,1,601,601)
x[0][0][0][0]=1
x = model(x)
i = 1
while x[0][0][i][i]>0:
i+=1
return i
VGG = EmptyVGG()
print(measureReceptivefield(VGG))
```
**Q bonus : adapter le code pour calculer le champs récepteur d'un réseau UNET (regarder sur internet).**
```
print("TODO")
```
|
github_jupyter
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torch.autograd
import torch.autograd.variable
image = torch.rand((1,3,32,32))
print(image.shape)
conv = nn.Conv2d(3,5,kernel_size = (5))
print(conv.weight.shape)
imageApresConv = conv(image)
print(imageApresConv.shape)
convpadding = nn.Conv2d(3,5,kernel_size = (5),padding=2)
print(convpadding.weight.shape)
imageApresConvPadding = convpadding(image)
print(imageApresConvPadding.shape)
print("TODO")
print(image.shape)
old_channels = 3 # to have image.shape[1]*image.shape[2]*image.shape[3]
convFor1D = nn.Conv2d(image.shape[1], image.shape[1], kernel_size = (1), padding=0, stride=1 )
oneVecImg = convFor1D(image)
print(oneVecImg.shape)
print("TODO")
image = torch.rand((1,1,6,6))-0.5
print(image)
imagerelu = F.relu(image)
print(imagerelu)
print("TODO")
image = torch.rand((1,3,32,32))
print(image.shape)
imagepool = F.max_pool2d(image, kernel_size=2, stride=2)
print(imagepool.shape)
print("TODO")
class EmptyVGG(nn.Module):
def __init__(self):
super(EmptyVGG, self).__init__()
self.conv = nn.Conv2d(1,1,kernel_size = 3,padding=1,bias=False)
self.conv.weight.data = torch.ones(1,1,3,3)
def forward(self,x):
x = self.conv(x)
x = self.conv(x)
x = F.max_pool2d(x, kernel_size=2, stride=2)
x = self.conv(x)
x = self.conv(x)
x = F.max_pool2d(x, kernel_size=2, stride=2)
x = self.conv(x)
x = self.conv(x)
x = self.conv(x)
x = F.max_pool2d(x, kernel_size=2, stride=2)
x = self.conv(x)
x = self.conv(x)
x = self.conv(x)
x = F.max_pool2d(x, kernel_size=2, stride=2)
x = self.conv(x)
x = self.conv(x)
x = self.conv(x)
x = F.upsample(x,scale_factor=16)
return x
def measureReceptivefield(model):
x = torch.torch.zeros(1,1,601,601)
x[0][0][0][0]=1
x = model(x)
i = 1
while x[0][0][i][i]>0:
i+=1
return i
VGG = EmptyVGG()
print(measureReceptivefield(VGG))
print("TODO")
| 0.654784 | 0.979036 |
### Acknowledgement
The code base is from the starter nb released by Johno W.
starter code link :
https://zindi.africa/competitions/cgiar-crop-yield-prediction-challenge/data/ --> Starter_Notebook_CGIAR_Yield_Estimation.ipynb
# Setup
```
import pandas as pd
import numpy as np
import os
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# config setup for fast experiment
from src.config import Config
# some utilities
from src.utils import show_samples, process_im
```
# Small EDA
```
# Train.csv has the Field_IDs needed to find the npy files
train = pd.read_csv(os.path.join(Config.data_dir, 'Train.csv'))
print(train.shape)
train.head()
arr = show_samples(data_dir = Config.train_data_dir, df=train)
# View false colour images from each month in the year:
fig, axs = plt.subplots(3, 4, figsize=(12, 8), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(12):
rgb = np.stack([arr[i*30 + 8], arr[i*30 + 4], arr[i*30 + 3]], axis=-1) # False colour (band 8, 4 and 3)
rgb = rgb / 4000 # Scaling consistently
axs[i].imshow(rgb.clip(0, 1))
axs[i].set_title(str(i+1))
```
What's with the white fluffy stuff? These are clouds - the bane of all remote sensing analysts...
```
# Show the SWIR band (B12) where clouds have a high reflectance
fig, axs = plt.subplots(3, 4, figsize=(12, 8), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(12):
cloud = arr[i*30 + 11]
axs[i].imshow(cloud, vmin=0, vmax=4000)
axs[i].set_title(str(i+1))
band_names = [l.strip() for l in open('../data/bandnames.txt', 'r').readlines()]
for line in band_names:
print(line + '\n')
```
# Sampling from the images
There are some hard-coded band indexes in the examples above that won't have made sense - how did we know which bands were which?
There are 30 bands for each month. You can see the full list of bands with:
0_S2_B1 is band one from the Sentinel 2 image for January (month 0). They're ordered, so we know that the first image band in the array is 0_S2_B1...
You'll likely want to examine specific bands. Here's an example where we create a function to sample the center point (20, 20) for specified bands from each month:
With this, we can sample the inputs for each field in train and use that to build a dataframe of input features:
```
# Make a new DF with the sampled values from each field
train_sampled = pd.DataFrame([process_im(fid) for fid in train['Field_ID'].values])
# Add in the field ID and yield
train_sampled['Field_ID'] = train['Field_ID'].values
train_sampled['Yield'] = train['Yield'].values
train_sampled.head()
# save train_sampled dataframe
train_sampled.to_csv(os.path.join(Config.data_dir, 'train_sampled.csv'), index=False)
# save train_sampled dataframe
ss = pd.read_csv(os.path.join(Config.data_dir, 'SampleSubmission.csv'))
test_sampled = pd.DataFrame([process_im(fid, folder=os.path.join(Config.data_dir, 'image_arrays_test')) for fid in ss['Field_ID'].values])
test_sampled.to_csv(os.path.join(Config.data_dir, 'test_sampled.csv'), index=False)
```
|
github_jupyter
|
import pandas as pd
import numpy as np
import os
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# config setup for fast experiment
from src.config import Config
# some utilities
from src.utils import show_samples, process_im
# Train.csv has the Field_IDs needed to find the npy files
train = pd.read_csv(os.path.join(Config.data_dir, 'Train.csv'))
print(train.shape)
train.head()
arr = show_samples(data_dir = Config.train_data_dir, df=train)
# View false colour images from each month in the year:
fig, axs = plt.subplots(3, 4, figsize=(12, 8), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(12):
rgb = np.stack([arr[i*30 + 8], arr[i*30 + 4], arr[i*30 + 3]], axis=-1) # False colour (band 8, 4 and 3)
rgb = rgb / 4000 # Scaling consistently
axs[i].imshow(rgb.clip(0, 1))
axs[i].set_title(str(i+1))
# Show the SWIR band (B12) where clouds have a high reflectance
fig, axs = plt.subplots(3, 4, figsize=(12, 8), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(12):
cloud = arr[i*30 + 11]
axs[i].imshow(cloud, vmin=0, vmax=4000)
axs[i].set_title(str(i+1))
band_names = [l.strip() for l in open('../data/bandnames.txt', 'r').readlines()]
for line in band_names:
print(line + '\n')
# Make a new DF with the sampled values from each field
train_sampled = pd.DataFrame([process_im(fid) for fid in train['Field_ID'].values])
# Add in the field ID and yield
train_sampled['Field_ID'] = train['Field_ID'].values
train_sampled['Yield'] = train['Yield'].values
train_sampled.head()
# save train_sampled dataframe
train_sampled.to_csv(os.path.join(Config.data_dir, 'train_sampled.csv'), index=False)
# save train_sampled dataframe
ss = pd.read_csv(os.path.join(Config.data_dir, 'SampleSubmission.csv'))
test_sampled = pd.DataFrame([process_im(fid, folder=os.path.join(Config.data_dir, 'image_arrays_test')) for fid in ss['Field_ID'].values])
test_sampled.to_csv(os.path.join(Config.data_dir, 'test_sampled.csv'), index=False)
| 0.489015 | 0.839076 |
```
from dolfin import *
from mshr import *
import numpy
from datetime import datetime
import csv
import os
import sys
import matplotlib.pyplot as plt
#-------------------------------------------------------
# USER DEFINED PARAMETERS:
# Set the following parameters according to your problem
# Choose one IO format
#fileio = 'xdmf'
fileio = 'pvd'
# Space dimensions
nsd = 2
# Number of immersed balls
nballs = 3
# Computational domain
Lx = 2.0
Ly = 2.0
# Balls initial positions
centers = [[0.5,1], [1,1.5], [1.5,1]]
radii = [0.25, 0.15, 0.25]
xc = [[] for ib in range(nballs)]
for ib in range(nballs):
[xc[ib].append(centers[ib][j]) for j in range(nsd)]
# Thermal conductivity
kA,kB = 1.2, 10000.2
condA, condB = Constant(kA), Constant(kB)
# Volumetric source
f = Constant(0)
# Boundary temperatures
Tleft = Constant(100)
Tright = Constant(0)
# Variational problem: Preliminaries
# Finite elements
order = 2
Pk = FiniteElement("Lagrange", 'triangle', order)
# Dirichlet boundary conditions
# Subdomains
class left(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[0]-0.0) < DOLFIN_EPS
class right(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[0]-Lx) < DOLFIN_EPS
class top(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[1]-0.0) < DOLFIN_EPS
class bottom(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[1]-Ly) < DOLFIN_EPS
class ball(SubDomain):
def __init__(self,xc,yc,R):
self.xc = xc
self.yc = yc
self.R = R
SubDomain.__init__(self) # Call base class constructor!
def inside (self, x, on_boundary ):
r = sqrt ( ( x[0] - self.xc ) ** 2 + ( x[1] - self.yc ) ** 2 )
return ( on_boundary and ( r < self.R * 1.1 ) )
left = left()
right = right()
top = top()
bottom = bottom()
# IO
dir_ = './results'
if not os.path.exists(dir_):
os.mkdir(dir_)
if fileio == 'xdmf':
filex = XDMFFile(dir_+'/sol.xdmf')
filex.parameters['functions_share_mesh'] = True
filex.parameters['rewrite_function_mesh'] = True
filex.parameters["flush_output"] = True
elif fileio == 'pvd':
ufile_pvd = File(dir_+"/temperature.pvd")
domfile_pvd = File(dir_+"/auxfunc.pvd")
# Begin loop over time steps
startTime = datetime.now()
print('\n ::> Begin computations')
#----------------------------------------------
# Mesh generation
if(nsd == 2):
domain = Rectangle(Point(0.0,0.0), Point(Lx,Ly))
for ib in range(nballs):
inc = Circle(Point(xc[ib][0],xc[ib][1]),radii[ib])
domain.set_subdomain(ib+1, inc)
else:
sys.exit("nsd.eq.3 not implemented")
mesh = generate_mesh ( domain, 40 )
print(" |-Mesh done")
print(" |--Number of vertices = "+str(mesh.num_vertices()))
print(" |--Number of cells = "+str(mesh.num_cells()))
print(" |--Cell size hmax,hmin = %.3g %.3g" % (mesh.hmax(), mesh.hmin()))
# Finite element space
W = FunctionSpace(mesh, Pk)
# Dirichlet restrictions on W
bcs = []
# Fixed temperature: left and right
bcleft = DirichletBC(W, Tleft, left)
bcs.append(bcleft)
bcright = DirichletBC(W, Tright, right)
bcs.append(bcright)
#-----------------------------------------
# Variational formulation: Poisson problem
u = TrialFunction(W)
v = TestFunction(W)
# Add the different inclusions to the domain of integration
funcdom = MeshFunction("size_t", mesh, mesh.topology().dim(), mesh.domains())
dx = Measure("dx")(subdomain_data=funcdom)
dxf = dx(1)
for ib in range(nballs-1):
dxf = dxf + dx(ib+2)
# Bilinear and linear forms
a = inner(condA*grad(u), grad(v))*dx(0) + inner(condB*grad(u), grad(v))*dxf
L = f*v*dx
#---------
# Solution
w = Function(W)
solve(a == L, w, bcs)
# IO
w.rename("T","T")
if fileio == 'xdmf':
filex.write(w, 0)
filex.write(funcdom, 0)
elif fileio == 'pvd':
ufile_pvd << w
domfile_pvd << funcdom
elapsed_time = datetime.now() - startTime
print('\n ::> Elapsed time: ', str(elapsed_time), '\n')
if fileio == 'xdmf':
filex.close()
```
# Make sure to understand the code
```
from dolfin import *
from mshr import *
import numpy
from datetime import datetime
import csv
import os
import sys
import matplotlib.pyplot as plt
#-------------------------------------------------------
# USER DEFINED PARAMETERS:
# Set the following parameters according to your problem
# Choose one IO format
#fileio = 'xdmf'
fileio = 'pvd'
# Space dimensions
nsd = 2
# Number of immersed balls
nballs = 3
# Computational domain
Lx = 2.0
Ly = 2.0
# Balls initial positions
centers = [[0.5,1], [1,1.5], [1.5,1]]
radii = [0.25, 0.15, 0.25]
xc = [[] for ib in range(nballs)]
for ib in range(nballs):
[xc[ib].append(centers[ib][j]) for j in range(nsd)]
# Thermal conductivity
kA, kB = 1.0, 1.0
condA, condB = Constant(kA), Constant(kB)
# Volumetric source
f = Constant(0)
# Boundary temperatures
Tleft = Constant(100)
Tright = Constant(0)
# Variational problem: Preliminaries
# Finite elements
order = 1
Pk = FiniteElement("Lagrange", 'triangle', order)
# Dirichlet boundary conditions
# Subdomains
class left(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[0]-0.0) < DOLFIN_EPS
class right(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[0]-Lx) < DOLFIN_EPS
class top(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[1]-0.0) < DOLFIN_EPS
class bottom(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[1]-Ly) < DOLFIN_EPS
class ball(SubDomain):
def __init__(self,xc,yc,R):
self.xc = xc
self.yc = yc
self.R = R
SubDomain.__init__(self) # Call base class constructor!
def inside (self, x, on_boundary ):
r = sqrt ( ( x[0] - self.xc ) ** 2 + ( x[1] - self.yc ) ** 2 )
return ( on_boundary and ( r < self.R * 1.1 ) )
left = left()
right = right()
top = top()
bottom = bottom()
# IO
dir_ = './results'
if not os.path.exists(dir_):
os.mkdir(dir_)
if fileio == 'xdmf':
filex = XDMFFile(dir_+'/sol.xdmf')
filex.parameters['functions_share_mesh'] = True
filex.parameters['rewrite_function_mesh'] = True
filex.parameters["flush_output"] = True
elif fileio == 'pvd':
ufile_pvd = File(dir_+"/temperature.pvd")
domfile_pvd = File(dir_+"/auxfunc.pvd")
# Begin loop over time steps
startTime = datetime.now()
print('\n ::> Begin computations')
#----------------------------------------------
# Mesh generation
if(nsd == 2):
domain = Rectangle(Point(0.0,0.0), Point(Lx,Ly))
for ib in range(nballs):
inc = Circle(Point(xc[ib][0],xc[ib][1]),radii[ib])
domain.set_subdomain(ib+1, inc)
else:
sys.exit("nsd.eq.3 not implemented")
mesh = generate_mesh ( domain, 40 )
print(" |-Mesh done")
print(" |--Number of vertices = "+str(mesh.num_vertices()))
print(" |--Number of cells = "+str(mesh.num_cells()))
print(" |--Cell size hmax,hmin = %.3g %.3g" % (mesh.hmax(), mesh.hmin()))
# Finite element space
W = FunctionSpace(mesh, Pk)
# Dirichlet restrictions on W
bcs = []
# Fixed temperature: left and right
bcleft = DirichletBC(W, Tleft, left)
bcs.append(bcleft)
bcright = DirichletBC(W, Tright, right)
bcs.append(bcright)
#-----------------------------------------
# Variational formulation: Poisson problem
u = TrialFunction(W)
v = TestFunction(W)
# Add the different inclusions to the domain of integration
funcdom = MeshFunction("size_t", mesh, mesh.topology().dim(), mesh.domains())
dx = Measure("dx")(subdomain_data=funcdom)
dxf = dx(1)
for ib in range(nballs-1):
dxf = dxf + dx(ib+2)
# Bilinear and linear forms
a = inner(condA*grad(u), grad(v))*dx(0) + inner(condB*grad(u), grad(v))*dxf
L = f*v*dx
#---------
# Solution
w = Function(W)
solve(a == L, w, bcs)
# IO
w.rename("T","T")
if fileio == 'xdmf':
filex.write(w, 0)
filex.write(funcdom, 0)
elif fileio == 'pvd':
ufile_pvd << w
domfile_pvd << funcdom
elapsed_time = datetime.now() - startTime
print('\n ::> Elapsed time: ', str(elapsed_time), '\n')
if fileio == 'xdmf':
filex.close()
```
# and 3 Compute the error in the L2(Ω) and H1 (Ω)-norms
------------------------------------
```
ue = Expression('Tleft -( Tleft - Tright )*x [0]/ Lx', degree=1, Tleft=100,
Tright=0, Lx=2)
gradue = Expression(('-(Tleft - Tright )/Lx','0'), degree=0, Tleft=100,
Tright=0, Lx =2)
w = Function (W)
solve (a == L, w, bcs)
errorL2 = assemble ((w - ue )**2*dx)
errorH1 = errorL2 + assemble ((grad (w) - gradue)**2* dx)
print (" | - Errors =", sqrt ( errorL2 ) , sqrt ( errorH1 ) )
```
# Run the script setting different values for κB (variable kB in the code)
```
dx = Measure("dx")( subdomain_data = funcdom )
dxf = dx(1)
for ib in range (nballs -1) :
dxf = dxf + dx (ib +2)
L2_errors = []
H1_errors = []
for kB in np.arange(0.1, 5, 0.45):# np.linspace(1, 10, 10): #[1, 2 , 3, 5, 7, 8, 10, 24]:
condB = Constant (kB)
# Bilinear and linear forms
a = inner (condA * grad (u) , grad(v )) * dx (0)
a = a + inner (condB * grad (u) , grad(v )) * dxf
L = f * v * dx
# Solution
w = Function (W)
solve (a == L, w, bcs)
errorL2 = assemble ((w - ue )**2*dx)
errorH1 =errorL2 + assemble ((grad (w) - gradue)**2* dx)
L2_errors.append(sqrt(errorL2))
H1_errors.append(sqrt(errorH1))
print (" | - Errors =", sqrt(errorL2), sqrt(errorH1))
boundaries = MeshFunction("size_t", mesh, mesh.topology().dim ()-1)
boundaries.set_all(0)
left.mark(boundaries, 1)
right.mark(boundaries, 3)
ds = Measure("ds")(subdomain_data=boundaries)
n = FacetNormal(mesh)
Qin = assemble(kA * inner(grad(w), n) * ds(1))
Qout = assemble(kA * inner(grad(w), n) * ds(3))
print (" | -- Q_in =", Qin, ", Q_out = ", Qout)
ufile_pvd = File(dir_ +"/temperature_"+ str(kB)+ ".pvd")
ufile_pvd << w
import pandas as pd
df = pd.DataFrame(np.array([L2_errors, H1_errors]).T, columns=['L2', 'H1'])
df
plt.plot(L2_errors, c='navy', label='L_2')
plt.plot(H1_errors, label='H_1')
#plt.gca().set(xscale='log')
plt.gca().set(yscale='log')
plt.legend()
plt.grid()
plt.show()
```
# Implement the computation of the amount of heat coming in and out the domain through the left and right boundaries
```
boundaries = MeshFunction("size_t", mesh, mesh.topology().dim ()-1)
boundaries.set_all(0)
left.mark(boundaries, 1)
right.mark(boundaries, 3)
ds = Measure("ds")(subdomain_data=boundaries)
n = FacetNormal(mesh)
Qin = assemble(kA * inner(grad(w), n) * ds(1))
Qout = assemble(kA * inner(grad(w), n) * ds(3))
print (" | -- Q_in =", Qin, ", Q_out = ", Qout)
```
# Let consider κB >> κA, such that the temperature on each circular region is approximately constant.
```
faux = Function(W)
faux = interpolate(Constant(1.0), W)
avgT = []
for ib in range (nballs) :
area = assemble (faux * dx(ib + 1))
avgT.append(assemble(w * dx(ib + 1))/area)
avgT
orders = [1, 2, 3, 4]
df_os = []
set_log_level(50)
for o in orders:
print ("| -- Order =", o)
order = o
Pk = FiniteElement("Lagrange", 'triangle', order)
if(nsd == 2):
domain = Rectangle(Point(0.0,0.0), Point(Lx,Ly))
for ib in range(nballs):
inc = Circle(Point(xc[ib][0],xc[ib][1]),radii[ib])
domain.set_subdomain(ib+1, inc)
else:
sys.exit("nsd.eq.3 not implemented")
mesh = generate_mesh (domain, 40 )
W = FunctionSpace(mesh, Pk)
# Dirichlet restrictions on W
bcs = []
# Fixed temperature: left and right
bcleft = DirichletBC(W, Tleft, left)
bcs.append(bcleft)
bcright = DirichletBC(W, Tright, right)
bcs.append(bcright)
#-----------------------------------------
# Variational formulation: Poisson problem
u = TrialFunction(W)
v = TestFunction(W)
# Add the different inclusions to the domain of integration
funcdom = MeshFunction("size_t", mesh, mesh.topology().dim(), mesh.domains())
dx = Measure("dx")(subdomain_data=funcdom)
dxf = dx(1)
for ib in range(nballs-1):
dxf = dxf + dx(ib+2)
# Bilinear and linear forms
a = inner(condA*grad(u), grad(v))*dx(0) + inner(condB*grad(u), grad(v))*dxf
L = f*v*dx
dx = Measure("dx")( subdomain_data = funcdom )
dxf = dx(1)
for ib in range (nballs -1) :
dxf = dxf + dx (ib +2)
L2_errors = []
H1_errors = []
for kB in np.arange(0.1, 2, 0.45):# np.linspace(1, 10, 10): #[1, 2 , 3, 5, 7, 8, 10, 24]:
condB = Constant (kB)
# Bilinear and linear forms
a = inner (condA * grad (u) , grad(v )) * dx (0)
a = a + inner (condB * grad (u) , grad(v )) * dxf
L = f * v * dx
# Solution
w = Function (W)
solve (a == L, w, bcs)
errorL2 = assemble ((w - ue )**2*dx)
errorH1 =errorL2 + assemble ((grad (w) - gradue)**2* dx)
L2_errors.append(sqrt(errorL2))
H1_errors.append(sqrt(errorH1))
print (" | - Errors =", sqrt(errorL2), sqrt(errorH1))
boundaries = MeshFunction("size_t", mesh, mesh.topology().dim ()-1)
boundaries.set_all(0)
left.mark(boundaries, 1)
right.mark(boundaries, 3)
ds = Measure("ds")(subdomain_data=boundaries)
n = FacetNormal(mesh)
Qin = assemble(kA * inner(grad(w), n) * ds(1))
Qout = assemble(kA * inner(grad(w), n) * ds(3))
print (" | -- Q_in =", Qin, ", Q_out = ", Qout)
print( )
ufile_pvd = File(dir_ +"/temperature_"+ str(kB)+ ".pvd")
ufile_pvd << w
df_os.append(pd.DataFrame(np.array([L2_errors, H1_errors]).T,
columns=['L2', 'H1']))
ls = ['-', '--', ':', '-.']
plt.figure()
for i, df in enumerate(df_os):
df.plot(y='L2', c='navy', ax=plt.gca(), ls=ls[i], label='L2 - Order='+str(i+1))
df.plot(y='H1', c='C0', ax=plt.gca(), ls=ls[i])
plt.gca().set(yscale='log')
plt.legend()
plt.grid()
plt.show()
```
|
github_jupyter
|
from dolfin import *
from mshr import *
import numpy
from datetime import datetime
import csv
import os
import sys
import matplotlib.pyplot as plt
#-------------------------------------------------------
# USER DEFINED PARAMETERS:
# Set the following parameters according to your problem
# Choose one IO format
#fileio = 'xdmf'
fileio = 'pvd'
# Space dimensions
nsd = 2
# Number of immersed balls
nballs = 3
# Computational domain
Lx = 2.0
Ly = 2.0
# Balls initial positions
centers = [[0.5,1], [1,1.5], [1.5,1]]
radii = [0.25, 0.15, 0.25]
xc = [[] for ib in range(nballs)]
for ib in range(nballs):
[xc[ib].append(centers[ib][j]) for j in range(nsd)]
# Thermal conductivity
kA,kB = 1.2, 10000.2
condA, condB = Constant(kA), Constant(kB)
# Volumetric source
f = Constant(0)
# Boundary temperatures
Tleft = Constant(100)
Tright = Constant(0)
# Variational problem: Preliminaries
# Finite elements
order = 2
Pk = FiniteElement("Lagrange", 'triangle', order)
# Dirichlet boundary conditions
# Subdomains
class left(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[0]-0.0) < DOLFIN_EPS
class right(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[0]-Lx) < DOLFIN_EPS
class top(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[1]-0.0) < DOLFIN_EPS
class bottom(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[1]-Ly) < DOLFIN_EPS
class ball(SubDomain):
def __init__(self,xc,yc,R):
self.xc = xc
self.yc = yc
self.R = R
SubDomain.__init__(self) # Call base class constructor!
def inside (self, x, on_boundary ):
r = sqrt ( ( x[0] - self.xc ) ** 2 + ( x[1] - self.yc ) ** 2 )
return ( on_boundary and ( r < self.R * 1.1 ) )
left = left()
right = right()
top = top()
bottom = bottom()
# IO
dir_ = './results'
if not os.path.exists(dir_):
os.mkdir(dir_)
if fileio == 'xdmf':
filex = XDMFFile(dir_+'/sol.xdmf')
filex.parameters['functions_share_mesh'] = True
filex.parameters['rewrite_function_mesh'] = True
filex.parameters["flush_output"] = True
elif fileio == 'pvd':
ufile_pvd = File(dir_+"/temperature.pvd")
domfile_pvd = File(dir_+"/auxfunc.pvd")
# Begin loop over time steps
startTime = datetime.now()
print('\n ::> Begin computations')
#----------------------------------------------
# Mesh generation
if(nsd == 2):
domain = Rectangle(Point(0.0,0.0), Point(Lx,Ly))
for ib in range(nballs):
inc = Circle(Point(xc[ib][0],xc[ib][1]),radii[ib])
domain.set_subdomain(ib+1, inc)
else:
sys.exit("nsd.eq.3 not implemented")
mesh = generate_mesh ( domain, 40 )
print(" |-Mesh done")
print(" |--Number of vertices = "+str(mesh.num_vertices()))
print(" |--Number of cells = "+str(mesh.num_cells()))
print(" |--Cell size hmax,hmin = %.3g %.3g" % (mesh.hmax(), mesh.hmin()))
# Finite element space
W = FunctionSpace(mesh, Pk)
# Dirichlet restrictions on W
bcs = []
# Fixed temperature: left and right
bcleft = DirichletBC(W, Tleft, left)
bcs.append(bcleft)
bcright = DirichletBC(W, Tright, right)
bcs.append(bcright)
#-----------------------------------------
# Variational formulation: Poisson problem
u = TrialFunction(W)
v = TestFunction(W)
# Add the different inclusions to the domain of integration
funcdom = MeshFunction("size_t", mesh, mesh.topology().dim(), mesh.domains())
dx = Measure("dx")(subdomain_data=funcdom)
dxf = dx(1)
for ib in range(nballs-1):
dxf = dxf + dx(ib+2)
# Bilinear and linear forms
a = inner(condA*grad(u), grad(v))*dx(0) + inner(condB*grad(u), grad(v))*dxf
L = f*v*dx
#---------
# Solution
w = Function(W)
solve(a == L, w, bcs)
# IO
w.rename("T","T")
if fileio == 'xdmf':
filex.write(w, 0)
filex.write(funcdom, 0)
elif fileio == 'pvd':
ufile_pvd << w
domfile_pvd << funcdom
elapsed_time = datetime.now() - startTime
print('\n ::> Elapsed time: ', str(elapsed_time), '\n')
if fileio == 'xdmf':
filex.close()
from dolfin import *
from mshr import *
import numpy
from datetime import datetime
import csv
import os
import sys
import matplotlib.pyplot as plt
#-------------------------------------------------------
# USER DEFINED PARAMETERS:
# Set the following parameters according to your problem
# Choose one IO format
#fileio = 'xdmf'
fileio = 'pvd'
# Space dimensions
nsd = 2
# Number of immersed balls
nballs = 3
# Computational domain
Lx = 2.0
Ly = 2.0
# Balls initial positions
centers = [[0.5,1], [1,1.5], [1.5,1]]
radii = [0.25, 0.15, 0.25]
xc = [[] for ib in range(nballs)]
for ib in range(nballs):
[xc[ib].append(centers[ib][j]) for j in range(nsd)]
# Thermal conductivity
kA, kB = 1.0, 1.0
condA, condB = Constant(kA), Constant(kB)
# Volumetric source
f = Constant(0)
# Boundary temperatures
Tleft = Constant(100)
Tright = Constant(0)
# Variational problem: Preliminaries
# Finite elements
order = 1
Pk = FiniteElement("Lagrange", 'triangle', order)
# Dirichlet boundary conditions
# Subdomains
class left(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[0]-0.0) < DOLFIN_EPS
class right(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[0]-Lx) < DOLFIN_EPS
class top(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[1]-0.0) < DOLFIN_EPS
class bottom(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and abs(x[1]-Ly) < DOLFIN_EPS
class ball(SubDomain):
def __init__(self,xc,yc,R):
self.xc = xc
self.yc = yc
self.R = R
SubDomain.__init__(self) # Call base class constructor!
def inside (self, x, on_boundary ):
r = sqrt ( ( x[0] - self.xc ) ** 2 + ( x[1] - self.yc ) ** 2 )
return ( on_boundary and ( r < self.R * 1.1 ) )
left = left()
right = right()
top = top()
bottom = bottom()
# IO
dir_ = './results'
if not os.path.exists(dir_):
os.mkdir(dir_)
if fileio == 'xdmf':
filex = XDMFFile(dir_+'/sol.xdmf')
filex.parameters['functions_share_mesh'] = True
filex.parameters['rewrite_function_mesh'] = True
filex.parameters["flush_output"] = True
elif fileio == 'pvd':
ufile_pvd = File(dir_+"/temperature.pvd")
domfile_pvd = File(dir_+"/auxfunc.pvd")
# Begin loop over time steps
startTime = datetime.now()
print('\n ::> Begin computations')
#----------------------------------------------
# Mesh generation
if(nsd == 2):
domain = Rectangle(Point(0.0,0.0), Point(Lx,Ly))
for ib in range(nballs):
inc = Circle(Point(xc[ib][0],xc[ib][1]),radii[ib])
domain.set_subdomain(ib+1, inc)
else:
sys.exit("nsd.eq.3 not implemented")
mesh = generate_mesh ( domain, 40 )
print(" |-Mesh done")
print(" |--Number of vertices = "+str(mesh.num_vertices()))
print(" |--Number of cells = "+str(mesh.num_cells()))
print(" |--Cell size hmax,hmin = %.3g %.3g" % (mesh.hmax(), mesh.hmin()))
# Finite element space
W = FunctionSpace(mesh, Pk)
# Dirichlet restrictions on W
bcs = []
# Fixed temperature: left and right
bcleft = DirichletBC(W, Tleft, left)
bcs.append(bcleft)
bcright = DirichletBC(W, Tright, right)
bcs.append(bcright)
#-----------------------------------------
# Variational formulation: Poisson problem
u = TrialFunction(W)
v = TestFunction(W)
# Add the different inclusions to the domain of integration
funcdom = MeshFunction("size_t", mesh, mesh.topology().dim(), mesh.domains())
dx = Measure("dx")(subdomain_data=funcdom)
dxf = dx(1)
for ib in range(nballs-1):
dxf = dxf + dx(ib+2)
# Bilinear and linear forms
a = inner(condA*grad(u), grad(v))*dx(0) + inner(condB*grad(u), grad(v))*dxf
L = f*v*dx
#---------
# Solution
w = Function(W)
solve(a == L, w, bcs)
# IO
w.rename("T","T")
if fileio == 'xdmf':
filex.write(w, 0)
filex.write(funcdom, 0)
elif fileio == 'pvd':
ufile_pvd << w
domfile_pvd << funcdom
elapsed_time = datetime.now() - startTime
print('\n ::> Elapsed time: ', str(elapsed_time), '\n')
if fileio == 'xdmf':
filex.close()
ue = Expression('Tleft -( Tleft - Tright )*x [0]/ Lx', degree=1, Tleft=100,
Tright=0, Lx=2)
gradue = Expression(('-(Tleft - Tright )/Lx','0'), degree=0, Tleft=100,
Tright=0, Lx =2)
w = Function (W)
solve (a == L, w, bcs)
errorL2 = assemble ((w - ue )**2*dx)
errorH1 = errorL2 + assemble ((grad (w) - gradue)**2* dx)
print (" | - Errors =", sqrt ( errorL2 ) , sqrt ( errorH1 ) )
dx = Measure("dx")( subdomain_data = funcdom )
dxf = dx(1)
for ib in range (nballs -1) :
dxf = dxf + dx (ib +2)
L2_errors = []
H1_errors = []
for kB in np.arange(0.1, 5, 0.45):# np.linspace(1, 10, 10): #[1, 2 , 3, 5, 7, 8, 10, 24]:
condB = Constant (kB)
# Bilinear and linear forms
a = inner (condA * grad (u) , grad(v )) * dx (0)
a = a + inner (condB * grad (u) , grad(v )) * dxf
L = f * v * dx
# Solution
w = Function (W)
solve (a == L, w, bcs)
errorL2 = assemble ((w - ue )**2*dx)
errorH1 =errorL2 + assemble ((grad (w) - gradue)**2* dx)
L2_errors.append(sqrt(errorL2))
H1_errors.append(sqrt(errorH1))
print (" | - Errors =", sqrt(errorL2), sqrt(errorH1))
boundaries = MeshFunction("size_t", mesh, mesh.topology().dim ()-1)
boundaries.set_all(0)
left.mark(boundaries, 1)
right.mark(boundaries, 3)
ds = Measure("ds")(subdomain_data=boundaries)
n = FacetNormal(mesh)
Qin = assemble(kA * inner(grad(w), n) * ds(1))
Qout = assemble(kA * inner(grad(w), n) * ds(3))
print (" | -- Q_in =", Qin, ", Q_out = ", Qout)
ufile_pvd = File(dir_ +"/temperature_"+ str(kB)+ ".pvd")
ufile_pvd << w
import pandas as pd
df = pd.DataFrame(np.array([L2_errors, H1_errors]).T, columns=['L2', 'H1'])
df
plt.plot(L2_errors, c='navy', label='L_2')
plt.plot(H1_errors, label='H_1')
#plt.gca().set(xscale='log')
plt.gca().set(yscale='log')
plt.legend()
plt.grid()
plt.show()
boundaries = MeshFunction("size_t", mesh, mesh.topology().dim ()-1)
boundaries.set_all(0)
left.mark(boundaries, 1)
right.mark(boundaries, 3)
ds = Measure("ds")(subdomain_data=boundaries)
n = FacetNormal(mesh)
Qin = assemble(kA * inner(grad(w), n) * ds(1))
Qout = assemble(kA * inner(grad(w), n) * ds(3))
print (" | -- Q_in =", Qin, ", Q_out = ", Qout)
faux = Function(W)
faux = interpolate(Constant(1.0), W)
avgT = []
for ib in range (nballs) :
area = assemble (faux * dx(ib + 1))
avgT.append(assemble(w * dx(ib + 1))/area)
avgT
orders = [1, 2, 3, 4]
df_os = []
set_log_level(50)
for o in orders:
print ("| -- Order =", o)
order = o
Pk = FiniteElement("Lagrange", 'triangle', order)
if(nsd == 2):
domain = Rectangle(Point(0.0,0.0), Point(Lx,Ly))
for ib in range(nballs):
inc = Circle(Point(xc[ib][0],xc[ib][1]),radii[ib])
domain.set_subdomain(ib+1, inc)
else:
sys.exit("nsd.eq.3 not implemented")
mesh = generate_mesh (domain, 40 )
W = FunctionSpace(mesh, Pk)
# Dirichlet restrictions on W
bcs = []
# Fixed temperature: left and right
bcleft = DirichletBC(W, Tleft, left)
bcs.append(bcleft)
bcright = DirichletBC(W, Tright, right)
bcs.append(bcright)
#-----------------------------------------
# Variational formulation: Poisson problem
u = TrialFunction(W)
v = TestFunction(W)
# Add the different inclusions to the domain of integration
funcdom = MeshFunction("size_t", mesh, mesh.topology().dim(), mesh.domains())
dx = Measure("dx")(subdomain_data=funcdom)
dxf = dx(1)
for ib in range(nballs-1):
dxf = dxf + dx(ib+2)
# Bilinear and linear forms
a = inner(condA*grad(u), grad(v))*dx(0) + inner(condB*grad(u), grad(v))*dxf
L = f*v*dx
dx = Measure("dx")( subdomain_data = funcdom )
dxf = dx(1)
for ib in range (nballs -1) :
dxf = dxf + dx (ib +2)
L2_errors = []
H1_errors = []
for kB in np.arange(0.1, 2, 0.45):# np.linspace(1, 10, 10): #[1, 2 , 3, 5, 7, 8, 10, 24]:
condB = Constant (kB)
# Bilinear and linear forms
a = inner (condA * grad (u) , grad(v )) * dx (0)
a = a + inner (condB * grad (u) , grad(v )) * dxf
L = f * v * dx
# Solution
w = Function (W)
solve (a == L, w, bcs)
errorL2 = assemble ((w - ue )**2*dx)
errorH1 =errorL2 + assemble ((grad (w) - gradue)**2* dx)
L2_errors.append(sqrt(errorL2))
H1_errors.append(sqrt(errorH1))
print (" | - Errors =", sqrt(errorL2), sqrt(errorH1))
boundaries = MeshFunction("size_t", mesh, mesh.topology().dim ()-1)
boundaries.set_all(0)
left.mark(boundaries, 1)
right.mark(boundaries, 3)
ds = Measure("ds")(subdomain_data=boundaries)
n = FacetNormal(mesh)
Qin = assemble(kA * inner(grad(w), n) * ds(1))
Qout = assemble(kA * inner(grad(w), n) * ds(3))
print (" | -- Q_in =", Qin, ", Q_out = ", Qout)
print( )
ufile_pvd = File(dir_ +"/temperature_"+ str(kB)+ ".pvd")
ufile_pvd << w
df_os.append(pd.DataFrame(np.array([L2_errors, H1_errors]).T,
columns=['L2', 'H1']))
ls = ['-', '--', ':', '-.']
plt.figure()
for i, df in enumerate(df_os):
df.plot(y='L2', c='navy', ax=plt.gca(), ls=ls[i], label='L2 - Order='+str(i+1))
df.plot(y='H1', c='C0', ax=plt.gca(), ls=ls[i])
plt.gca().set(yscale='log')
plt.legend()
plt.grid()
plt.show()
| 0.443359 | 0.422445 |
```
# Импорт библиотек
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# Загрузка данных
data = pd.read_csv('/Users/Arbiter/Documents/Airport_Stat/airstat.csv')
```
# Задание первое
Проверить количество поврежденных строк
```
good_symbols_string = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z '
good_symbols_string += 'a b c d e f g h i j k l m n o p q r s t u v w x y z '
good_symbols_string += '- ) ( '
good_symbols_string += '0 1 2 3 4 5 6 7 8 9'
good_symbols = good_symbols_string.split(' ')
good_symbols.append(' ')
def bad_symbol(a, good_symbols):
for i in a:
if i not in good_symbols:
return False
return True
good_port_list = []
for i in data['Airport name']:
if bad_symbol(i, good_symbols) == True:
good_port_list.append(i)
df = data[data['Airport name'].isin(good_port_list) == True]
backup = data[data['Airport name'].isin(good_port_list) == False]
backup.info()
```
Ответ: 332
```
backup
```
# Задание второе
Сколько аэропортов не принимают воздушные суда?
```
a = df.groupby('Airport name')['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'Whole year'].agg('sum')
a = a.reset_index()
a[a['Whole year'] == 0]['Airport name'].count()
```
Ответ: 162
# Задание третье
Сколько аэропортов прекратили работу в 2018 - 2020?
```
working_airport_df = df[((df['Whole year'] > 0) & (df['Year'] <= 2017))]
working_airport = list(working_airport_df['Airport name'])
df[(df['Airport name'].isin(working_airport) == True) & (df['Year'] == 2018 ) & (df['Whole year'] == 0)]
df[(df['Airport name'].isin(working_airport) == True) & (df['Year'] == 2019 ) & (df['Whole year'] == 0)]
df[(df['Airport name'].isin(working_airport) == True) & (df['Year'] == 2020 ) & (df['Whole year'] == 0)]
```
Ответ: 2
# Задание четвертое
Какова разница между наиболее и наименее загруженным месяцем в тыс. человек?
```
import math
more_5_mln = df[(df['Whole year'] > 5000000) & (df['Year'] != 2020)]
more_5_mln_airport = set(more_5_mln['Airport name'])
less_5_mln = df[(df['Airport name'].isin(more_5_mln_airport) == False)]
top_50 = less_5_mln.groupby('Airport name')['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December','Whole year'].agg('sum')
top_50 = top_50.sort_values(by='Whole year', ascending = False)
top_50 = top_50.head(50)
January = top_50['January'].sum()
February = top_50['February'].sum()
March = top_50['March'].sum()
April = top_50['April'].sum()
May = top_50['May'].sum()
June = top_50['June'].sum()
July = top_50['July'].sum()
August = top_50['August'].sum()
September = top_50['September'].sum()
October = top_50['October'].sum()
November = top_50['November'].sum()
December = top_50['December'].sum()
x = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
y = [January, February, March, April, May, June, July, August, September, October, November, December]
plt.grid(True)
plt.plot(x, y)
math.floor((August - February) / 1000)
```
Ответ: 26114
# Задание пятое
Укажите эти топ-5 аэропортов
```
result = {}
top_50 = top_50.reset_index()
top_50_list = list(top_50['Airport name'])
df_2007 = df[(df['Year'] == 2007) & (df['Airport name'].isin(top_50_list) == True) ]
df_2019 = df[(df['Year'] == 2019) & (df['Airport name'].isin(top_50_list) == True) ]
for i in top_50_list:
if str(df_2019[df_2019['Airport name'] == i]['Whole year'].max()).isdigit() == True:
a = int(df_2019[df_2019['Airport name'] == i]['Whole year'].max())
if str(df_2007[df_2007['Airport name'] == i]['Whole year'].max()).isdigit() == True:
b = int(df_2007[df_2007['Airport name'] == i]['Whole year'].max())
if b != 0:
change = (a - b) / b
result[i] = change
new_df = pd.DataFrame(index = result.keys(), data = result.values())
new_df.sort_values(by=0, ascending = False)
```
Ответ:
- Voronezh (Chertovitskoe)
- Nizhny Novgorod (Strigino)
- Astrakhan (Narimanovo)
- Stavropol (Shpakovskoye)
- Vladivostok (Knevichi)
|
github_jupyter
|
# Импорт библиотек
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# Загрузка данных
data = pd.read_csv('/Users/Arbiter/Documents/Airport_Stat/airstat.csv')
good_symbols_string = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z '
good_symbols_string += 'a b c d e f g h i j k l m n o p q r s t u v w x y z '
good_symbols_string += '- ) ( '
good_symbols_string += '0 1 2 3 4 5 6 7 8 9'
good_symbols = good_symbols_string.split(' ')
good_symbols.append(' ')
def bad_symbol(a, good_symbols):
for i in a:
if i not in good_symbols:
return False
return True
good_port_list = []
for i in data['Airport name']:
if bad_symbol(i, good_symbols) == True:
good_port_list.append(i)
df = data[data['Airport name'].isin(good_port_list) == True]
backup = data[data['Airport name'].isin(good_port_list) == False]
backup.info()
backup
a = df.groupby('Airport name')['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'Whole year'].agg('sum')
a = a.reset_index()
a[a['Whole year'] == 0]['Airport name'].count()
working_airport_df = df[((df['Whole year'] > 0) & (df['Year'] <= 2017))]
working_airport = list(working_airport_df['Airport name'])
df[(df['Airport name'].isin(working_airport) == True) & (df['Year'] == 2018 ) & (df['Whole year'] == 0)]
df[(df['Airport name'].isin(working_airport) == True) & (df['Year'] == 2019 ) & (df['Whole year'] == 0)]
df[(df['Airport name'].isin(working_airport) == True) & (df['Year'] == 2020 ) & (df['Whole year'] == 0)]
import math
more_5_mln = df[(df['Whole year'] > 5000000) & (df['Year'] != 2020)]
more_5_mln_airport = set(more_5_mln['Airport name'])
less_5_mln = df[(df['Airport name'].isin(more_5_mln_airport) == False)]
top_50 = less_5_mln.groupby('Airport name')['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December','Whole year'].agg('sum')
top_50 = top_50.sort_values(by='Whole year', ascending = False)
top_50 = top_50.head(50)
January = top_50['January'].sum()
February = top_50['February'].sum()
March = top_50['March'].sum()
April = top_50['April'].sum()
May = top_50['May'].sum()
June = top_50['June'].sum()
July = top_50['July'].sum()
August = top_50['August'].sum()
September = top_50['September'].sum()
October = top_50['October'].sum()
November = top_50['November'].sum()
December = top_50['December'].sum()
x = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
y = [January, February, March, April, May, June, July, August, September, October, November, December]
plt.grid(True)
plt.plot(x, y)
math.floor((August - February) / 1000)
result = {}
top_50 = top_50.reset_index()
top_50_list = list(top_50['Airport name'])
df_2007 = df[(df['Year'] == 2007) & (df['Airport name'].isin(top_50_list) == True) ]
df_2019 = df[(df['Year'] == 2019) & (df['Airport name'].isin(top_50_list) == True) ]
for i in top_50_list:
if str(df_2019[df_2019['Airport name'] == i]['Whole year'].max()).isdigit() == True:
a = int(df_2019[df_2019['Airport name'] == i]['Whole year'].max())
if str(df_2007[df_2007['Airport name'] == i]['Whole year'].max()).isdigit() == True:
b = int(df_2007[df_2007['Airport name'] == i]['Whole year'].max())
if b != 0:
change = (a - b) / b
result[i] = change
new_df = pd.DataFrame(index = result.keys(), data = result.values())
new_df.sort_values(by=0, ascending = False)
| 0.124213 | 0.773986 |
# Classifying Fashion-MNIST
Now it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 97% accuracy. Fashion-MNIST is a set of 28x28 greyscale images of clothes. It's more complex than MNIST, so it's a better representation of the actual performance of your network, and a better representation of datasets you'll use in the real world.
<img src='assets/fashion-mnist-sprite.png' width=500px>
In this notebook, you'll build your own neural network. For the most part, you could just copy and paste the code from Part 3, but you wouldn't be learning. It's important for you to write the code yourself and get it to work. Feel free to consult the previous notebooks though as you work through this.
First off, let's load the dataset through torchvision.
```
import torch
from torchvision import datasets, transforms
import helper
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# Download and load the training data
trainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
# Download and load the test data
testset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)
```
Here we can see one of the images.
```
image, label = next(iter(trainloader))
helper.imshow(image[0,:]);
```
## Building the network
Here you should define your network. As with MNIST, each image is 28x28 which is a total of 784 pixels, and there are 10 classes. You should include at least one hidden layer. We suggest you use ReLU activations for the layers and to return the logits or log-softmax from the forward pass. It's up to you how many layers you add and the size of those layers.
```
from torch import nn, optim
import torch.nn.functional as F
# TODO: Define your network architecture here
class Classifier(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 256)
self.fc2 = nn.Linear(256, 128)
self.fc3 = nn.Linear(128, 64)
self.fc4 = nn.Linear(64, 10)
def forward(self, x):
# make sure input tensor is flattened
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = F.log_softmax(self.fc4(x), dim=1)
return x
```
# Train the network
Now you should create your network and train it. First you'll want to define [the criterion](http://pytorch.org/docs/master/nn.html#loss-functions) (something like `nn.CrossEntropyLoss` or `nn.NLLLoss`) and [the optimizer](http://pytorch.org/docs/master/optim.html) (typically `optim.SGD` or `optim.Adam`).
Then write the training code. Remember the training pass is a fairly straightforward process:
* Make a forward pass through the network to get the logits
* Use the logits to calculate the loss
* Perform a backward pass through the network with `loss.backward()` to calculate the gradients
* Take a step with the optimizer to update the weights
By adjusting the hyperparameters (hidden units, learning rate, etc), you should be able to get the training loss below 0.4.
```
# TODO: Create the network, define the criterion and optimizer
model = Classifier()
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(), lr=0.003)
# TODO: Train the network here
epochs = 5
for e in range(epochs):
running_loss = 0
for images, labels in trainloader:
log_ps = model(images)
loss = criterion(log_ps, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
running_loss += loss.item()
else:
print(f"Training loss: {running_loss/len(trainloader)}")
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import helper
# Test out your network!
dataiter = iter(testloader)
images, labels = dataiter.next()
img = images[1]
# TODO: Calculate the class probabilities (softmax) for img
ps = torch.exp(model(img))
# Plot the image and probabilities
helper.view_classify(img, ps, version='Fashion')
```
|
github_jupyter
|
import torch
from torchvision import datasets, transforms
import helper
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# Download and load the training data
trainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
# Download and load the test data
testset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)
image, label = next(iter(trainloader))
helper.imshow(image[0,:]);
from torch import nn, optim
import torch.nn.functional as F
# TODO: Define your network architecture here
class Classifier(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 256)
self.fc2 = nn.Linear(256, 128)
self.fc3 = nn.Linear(128, 64)
self.fc4 = nn.Linear(64, 10)
def forward(self, x):
# make sure input tensor is flattened
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = F.log_softmax(self.fc4(x), dim=1)
return x
# TODO: Create the network, define the criterion and optimizer
model = Classifier()
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(), lr=0.003)
# TODO: Train the network here
epochs = 5
for e in range(epochs):
running_loss = 0
for images, labels in trainloader:
log_ps = model(images)
loss = criterion(log_ps, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
running_loss += loss.item()
else:
print(f"Training loss: {running_loss/len(trainloader)}")
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import helper
# Test out your network!
dataiter = iter(testloader)
images, labels = dataiter.next()
img = images[1]
# TODO: Calculate the class probabilities (softmax) for img
ps = torch.exp(model(img))
# Plot the image and probabilities
helper.view_classify(img, ps, version='Fashion')
| 0.806624 | 0.990083 |
# Computation of cutting planes: example 1
# The set-up
```
import numpy as np
import pandas as pd
import scipy.optimize as opt
from scipy.special import expit # The logistic sigmoid function
import accpm
%load_ext autoreload
%autoreload 1
%aimport accpm
np.set_printoptions(precision=4)
```
$\DeclareMathOperator{\domain}{dom}
\newcommand{\transpose}{\text{T}}
\newcommand{\vec}[1]{\begin{pmatrix}#1\end{pmatrix}}$
# Example
To test the computation of cutting planes we consider a logistic regression problem. Particularly, we consider the problem of predicting the incidence of diabetes based on various measurements (see [description](https://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes)). We use a normalised version of the data (which can be found at [mldata.org](http://mldata.org/repository/data/download/csv/diabetes_scale/)) where the label to be predicted (the incidence of diabetes) is in the first column. We have the following data processing:
```
names = ['diabetes', 'num preg', 'plasma', 'bp', 'skin fold', 'insulin', 'bmi', 'pedigree', 'age']
data = pd.read_csv('diabetes_scale.csv', header=None, names=names)
data['diabetes'].replace(-1, 0, inplace=True) # The target variable need be 1 or 0, not 1 or -1
data['ones'] = np.ones((data.shape[0], 1)) # Add a column of ones to represent the constant bias
data.head()
np.random.seed(1)
size = data.shape[0]
index = np.arange(size)
np.random.shuffle(index)
training_index = index[:int(size/2)]
testing_index = index[int(size/2):]
Y = data['diabetes']
X = data[['num preg', 'plasma', 'bp', 'skin fold', 'insulin', 'bmi', 'pedigree', 'age', 'ones']]
X = np.array(X)
Y = np.array(Y)
X_training = X[training_index]
Y_training = Y[training_index]
X_testing = X[testing_index]
Y_testing = Y[testing_index]
```
This model has 9 input variables $x_0, \dots, x_8$ where $x_8$ is the dummy input variable fixed at 1. (The fixed dummy input variable could easily be $x_5$ or $x_7$, it's index is unimportant.) We set the basis functions to the simplest choice $\phi_0(\mathbf{x}) = x_0, \dots, \phi_8(\mathbf{x}) = x_8$. Our model then has the form
$$
y(\mathbf{x}) = \sigma(\sum_{j=0}^{8} w_j x_j) = \sigma(\mathbf{w}^T \mathbf{x}.)
$$
Here we have a dataset, $\{(\mathbf{x}_n, t_n)\}_{n=0}^{N}$ where $t_n \in \{0, 1\}$, with $N + 1 =767 + 1 = 768$ examples. We train our model by finding the parameter vector $\mathbf{w}$ which minimizes the (data-dependent) cross-entropy error function
$$
E_D(\mathbf{w}) = - \sum_{n=0}^{N} \{t_n \ln \sigma(\mathbf{w}^T \mathbf{x}_n) + (1 - t_n)\ln(1 - \sigma(\mathbf{w}^T \mathbf{x}_n))\}.
$$
The gradient of this function is given by
$$
\nabla E(\mathbf{w}) = \sum_{i=0}^{N} (\sigma(\mathbf{w}^T \mathbf{x}_n) - t_n)\mathbf{x}_n.
$$
We can then implement these as follows:
```
def cost(w, X, y, c=0):
"""
Returns the cross-entropy error function with (optional) sum-of-squares regularization term.
w -- parameters
X -- dataset of features where each row corresponds to a single sample
y -- dataset of labels where each row corresponds to a single sample
c -- regularization coefficient (default = 0)
"""
outputs = expit(X.dot(w)) # Vector of outputs (or predictions)
return -( y.transpose().dot(np.log(outputs)) + (1-y).transpose().dot(np.log(1-outputs)) ) + c*0.5*w.dot(w)
def grad(w, X, y, c=0):
"""
Returns the gradient of the cross-entropy error function with (optional) sum-of-squares regularization term.
"""
outputs = expit(X.dot(w))
return X.transpose().dot(outputs-y) + c*w
def train(X, y,c=0):
"""
Returns the vector of parameters which minimizes the error function via the BFGS algorithm.
"""
initial_values = np.zeros(X.shape[1]) # Error occurs if inital_values is set too high
return opt.fmin_bfgs(cost, initial_values, fprime=grad, args=(X,y,c))
def predict(w, X):
"""
Returns a vector of predictions.
"""
return expit(X.dot(w))
```
We test $\texttt{accpm}$ against the parameters attained using SciPy's $\texttt{fmin_bfgs}$ function via the $\texttt{train}$ function. The latter produces the following:
```
theta_best1 = train(X_training, Y_training)
print('---------------- Results ----------------')
print("The parameters attained using SciPy's fmin_bfgs are\n", theta_best1)
print('With these parameters the gradient is\n', grad(theta_best1, X_training, Y_training))
print('With these parameters the norm of the gradient is', np.linalg.norm(grad(theta_best1, X_training, Y_training)))
```
We now compute the accuracy from the parameter vector attained using SciPy's $\texttt{fmin_bfgs}$
```
predictions_sp = predict(theta_best1, X_testing).round()
results_sp = predictions_sp == Y_testing
correct_sp = np.count_nonzero(results_sp)
accuracy_sp = correct_sp/X_testing.shape[0]
print(accuracy_sp)
```
The former gives the following where we take the initial polyhedron to be the 9-dimensional cube centered at the origin with side length 20:
```
A = []
b = []
for i in range(X.shape[1]):
a_upper = [0]*X.shape[1]
a_lower = [0]*X.shape[1]
a_upper[i] = 1
a_lower[i] = -1
A.append(a_upper)
A.append(a_lower)
b.append(10)
b.append(10)
A = np.array(A, dtype = accpm.myfloat)
b = np.array(b, dtype = accpm.myfloat)
theta_best2 = accpm.accpm(A, b, cost, grad, args = (X_training, Y_training),
alpha=0.01, beta=0.7, start=1, maxiter = 300,
summary=1, testing=1)[1]
A = []
b = []
for i in range(X.shape[1]):
a_upper = [0]*X.shape[1]
a_lower = [0]*X.shape[1]
a_upper[i] = 1
a_lower[i] = -1
A.append(a_upper)
A.append(a_lower)
b.append(10)
b.append(10)
A = np.array(A, dtype = accpm.myfloat)
b = np.array(b, dtype = accpm.myfloat)
theta_all = accpm.accpm(A, b, cost, grad, args = (X_training, Y_training),
alpha=0.01, beta=0.7, start=1, maxiter = 300,
summary=1, testing=3)[2]
np.array(theta_all).shape
print(theta_all)
```
The algorithm converged in 140 iterations and we observe that
```
difference = np.abs(theta_all[1]-theta_best2)
print("The absolute element wise difference between the parameters attained via SciPy's",
"fmin_bfgs function and the ACCPM are\n", difference)
print("The norm value of this difference is", np.linalg.norm(difference))
```
and so the results of the two functions are comparable.
Indeed, having gathered the parameter collected at each iteration we can see how the accuracy improved over time
```
import matplotlib.pyplot as plt
%matplotlib inline
theta_all = np.array(theta_all)
queries = np.arange(1, theta_all.shape[0] + 1)
accuracies = []
for i in range(theta_all.shape[0]):
predictions = predict(theta_all[i], X_testing).round()
results = predictions == Y_testing
correct = np.count_nonzero(results)
accuracy = correct/X_testing.shape[0]
accuracies.append(accuracy)
accuracies = np.array(accuracies)
accuracies[-1]
accuracies.shape
plt.figure(figsize=(12,7))
plt.plot(queries, accuracies, 'mx-', label='LR',
markevery=5,
lw=1.5, ms=10, markerfacecolor='none', markeredgewidth=1.5,
markeredgecolor = 'm')
plt.xlabel('Number of iterations')
plt.ylabel('Accuracy on testing data sat')
plt.title('Accuracy of logistic regression as a single run of ACCPM converges (diabetes data set)')
plt.legend(loc='best')
plt.savefig('accpm_experiment.png', dpi=600, bbox_inches='tight', transparent=True)
plt.show()
```
Below we run some more tests and observe that the algorithm converges for smaller initial polyhedrons but fails entirely for larger polyhedrons.
```
A = []
b = []
for i in range(X.shape[1]):
a_upper = [0]*X.shape[1]
a_lower = [0]*X.shape[1]
a_upper[i] = 1
a_lower[i] = -1
A.append(a_upper)
A.append(a_lower)
b.append(5)
b.append(5)
A = np.array(A, dtype = accpm.myfloat)
b = np.array(b, dtype = accpm.myfloat)
theta_best3 = accpm.accpm(A, b, cost, grad, args = (X, Y),
alpha=0.01, beta=0.7, start=1, maxiter = 300,
summary=1, testing=1)[1]
A = []
b = []
for i in range(X.shape[1]):
a_upper = [0]*X.shape[1]
a_lower = [0]*X.shape[1]
a_lower[i] = -1
A.append(a_upper)
A.append(a_lower)
b.append(20)
b.append(20)
A = np.array(A, dtype = accpm.myfloat)
b = np.array(b, dtype = accpm.myfloat)
theta_best4 = accpm.accpm(A, b, cost, grad, args = (X, Y),
alpha=0.01, beta=0.7, start=1, maxiter = 300,
summary=1, testing=1)[1]
A = []
b = []
for i in range(X.shape[1]):
a_upper = [0]*X.shape[1]
a_lower = [0]*X.shape[1]
a_upper[i] = 1
a_lower[i] = -1
A.append(a_upper)
A.append(a_lower)
b.append(20)
b.append(20)
A = np.array(A, dtype = accpm.myfloat)
b = np.array(b, dtype = accpm.myfloat)
theta_best5 = accpm.accpm(A, b, cost, grad, args = (X, Y),
alpha=0.01, beta=0.7, start=1, maxiter = 300,
summary=1, testing=1)[1]
```
|
github_jupyter
|
import numpy as np
import pandas as pd
import scipy.optimize as opt
from scipy.special import expit # The logistic sigmoid function
import accpm
%load_ext autoreload
%autoreload 1
%aimport accpm
np.set_printoptions(precision=4)
names = ['diabetes', 'num preg', 'plasma', 'bp', 'skin fold', 'insulin', 'bmi', 'pedigree', 'age']
data = pd.read_csv('diabetes_scale.csv', header=None, names=names)
data['diabetes'].replace(-1, 0, inplace=True) # The target variable need be 1 or 0, not 1 or -1
data['ones'] = np.ones((data.shape[0], 1)) # Add a column of ones to represent the constant bias
data.head()
np.random.seed(1)
size = data.shape[0]
index = np.arange(size)
np.random.shuffle(index)
training_index = index[:int(size/2)]
testing_index = index[int(size/2):]
Y = data['diabetes']
X = data[['num preg', 'plasma', 'bp', 'skin fold', 'insulin', 'bmi', 'pedigree', 'age', 'ones']]
X = np.array(X)
Y = np.array(Y)
X_training = X[training_index]
Y_training = Y[training_index]
X_testing = X[testing_index]
Y_testing = Y[testing_index]
def cost(w, X, y, c=0):
"""
Returns the cross-entropy error function with (optional) sum-of-squares regularization term.
w -- parameters
X -- dataset of features where each row corresponds to a single sample
y -- dataset of labels where each row corresponds to a single sample
c -- regularization coefficient (default = 0)
"""
outputs = expit(X.dot(w)) # Vector of outputs (or predictions)
return -( y.transpose().dot(np.log(outputs)) + (1-y).transpose().dot(np.log(1-outputs)) ) + c*0.5*w.dot(w)
def grad(w, X, y, c=0):
"""
Returns the gradient of the cross-entropy error function with (optional) sum-of-squares regularization term.
"""
outputs = expit(X.dot(w))
return X.transpose().dot(outputs-y) + c*w
def train(X, y,c=0):
"""
Returns the vector of parameters which minimizes the error function via the BFGS algorithm.
"""
initial_values = np.zeros(X.shape[1]) # Error occurs if inital_values is set too high
return opt.fmin_bfgs(cost, initial_values, fprime=grad, args=(X,y,c))
def predict(w, X):
"""
Returns a vector of predictions.
"""
return expit(X.dot(w))
theta_best1 = train(X_training, Y_training)
print('---------------- Results ----------------')
print("The parameters attained using SciPy's fmin_bfgs are\n", theta_best1)
print('With these parameters the gradient is\n', grad(theta_best1, X_training, Y_training))
print('With these parameters the norm of the gradient is', np.linalg.norm(grad(theta_best1, X_training, Y_training)))
predictions_sp = predict(theta_best1, X_testing).round()
results_sp = predictions_sp == Y_testing
correct_sp = np.count_nonzero(results_sp)
accuracy_sp = correct_sp/X_testing.shape[0]
print(accuracy_sp)
A = []
b = []
for i in range(X.shape[1]):
a_upper = [0]*X.shape[1]
a_lower = [0]*X.shape[1]
a_upper[i] = 1
a_lower[i] = -1
A.append(a_upper)
A.append(a_lower)
b.append(10)
b.append(10)
A = np.array(A, dtype = accpm.myfloat)
b = np.array(b, dtype = accpm.myfloat)
theta_best2 = accpm.accpm(A, b, cost, grad, args = (X_training, Y_training),
alpha=0.01, beta=0.7, start=1, maxiter = 300,
summary=1, testing=1)[1]
A = []
b = []
for i in range(X.shape[1]):
a_upper = [0]*X.shape[1]
a_lower = [0]*X.shape[1]
a_upper[i] = 1
a_lower[i] = -1
A.append(a_upper)
A.append(a_lower)
b.append(10)
b.append(10)
A = np.array(A, dtype = accpm.myfloat)
b = np.array(b, dtype = accpm.myfloat)
theta_all = accpm.accpm(A, b, cost, grad, args = (X_training, Y_training),
alpha=0.01, beta=0.7, start=1, maxiter = 300,
summary=1, testing=3)[2]
np.array(theta_all).shape
print(theta_all)
difference = np.abs(theta_all[1]-theta_best2)
print("The absolute element wise difference between the parameters attained via SciPy's",
"fmin_bfgs function and the ACCPM are\n", difference)
print("The norm value of this difference is", np.linalg.norm(difference))
import matplotlib.pyplot as plt
%matplotlib inline
theta_all = np.array(theta_all)
queries = np.arange(1, theta_all.shape[0] + 1)
accuracies = []
for i in range(theta_all.shape[0]):
predictions = predict(theta_all[i], X_testing).round()
results = predictions == Y_testing
correct = np.count_nonzero(results)
accuracy = correct/X_testing.shape[0]
accuracies.append(accuracy)
accuracies = np.array(accuracies)
accuracies[-1]
accuracies.shape
plt.figure(figsize=(12,7))
plt.plot(queries, accuracies, 'mx-', label='LR',
markevery=5,
lw=1.5, ms=10, markerfacecolor='none', markeredgewidth=1.5,
markeredgecolor = 'm')
plt.xlabel('Number of iterations')
plt.ylabel('Accuracy on testing data sat')
plt.title('Accuracy of logistic regression as a single run of ACCPM converges (diabetes data set)')
plt.legend(loc='best')
plt.savefig('accpm_experiment.png', dpi=600, bbox_inches='tight', transparent=True)
plt.show()
A = []
b = []
for i in range(X.shape[1]):
a_upper = [0]*X.shape[1]
a_lower = [0]*X.shape[1]
a_upper[i] = 1
a_lower[i] = -1
A.append(a_upper)
A.append(a_lower)
b.append(5)
b.append(5)
A = np.array(A, dtype = accpm.myfloat)
b = np.array(b, dtype = accpm.myfloat)
theta_best3 = accpm.accpm(A, b, cost, grad, args = (X, Y),
alpha=0.01, beta=0.7, start=1, maxiter = 300,
summary=1, testing=1)[1]
A = []
b = []
for i in range(X.shape[1]):
a_upper = [0]*X.shape[1]
a_lower = [0]*X.shape[1]
a_lower[i] = -1
A.append(a_upper)
A.append(a_lower)
b.append(20)
b.append(20)
A = np.array(A, dtype = accpm.myfloat)
b = np.array(b, dtype = accpm.myfloat)
theta_best4 = accpm.accpm(A, b, cost, grad, args = (X, Y),
alpha=0.01, beta=0.7, start=1, maxiter = 300,
summary=1, testing=1)[1]
A = []
b = []
for i in range(X.shape[1]):
a_upper = [0]*X.shape[1]
a_lower = [0]*X.shape[1]
a_upper[i] = 1
a_lower[i] = -1
A.append(a_upper)
A.append(a_lower)
b.append(20)
b.append(20)
A = np.array(A, dtype = accpm.myfloat)
b = np.array(b, dtype = accpm.myfloat)
theta_best5 = accpm.accpm(A, b, cost, grad, args = (X, Y),
alpha=0.01, beta=0.7, start=1, maxiter = 300,
summary=1, testing=1)[1]
| 0.566858 | 0.988874 |
```
import numpy as np
import pandas as pd
import scipy
import scipy.io as sio
from scipy.optimize import linprog
```
# 0.Data Preparation
```
# set the data
dataFile = "Vehicle_data.mat"
data = sio.loadmat(dataFile)
data
data['Q']=np.dot(data['Qb'],np.ones((3,14)))
data['Q']
```
# 1.Organize data
```
data['Qd']=np.dot(data['r'],data['D'])
# electricity consumed on the road of Car i
data['Qb']=np.dot((np.eye(3)-data['q']),data['E'])
# electricity need of Car i
data['Q']=np.dot(data['Qb'],np.ones((3,14)))+data['Qd']
# Total electricity need of Car i
data['Tc']=np.array([[12.40537143, 12.36514286, 12.38022857, 12.46571429, 12.49085714,
12.39028571, 12.42045714, 12.4808 , 12.4808 , 12.53611429,
1.08547 , 1.08327 , 1.08415 , 1.09207 ],
[ 4.79308571, 4.76085714, 4.77294286, 4.84142857, 4.86157143,
4.781 , 4.80517143, 4.85351429, 4.85351429, 4.89782857,
0.419395 , 0.4176325 , 0.4183375 , 0.4246825 ],
[ 9.18131429, 9.14314286, 9.15745714, 9.23857143, 9.26242857,
9.167 , 9.19562857, 9.25288571, 9.25288571, 9.30537143,
0.803365 , 0.8012775 , 0.8021125 , 0.8096275 ]])
# data['Q'] / data['p']
# time needed for charging of Car i in Station j
data['Pc']=np.dot(np.ones((3,1)),data['pc'])*data['Q']
# Charging fee of Car i in Station j
data['Ps']=np.dot(np.ones((3,1)),data['ps'])*data['Q']
# Service fee of Car i in Station j
data['Pp']=np.dot(np.ones((3,1)),data['pp'])*data['Tc']
# Parking fee of Car i in Station j
data['P']=data['Pc']+data['Ps']+data['Pp']
# Total fee of Car i in Station j
```
# 2.Set the goal function
According to the utility, give the weights
```
# Normal Charging
F1=0.3*data['D']+0.13*data['Td']+0.01*data['Tc']+0.3*data['P']
-0.13*np.dot(np.ones((3,1)),data['S'])-0.13*np.ones((3,1))*data['R']
# Urgent Charging
F2=0.3*data['D']+0.1*data['Td']+0.3*data['Tc']+0.1*data['P']
-0.1*np.dot(np.ones((3,1)),data['S'])-0.11*np.ones((3,1))*data['R']
# Rush Hour
F3=0.1*data['D']+0.3*data['Td']+0.3*data['Tc']+0.1*data['P']
-0.3*np.dot(np.ones((3,1)),data['S'])-0.11*np.ones((3,1))*data['R']
# Shortest Distance
F4=data['D']
# Arrive earliest
F5=data['Td']
# Finish Charge earliest
F6=data['Tc']
# Cheapest
F7=data['P']
# Hightest Score(Highest Satisfaction)
F8=np.dot(-np.ones((3,1)),data['S'] )
# Most spot
F9=np.dot(-np.ones((3,1)),data['R'] )
```
# 3.Set the parameters of Linear Programming
```
# build a function which make it easier to iterate every goal function
# function could generate every parameters
def parameters(goal):
C=goal
# calculate the row
n=C.shape[0]
# calculate the column
m=C.shape[1]
# Calculate the goal function
c=C.flatten('F')
# set the unequation restriction
Qz=np.dot(data['r'],data['D'])-np.dot(np.dot(data['q'],data['E']),np.ones((n,m)))
Qz=Qz.flatten('F')
a=np.zeros((m,n*m))
for i in range(0,m):
for j in range(i*n, n*(i+1)):
a[i:i+1,j:j+1]=1
Qz=Qz*np.ones((1,n*m))
A=np.vstack((a,Qz))
# unequation coefficient
B=np.vstack((data['R'].conj().T,np.zeros((1,1))))
# set the equation restriction
Ae = np.zeros((n,n*m))
for i in range(0,n):
for k in range(i, n*m, n):
Ae[i:i+1,k:k+1]=1
# equation coefficient
Be=np.ones((n,1))
return (c,A,B,Ae,Be)
```
# 4.Modelling and get answer
```
func = [F1,F2,F3,F4,F5,F6,F7,F8,F9]
funcname = ['F1','F2','F3','F4','F5','F6','F7','F8','F9']
i=0
for goal in func:
(c,A,B,Ae,Be) = parameters(goal)
res=linprog(c,A,B,Ae,Be,bounds = (0,1))
print("---")
print(funcname[i])
print("---")
print(res)
print("***********************")
print("")
print("")
i+=1
```
|
github_jupyter
|
import numpy as np
import pandas as pd
import scipy
import scipy.io as sio
from scipy.optimize import linprog
# set the data
dataFile = "Vehicle_data.mat"
data = sio.loadmat(dataFile)
data
data['Q']=np.dot(data['Qb'],np.ones((3,14)))
data['Q']
data['Qd']=np.dot(data['r'],data['D'])
# electricity consumed on the road of Car i
data['Qb']=np.dot((np.eye(3)-data['q']),data['E'])
# electricity need of Car i
data['Q']=np.dot(data['Qb'],np.ones((3,14)))+data['Qd']
# Total electricity need of Car i
data['Tc']=np.array([[12.40537143, 12.36514286, 12.38022857, 12.46571429, 12.49085714,
12.39028571, 12.42045714, 12.4808 , 12.4808 , 12.53611429,
1.08547 , 1.08327 , 1.08415 , 1.09207 ],
[ 4.79308571, 4.76085714, 4.77294286, 4.84142857, 4.86157143,
4.781 , 4.80517143, 4.85351429, 4.85351429, 4.89782857,
0.419395 , 0.4176325 , 0.4183375 , 0.4246825 ],
[ 9.18131429, 9.14314286, 9.15745714, 9.23857143, 9.26242857,
9.167 , 9.19562857, 9.25288571, 9.25288571, 9.30537143,
0.803365 , 0.8012775 , 0.8021125 , 0.8096275 ]])
# data['Q'] / data['p']
# time needed for charging of Car i in Station j
data['Pc']=np.dot(np.ones((3,1)),data['pc'])*data['Q']
# Charging fee of Car i in Station j
data['Ps']=np.dot(np.ones((3,1)),data['ps'])*data['Q']
# Service fee of Car i in Station j
data['Pp']=np.dot(np.ones((3,1)),data['pp'])*data['Tc']
# Parking fee of Car i in Station j
data['P']=data['Pc']+data['Ps']+data['Pp']
# Total fee of Car i in Station j
# Normal Charging
F1=0.3*data['D']+0.13*data['Td']+0.01*data['Tc']+0.3*data['P']
-0.13*np.dot(np.ones((3,1)),data['S'])-0.13*np.ones((3,1))*data['R']
# Urgent Charging
F2=0.3*data['D']+0.1*data['Td']+0.3*data['Tc']+0.1*data['P']
-0.1*np.dot(np.ones((3,1)),data['S'])-0.11*np.ones((3,1))*data['R']
# Rush Hour
F3=0.1*data['D']+0.3*data['Td']+0.3*data['Tc']+0.1*data['P']
-0.3*np.dot(np.ones((3,1)),data['S'])-0.11*np.ones((3,1))*data['R']
# Shortest Distance
F4=data['D']
# Arrive earliest
F5=data['Td']
# Finish Charge earliest
F6=data['Tc']
# Cheapest
F7=data['P']
# Hightest Score(Highest Satisfaction)
F8=np.dot(-np.ones((3,1)),data['S'] )
# Most spot
F9=np.dot(-np.ones((3,1)),data['R'] )
# build a function which make it easier to iterate every goal function
# function could generate every parameters
def parameters(goal):
C=goal
# calculate the row
n=C.shape[0]
# calculate the column
m=C.shape[1]
# Calculate the goal function
c=C.flatten('F')
# set the unequation restriction
Qz=np.dot(data['r'],data['D'])-np.dot(np.dot(data['q'],data['E']),np.ones((n,m)))
Qz=Qz.flatten('F')
a=np.zeros((m,n*m))
for i in range(0,m):
for j in range(i*n, n*(i+1)):
a[i:i+1,j:j+1]=1
Qz=Qz*np.ones((1,n*m))
A=np.vstack((a,Qz))
# unequation coefficient
B=np.vstack((data['R'].conj().T,np.zeros((1,1))))
# set the equation restriction
Ae = np.zeros((n,n*m))
for i in range(0,n):
for k in range(i, n*m, n):
Ae[i:i+1,k:k+1]=1
# equation coefficient
Be=np.ones((n,1))
return (c,A,B,Ae,Be)
func = [F1,F2,F3,F4,F5,F6,F7,F8,F9]
funcname = ['F1','F2','F3','F4','F5','F6','F7','F8','F9']
i=0
for goal in func:
(c,A,B,Ae,Be) = parameters(goal)
res=linprog(c,A,B,Ae,Be,bounds = (0,1))
print("---")
print(funcname[i])
print("---")
print(res)
print("***********************")
print("")
print("")
i+=1
| 0.218003 | 0.635788 |
<a href="https://colab.research.google.com/github/westjin12321/westjin12321.github.io/blob/master/24/simple_ppo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
!mkdir PPO
import os
import numpy as np
import torch as T
import torch.nn as nn
import torch.optim as optim
from torch.distributions.categorical import Categorical
class PPOMemory:
def __init__(self, batch_size):
self.states = []
self.probs = []
self.vals = []
self.actions = []
self.rewards = []
self.dones = []
self.batch_size = batch_size
def generate_batches(self):
n_states = len(self.states)
batch_start = np.arange(0, n_states, self.batch_size)
indices = np.arange(n_states, dtype=np.int64)
np.random.shuffle(indices)
batches = [indices[i:i+self.batch_size] for i in batch_start]
return np.array(self.states),\
np.array(self.actions),\
np.array(self.probs),\
np.array(self.vals),\
np.array(self.rewards),\
np.array(self.dones),\
batches
def store_memory(self, state, action, probs, vals, reward, done):
self.states.append(state)
self.actions.append(action)
self.probs.append(probs)
self.vals.append(vals)
self.rewards.append(reward)
self.dones.append(done)
def clear_memory(self):
self.states = []
self.probs = []
self.actions = []
self.rewards = []
self.dones = []
self.vals = []
class ActorNetwork(nn.Module):
def __init__(self, n_actions, input_dims, alpha,
fc1_dims=256, fc2_dims=256, chkpt_dir='PPO'):
super(ActorNetwork, self).__init__()
self.checkpoint_file = os.path.join(chkpt_dir, 'actor_torch_ppo')
self.actor = nn.Sequential(
nn.Linear(*input_dims, fc1_dims),
nn.ReLU(),
nn.Linear(fc1_dims, fc2_dims),
nn.ReLU(),
nn.Linear(fc2_dims, n_actions),
nn.Softmax(dim=-1)
)
self.optimizer = optim.Adam(self.parameters(), lr=alpha)
self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu')
self.to(self.device)
def forward(self, state):
dist = self.actor(state)
dist = Categorical(dist)
return dist
def save_checkpoint(self):
T.save(self.state_dict(), self.checkpoint_file)
def load_checkpoint(self):
self.load_state_dict(T.load(self.checkpoint_file))
class CriticNetwork(nn.Module):
def __init__(self, input_dims, alpha, fc1_dims=256, fc2_dims=256,
chkpt_dir='PPO'):
super(CriticNetwork, self).__init__()
self.checkpoint_file = os.path.join(chkpt_dir, 'critic_torch_ppo')
self.critic = nn.Sequential(
nn.Linear(*input_dims, fc1_dims),
nn.ReLU(),
nn.Linear(fc1_dims, fc2_dims),
nn.ReLU(),
nn.Linear(fc2_dims, 1)
)
self.optimizer = optim.Adam(self.parameters(), lr=alpha)
self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu')
self.to(self.device)
def forward(self, state):
value = self.critic(state)
return value
def save_checkpoint(self):
T.save(self.state_dict(), self.checkpoint_file)
def load_checkpoint(self):
self.load_state_dict(T.load(self.checkpoint_file))
class Agent:
def __init__(self, n_actions, input_dims, gamma=0.99, alpha=0.0003, gae_lambda=0.95,
policy_clip=0.2, batch_size=64, n_epochs=10):
self.gamma = gamma
self.policy_clip = policy_clip
self.n_epochs = n_epochs
self.gae_lambda = gae_lambda
self.actor = ActorNetwork(n_actions, input_dims, alpha)
self.critic = CriticNetwork(input_dims, alpha)
self.memory = PPOMemory(batch_size)
def remember(self, state, action, probs, vals, reward, done):
self.memory.store_memory(state, action, probs, vals, reward, done)
def save_models(self):
print('... saving models ...')
self.actor.save_checkpoint()
self.critic.save_checkpoint()
def load_models(self):
print('... loading models ...')
self.actor.load_checkpoint()
self.critic.load_checkpoint()
def choose_action(self, observation):
state = T.tensor([observation], dtype=T.float).to(self.actor.device)
dist = self.actor(state)
value = self.critic(state)
action = dist.sample()
probs = T.squeeze(dist.log_prob(action)).item()
action = T.squeeze(action).item()
value = T.squeeze(value).item()
return action, probs, value
def learn(self):
for _ in range(self.n_epochs):
state_arr, action_arr, old_prob_arr, vals_arr,\
reward_arr, dones_arr, batches = \
self.memory.generate_batches()
values = vals_arr
advantage = np.zeros(len(reward_arr), dtype=np.float32)
for t in range(len(reward_arr)-1):
discount = 1
a_t = 0
for k in range(t, len(reward_arr)-1):
a_t += discount*(reward_arr[k] + self.gamma*values[k+1]*\
(1-int(dones_arr[k])) - values[k])
discount *= self.gamma*self.gae_lambda
advantage[t] = a_t
advantage = T.tensor(advantage).to(self.actor.device)
values = T.tensor(values).to(self.actor.device)
for batch in batches:
states = T.tensor(state_arr[batch], dtype=T.float).to(self.actor.device)
old_probs = T.tensor(old_prob_arr[batch]).to(self.actor.device)
actions = T.tensor(action_arr[batch]).to(self.actor.device)
dist = self.actor(states)
critic_value = self.critic(states)
critic_value = T.squeeze(critic_value)
new_probs = dist.log_prob(actions)
prob_ratio = new_probs.exp() / old_probs.exp()
#prob_ratio = (new_probs - old_probs).exp()
weighted_probs = advantage[batch] * prob_ratio
weighted_clipped_probs = T.clamp(prob_ratio, 1-self.policy_clip,
1+self.policy_clip)*advantage[batch]
actor_loss = -T.min(weighted_probs, weighted_clipped_probs).mean()
returns = advantage[batch] + values[batch]
critic_loss = (returns-critic_value)**2
critic_loss = critic_loss.mean()
total_loss = actor_loss + 0.5*critic_loss
self.actor.optimizer.zero_grad()
self.critic.optimizer.zero_grad()
total_loss.backward()
self.actor.optimizer.step()
self.critic.optimizer.step()
self.memory.clear_memory()
import numpy as np
import matplotlib.pyplot as plt
def plot_learning_curve(x, scores, figure_file):
running_avg = np.zeros(len(scores))
for i in range(len(running_avg)):
running_avg[i] = np.mean(scores[max(0, i-100):(i+1)])
plt.plot(x, running_avg)
plt.title('Running average of previous 100 scores')
plt.savefig(figure_file)
import gym
import numpy as np
env = gym.make('CartPole-v0')
N = 20
batch_size = 5
n_epochs = 4
alpha = 0.0003
agent = Agent(n_actions=env.action_space.n, batch_size=batch_size,
alpha=alpha, n_epochs=n_epochs,
input_dims=env.observation_space.shape)
n_games = 300
figure_file = 'PPO/cartpole.png'
best_score = env.reward_range[0]
score_history = []
learn_iters = 0
avg_score = 0
n_steps = 0
for i in range(n_games):
observation = env.reset()
done = False
score = 0
while not done:
action, prob, val = agent.choose_action(observation)
observation_, reward, done, info = env.step(action)
n_steps += 1
score += reward
agent.remember(observation, action, prob, val, reward, done)
if n_steps % N == 0:
agent.learn()
learn_iters += 1
observation = observation_
score_history.append(score)
avg_score = np.mean(score_history[-100:])
if avg_score > best_score:
best_score = avg_score
agent.save_models()
print('episode', i, 'score %.1f' % score, 'avg score %.1f' % avg_score,
'time_steps', n_steps, 'learning_steps', learn_iters)
x = [i+1 for i in range(len(score_history))]
plot_learning_curve(x, score_history, figure_file)
```
|
github_jupyter
|
!mkdir PPO
import os
import numpy as np
import torch as T
import torch.nn as nn
import torch.optim as optim
from torch.distributions.categorical import Categorical
class PPOMemory:
def __init__(self, batch_size):
self.states = []
self.probs = []
self.vals = []
self.actions = []
self.rewards = []
self.dones = []
self.batch_size = batch_size
def generate_batches(self):
n_states = len(self.states)
batch_start = np.arange(0, n_states, self.batch_size)
indices = np.arange(n_states, dtype=np.int64)
np.random.shuffle(indices)
batches = [indices[i:i+self.batch_size] for i in batch_start]
return np.array(self.states),\
np.array(self.actions),\
np.array(self.probs),\
np.array(self.vals),\
np.array(self.rewards),\
np.array(self.dones),\
batches
def store_memory(self, state, action, probs, vals, reward, done):
self.states.append(state)
self.actions.append(action)
self.probs.append(probs)
self.vals.append(vals)
self.rewards.append(reward)
self.dones.append(done)
def clear_memory(self):
self.states = []
self.probs = []
self.actions = []
self.rewards = []
self.dones = []
self.vals = []
class ActorNetwork(nn.Module):
def __init__(self, n_actions, input_dims, alpha,
fc1_dims=256, fc2_dims=256, chkpt_dir='PPO'):
super(ActorNetwork, self).__init__()
self.checkpoint_file = os.path.join(chkpt_dir, 'actor_torch_ppo')
self.actor = nn.Sequential(
nn.Linear(*input_dims, fc1_dims),
nn.ReLU(),
nn.Linear(fc1_dims, fc2_dims),
nn.ReLU(),
nn.Linear(fc2_dims, n_actions),
nn.Softmax(dim=-1)
)
self.optimizer = optim.Adam(self.parameters(), lr=alpha)
self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu')
self.to(self.device)
def forward(self, state):
dist = self.actor(state)
dist = Categorical(dist)
return dist
def save_checkpoint(self):
T.save(self.state_dict(), self.checkpoint_file)
def load_checkpoint(self):
self.load_state_dict(T.load(self.checkpoint_file))
class CriticNetwork(nn.Module):
def __init__(self, input_dims, alpha, fc1_dims=256, fc2_dims=256,
chkpt_dir='PPO'):
super(CriticNetwork, self).__init__()
self.checkpoint_file = os.path.join(chkpt_dir, 'critic_torch_ppo')
self.critic = nn.Sequential(
nn.Linear(*input_dims, fc1_dims),
nn.ReLU(),
nn.Linear(fc1_dims, fc2_dims),
nn.ReLU(),
nn.Linear(fc2_dims, 1)
)
self.optimizer = optim.Adam(self.parameters(), lr=alpha)
self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu')
self.to(self.device)
def forward(self, state):
value = self.critic(state)
return value
def save_checkpoint(self):
T.save(self.state_dict(), self.checkpoint_file)
def load_checkpoint(self):
self.load_state_dict(T.load(self.checkpoint_file))
class Agent:
def __init__(self, n_actions, input_dims, gamma=0.99, alpha=0.0003, gae_lambda=0.95,
policy_clip=0.2, batch_size=64, n_epochs=10):
self.gamma = gamma
self.policy_clip = policy_clip
self.n_epochs = n_epochs
self.gae_lambda = gae_lambda
self.actor = ActorNetwork(n_actions, input_dims, alpha)
self.critic = CriticNetwork(input_dims, alpha)
self.memory = PPOMemory(batch_size)
def remember(self, state, action, probs, vals, reward, done):
self.memory.store_memory(state, action, probs, vals, reward, done)
def save_models(self):
print('... saving models ...')
self.actor.save_checkpoint()
self.critic.save_checkpoint()
def load_models(self):
print('... loading models ...')
self.actor.load_checkpoint()
self.critic.load_checkpoint()
def choose_action(self, observation):
state = T.tensor([observation], dtype=T.float).to(self.actor.device)
dist = self.actor(state)
value = self.critic(state)
action = dist.sample()
probs = T.squeeze(dist.log_prob(action)).item()
action = T.squeeze(action).item()
value = T.squeeze(value).item()
return action, probs, value
def learn(self):
for _ in range(self.n_epochs):
state_arr, action_arr, old_prob_arr, vals_arr,\
reward_arr, dones_arr, batches = \
self.memory.generate_batches()
values = vals_arr
advantage = np.zeros(len(reward_arr), dtype=np.float32)
for t in range(len(reward_arr)-1):
discount = 1
a_t = 0
for k in range(t, len(reward_arr)-1):
a_t += discount*(reward_arr[k] + self.gamma*values[k+1]*\
(1-int(dones_arr[k])) - values[k])
discount *= self.gamma*self.gae_lambda
advantage[t] = a_t
advantage = T.tensor(advantage).to(self.actor.device)
values = T.tensor(values).to(self.actor.device)
for batch in batches:
states = T.tensor(state_arr[batch], dtype=T.float).to(self.actor.device)
old_probs = T.tensor(old_prob_arr[batch]).to(self.actor.device)
actions = T.tensor(action_arr[batch]).to(self.actor.device)
dist = self.actor(states)
critic_value = self.critic(states)
critic_value = T.squeeze(critic_value)
new_probs = dist.log_prob(actions)
prob_ratio = new_probs.exp() / old_probs.exp()
#prob_ratio = (new_probs - old_probs).exp()
weighted_probs = advantage[batch] * prob_ratio
weighted_clipped_probs = T.clamp(prob_ratio, 1-self.policy_clip,
1+self.policy_clip)*advantage[batch]
actor_loss = -T.min(weighted_probs, weighted_clipped_probs).mean()
returns = advantage[batch] + values[batch]
critic_loss = (returns-critic_value)**2
critic_loss = critic_loss.mean()
total_loss = actor_loss + 0.5*critic_loss
self.actor.optimizer.zero_grad()
self.critic.optimizer.zero_grad()
total_loss.backward()
self.actor.optimizer.step()
self.critic.optimizer.step()
self.memory.clear_memory()
import numpy as np
import matplotlib.pyplot as plt
def plot_learning_curve(x, scores, figure_file):
running_avg = np.zeros(len(scores))
for i in range(len(running_avg)):
running_avg[i] = np.mean(scores[max(0, i-100):(i+1)])
plt.plot(x, running_avg)
plt.title('Running average of previous 100 scores')
plt.savefig(figure_file)
import gym
import numpy as np
env = gym.make('CartPole-v0')
N = 20
batch_size = 5
n_epochs = 4
alpha = 0.0003
agent = Agent(n_actions=env.action_space.n, batch_size=batch_size,
alpha=alpha, n_epochs=n_epochs,
input_dims=env.observation_space.shape)
n_games = 300
figure_file = 'PPO/cartpole.png'
best_score = env.reward_range[0]
score_history = []
learn_iters = 0
avg_score = 0
n_steps = 0
for i in range(n_games):
observation = env.reset()
done = False
score = 0
while not done:
action, prob, val = agent.choose_action(observation)
observation_, reward, done, info = env.step(action)
n_steps += 1
score += reward
agent.remember(observation, action, prob, val, reward, done)
if n_steps % N == 0:
agent.learn()
learn_iters += 1
observation = observation_
score_history.append(score)
avg_score = np.mean(score_history[-100:])
if avg_score > best_score:
best_score = avg_score
agent.save_models()
print('episode', i, 'score %.1f' % score, 'avg score %.1f' % avg_score,
'time_steps', n_steps, 'learning_steps', learn_iters)
x = [i+1 for i in range(len(score_history))]
plot_learning_curve(x, score_history, figure_file)
| 0.875468 | 0.773174 |
# Activation Functions
Each node in a neural net has an activation function. While it is theoretically possible for each individual node to have a unique activation function, it's quite uncommon. Typically, every node in any particular layer uses the same activation function.
Consider this image of a single node:

In this case, the "activation function" is the sigmoid function. That function looks like this:
```
import matplotlib.pyplot as plt
import numpy as np
# np.e is Euler's constant, the base of the natural logarithm
def sigmoid(x):
return (1 / (1 + np.exp(-x)))
# Construct a range to plot
r = np.linspace(-10, 10, 100)
plt.plot(r, sigmoid(r), 'b')
plt.show()
```
This function is a common choice, and is the O.G. activation function. It has some important and nice properties:
* is differentiable, which is very important because of how gradient descent and backpropogation work.
* Is bounded between 0 and 1.
It also has some problems, in particlar one of the reasons sigmoid is falling out of favor is called the vanishing gradient problem. Consider this plot with sigmoid and it's derivative:
```
# Yes, it's freaky that the derivative involves the function itself.
# Calculus is cool, but we're not going to talk about that today!
def sigmoid_prime(x):
return sigmoid(x) * (1 - sigmoid(x))
r = np.linspace(-10, 10, 100)
plt.plot(r, sigmoid(r), 'b')
plt.plot(r, sigmoid_prime(r), 'r')
plt.show()
```
Notice that at both ends of the range the derivative (red line) approaches 0. In terms of tuning neural networks, this means that the corrections applied based on the loss function can become very small—causing the node to effectively stop learning. This is especially true of neural networks with several layers, because the vanishing gradient problem stacks across the layers.
Let's examine this problem in context, this code should look familiar from previous exercises:
```
# Imports and formatting the data
# See previous lab if this is confusing
from matplotlib import pyplot as plt
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
num_classes = 10
image_size = 784
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_data = training_images.reshape(training_images.shape[0], image_size)
test_data = test_images.reshape(test_images.shape[0], image_size)
training_labels = to_categorical(training_labels, num_classes)
test_labels = to_categorical(test_labels, num_classes)
# A helpful function we'll be using all over the place to plot training information:
def plot_training_history(history, model):
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['training', 'validation'], loc='best')
plt.show()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['training', 'validation'], loc='best')
plt.show()
loss, accuracy = model.evaluate(test_data, test_labels, verbose=False)
print(f'Test loss: {loss:.3}')
print(f'Test accuracy: {accuracy:.3}')
model = Sequential()
model.add(Dense(units=10, activation='sigmoid', input_shape=(image_size,)))
for _ in range(10):
model.add(Dense(units=10, activation='sigmoid'))
model.add(Dense(units=num_classes, activation='softmax'))
model.compile(optimizer="sgd", loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
history = model.fit(training_data, training_labels, batch_size=128, epochs=20, verbose=False, validation_split=.1)
plot_training_history(history, model)
```
Notice that the network didn't REALLY learn anything after the first epoch... we could guess that the network is too complex, but consider this:
```
model = Sequential()
model.add(Dense(units=10, activation='relu', input_shape=(image_size,)))
for _ in range(10):
model.add(Dense(units=10, activation='relu'))
model.add(Dense(units=num_classes, activation='softmax'))
model.compile(optimizer="sgd", loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
history = model.fit(training_data, training_labels, batch_size=128, epochs=20, verbose=False, validation_split=.1)
plot_training_history(history, model)
```
These results are not great, because this architecture isn't great, but changing the activation function to the Rectified Linear Unit (often called ReLU) we dramatically improved the performance of the network. This is the vanishing gradient problem rearing it's head.
Why doesn't ReLU suffer from the vanishing gradient? Let's define and plot it, the function is almost hilariously simple:
```
# This function is hard to read because we're applying it to
# numpy arrays, but for each item in x we return max(0, x[i])
def relu(x):
return np.maximum(x, np.zeros(len(x)))
# This function is non-continuous, but the derivative can be
# expressed as a very simple discrete function that works for
# our purpose, if x[i] > 0 return 1, else return 0:
def relu_prime(x):
return np.array([1 if num > 0 else 0 for num in x])
# Construct a range to plot
r = np.linspace(-10, 10, 100)
plt.plot(r, relu(r), 'b')
plt.plot(r, relu_prime(r), 'r')
plt.show()
```
ReLU still has a kind of vanishing gradient problem, in fact the gradient can simply be 0, and once that happens the weights attached to that node will no longer be updated at all!
The simplicity of this function servers as an important reminder about neural networks and machine learning in general: fundamentally we are combining a lot of very simple things, and repeating a simple process MANY MANY times. The result is complex, but the procecss itself is built of simple parts.
With that in mind, brilliant machine learning specialists came up with a simple solution to ReLU's problems. They invented a function called "Leaky ReLU":
```
# For values greater than 0, leaky ReLU is the same as ReLU.
# For values less than 0, we return x[i] * 0.01 instead of just 0
# Now the gradient cannot die, because the line always has a slope.
def leaky_relu(x):
return np.array([num if num > 0 else num * .01 for num in x])
def leaky_relu_prime(x):
return np.array([1 if num > 0 else .01 for num in x])
r = np.linspace(-10, 10, 100)
plt.plot(r, leaky_relu(r), 'b')
plt.plot(r, leaky_relu_prime(r), 'r')
plt.show()
```
Leaky is not strictly better, and it can sometimes be hard to know when it will be better or not. As with many neural network tasks, the best way to prove something is empirically. Lets see if Leaky ReLU improves our 10 layer network
```
# Using Leakly ReLU is slightly different in Keras, which can be annoying.
# Additionally, Keras allows us to choose any slope we want for the "leaky" part
# rather than being statically 0.01 as in the above two functions.
from keras.layers import LeakyReLU
model = Sequential()
model.add(Dense(units=10, input_shape=(image_size,)))
model.add(LeakyReLU(alpha=.01))
for _ in range(10):
model.add(Dense(units=10))
model.add(LeakyReLU(alpha=.01))
model.add(Dense(units=num_classes, activation='softmax'))
model.compile(optimizer="sgd", loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
history = model.fit(training_data, training_labels, batch_size=128, epochs=20, verbose=False, validation_split=.1)
plot_training_history(history, model)
```
There are other activation functions, and there is ongoing research into which ones perform best and experimenting with new activation functions.
In addition to the vanishing and dying gradient problems, another factor in the performance of activation functions is how efficent they are to compute, and how efficent their derivatives are to compute. Remember that we're computing these functions billions of times (or more!) during training. Relu is VERY FAST to compute, and so is it's derivative. Sigmoid, tanh, and some other commonly used activations are more expensive.
Also remember that it's not nessesary to use the same activation for every layer in a network! For example, starting with a sigmoid and following up with ReLU's can work just fine, although it is rather uncommon:
```
model = Sequential()
model.add(Dense(units=10, activation='sigmoid', input_shape=(image_size,)))
model.add(Dense(units=10, activation='tanh'))
model.add(Dense(units=10, activation='exponential'))
model.add(Dense(units=10))
model.add(LeakyReLU(alpha=.01))
model.add(Dense(units=10))
model.add(LeakyReLU(alpha=.05))
model.add(Dense(units=10))
model.add(LeakyReLU(alpha=.3))
model.add(Dense(units=num_classes, activation='softmax'))
model.compile(optimizer="sgd", loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
history = model.fit(training_data, training_labels, batch_size=128, epochs=20, verbose=False, validation_split=.1)
plot_training_history(history, model)
```
A rule of thumb: Things are changing quickly. Do some quick research before you build a new model to determine if there is a new "activation function of the week". Use that one. If it doesn't produce results, try a different one. Repeat until one works, or you have exhausted the activation functions that you know of. At that point, you may need to collect more data, change your architecture, or try a different kind of model.
At the time of this writing, one of the most popular activation functions is the Scaled Exponential Linear Unit (SELU). This activation is another modified ReLU, where the values greater than zero are still a linear function, the values below zero are an exponential curve, and the function scales the output to avoid a problem called "exploding gradient" which is the opposite of a dying or vanishing gradient:
```
model = Sequential()
model.add(Dense(units=10, activation='selu', input_shape=(image_size,)))
for _ in range(10):
model.add(Dense(units=10, activation='selu'))
model.add(Dense(units=num_classes, activation='softmax'))
model.compile(optimizer="sgd", loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
history = model.fit(training_data, training_labels, batch_size=128, epochs=20, verbose=False, validation_split=.1)
plot_training_history(history, model)
```
## The Importance of Non-Linearity
In order to satisfy the Universal Function Approximation theorem we must choose activation functions that are not strictly linear. Even ReLU counts, but if we only use linear activation functions then our neural networks, no matter how complex, can only learn to approximate linear functions themselves. See [Deep Learning and Neural Network's Chapter 5](http://neuralnetworksanddeeplearning.com/chap5.html) for a comprehensive proof of this.
## Special Cases
While many of these activation functions are "general purpose", especially in the hidden layers, there are a handful of important activation functions that serve special purposes. The softmax function is one such activation function that is widely used.
Softmax is used to produce N output values that always sum to one. It is almost always used in the final layer of classification networks, and we interpret the results as the proababilities or confidence of our network's predictions. [Read more about softmax](https://medium.com/data-science-bootcamp/understand-the-softmax-function-in-minutes-f3a59641e86d)
|
github_jupyter
|
import matplotlib.pyplot as plt
import numpy as np
# np.e is Euler's constant, the base of the natural logarithm
def sigmoid(x):
return (1 / (1 + np.exp(-x)))
# Construct a range to plot
r = np.linspace(-10, 10, 100)
plt.plot(r, sigmoid(r), 'b')
plt.show()
# Yes, it's freaky that the derivative involves the function itself.
# Calculus is cool, but we're not going to talk about that today!
def sigmoid_prime(x):
return sigmoid(x) * (1 - sigmoid(x))
r = np.linspace(-10, 10, 100)
plt.plot(r, sigmoid(r), 'b')
plt.plot(r, sigmoid_prime(r), 'r')
plt.show()
# Imports and formatting the data
# See previous lab if this is confusing
from matplotlib import pyplot as plt
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
num_classes = 10
image_size = 784
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_data = training_images.reshape(training_images.shape[0], image_size)
test_data = test_images.reshape(test_images.shape[0], image_size)
training_labels = to_categorical(training_labels, num_classes)
test_labels = to_categorical(test_labels, num_classes)
# A helpful function we'll be using all over the place to plot training information:
def plot_training_history(history, model):
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['training', 'validation'], loc='best')
plt.show()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['training', 'validation'], loc='best')
plt.show()
loss, accuracy = model.evaluate(test_data, test_labels, verbose=False)
print(f'Test loss: {loss:.3}')
print(f'Test accuracy: {accuracy:.3}')
model = Sequential()
model.add(Dense(units=10, activation='sigmoid', input_shape=(image_size,)))
for _ in range(10):
model.add(Dense(units=10, activation='sigmoid'))
model.add(Dense(units=num_classes, activation='softmax'))
model.compile(optimizer="sgd", loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
history = model.fit(training_data, training_labels, batch_size=128, epochs=20, verbose=False, validation_split=.1)
plot_training_history(history, model)
model = Sequential()
model.add(Dense(units=10, activation='relu', input_shape=(image_size,)))
for _ in range(10):
model.add(Dense(units=10, activation='relu'))
model.add(Dense(units=num_classes, activation='softmax'))
model.compile(optimizer="sgd", loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
history = model.fit(training_data, training_labels, batch_size=128, epochs=20, verbose=False, validation_split=.1)
plot_training_history(history, model)
# This function is hard to read because we're applying it to
# numpy arrays, but for each item in x we return max(0, x[i])
def relu(x):
return np.maximum(x, np.zeros(len(x)))
# This function is non-continuous, but the derivative can be
# expressed as a very simple discrete function that works for
# our purpose, if x[i] > 0 return 1, else return 0:
def relu_prime(x):
return np.array([1 if num > 0 else 0 for num in x])
# Construct a range to plot
r = np.linspace(-10, 10, 100)
plt.plot(r, relu(r), 'b')
plt.plot(r, relu_prime(r), 'r')
plt.show()
# For values greater than 0, leaky ReLU is the same as ReLU.
# For values less than 0, we return x[i] * 0.01 instead of just 0
# Now the gradient cannot die, because the line always has a slope.
def leaky_relu(x):
return np.array([num if num > 0 else num * .01 for num in x])
def leaky_relu_prime(x):
return np.array([1 if num > 0 else .01 for num in x])
r = np.linspace(-10, 10, 100)
plt.plot(r, leaky_relu(r), 'b')
plt.plot(r, leaky_relu_prime(r), 'r')
plt.show()
# Using Leakly ReLU is slightly different in Keras, which can be annoying.
# Additionally, Keras allows us to choose any slope we want for the "leaky" part
# rather than being statically 0.01 as in the above two functions.
from keras.layers import LeakyReLU
model = Sequential()
model.add(Dense(units=10, input_shape=(image_size,)))
model.add(LeakyReLU(alpha=.01))
for _ in range(10):
model.add(Dense(units=10))
model.add(LeakyReLU(alpha=.01))
model.add(Dense(units=num_classes, activation='softmax'))
model.compile(optimizer="sgd", loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
history = model.fit(training_data, training_labels, batch_size=128, epochs=20, verbose=False, validation_split=.1)
plot_training_history(history, model)
model = Sequential()
model.add(Dense(units=10, activation='sigmoid', input_shape=(image_size,)))
model.add(Dense(units=10, activation='tanh'))
model.add(Dense(units=10, activation='exponential'))
model.add(Dense(units=10))
model.add(LeakyReLU(alpha=.01))
model.add(Dense(units=10))
model.add(LeakyReLU(alpha=.05))
model.add(Dense(units=10))
model.add(LeakyReLU(alpha=.3))
model.add(Dense(units=num_classes, activation='softmax'))
model.compile(optimizer="sgd", loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
history = model.fit(training_data, training_labels, batch_size=128, epochs=20, verbose=False, validation_split=.1)
plot_training_history(history, model)
model = Sequential()
model.add(Dense(units=10, activation='selu', input_shape=(image_size,)))
for _ in range(10):
model.add(Dense(units=10, activation='selu'))
model.add(Dense(units=num_classes, activation='softmax'))
model.compile(optimizer="sgd", loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
history = model.fit(training_data, training_labels, batch_size=128, epochs=20, verbose=False, validation_split=.1)
plot_training_history(history, model)
| 0.922097 | 0.987104 |
# Transformations
Apart from modifying graphs manually using the SDFG API, you can also define more complex behavior that matches certain patterns in SDFGs and makes changes. This behavior is expressed in classes called `Transformation`s. Transformations are a powerful tool to optimize applications in DaCe. You can go from naive code to state-of-the-art performance using only transformations.
There are two general types of transformations: **pattern-matching transformations** (extending the `Transformation` class) and **subgraph transformations** (extending the `SubgraphTransformation` class). The former is based on one or more specific subgraph expressions, and the latter can be applied to any subgraph that passes the conditions. Internally, there are two methods to a Transformation: `can_be_applied`, which returns True if it can be applied on a given subgraph; and `apply`, which modifies the graph using the SDFG API. Some transformations run automatically on each graph (we call them "strict" since they strictly improve the performance of an SDFG), and others have to be called manually.
You can find a list of the built-in standard transformations [here](https://spcldace.readthedocs.io/en/latest/source/dace.transformation.html). While these transformations cover many use-cases, they cannot cover everything (for example, domain-specific behavior). Thus, Transformations are easily extensible and [below](#Creating-New-Transformations) we show how to register a new one. You can register your transformations to be pattern-based, subgraph-based, strict, or not, upon defining a new class.
This tutorial will deal with the different ways transformations can be applied on code:
* [Apply anywhere or everywhere](#Applying-Transformations)
* [Enumerate matches of a transformation](#Enumerating-Matches)
* [Apply at a specific location](#Apply-to-Specific-Location)
* [Interactive optimization](#Interactive-Optimization) ([command-line](#Command-line-interface), [Visual Studio Code](#Visual-Studio-Code))
* [Create your own transformation](#Creating-New-Transformations)
We will use the following example throughout this tutorial:
```
import dace
@dace.function
def dbladd(A: dace.float64[1000, 1000], B: dace.float64[1000, 1000]):
dbl = B
return A + dbl * B
```
## Applying Transformations
The easiest way to apply a transformation is to import the Transformation subclass and call `apply_transformations` or `apply_transformations_repeated` on the SDFG. The methods accept a transformation or a list of transformations, their parameters, and other parameters (for more info, see its [documentation](https://spcldace.readthedocs.io/en/latest/source/dace.sdfg.html#dace.sdfg.sdfg.SDFG.apply_transformations)).
To demonstrate transformations, we will first show the raw SDFG of `dbladd`, without strict transformations:
```
sdfg = dbladd.to_sdfg(strict=False)
sdfg
```
There are four states in this SDFG, and an unnecessary copy to `dbl`. In order to fuse the states, we can apply the `StateFusion` transformation:
```
from dace.transformation.interstate import StateFusion
sdfg.apply_transformations(StateFusion)
sdfg
```
This fused the first two states. Since we want to fuse the entire graph, we can use the method that repeatedly applies the transformation until no more states can be fused without breaking the correctness of the graph:
```
sdfg.apply_transformations_repeated(StateFusion)
sdfg
```
Now that the dataflow aspects of the graph are clearer, it is easy to see that the `dbl` array is redundant. One of the strict transformations in the DaCe standard library deals with redundant array copies when one array is transient and unused anywhere else. To invoke this transformation, we can either import it directly, or simply try to apply all strict transformations. Note that this happens automatically when a Python function is defined without our special `strict=False` argument:
```
sdfg.apply_strict_transformations()
sdfg
```
## Enumerating Matches
As graphs grow larger, there will be more than one match to a transformation. For pattern matching transformations, we can enumerate the matching subgraphs in an SDFG for a given transformation using the `dace.transformation.optimizer.Optimizer` class.
In the example below, we try to find which maps can be tiled (to increase the locality of the computation) within the current SDFG:
```
from dace.transformation.dataflow import MapTiling
from dace.transformation.optimizer import Optimizer
for xform in Optimizer(sdfg).get_pattern_matches(patterns=[MapTiling]):
print('Match:', xform.print_match(sdfg))
```
The transformation can then be applied by calling `xform.apply(sdfg)`.
### Custom Subgraph Enumeration
If you want to match a certain subgraph (in the SDFG or within a state) without creating a transformation, you can use the `enumerate_matches` API in `dace.transformation.pattern_matching`. It uses the same mechanism as transformations but can be used for general pattern matching:
```
from dace.transformation.pattern_matching import enumerate_matches
from dace.sdfg import utils as sdutil # For creating path graphs
# Construct subgraph pattern (MapExit -> AccessNode -> MapEntry)
pattern = sdutil.node_path_graph(dace.nodes.MapExit, dace.nodes.AccessNode,
dace.nodes.MapEntry)
# Loop over matches
for subgraph in enumerate_matches(sdfg, pattern):
print("Match found in state", subgraph.graph.label, ". Nodes:", subgraph.nodes())
```
## Apply to Specific Location
We can also invoke transformations at specific locations using the `apply_to` static function of each transformation. In each transformation class, a list of statically constructed nodes define the transformation structure. For example, in `MapFusion`, there are three such nodes, called `first_map_exit`, `array`, and `second_map_entry`. If you know which maps to apply the transformation to, simply use these three names as keyword arguments to the `apply_to` function. Below is an example that finds the multiplication map exit, addition map entry, and the array between them:
```
# Since there is only one state (thanks to StateFusion), we can use the first one in the SDFG
state = sdfg.node(0)
# The multiplication map is called "_Mult__map" (see above graph), we can query it
mult_exit = next(n for n in state.nodes() if isinstance(n, dace.nodes.MapExit) and n.label == '_Mult__map')
# Same goes for the addition entry
add_entry = next(n for n in state.nodes() if isinstance(n, dace.nodes.MapEntry) and n.label == '_Add__map')
# Since all redundant arrays have been removed by strict transformations, we can get the only transient
# array that remains in the graph
transient = next(aname for aname, desc in sdfg.arrays.items() if desc.transient)
access_node = next(n for n in state.nodes() if isinstance(n, dace.nodes.AccessNode) and n.data == transient)
# We will apply the transformation on these three nodes
print(mult_exit, '->', access_node, '->', add_entry)
from dace.transformation.dataflow import MapFusion
MapFusion.apply_to(sdfg,
first_map_exit=mult_exit,
array=access_node,
second_map_entry=add_entry)
sdfg
```
and now the two maps are fused.
### Subgraph Transformations
The same can be applied with subgraph transformations, but a subgraph is required instead of a pattern. In the following example we reload the SDFG (in the default mode, namely with strict transformations), and then apply `SubgraphFusion` on the entire state (namely all of its nodes, or `state.nodes()`). The result will be similar to fusing the two maps as above, but can generalize to fuse any number of maps, parallel regions, and other cases.
```
from dace.transformation.subgraph import SubgraphFusion
sdfg = dbladd.to_sdfg()
# Single-state SDFG
state = sdfg.node(0)
SubgraphFusion.apply_to(sdfg, state.nodes())
sdfg
```
## Interactive Optimization
Sometimes it is useful to apply transformations in sequence interactively. To open the prompt from Jupyter or Python, call `sdfg.optimize()`:
```
sdfg.optimize()
```
The prompt can be used with numbers (e.g., `7` for the 8th transformation) or names (`MapExpansion$0` is the first occurrence of `MapExpansion`). If parameters are given, as in the above example, they are called as it was a Python dictionary: `MapTiling$0(tile_sizes=(128,))`.
If the "Enter" key is pressed, the SDFG is no longer transformed and the function returns with the resulting graph.
Internally, the default behavior calls the SDFG console optimizer (`dace.transformation.optimizer.SDFGOptimizer`). This can be modified in the configuration value `optimizer.interface`.
### Command-line interface
The console interactive optimizer can also be called from the command line directly, through the `sdfgcc` tool:
```sh
sdfgcc --optimize path/to/file.sdfg
```
You could also trigger the command-line interface every time a `@dace` function is called. It can be done through the configuration (`optimizer.transform_on_call`), or by setting the environment variable `DACE_optimizer_transform_on_call` to `1`.
Example:
```sh
DACE_optimizer_transform_on_call=1 python myfile.py
```
### Visual Studio Code
An extension that integrates DaCe into VSCode can be used to interactively edit and transform SDFGs.
To install it, go to the [VSCode Marketplace](https://marketplace.visualstudio.com/items?itemName=phschaad.sdfv) and download the DaCe plugin. Alternatively, open an .sdfg file in VSCode, or search for the extension directly.
Upon opening an SDFG file, the viewer will prompt for transformations in the "SDFG Optimization" pane. As you change the view (panning, zooming, collapsing nodes), the transformations under "Viewport" will change.
Selecting nodes (through single click, ctrl-click, or the box select mode at the top pane) will add transformations and matching subgraph transformations to the "Selection" pane. History appears at the bottom and saves as part of the SDFG file, which you can then use to revert and apply new transformations. See the example below:

# Creating New Transformations
Extending the standard transformations is easy. New transformations can be used for domain-specific optimizations, or simply wrapping expertise gathered over time. In pattern-based transformations, there are three main parts to an implementation: the **pattern(s)**, the **match** function, and the **replacement** (apply) method. Subgraph transformations behave exactly the same, but without the pattern part.
A pattern-based transformation extends the `dace.transformation.transformation.Transformation` class, whereas subgraph transformation extends `SubgraphTransformation` from the same module. There are several helper functions in `dace.transformation.helpers` and `dace.transformation.subgraph.helpers` that may make your life easier while writing transformations, please check them out in the [documentation](https://spcldace.readthedocs.io/en/latest/source/dace.transformation.html).
In this section, we will make a new pattern-based transformation that takes care of the SDFG we made in the last section:
```
sdfg
```
As you can see, there is an unnecessary `__tmp1` transient array between the two tasklets, as a result of `SubgraphFusion`. We can make a "Redundant array between tasklets" transformation that checks for such cases, and removes that array if it is not used anywhere else, directly connecting the two tasklets instead.
Using the three parts, we can define a pattern-based transformation:
1. **Pattern**: Our pattern graph should be `Tasklet -> AccessNode -> Tasklet`, which is the minimal subgraph in which this occurs. Since the transformation matches within a state, we will register it as a `singlestate` transformation.
2. **Match**: We should only match such a subgaph if the array (a) is only a scalar or size 1, (b) is transient (i.e., not defined outside this SDFG), and (c) never used again apart from between those two tasklets. Only this way can we guarantee the correctness of the transformed program.
3. **Replacement**: If the transformation is matched, we will remove the array and reconnect the tasklets together.
For the pattern part, we must construct node objects as static fields within the class (that must start with an underscore in order to not be recognized as properties). Some of them require arguments, but anything can be set there. Then, we should define an implementation of the `expressions` class method to state how those node objects should be connected.
The match and replacement parts are implemented by the `can_be_applied` class method, returning a boolean for a specific subgraph candidate, and the `apply` instance method, which modifies the given SDFG using the SDFG API.
We can now start implementing the transformation:
```
from dace.transformation.transformation import Transformation
from dace.sdfg import utils as sdutil
from dace import registry
@registry.autoregister_params(singlestate=True) # Important to register transformation as single-state
class RedundantArrayTasklet(Transformation):
""" Removes a redundant transient array if and only if it is between two tasklets. """
# Pattern: define pattern nodes (note the underscore prefix in the field name)
_tasklet_a = dace.nodes.Tasklet('')
_array = dace.nodes.AccessNode('')
_tasklet_b = dace.nodes.Tasklet('')
# This method returns a list of graphs that represent the pattern
@classmethod
def expressions(cls):
# We have only one expression, and it is a path graph between the three nodes
return [sdutil.node_path_graph(cls._tasklet_a, cls._array, cls._tasklet_b)]
# Match function
@classmethod
def can_be_applied(cls, graph, candidate, expr_index, sdfg, strict=False):
# Getting the actual node in the graph requires querying the subgraph for it
array_node = graph.node(candidate[cls._array])
# Get data descriptor from SDFG registry and access node
desc = sdfg.arrays[array_node.data]
# Match (a): Check array size
if desc.total_size != 1:
return False
# Match (b): Check if transient
if not desc.transient:
return False
# Match (c): Check if used again in any state in this SDFG
if len([node for state in sdfg.nodes()
for node in state.nodes()
if isinstance(node, dace.nodes.AccessNode)
and node.data == array_node.data]) > 1:
return False
# Match (c): Check if any other tasklet uses this transient
if graph.in_degree(array_node) + graph.out_degree(array_node) != 2:
return False
# Match found!
return True
# Replacement (note that this is a method of a transformation instance)
def apply(self, sdfg):
# Get the relevant SDFG state to work with
state = sdfg.node(self.state_id)
# Query the state for the actual node
array_node = state.node(self.subgraph[self._array])
# Get incoming and outgoing edges of the access node
# (there are only one of each according to `can_be_applied`)
in_edge = state.in_edges(array_node)[0]
out_edge = state.out_edges(array_node)[0]
# Construct a new edge between the two nodes, using the input/output
# nodes and connectors
state.add_edge(in_edge.src, in_edge.src_conn,
out_edge.dst, out_edge.dst_conn,
dace.Memlet())
# Finally, remove the redundant array node from the graph
state.remove_node(array_node)
```
Now that the transformation is implemented, we can check if it works:
```
sdfg.apply_transformations(RedundantArrayTasklet)
```
As the return value states the number of times a transformation was applied, the transformation was applied once. Let's look at the graph:
```
sdfg
```
The node is now removed.
### Composing Transformations
Transformations can call other transformations to create powerful compositions and make verification easier. Simply use one of the APIs to invoke a transformation (such as `apply_to`) within the code of another transformation to do so.
### Optimization and Customization
There are more methods you can implement to optimize transformations:
* `annotates_memlets`: If the method returns True, memlets will not be propagated after transformation is applied (for performance and/or overriding default propagation behavior).
* `match_to_str`: Returns a string-representation of the match to customize printout in the command-line interface.
|
github_jupyter
|
import dace
@dace.function
def dbladd(A: dace.float64[1000, 1000], B: dace.float64[1000, 1000]):
dbl = B
return A + dbl * B
sdfg = dbladd.to_sdfg(strict=False)
sdfg
from dace.transformation.interstate import StateFusion
sdfg.apply_transformations(StateFusion)
sdfg
sdfg.apply_transformations_repeated(StateFusion)
sdfg
sdfg.apply_strict_transformations()
sdfg
from dace.transformation.dataflow import MapTiling
from dace.transformation.optimizer import Optimizer
for xform in Optimizer(sdfg).get_pattern_matches(patterns=[MapTiling]):
print('Match:', xform.print_match(sdfg))
from dace.transformation.pattern_matching import enumerate_matches
from dace.sdfg import utils as sdutil # For creating path graphs
# Construct subgraph pattern (MapExit -> AccessNode -> MapEntry)
pattern = sdutil.node_path_graph(dace.nodes.MapExit, dace.nodes.AccessNode,
dace.nodes.MapEntry)
# Loop over matches
for subgraph in enumerate_matches(sdfg, pattern):
print("Match found in state", subgraph.graph.label, ". Nodes:", subgraph.nodes())
# Since there is only one state (thanks to StateFusion), we can use the first one in the SDFG
state = sdfg.node(0)
# The multiplication map is called "_Mult__map" (see above graph), we can query it
mult_exit = next(n for n in state.nodes() if isinstance(n, dace.nodes.MapExit) and n.label == '_Mult__map')
# Same goes for the addition entry
add_entry = next(n for n in state.nodes() if isinstance(n, dace.nodes.MapEntry) and n.label == '_Add__map')
# Since all redundant arrays have been removed by strict transformations, we can get the only transient
# array that remains in the graph
transient = next(aname for aname, desc in sdfg.arrays.items() if desc.transient)
access_node = next(n for n in state.nodes() if isinstance(n, dace.nodes.AccessNode) and n.data == transient)
# We will apply the transformation on these three nodes
print(mult_exit, '->', access_node, '->', add_entry)
from dace.transformation.dataflow import MapFusion
MapFusion.apply_to(sdfg,
first_map_exit=mult_exit,
array=access_node,
second_map_entry=add_entry)
sdfg
from dace.transformation.subgraph import SubgraphFusion
sdfg = dbladd.to_sdfg()
# Single-state SDFG
state = sdfg.node(0)
SubgraphFusion.apply_to(sdfg, state.nodes())
sdfg
sdfg.optimize()
sdfgcc --optimize path/to/file.sdfg
DACE_optimizer_transform_on_call=1 python myfile.py
sdfg
from dace.transformation.transformation import Transformation
from dace.sdfg import utils as sdutil
from dace import registry
@registry.autoregister_params(singlestate=True) # Important to register transformation as single-state
class RedundantArrayTasklet(Transformation):
""" Removes a redundant transient array if and only if it is between two tasklets. """
# Pattern: define pattern nodes (note the underscore prefix in the field name)
_tasklet_a = dace.nodes.Tasklet('')
_array = dace.nodes.AccessNode('')
_tasklet_b = dace.nodes.Tasklet('')
# This method returns a list of graphs that represent the pattern
@classmethod
def expressions(cls):
# We have only one expression, and it is a path graph between the three nodes
return [sdutil.node_path_graph(cls._tasklet_a, cls._array, cls._tasklet_b)]
# Match function
@classmethod
def can_be_applied(cls, graph, candidate, expr_index, sdfg, strict=False):
# Getting the actual node in the graph requires querying the subgraph for it
array_node = graph.node(candidate[cls._array])
# Get data descriptor from SDFG registry and access node
desc = sdfg.arrays[array_node.data]
# Match (a): Check array size
if desc.total_size != 1:
return False
# Match (b): Check if transient
if not desc.transient:
return False
# Match (c): Check if used again in any state in this SDFG
if len([node for state in sdfg.nodes()
for node in state.nodes()
if isinstance(node, dace.nodes.AccessNode)
and node.data == array_node.data]) > 1:
return False
# Match (c): Check if any other tasklet uses this transient
if graph.in_degree(array_node) + graph.out_degree(array_node) != 2:
return False
# Match found!
return True
# Replacement (note that this is a method of a transformation instance)
def apply(self, sdfg):
# Get the relevant SDFG state to work with
state = sdfg.node(self.state_id)
# Query the state for the actual node
array_node = state.node(self.subgraph[self._array])
# Get incoming and outgoing edges of the access node
# (there are only one of each according to `can_be_applied`)
in_edge = state.in_edges(array_node)[0]
out_edge = state.out_edges(array_node)[0]
# Construct a new edge between the two nodes, using the input/output
# nodes and connectors
state.add_edge(in_edge.src, in_edge.src_conn,
out_edge.dst, out_edge.dst_conn,
dace.Memlet())
# Finally, remove the redundant array node from the graph
state.remove_node(array_node)
sdfg.apply_transformations(RedundantArrayTasklet)
sdfg
| 0.659186 | 0.992139 |
## 1. TV, halftime shows, and the Big Game
<p>Whether or not you like football, the Super Bowl is a spectacle. There's a little something for everyone at your Super Bowl party. Drama in the form of blowouts, comebacks, and controversy for the sports fan. There are the ridiculously expensive ads, some hilarious, others gut-wrenching, thought-provoking, and weird. The half-time shows with the biggest musicians in the world, sometimes <a href="https://youtu.be/ZD1QrIe--_Y?t=14">riding giant mechanical tigers</a> or <a href="https://youtu.be/mjrdywp5nyE?t=62">leaping from the roof of the stadium</a>. It's a show, baby. And in this notebook, we're going to find out how some of the elements of this show interact with each other. After exploring and cleaning our data a little, we're going to answer questions like:</p>
<ul>
<li>What are the most extreme game outcomes?</li>
<li>How does the game affect television viewership?</li>
<li>How have viewership, TV ratings, and ad cost evolved over time?</li>
<li>Who are the most prolific musicians in terms of halftime show performances?</li>
</ul>
<p><img src="https://assets.datacamp.com/production/project_684/img/left_shark.jpg" alt="Left Shark Steals The Show">
<em><a href="https://www.flickr.com/photos/huntleypaton/16464994135/in/photostream/">Left Shark Steals The Show</a>. Katy Perry performing at halftime of Super Bowl XLIX. Photo by Huntley Paton. Attribution-ShareAlike 2.0 Generic (CC BY-SA 2.0).</em></p>
<p>The dataset we'll use was <a href="https://en.wikipedia.org/wiki/Web_scraping">scraped</a> and polished from Wikipedia. It is made up of three CSV files, one with <a href="https://en.wikipedia.org/wiki/List_of_Super_Bowl_champions">game data</a>, one with <a href="https://en.wikipedia.org/wiki/Super_Bowl_television_ratings">TV data</a>, and one with <a href="https://en.wikipedia.org/wiki/List_of_Super_Bowl_halftime_shows">halftime musician data</a> for all 52 Super Bowls through 2018. Let's take a look, using <code>display()</code> instead of <code>print()</code> since its output is much prettier in Jupyter Notebooks.</p>
```
# Import pandas
import pandas as pd
# Load the CSV data into DataFrames
super_bowls = pd.read_csv('datasets/super_bowls.csv')
tv = pd.read_csv('datasets/tv.csv')
halftime_musicians = pd.read_csv('datasets/halftime_musicians.csv')
# Display the first five rows of each DataFrame
display(super_bowls.head())
display(tv.head())
display(halftime_musicians.head())
```
## 2. Taking note of dataset issues
<p>For the Super Bowl game data, we can see the dataset appears whole except for missing values in the backup quarterback columns (<code>qb_winner_2</code> and <code>qb_loser_2</code>), which make sense given most starting QBs in the Super Bowl (<code>qb_winner_1</code> and <code>qb_loser_1</code>) play the entire game.</p>
<p>From the visual inspection of TV and halftime musicians data, there is only one missing value displayed, but I've got a hunch there are more. The Super Bowl goes all the way back to 1967, and the more granular columns (e.g. the number of songs for halftime musicians) probably weren't tracked reliably over time. Wikipedia is great but not perfect.</p>
<p>An inspection of the <code>.info()</code> output for <code>tv</code> and <code>halftime_musicians</code> shows us that there are multiple columns with null values.</p>
```
# Summary of the TV data to inspect
tv.info()
print('\n')
# Summary of the halftime musician data to inspect
halftime_musicians.info()
```
## 3. Combined points distribution
<p>For the TV data, the following columns have missing values and a lot of them:</p>
<ul>
<li><code>total_us_viewers</code> (amount of U.S. viewers who watched at least some part of the broadcast)</li>
<li><code>rating_18_49</code> (average % of U.S. adults 18-49 who live in a household with a TV that were watching for the entire broadcast)</li>
<li><code>share_18_49</code> (average % of U.S. adults 18-49 who live in a household with a TV <em>in use</em> that were watching for the entire broadcast)</li>
</ul>
<p>For the halftime musician data, there are missing numbers of songs performed (<code>num_songs</code>) for about a third of the performances.</p>
<p>There are a lot of potential reasons for these missing values. Was the data ever tracked? Was it lost in history? Is the research effort to make this data whole worth it? Maybe. Watching every Super Bowl halftime show to get song counts would be pretty fun. But we don't have the time to do that kind of stuff now! Let's take note of where the dataset isn't perfect and start uncovering some insights.</p>
<p>Let's start by looking at combined points for each Super Bowl by visualizing the distribution. Let's also pinpoint the Super Bowls with the highest and lowest scores.</p>
```
# Import matplotlib and set plotting style
from matplotlib import pyplot as plt
%matplotlib inline
plt.style.use('seaborn')
# Plot a histogram of combined points
plt.hist(super_bowls.combined_pts)
plt.xlabel('Combined Points')
plt.ylabel('Number of Super Bowls')
plt.show()
# Display the Super Bowls with the highest and lowest combined scores
display(super_bowls[super_bowls['combined_pts'] > 70])
display(super_bowls[super_bowls['combined_pts'] < 70])
```
## 4. Point difference distribution
<p>Most combined scores are around 40-50 points, with the extremes being roughly equal distance away in opposite directions. Going up to the highest combined scores at 74 and 75, we find two games featuring dominant quarterback performances. One even happened recently in 2018's Super Bowl LII where Tom Brady's Patriots lost to Nick Foles' underdog Eagles 41-33 for a combined score of 74.</p>
<p>Going down to the lowest combined scores, we have Super Bowl III and VII, which featured tough defenses that dominated. We also have Super Bowl IX in New Orleans in 1975, whose 16-6 score can be attributed to inclement weather. The field was slick from overnight rain, and it was cold at 46 °F (8 °C), making it hard for the Steelers and Vikings to do much offensively. This was the second-coldest Super Bowl ever and the last to be played in inclement weather for over 30 years. The NFL realized people like points, I guess.</p>
<p><em>UPDATE: In Super Bowl LIII in 2019, the Patriots and Rams broke the record for the lowest-scoring Super Bowl with a combined score of 16 points (13-3 for the Patriots).</em></p>
<p>Let's take a look at point <em>difference</em> now.</p>
```
# Plot a histogram of point differences
plt.hist(super_bowls.difference_pts)
plt.xlabel('Point Difference')
plt.ylabel('Number of Super Bowls')
plt.show()
# Display the closest game(s) and biggest blowouts
display(super_bowls[super_bowls['difference_pts'] == 1])
display(super_bowls[super_bowls['difference_pts'] >= 35])
```
## 5. Do blowouts translate to lost viewers?
<p>The vast majority of Super Bowls are close games. Makes sense. Both teams are likely to be deserving if they've made it this far. The closest game ever was when the Buffalo Bills lost to the New York Giants by 1 point in 1991, which was best remembered for Scott Norwood's last-second missed field goal attempt that went <em><a href="https://www.youtube.com/watch?v=RPFZCGgjDSg">wide right</a></em>, kicking off four Bills Super Bowl losses in a row. Poor Scott. The biggest point discrepancy ever was 45 points (!) where Hall of Famer Joe Montana's led the San Francisco 49ers to victory in 1990, one year before the closest game ever.</p>
<p>I remember watching the Seahawks crush the Broncos by 35 points (43-8) in 2014, which was a boring experience in my opinion. The game was never really close. I'm pretty sure we changed the channel at the end of the third quarter. Let's combine our game data and TV to see if this is a universal phenomenon. Do large point differences translate to lost viewers? We can plot <a href="https://en.wikipedia.org/wiki/Nielsen_ratings">household share</a> <em>(average percentage of U.S. households with a TV in use that were watching for the entire broadcast)</em> vs. point difference to find out.</p>
```
# Join game and TV data, filtering out SB I because it was split over two networks
games_tv = pd.merge(tv[tv['super_bowl'] > 1], super_bowls, on='super_bowl')
# Import seaborn
import seaborn as sns
# Create a scatter plot with a linear regression model fit
sns.regplot(x='difference_pts', y='share_household', data=games_tv)
```
## 6. Viewership and the ad industry over time
<p>The downward sloping regression line and the 95% confidence interval for that regression <em>suggest</em> that bailing on the game if it is a blowout is common. Though it matches our intuition, we must take it with a grain of salt because the linear relationship in the data is weak due to our small sample size of 52 games.</p>
<p>Regardless of the score though, I bet most people stick it out for the halftime show, which is good news for the TV networks and advertisers. A 30-second spot costs a pretty <a href="https://www.businessinsider.com/super-bowl-commercials-cost-more-than-eagles-quarterback-earns-2018-1">\$5 million</a> now, but has it always been that way? And how have number of viewers and household ratings trended alongside ad cost? We can find out using line plots that share a "Super Bowl" x-axis.</p>
```
# Create a figure with 3x1 subplot and activate the top subplot
plt.subplot(3, 1, 1)
plt.plot(tv['super_bowl'], tv['avg_us_viewers'], color='#648FFF')
plt.title('Average Number of US Viewers')
# Activate the middle subplot
plt.subplot(3, 1, 2)
plt.plot(tv['super_bowl'], tv['rating_household'], color='#DC267F')
plt.title('Household Rating')
# Activate the bottom subplot
plt.subplot(3, 1, 3)
plt.plot(tv['super_bowl'], tv['ad_cost'], color='#FFB000')
plt.title('Ad Cost')
plt.xlabel('SUPER BOWL')
# Improve the spacing between subplots
plt.tight_layout()
```
## 7. Halftime shows weren't always this great
<p>We can see viewers increased before ad costs did. Maybe the networks weren't very data savvy and were slow to react? Makes sense since DataCamp didn't exist back then.</p>
<p>Another hypothesis: maybe halftime shows weren't that good in the earlier years? The modern spectacle of the Super Bowl has a lot to do with the cultural prestige of big halftime acts. I went down a YouTube rabbit hole and it turns out the old ones weren't up to today's standards. Some offenders:</p>
<ul>
<li><a href="https://youtu.be/6wMXHxWO4ns?t=263">Super Bowl XXVI</a> in 1992: A Frosty The Snowman rap performed by children.</li>
<li><a href="https://www.youtube.com/watch?v=PKQTL1PYSag">Super Bowl XXIII</a> in 1989: An Elvis impersonator that did magic tricks and didn't even sing one Elvis song.</li>
<li><a href="https://youtu.be/oSXMNbK2e98?t=436">Super Bowl XXI</a> in 1987: Tap dancing ponies. (Okay, that's pretty awesome actually.)</li>
</ul>
<p>It turns out Michael Jackson's Super Bowl XXVII performance, one of the most watched events in American TV history, was when the NFL realized the value of Super Bowl airtime and decided they needed to sign big name acts from then on out. The halftime shows before MJ indeed weren't that impressive, which we can see by filtering our <code>halftime_musician</code> data.</p>
```
# Display all halftime musicians for Super Bowls up to and including Super Bowl XXVII
halftime_musicians[halftime_musicians['super_bowl'] <= 27]
```
## 8. Who has the most halftime show appearances?
<p>Lots of marching bands. American jazz clarinetist Pete Fountain. Miss Texas 1973 playing a violin. Nothing against those performers, they're just simply not <a href="https://www.youtube.com/watch?v=suIg9kTGBVI">Beyoncé</a>. To be fair, no one is.</p>
<p>Let's see all of the musicians that have done more than one halftime show, including their performance counts.</p>
```
# Count halftime show appearances for each musician and sort them from most to least
halftime_appearances = halftime_musicians.groupby('musician').count()['super_bowl'].reset_index()
halftime_appearances = halftime_appearances.sort_values('super_bowl', ascending=False)
# Display musicians with more than one halftime show appearance
halftime_appearances[halftime_appearances['super_bowl'] > 1]
```
## 9. Who performed the most songs in a halftime show?
<p>The world famous <a href="https://www.youtube.com/watch?v=RL_3oqpHiDg">Grambling State University Tiger Marching Band</a> takes the crown with six appearances. Beyoncé, Justin Timberlake, Nelly, and Bruno Mars are the only post-Y2K musicians with multiple appearances (two each).</p>
<p>From our previous inspections, the <code>num_songs</code> column has lots of missing values:</p>
<ul>
<li>A lot of the marching bands don't have <code>num_songs</code> entries.</li>
<li>For non-marching bands, missing data starts occurring at Super Bowl XX.</li>
</ul>
<p>Let's filter out marching bands by filtering out musicians with the word "Marching" in them and the word "Spirit" (a common naming convention for marching bands is "Spirit of [something]"). Then we'll filter for Super Bowls after Super Bowl XX to address the missing data issue, <em>then</em> let's see who has the most number of songs.</p>
```
# Filter out most marching bands
no_bands = halftime_musicians[~halftime_musicians.musician.str.contains('Marching')]
no_bands = no_bands[~no_bands.musician.str.contains('Spirit')]
# Plot a histogram of number of songs per performance
most_songs = int(max(no_bands['num_songs'].values))
plt.hist(no_bands.num_songs.dropna(), bins=most_songs)
plt.xlabel('Number of Songs Per Halftime Show Performance')
plt.ylabel('Number of Musicians')
plt.show()
# Sort the non-band musicians by number of songs per appearance...
no_bands = no_bands.sort_values('num_songs', ascending=False)
# ...and display the top 15
display(no_bands.head(15))
```
## 10. Conclusion
<p>So most non-band musicians do 1-3 songs per halftime show. It's important to note that the duration of the halftime show is fixed (roughly 12 minutes) so songs per performance is more a measure of how many hit songs you have. JT went off in 2018, wow. 11 songs! Diana Ross comes in second with 10 in her medley in 1996.</p>
<p>In this notebook, we loaded, cleaned, then explored Super Bowl game, television, and halftime show data. We visualized the distributions of combined points, point differences, and halftime show performances using histograms. We used line plots to see how ad cost increases lagged behind viewership increases. And we discovered that blowouts do appear to lead to a drop in viewers.</p>
<p>This year's Big Game will be here before you know it. Who do you think will win Super Bowl LIII?</p>
<p><em>UPDATE: <a href="https://en.wikipedia.org/wiki/Super_Bowl_LIII">Spoiler alert</a>.</em></p>
```
# 2018-2019 conference champions
patriots = 'New England Patriots'
rams = 'Los Angeles Rams'
# Who will win Super Bowl LIII?
super_bowl_LIII_winner = patriots
print('The winner of Super Bowl LIII will be the', super_bowl_LIII_winner)
```
|
github_jupyter
|
# Import pandas
import pandas as pd
# Load the CSV data into DataFrames
super_bowls = pd.read_csv('datasets/super_bowls.csv')
tv = pd.read_csv('datasets/tv.csv')
halftime_musicians = pd.read_csv('datasets/halftime_musicians.csv')
# Display the first five rows of each DataFrame
display(super_bowls.head())
display(tv.head())
display(halftime_musicians.head())
# Summary of the TV data to inspect
tv.info()
print('\n')
# Summary of the halftime musician data to inspect
halftime_musicians.info()
# Import matplotlib and set plotting style
from matplotlib import pyplot as plt
%matplotlib inline
plt.style.use('seaborn')
# Plot a histogram of combined points
plt.hist(super_bowls.combined_pts)
plt.xlabel('Combined Points')
plt.ylabel('Number of Super Bowls')
plt.show()
# Display the Super Bowls with the highest and lowest combined scores
display(super_bowls[super_bowls['combined_pts'] > 70])
display(super_bowls[super_bowls['combined_pts'] < 70])
# Plot a histogram of point differences
plt.hist(super_bowls.difference_pts)
plt.xlabel('Point Difference')
plt.ylabel('Number of Super Bowls')
plt.show()
# Display the closest game(s) and biggest blowouts
display(super_bowls[super_bowls['difference_pts'] == 1])
display(super_bowls[super_bowls['difference_pts'] >= 35])
# Join game and TV data, filtering out SB I because it was split over two networks
games_tv = pd.merge(tv[tv['super_bowl'] > 1], super_bowls, on='super_bowl')
# Import seaborn
import seaborn as sns
# Create a scatter plot with a linear regression model fit
sns.regplot(x='difference_pts', y='share_household', data=games_tv)
# Create a figure with 3x1 subplot and activate the top subplot
plt.subplot(3, 1, 1)
plt.plot(tv['super_bowl'], tv['avg_us_viewers'], color='#648FFF')
plt.title('Average Number of US Viewers')
# Activate the middle subplot
plt.subplot(3, 1, 2)
plt.plot(tv['super_bowl'], tv['rating_household'], color='#DC267F')
plt.title('Household Rating')
# Activate the bottom subplot
plt.subplot(3, 1, 3)
plt.plot(tv['super_bowl'], tv['ad_cost'], color='#FFB000')
plt.title('Ad Cost')
plt.xlabel('SUPER BOWL')
# Improve the spacing between subplots
plt.tight_layout()
# Display all halftime musicians for Super Bowls up to and including Super Bowl XXVII
halftime_musicians[halftime_musicians['super_bowl'] <= 27]
# Count halftime show appearances for each musician and sort them from most to least
halftime_appearances = halftime_musicians.groupby('musician').count()['super_bowl'].reset_index()
halftime_appearances = halftime_appearances.sort_values('super_bowl', ascending=False)
# Display musicians with more than one halftime show appearance
halftime_appearances[halftime_appearances['super_bowl'] > 1]
# Filter out most marching bands
no_bands = halftime_musicians[~halftime_musicians.musician.str.contains('Marching')]
no_bands = no_bands[~no_bands.musician.str.contains('Spirit')]
# Plot a histogram of number of songs per performance
most_songs = int(max(no_bands['num_songs'].values))
plt.hist(no_bands.num_songs.dropna(), bins=most_songs)
plt.xlabel('Number of Songs Per Halftime Show Performance')
plt.ylabel('Number of Musicians')
plt.show()
# Sort the non-band musicians by number of songs per appearance...
no_bands = no_bands.sort_values('num_songs', ascending=False)
# ...and display the top 15
display(no_bands.head(15))
# 2018-2019 conference champions
patriots = 'New England Patriots'
rams = 'Los Angeles Rams'
# Who will win Super Bowl LIII?
super_bowl_LIII_winner = patriots
print('The winner of Super Bowl LIII will be the', super_bowl_LIII_winner)
| 0.820254 | 0.944791 |
Formal Proposal:
Our team’s goal is to create a neural network to play the United States version of the game, GeoGuessr, and beat the average player’s score. GeoGuessr is a game in which the player is placed in a semi-randomized street view location around the world. The player can rotate the view of the camera 360 degrees and move farther along the street to gather any possible geographical clues (terrain, vegetation, climate, etc.) or even road signs, businesses, and landmarks to determine their best guess for the exact location they are viewing.
We must first gather a large dataset for the network to learn from to train our model. The current best approach to gathering this dataset is by using Google Street View’s static view API. The challenges with this approach are maintaining a free (or cheap) way to extract both the images and the metadata, specifically the latitude and longitude coordinates of each image. Google provides some cost-free use of their developer tools, so we plan to gather enough data to both stay beneath this threshold and provide enough images to create a successful network to use for the game.
Following a similar location system to the United States National Grid (USNG), our dataset will consist of a select number of locations in each grid to provide the network a fair and equal number of images from each small region. Our current prediction is to divide each of the 30 grids from the USNG into 4 smaller grids and extract up to 350 coordinates and images from each of these 120 grids in the continental United States.
We are expecting to implement a multi-layered neural network that is ideal for processing two-dimensional images. The network will begin with learning basic features in the images and associate them with other images in the region to get a generalized understanding of what it expects each grid to look visually. When our network has created a successful model, GeoGuessr will be ready to be played by the model.
Our planned outcome of our model is for it to make its best estimate of which of the 120 regions the game has placed you in. The success of our model will be easily quantified by comparing our model’s score with the average player’s score in the United States version of GeoGuesser (\~9,500 points). A player is given five different locations in each round, and each round can result in 0 to 5,000 points depending on how far away their guess is from the actual location (a maximum of 25,000 points is given if each guess is within 150m of the street view’s actual location. Because each game only consists of five images and the difficulty of each round is nearly impossible to compare with another, the quality of our model will be determined by a consistently higher than average score than the average player. There is potential for the model to only guess two locations within 150m and still beat the player, so another means to determine the quality of the model is by comparing the average player’s individual location score (\~1,900 points) with the network’s individual scores.
|
github_jupyter
|
Formal Proposal:
Our team’s goal is to create a neural network to play the United States version of the game, GeoGuessr, and beat the average player’s score. GeoGuessr is a game in which the player is placed in a semi-randomized street view location around the world. The player can rotate the view of the camera 360 degrees and move farther along the street to gather any possible geographical clues (terrain, vegetation, climate, etc.) or even road signs, businesses, and landmarks to determine their best guess for the exact location they are viewing.
We must first gather a large dataset for the network to learn from to train our model. The current best approach to gathering this dataset is by using Google Street View’s static view API. The challenges with this approach are maintaining a free (or cheap) way to extract both the images and the metadata, specifically the latitude and longitude coordinates of each image. Google provides some cost-free use of their developer tools, so we plan to gather enough data to both stay beneath this threshold and provide enough images to create a successful network to use for the game.
Following a similar location system to the United States National Grid (USNG), our dataset will consist of a select number of locations in each grid to provide the network a fair and equal number of images from each small region. Our current prediction is to divide each of the 30 grids from the USNG into 4 smaller grids and extract up to 350 coordinates and images from each of these 120 grids in the continental United States.
We are expecting to implement a multi-layered neural network that is ideal for processing two-dimensional images. The network will begin with learning basic features in the images and associate them with other images in the region to get a generalized understanding of what it expects each grid to look visually. When our network has created a successful model, GeoGuessr will be ready to be played by the model.
Our planned outcome of our model is for it to make its best estimate of which of the 120 regions the game has placed you in. The success of our model will be easily quantified by comparing our model’s score with the average player’s score in the United States version of GeoGuesser (\~9,500 points). A player is given five different locations in each round, and each round can result in 0 to 5,000 points depending on how far away their guess is from the actual location (a maximum of 25,000 points is given if each guess is within 150m of the street view’s actual location. Because each game only consists of five images and the difficulty of each round is nearly impossible to compare with another, the quality of our model will be determined by a consistently higher than average score than the average player. There is potential for the model to only guess two locations within 150m and still beat the player, so another means to determine the quality of the model is by comparing the average player’s individual location score (\~1,900 points) with the network’s individual scores.
| 0.831896 | 0.993429 |
```
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
```
=================================================================================================================
# Lecture Notes: Ensemble Learning
##### D.Vidotto, Data Mining: JBI030 2019/2020
=================================================================================================================
So far, we have considered regressors and classifiers individually. **Ensembles**, on the other hand, consider the predictions provided by combinations of estimators, with the goal of decreasing the *variance* of low bias models, or decreasing the bias of low variance models. By combining the predictions of each of such base algorithms (called *base learners*), ensembles constitute a very powerful predictive method (although not easily interpretable); an extra advantage is that they do not require too much tuning to work well. In this notebook we will mostly explore two ensemble methods that have been proven effective when applied to several datasets: *Bagging* (which includes *Random Forests*) and *Boosting*.
In this notebook, the following topics will be discussed:
1. Introduction
1. Bagging
* Motivation
* Bagging
* Random Forests
* Hyperparameters
* Out-Of-Bag Performance
1. Boosting
* Motivation
* Gradient Boosting
* AdaBoost
* Boosting: Hyperparameters
1. Interpretation and Feature Importance
1. Other Remarks
1. Examples in Python
* Bagging
* Random Forests
* Gradient Boosting
* AdaBoost
1. Other Ensembles
* Voting
* Stacking
* XGBoost
1. Example on the Heart Data
## 1. Introduction
Consider the case in which you have to make a critical decision. In this case, rather than trust the opinion of just one advisor, you could try to collect opinions from several experts, so to obtain different viewpoints. In a democratic setting, then, you would combine the opinions of these experts either with consensus, or with a majority vote.
This is exactly the idea behind ensembles: they combine the predictions of several "experts" (base learners, which can be classifiers or regressors depending on the problem) whose individual predictions are not that reliable. When these predictions are combined together, however, ensemble models can reach incredibly good performance.
The main goal of ensembles is rather simple to understand: they either use a combination of high-variance, low-bias learners to reduce variance (bagging), or they use a combination of high-bias, low-variance learners to reduce bias (boosting).
Let's start with bagging.
## 2. Bagging
### 2.1 Motivation
Remember the bias/variance decomposition:
$$ \mathbb{E}[(y^* - \hat{f}(x^*))^2] = \left(Bias[\hat{f}(x^*)]\right)^2 + Var[\hat{f}(x^*)] + Var(e^*)$$
where
$$ Var[\hat{f}(x^*)] = \mathbb{E}\left\{\left(\hat{f}(x^*)-\mathbb{E}[\hat{f}(x^*)]\right)^2\right\} $$
and $\mathbb{E}[\hat{f}(x^*)]$ represents the expected prediction of an estimator $f$ across all possible samples in a population.
Suppose that $f$ is a low-bias, high-variance estimator (regressor or classifier). If we got the chance to get the prediction of $f$ closer to its average, we could reduce its variance while keeping the bias term untouched. Ideally, we would like to achieve $\hat{f}(x^*) \rightarrow \mathbb{E}[\hat{f}(x^*)]$.
In probability theory, the [law of large numbers](https://en.wikipedia.org/wiki/Law_of_large_numbers) states that the average results of an experiment repeated for a large enough number of times approaches its expected value:
$$\frac{1}{B}\sum_{i=1}^{B}y_b \rightarrow \mathbb{E}(y)\ as\ B \rightarrow +\infty$$
Imagine the following experiment. We toss four perfectly balanced coins (50-50 chances of Heads and Tails) ten times each, and we take note of the number of times (proportion) that we obtain "Head". The following histograms report the results of the experiments:
<br>
<img src="./img/ensembles/coin_trials.png" width="400"/>
<br>
As you can see, the proportion of Heads is on average around 0.5 across different trials, but it can vary from experiment to experiment. Now, suppose that for each coin we repeat the same experiment 5000 times, and each time we calculate the "average proportion" obtained across the various trials. The following figure reports the results.
<br>
<img src="./img/ensembles/coin_bootstrap.png" width="600"/>
<br>
Now, the average proportions keep being rather unstable for the first 10000 trials, but as the experiment proceeds, the all tend to converge to the expected value of 0.5, decreasing in this way the variability of the estimate: this is the law of large numbers in action.
When dealing with a dataset, imagine that the dataset you are analysing is like an experiment with one coin, and that the calculated proportion is the prediction returned by an estimator. If we had the chance to replicate the dataset for a large enough number of times, then we could exploit the law of large number to reduce the variance of the estimator. This is the purpose of *bagging*.
### 2.2 Bagging
**Bootstrap**. Bagging stands for *Bootstrap Aggregating*, and it exploits the [bootstrap](https://en.wikipedia.org/wiki/Bootstrapping_(statistics)) technique to replicate a dataset. In statistics, bootstrap works as follows:
Having a training dataset $\mathcal{D} = \{(\mathbf{x}_i, y_i), i=1,...,n\}$:
1. replicate the dataset $B$ times (where $B$ can be arbitrarily large) by resampling $n$ times its rows (the units) uniformly at random **with replacement**
1. for each replication $\mathcal{D}_b\ (b=1,...,B)$ calculate the estimate of interest (for example, a regression coefficient or a sample mean)
1. combine the results of point (2) (for example, by averaging them) to obtain the final estimate
In practice, bootstrapping is an alternative way to obtain the estimates of a population, taking into account the sampling uncertainty (actually bootstrap is used also for other purposes, but this is beyond the scope of this lecture). In particular, in step (1) it is very important that the resampling of the units is obtained with replacement: this will allow to obtain different datasets at each replication $b$ with high probability. For example, if our original dataset is composed of the following units ($n=3$):
$$ \mathcal{D} = [a, b, c], $$
then two possible bootstrap replications may look as follows:
$$ \mathcal{D}_1 = [b, b, a] $$
$$ \mathcal{D}_2 = [a, c, a] $$
In practice, each unit has a positive probability to be included in each replicate, but it has also positive probability of being excluded. This increases the probaibility of obtaining different samples every time (the probability increases with increasing $n$). Potentially, we could obtain a dataset where only one unit is present and replicated $n$ times (although this might happen only with probability $\left(\frac{1}{n}\right)^n$). Furthermore, it is possible to prove (asymptotically) that the probability for a unit to be part of a bootstrap sample $b$ is roughly 60%, while it has 40% chances not to belong to it. Last, it is important that data in $\mathcal{D}$ are i.i.d. (independent, identically distributed) in order for the bootstrap to work properly. Independence (as well as sampling with replacement) ensures that the bootstrap samples are independent with each other. The identical distribution assumption ensures that the bootstrap replications come from the same data generating mechanism, which gives it the chance to provide a good (approximate) representation of the distribution of the estimate of interest calculated in points (2) and (3).
**Bootstrap Aggregating**. Bagging uses the technique of bootstrap to improve the variance of an estimator. In practice, it works in the same way as statisticians use bootstrap to obtain statistical estimates, but with one difference: at each replicate, instead of the estimate of a parameter we are interested in the predictions of a base regressor/classifier (base learner), which has large variance. Evantually, its predictions are combined. The following figures gives a schematic representation of how bagging works:
<br>
<img src="./img/ensembles/bagging.png" width="500"/>
<br>
In bagging, each bootstrap sample is also called *bag*. The key that makes this method so effective is the bootstrap: by setting a sufficiently large $B$, bagging exploits the law of large numbers to reduce variance. As a consequence, the combined estimate $\hat{y}_{bagging}$ has lower variance than each single prediction $\hat{y}_b$ for $b=1,...,B$. This, of course, under the assumption that each prediction $\hat{y}_b$ comes from a high-variance and low-bias model (for instance, a tree growth to the maximum possible depth).
How are the bootstrap predictions of the base learners $\hat{y}_{b}$ combined? In regression (where $\hat{y} = f(\mathbf{x})$) by simple average over all bootstrap samples:
$$\hat{y}_{i, bagging} = \frac{1}{B}\sum_{b=1}^{B} \hat{y}_{i,b} = \frac{1}{B}\sum_{b=1}^{B} f_b(\mathbf{x}_i)$$
In classification, the prediction of the class occurs by **majority vote**: we predict the class that occurs the most over all replications. Alternatively, we can obtain the probability of a class $c$ by averaging the predicted probabilities at each replication:
$$\hat{p}_{bagging}\left({y_i=c}\right) = \frac{1}{B}\sum_{b=1}^{B} \hat{p}_{b}({y_i=c)}.$$
The class with the largest final $p$ will become the predicted class of unit $i$. This method is also called **soft voting** (and it is the one implemented, for example, by scikit-learn).
Bagging can be used with any high-variance base learner (for example, unregularized linear models, knn with $k=1$, and so on). However, in general trees are ideal candidates for ensemble methods (this is why ensembles are usually presented and implemented with trees). In the case of bagging, trees can capture high-order interaction structures in the data, and when grown sufficiently deep, have low bias. Moreover, deep trees produce rather noisy predictions, and so they can greatly benefit from the type of averaging performed with bagging.
Importantly, the predictions generated by bagging are i.d. (identically distributed), but not independent. Because the datasets generated at each bootstrap replications share some of the same data, the relationships found for example by a tree will hardly differ too much from replicate to replicate (for example, the first split detected by a tree in most of the bootstrap samples might occur at very similar points of the same feature); the resulting trees will then be likely correlated. As [we know from results in probability and statistics](https://en.wikipedia.org/wiki/Variance#Sum_of_correlated_variables), the variance of the sum of correlated variables is larger than the one of uncorrelated variables, which makes the gain in variance of a bagging estimator still significant, but not as strong as if we had independent samples (as the law of large numbers assume).
### 2.3 Random Forests
Random Forests is a popular method that uses bagging in combination with trees as base learners. The trees are usually grown until maximum possible depth (i.e., all leaves are pure) in order to obtain low-bias predictions for each bootstrap training sample.
However, Random Forests have a substantial difference with Bagging: each split of a tree is evaluated on a different (randomly drawn) subsample (of size $m<p$) of the features, rather than the whole set of features of the dataset. This increases the probability of obtaining more diverse trees at each bootstrap replication, and therefore it reduces the correlations among trees. In turn, this guarantees with high probability a further gain in variance w.r.t. the normal bagging. Random Forest is a very powerful prediction tool that have been proven effective in a wide range of applications.
We can summarize the Random Forest algorithm as follows:
1. Draw $B$ bootstrap replications of size $n$ of the training dataset
1. For $b=1,...,B$:
* grow a tree $T_b$ with bootstrap replication $b$, by repeating the following steps until all leaves are pure or some other criterion is met:
1. select m features at random among the p in the dataset
2. pick the best feature/split-point among the m
3. split the node
1. output the forest $T = \{T_1,...,T_B\}$
As seen for bagging, predictions are then obtained either with averaging (regression) or with majority/soft vote (classification) of the final forest. In this figure, we can see an example of classifications obtained for each tree of a Random Forest, along with the final forest. To simplify visualization, we use a small forest with $B=7$ trees.
<br>
<img src="./img/ensembles/random_forest.png" width="800"/>
<br>
In this example (where the features predict the classes by means of non-linear relationships), each single trees struggle to find a good decision boundary, and it overfits the dataset. However, when results are averaged the final forest can drastically reduce the mistakes made by each single tree, and it ends up with a decision boundary that will probably generalize well to new test data. Notice, furthermore, that the decision boundaries detected by random forest are not axis-aligned anymore as a result of the averaging. Of course, the number of trees used in this example (7) is very low for the typical forest size; increasing this number will further improve results (as the decrease in variance will be more clear-cut).
### 2.4 Hyperparameters
A nice feature of Bagging and Random Forest methods is that they have a very small number of hyperparameters, and these hyperparameters can be easily tuned.
* Number of replications $B$: in general, there is no limit to such number. It can be set arbitrarily large without deteriorating model performance. This is because there will always be (in general) a decrease in variance of the estimator, while bias won't grow. Thus, unless your dataset is very noisy, Bagging methods will rarely overfit. You can notice, however, that the improvement in the generalization performance of the model won't be that evident anymore after a certain number of replications, as the decrease in variance becomes less significant for too large $B$. Usually, values between 100/200 and 10000 should work well in several occasions (but you can increase it further if you want). Keep also in mind that the time taken by the computations increases with $B$
* Number of features to use for the split $m$: this is a parameter specific of Random Forest (Bagging can be seen as a Random Forest with $p=m$). While you can decide to tune such parameter, empirical studies have shown that setting $m = \sqrt{p}$ (rounded to the largest integer) works well in practice in classification problems, while $m = p/3$ can be used as a starting point in regression.
* Other hyperparameters that are learner-specific. It is important to remark that the base learners in Bagging use the same hyperparameters for all bootstrap replications. Keep also in mind that, if you want bagging to be effective, the base learner must be set in such a way that they lead to low-bias, and high-variance predictions.
In this figure, we can see an example of training and test set performance for a classification Random Forest with different values of $B$ and $m$. The dataset is composed of $p=200$ features and $n=199$ observations.
<br>
<img src="./img/ensembles/rf_hyperparameters.png" width="600"/>
<br>
Notice how the number of features selected affects the performance of the Forest, and how the test error tends to "stabilize" after some bootstrap iterations. Last, it should also be noticed how the training error goes to 0 quickly as we proceed with the estimation of the forest. For this dataset, it looks like that the best combination is using $\sqrt{p}$ features at each split, and stopping the boosting procedure at about 250 iterations.
### 2.5 Out-Of-Bag Performance
Bagging methodologies offer a further advantage w.r.t. other algorithms: they can automatically provide an estimate of the generalization performance without requiring a validation set. The reason is very simple: as mentioned above, at each replication only about 60% (asymptotically, 63.2%) of the units are included in the bootstrap sample. This means that, at each Bagging iteration, we have about 40% of units that are not included in the sample used to train the base learner. We can therefore calculate a performance metrics on the excluded units (called *out-of-bag* units) to evaluate how each single learner is performing. The average of this metrics across all bootstrap iterations and out-of-bag data points provide a final estimate of the generalization performance of bagging.
Formally, let's define for a generic unit $i$ in the orignal dataset its 'out-of-bag' prediction to be:
$$ \hat{y}_{i,oob} = \frac{1}{B_{-i}} \sum_{b\ \in\ \mathcal{D}_{-i}} f_b(\mathbf{x}^*_i) $$
where $\mathcal{D}_{-i}$ is the set of all bootstrapped datasets in which unit $i$ is not included, $B_{-i}$ is the number of these datasets, and we use the notation $f_b(\mathbf{x}^*_i)$ to stress that $i$ is treated as a test unit in replication $b$. The out-of-bag value of a metric $\mathcal{M}$ (which can be a squared loss, a classification error, accuracy, $f_1$ score, and so on) then is:
$$\mathcal{M}_{oob} = \frac{1}{n}\sum_{i=1}^{n} \mathcal{M}(\hat{y}_{i,oob}, y_i)$$
which in practice is the average OOB metric across all units in the original dataset.
The oob performance is a valid estimate of the test performance, as it is computed on units that are not used to train the base learners. In the next figure, we compare oob accuracy with the accuracy of a validation set for a Random Forest in a classification context, using a number of trees between 10 and 500 and $m=\sqrt{p}$.
<br>
<img src="./img/ensembles/rf_oob.png" width="600"/>
<br>
As the figure shows, the OOB and Validation accuracy convey similar information.
## 3. Boosting
### 3.1 Motivation
Boosting is a technique devised with the opposite purpose of Bagging: instead of using overfitting estimators and try to decrease their bias, boosting seeks to sequentially estimate a series of poor (high-bias) classifiers using at each iteration the residuals of the ensemble at step $t$. The goal is to reduce bias at each iteration.
Boosting has some analogy and differences with Bagging:
* like Bagging, it combines the results of several base learners ("experts") to perform a prediction
* unlike Bagging, boosting uses low-variance, high-bias base learners (called **weak learners** in this context)
* similar to Bagging, Decision Trees are default learners also for Boosting
* while bagging can be seen as a *parallel* algorithm, where each learner is trained independently of the others, boosting can be seen as a *sequential* algorithm, where the training at some iteration $t$ depends on the results obtained at iteration $t-1$
In Boosting, the definition of *weak learner* is a learner that can do just slightly better than random guessing. Similar to Bagging, typical choices for such learners are Decision Trees. Because the goal here is to improve the bias of the estimators, Boosting uses shallow -rather than deep- trees. The typical *maximum depth* of a tree in Boosting is between 1 (in which case it is called a Decision Stump) and 8. Of course, the use of other regressors and classifiers is possible, as long as it is a weak learner (high-bias estimator). In this notebook, we will present boosting using Decision Trees.
The typical Boosting estimator can be represented as:
$$\hat{y}_{boosting} = \sum_{t=1}^{T} \alpha f_t(\mathbf{x})$$
where $T$ is the number of boosting iterations (it is the analogous of $B$ in bagging), and $\alpha$ (usually set between 0 and 1) is the learning rate (it can be interpreted like the learning rate of Gradient Descent). To highlight the predictions made by the ensemble after $t'$ iterations, we will alternatively use this notation:
$$ F_{t'}(\mathbf{x}) = \sum_{t=1}^{t'} \alpha f_t(\mathbf{x})$$
While in the next sub-sections we are going to discuss some specific ways to do boosting, here we shall see a general idea of the algorithm. Roughly, boosting works as follows:
1. At iteration $t=0$, predict a constant value $F_0$ (for example 0 or the sample mean): predict $F_0$ for all units;
1. For $t=1,...,T$:
1. For all the training data points, compute the residuals $r_i$ between $y_i$ and the predictions of the model $F_{t-1}$
1. Train a weak learner $f_t$ using $r_i$ as target variable
1. Set $F_t = F_{t-1} + \alpha f_t$
The goal of boosting is to reduce the errors ($r_i$'s) at each iteration with the weak learners, to get the ensemble closer and closer to the true observed targets. The speed of such learning is controlled by the step size $\alpha$.
Here we shall see an example in a regression case (but boosting can be implemented also for classification problems), using shallow trees (max depth = 2) as weak learners. In the left column you can see the tree-specific predictions on the residuals at each iteration, while on the right you can see the predictions made by the ensemble. In the first row there is only one tree, so the predictions of the ensemble correspond to the ones of the tree. To keep things simple, we only show an example of the first three iterations of Boosting and $\alpha=1$.
<br>
<img src="./img/ensembles/boosting_intro.png" width="900"/>
<br>
Because the weak learners of Boosting have high bias, they do not learn the observed target in just one step, but they get slowly close to it at each iteration. In this way, Boosting can focus on specific aspects of the dataset (the iteration-specific residuals) one step at a time.
From the previous picture, we can also see how at each step boosting actually is solving two optimization problems: one, to optimize the global function $F$, and one to optimize the weak learners $f$.
### 3.2 Gradient Boosting
Gradient Boosting is an implementation of Boosting that works both in Classification and in Regression. Boosting can be seen as a Gradient Descent optimization problem, hence the name of the algorithm. In particular, we can see Boosting as GD in function (rather than parameter) space; therefore, we try to optimize a loss function directly w.r.t. the function of the estimator, rather than w.r.t. some parameter.
Besides a learning rate and a weak learner, Boosting methods also need a loss function $L(y_i, F(\mathbf{x}_i))$ to optimize. This, as usual, can be the Residuals Sum of Squares (or MSE) in regression and the cross-entropy in classification. The algorithm then proceeds as introduced previously. The residuals for the $i$-th unit are computed as the *negative gradient of the loss function w.r.t. the ensemble function F*:
$$ r_i = -\left[\frac{\partial L(y_i, F(\mathbf{x}_i))}{\partial F(\mathbf{x}_i)}\right]$$
and these are called *pseudo-residuals*. This calls for a bit of explanation. Optimizing w.r.t. a function means finding the direction towards which the function should be moved in order to get closer to the global minimum. Loosely speaking, the derivative w.r.t. $F$ is telling us *how much the loss is steep at that specific point*, and therefore how much we should move $F$ to get it closer to the optimum (for this reason it is called pseudo-residual). The negative sign is due to the fact the we want to minimize the loss, and therefore we want to move downward towards this minimum.
Although the formula for $r_i$ looks difficult, it is not actually! Let's take the squared loss as an example:
$$ \frac{\partial L(y_i, F(\mathbf{x}_i))}{\partial F(\mathbf{x}_i)} =
\frac{\partial \frac{1}{2}(y_i - F(\mathbf{x}_i))^2}{\partial F(\mathbf{x}_i)} =
F(\mathbf{x}_i) - y_i
$$
and in this case you can see that the pseudo-residuals are similar to the typical residuals of a regression problem.
In a multiclass classification case, the vector of labels is one-hot encoded so that $y_{i,c} \in \{0,1\}$ and it is equal to 1 only when $y_i=c$. We would execute a Boosting algorithm for each class. For the $c$-th class, then, the predicted probability is calculated through the softmax function:
$$ p_{i,c}(\mathbf{x}_i) = \frac{e^{F_c(\mathbf{x}_i)}}{\sum_k e^{F_k(\mathbf{x}_i)}}$$
In this case the negative derivative of the cross-entropy can be easily shown to be:
$$\frac{\partial L(y_i, F(\mathbf{x}_i))}{\partial F(\mathbf{x}_i)} = \mathcal{I}(y_{i,c}=1) - p_{i,c}$$
In the binary case, you can just train one ensemble and use the binary cross-entropy already encountered with Neural Networks. You can find more details about these and other loss functions in Table 10.2 at page 360 of [The Elements of Statistical Learning](https://web.stanford.edu/~hastie/Papers/ESLII.pdf).
Now that we have undestood how the gradients of the loss function $L$ are calculated, we can examine the algorithm for Gradient Boosting:
1. At iteration $t=0$, set for example $F_0 = 0$ for all units;
1. For $t=1,...,T$:
1. for $i=1,...,n$ compute the pseudo-residuals <br><br>$ r_i = -\left[\frac{\partial L(y_i, F_{t-1}(\mathbf{x}_i))}{\partial F_{t-1}(\mathbf{x}_i)}\right]$<br><br>
1. Train a weak learner (such as a tree) $f_t$ using ($\mathbf{x}_i, r_i$) for $i=1,...,n$ as training dataset such that the loss $L(r_i, f_t)$ is minimized
1. Set $F_t = F_{t-1} + \alpha f_t$
1. Output $F_T$
Importantly, because the $r_i$'s of step 2A are continuous values, the weak learner of step 2B must necessarily be a regression algorithm (e.g., a regression tree).
### 3.3 AdaBoost
AdaBoost is the first boosting algorithm ever appeared in the literature. AdaBoost is actually a specific instance of Gradient Boosting, which represent the more general version, although its algorithm was discovered later.
AdaBoost is tailored specifically for binary classification problems, where $y_i \in \{-1,1\}$ - and therefore its weak learner must also be a binary classifier (whose output is $f_t \in \{-1,1\}$). The main differences with the boosting algorithms we have ancountered so far are:
* at each iteration, AdABoost assigns a weight $w_i$ to each unit; the weak learners are trained giving different weights to each unit
* the step size $\alpha$ of AdaBoost is updated at each step with a specific analytic formula; the idea is that AdaBoost can recognize automatically which weak learners are more important, and gives them a larger weight. This is the feature of AdaBoost that gives it its name (AdaBoost stands for "Adaptive Boosting"). The ensemble of AdaBoost can then be written as <br> $$F_t(\mathbf{x}) = F_{t-1}(\mathbf{x}) + \alpha_t f_t(\mathbf{x})$$<br>
* AdaBoost uses a new loss function: the *exponential loss* defined as: <br>$$L(y_i,F(\mathbf{x}_i)) = e^{-y_iF(\mathbf{x}_i)}$$<br> We will see what this loss looks like shortly.
It turns out that these three elements are the main reasons of the success of AdaBoost:
* at each step, larger weights are given to those units miss-classified during the previous iteration (and smaller weights to the correctly classified ones), which allows the weak learners of AdaBoost to focus more on the errors (possibly until all units are correctly classified)
* the automatic update of the step size allows AdAboost to automatically recognize which weak learner should be given more importance when performing the predictions, and it allows it to converge faster by gradually reducing the step sizes as the algorithm gets close to the optimal solution
* the exponential loss (compared with other losses encountered so far) looks like as follows: <br> <br>
<img src="./img/ensembles/exponential_loss.png" width="400"/> <br> As you can see, the exponential loss gives much more weight to larger errors than any other loss; this means that, during training, the exponential loss will cause the classifier to adjust its predictions more towards the miss-classified unit, so that it can get close to 0 faster.
The following figure shows how the iterations of AdaBoost are run:
<img src="./img/ensembles/adaboost.png" width="300"/>
In the figure, $sign(z)$ is the function equal to -1 if $z<0$, and to 1 otherwise, and it helps to assign the final class to the units. The final ensemble is composed of the sum of the results of all the weak classifiers (remember that each $f_t \in \{-1,1\}$).
The next plots show the first three iterations of AdaBoost. Here, a Decision Stump (decision tree with max depth = 1) is used as weak learner. The point size corresponds to the weights given at each iteration by the algorithm (during the first iteration, all units are given the same weight).
<img src="./img/ensembles/adaboost_iter.png" width="700"/>
At each iteration, the algorithm detects the miss-classified points and give them more weights for the next iteration; points that are given more weights are more likely to be correctly classified at the next step. The final ensemble, which is a weighted sum of the predictions at each step (where the weights are given by the step size $\alpha_t$), produces an accurate classifier. Notice also how the step size decreases at each iteration.
Here is the AdaBoost algorithm:
1. initialize the weights $w_i=\frac{1}{n}$ for all the training units $i=1,...,n$
1. For t=1,...,T:
1. fit a weak classifier $f_t(\mathbf{x})$ with the training data, giving weights $w_i$ to each observation $i$
1. compute the weighted mis-classification error <br>$$err_t = \frac{\sum_{i:y_i\neq f_t(\mathbf{x}_i)}^n w_i}{\sum_{i=1}^n w_i}$$<br>
1. update the step size <br>$$\alpha_t=log\frac{1-err_t}{err_t}$$<br>
1. update the weigths for $i=1,...,n$: <br>$$w_i \leftarrow w_i \cdot e^{\alpha_t \cdot \mathcal{I}(y_i\neq f_t(\mathbf{x}_i))} $$<br>
1. Output $F(\mathbf{x}) = sign\left(\sum_{t=1}^T \alpha_t f_t(\mathbf{x})\right)$
* in the initial step, all units are given the same weight $1/n$; subsequently, units that are miss-classified are given larger weights, proportional to the miss-classification rate of classifier $f_t$
* the step-size is updated incrementally, and it is given a value proportional to the log-odds ratio of the weighted accuracy of $f_t$; the idea is to give more weight (larger step size) to those model that perform better (that have higher accuracy)
### 3.4 Boosting: Hyperparameters
Similar to Bagging, Boosting also does not have too many hyperparameters to tune. However, unlike Bagging, they can have a stronger influence on the final performance of the algorithm:
* number of iterations $T$: if $T$ is too small, the final ensemble might not be accurate enough, while if $T$ is too large, it might be over-fitting (although it has been observed that boosting starts to overfit after a veeery large number of iterations). A possible solution can be given by *early stopping* (already discussed with Neural Networks), which requires setting aside a small validation set to assess when the algorithm stops learning.
* The learning rate is a very delicate parameter in Boosting, and it interacts strongly with the number of iterations. A low value of the learning rate slows down learning, but it has been shown to provide very accurate results (decreasing the likelihood of overfitting). In AdaBoost, a fixed learning rate can be mulitplied by the step size of each iteration. The learning rate is also called *shrinkage* parameter
* Hyperparameters related of the weak learners. The weak learners can also be tuned, but it must be kept in mind that Boosting is effective only with high-bias (and low-variance) learners. When trees are used, usually what is tuned is the max depth of the tree. In general, values of max depth between 1 and 8 work well in practice (but a larger max depth can be beneficial sometimes). Some authors see a max depth equal to 6 as a good default choice.
The following figure shows the performance of a boosting algorithm with varying learning rate and number of iterations:
<img src="./img/ensembles/gb_hyperparameters.png" width="800"/>
The Boosted trees with lowest learning rate (0.001), in this case, takes more iterations to "kick in", but its test set accuracy overperforms the ones of Boosting with larger learning rates after a bunch of iterations. If early stopping was set with learning rate 0.001, it would have stopped computations probably after 100 iterations. Keep in mind that Boosting here was run in a small (two features) dataset, and probably in other applications a larger number of iterations should be used.
Let's now compare the performance of Boosting with varying maximum tree depth and number of iterations. This is done on the same two-features data:
<img src="./img/ensembles/gb_hyperparameters_2.png" width="800"/>
We see that also tree depth strongly affects the results of boosting (in this case, using weak decision trees with max. depth equal to 5 reaches a test set accuracy close to 90% between 30 and 70 iterations).
## 4. Interpretation and Feature Importance
A disadvantage of ensemble methods is that it is very hard (if not impossible) to interpret them, since they use the results of several models (whose results might even be in conflict with each other). However, there is a nice way to detect univariate feature importance for ensemble methods.
As you may recall from the Decision Trees lecture, we can calculate feature importance on a tree by summing the loss in impurity (e.g., loss in Gini/entropy index in classsification, or loss in MSE in regression) across all the splits of a tree caused by each specific feature. Ensembles can estimate the importance of a feature by simply taking the average feature importances obtained across each single tree of their algorithm. Such averages are then normalized so that we can interpret the output as the *relative importance* of the feature. For example:
<img src="./img/ensembles/feat_importance.png" width="500"/>
In the figure above, for example, we may say that 'feature 5' was the most important feature, determining (on average) about 17.5% of the gain in purity of the whole ensemble, followed by 'feature_17' with about 12% contribution.
This can be a way to give a simple interpretation to the results of an ensemble. Despite the simplicity of this method, there are some caveats:
* this method only accounts for univariate feature importances, disregarding possible interactions between features
* this method does not give any information about the *direction* of the relationships between the feature and the target. For example, we don't know if 'feature_5' above predicts a specific target when its value is increased or decreased
## 5. Other Remarks
* When trees are used as Base learners, ensembles require a minimum amount of preprocessing steps, for the same reasons seen when discussing Decision Trees. For example, continuous features need not be standardized
* In Bagging, since the base learners are trained independently of each other, we have an [Embarissingly Parallel](https://en.wikipedia.org/wiki/Embarrassingly_parallel) problem that can easily exploits multi-core computations
* Boosting, unlike Bagging, cannot be parallelized, as its next iteration depend on the results of the previous one. However, when trees are used as learners, an iteration of Boosting can be faster than an iteration of Bagging, as it uses shallow trees which are faster to compute
* It is possible to "bag" Boosting, by subsampling (without replacement) a fraction of the training data points from the dataset at each iteration. This has the advantage of speeding up computations, as well as to offer an "out-of-bag" measure of performance
* Learn more about Ensembles in the [scikit-learn documentation](https://scikit-learn.org/stable/modules/ensemble.html)
## 6. Examples in Python
In this section, we are going to see examples of implementations of Bagging and Boosting in scikit-learn. In particular, we will see the following models:
* Bagging in Regression using a linear model as base learner
* Random Forests in classification
* Gradient Boosting in Regression using a Regression Tree
* AdaBoost with classification Trees
We will see examples with the Boston housing dataset for the regression cases (already encountered in the Neural Networks lecture), and with the moons data in classification.
### 6.1 Bagging - Regression Case
*Bagging* can be implemented with two functions in scikit-learn:
* [BaggingRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.BaggingRegressor.html) in regression
* [BaggingClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.BaggingClassifier.html) in classification
The two functions require as input a `base_estimator`, which of course must be a regressor for regression, and a classifier for classifications. The reamining hyperparameters are the same for the two functions:
* `n_estimators` the number of bootstrap replications
* `max_samples` the number of units to resample at each iteration (the default value of 1 means 100% of the units, and it is usually a good choice)
* `oob_score` if an out-of-bag score ($R^2$ in regression, Accuracy in classification) is desired
Let's see Bagging in action. We first load the data:
```
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
bunch_data = load_boston()
features = bunch_data.feature_names
X_boston, y_boston = bunch_data.data, bunch_data.target
X_boston_train, X_boston_test, y_boston_train, y_boston_test = train_test_split(X_boston, y_boston,
test_size=0.1, random_state=10)
```
We now run the algorithm for increasing number of bootstrap replications, and will require the 'oob-score'. For reproducibility, we also set the `random_state`.
```
from sklearn.ensemble import BaggingRegressor
from sklearn.linear_model import LinearRegression
# Try every 50 number of bootstrap replications between 20 and 1000
n_iter = np.arange(20, 1000, 50)
# Here we will store the oob scores:
oob_scores = np.zeros(len(n_iter))
i = 0
for b in n_iter:
print("n_bags = ", b)
bag_reg = BaggingRegressor(base_estimator= LinearRegression(),
n_estimators = b, oob_score=True, n_jobs=-1, random_state=1)
bag_reg.fit(X_boston_train, y_boston_train)
oob_scores[i] = bag_reg.oob_score_
i += 1
```
Let's now plot the results.
```
plt.figure(figsize=(10,4))
plt.plot(n_iter, oob_scores, "b-", label="OOB Scores")
plt.xlabel("# Bootrstrap Replications")
plt.ylabel("OOB Score")
plt.title("Boston Data: Bagging with Linear Regression")
plt.show()
```
It seems like the linear model could slightly (probably not significantly) benefit from bagging. Let's now check the $R^2$ score on the test data:
```
best_B = n_iter[np.argmax(oob_scores)]
best_bag = BaggingRegressor(base_estimator= LinearRegression(),
n_estimators = best_B, n_jobs=-1, random_state=1)
best_bag.fit(X_boston_train, y_boston_train)
best_bag.score(X_boston_test, y_boston_test)
```
The reason why linear models do not benefit from Bagging too much is that they are usually rather stable (low-variance) models (unless multicollinearity is present in the dataset). As an exercise, try to bag a high-variance neural network and compare the results. This can be, for example, a NN with several neurons and layers. (Note: the computations might take a while)
### 6.2 RandomForest - Classification Case
*RandomForest* can also be implemented with two functions in scikit-learn:
* [RandomForestRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html) in regression
* [BaggingClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html) in classification
The two functions take as input similar arguments:
* `n_estimators` the number of trees in the forest
* `criterion` to perform the splits of the trees; this can be `gini` or `entropy` in classification, or `mse` in regression
* `oob_score` same as for the Bagging functions
* `max_features` the number of features $m$ to draw when evaluating each split
* other tree-specific hyperparameters (the default lets the tree grow until all leaves are pure, which works fine in most cases)
Let's load the "moons" dataset to see an implementation of RandomForestClassifier.
```
# Import Data
data = pd.read_csv("./data/ensembles/moons.csv")
X_moons = data.iloc[:,:2].to_numpy()
y_moons = data["y"].to_numpy()
X_moons_train, X_moons_test, y_moons_train, y_moons_test = train_test_split(X_moons, y_moons,
stratify=y_moons, test_size=0.2,
random_state=1)
plt.figure(figsize=(10,5))
plt.plot(X_moons_train[y_moons_train==0,0], X_moons_train[y_moons_train==0,1], "bo", label="Class 0")
plt.plot(X_moons_train[y_moons_train==1,0], X_moons_train[y_moons_train==1,1], "ro", label="Class 1")
plt.xlabel("x1")
plt.ylabel("x2")
plt.legend()
plt.show()
```
We are going to see an example of RandomForest in classification (circles data) with $m=\sqrt{p}$ and $B=500$ estimators (unlike what done in Bagging, we won't vary the number of iterations but if you wish to do that the commands are similar - the same holds also for the Boosting methods we will see in the next subsections). Trees are grown until full depth, and an 'oob' score will be requested.
```
from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier(n_estimators=500, criterion="gini", max_features="sqrt", oob_score=True, random_state=2)
rfc.fit(X_moons_train, y_moons_train)
```
Let's check the OOB and test-set scores:
```
rfc.oob_score_
rfc.score(X_moons_test, y_moons_test)
```
The decision boundary:
```
x1_r = np.arange(X_moons_train[:,0].min()-0.1, X_moons_train[:,0].max()+0.1, 0.01)
x2_r = np.arange(X_moons_train[:,1].min()-0.1, X_moons_train[:,1].max()+0.1, 0.01)
xx1, xx2 = np.meshgrid(x1_r, x2_r)
z = rfc.predict(np.c_[xx1.ravel(), xx2.ravel()]).reshape(xx1.shape)
plt.figure(figsize=(10,5))
plt.contour(xx1, xx2, z, levels=1, colors='k', alpha=1., linewidths=1, linestyles='-')
plt.plot(X_moons_train[y_moons_train==0,0], X_moons_train[y_moons_train==0,1], "bo", label="Class 0")
plt.plot(X_moons_train[y_moons_train==1,0], X_moons_train[y_moons_train==1,1], "ro", label="Class 1")
plt.xlabel("x1")
plt.ylabel("x2")
plt.legend()
plt.show()
```
Last, we can retrieve feature importance (it is trivial in this 2-features case):
```
rfc.feature_importances_
```
This is (roughly) telling us that $X_2$ gives about 60% of the total contribution to the prediction of the class.
### 6.3 Gradient Boosting - Regression Case
Also Gradient Boosting can be implemented in two ways:
* [GradientBoostingRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html) in regression
* [GradientBoostingClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html) in classification
The arguments taken by these functions are:
* `loss`, which can be `ls` (least squares) in regression and `deviance` in classification (note: Deviance in this context is the equivalent name that statisticians give to the cross-entropy)
* `learning_rate` for the ensemble learning rate
* `n_estimators` for the number of iterations
* `criterion` for the splits of the trees, for example `mse`
* other hyperparameters of the tree, among which `max_depth` is the most commonly tuned
We now apply Gradient Boosting to the Boston housing data, using $T=500$ iterations, learning rate equal to 0.1, least square loss and trees max depth of 1.
```
from sklearn.ensemble import GradientBoostingRegressor
gdb = GradientBoostingRegressor(loss='ls', learning_rate=1e-1, n_estimators=500, max_depth=1, random_state=1)
gdb.fit(X_boston_train, y_boston_train)
gdb.score(X_boston_test, y_boston_test)
```
This means that Boosting can explain about 87% of the variability in the target variable (House prices). Gradient Boosting also allows retrieving feature importances:
```
np.c_[features, gdb.feature_importances_]
```
It seems like that LSTAT (% lower status of population) and RM (avg. # of rooms per dwelling) are the most important predictor for house prices in the Boston dataset. Let's try to plot them against the target, to see if we can learn more about their (univariate) relationship with house prices:
```
plt.figure(figsize=(10,4))
plt.subplot(1,2, 1)
plt.plot(X_boston_train[:,12],y_boston_train, "bo")
plt.xlabel("LSTAT")
plt.ylabel("House Prices")
plt.subplot(1,2, 2)
plt.plot(X_boston_train[:,5],y_boston_train, "bo")
plt.xlabel("RM")
plt.ylabel("House Prices")
plt.show()
```
Indeed, there seems to be strong dependencies between the features LSTAT (apparently a negative linear one, with some curvature) and RM (roughly a relationship of linear type). Gradient Boosting was able to detect them.
As an exercise, try to vary learning rate and number of iterations, to see whether you can furhter improve the performance of Gradient Boosting.
### 6.2 AdaBoost
[AdaBoostClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostClassifier.html) takes the following main inputs:
* `base_estimator` (with the default `None`, it uses a Decision Tree with `max_depth=1`)
* `n_estimators` number of AdaBoost iterations
* `learning_rate`, which multiplies the step size at each iteration (in general the default of 1 works fine)
We come back to the "moons" data and show how AdaBoost works. We are going to use a Decision Tree with max depth equal to 1, 50 iterations, and learning rate equal to 1.
```
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
ada = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=1),
n_estimators=50, learning_rate=1., random_state=1)
ada.fit(X_moons_train, y_moons_train)
```
The accuracy on the test set:
```
ada.score(X_moons_test, y_moons_test)
```
Therefore, AdaBoost performs a bit worse than RandomForest in this case (but remember that the number of iterations, as well as the learning rate, can be tuned). The found decision boundary is:
```
x1_r = np.arange(X_moons_train[:,0].min()-0.1, X_moons_train[:,0].max()+0.1, 0.01)
x2_r = np.arange(X_moons_train[:,1].min()-0.1, X_moons_train[:,1].max()+0.1, 0.01)
xx1, xx2 = np.meshgrid(x1_r, x2_r)
z = ada.predict(np.c_[xx1.ravel(), xx2.ravel()]).reshape(xx1.shape)
plt.figure(figsize=(10,5))
plt.contour(xx1, xx2, z, levels=1, colors='k', alpha=1., linewidths=1, linestyles='-')
plt.plot(X_moons_train[y_moons_train==0,0], X_moons_train[y_moons_train==0,1], "bo", label="Class 0")
plt.plot(X_moons_train[y_moons_train==1,0], X_moons_train[y_moons_train==1,1], "ro", label="Class 1")
plt.xlabel("x1")
plt.ylabel("x2")
plt.legend()
plt.show()
```
Notice how the decision boundaries are less "noisy" than those of RandomForest; this is due to the fact that we are using shallow trees as base learners. Last, we can check feature importance according to AdaBoost:
```
ada.feature_importances_
```
In this case, the biggest contribution is given by feature $X_1$.
**Note**: scikit-learn allows also implementing a regression version of AdaBoost, [AdaBoostRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostRegressor.html). The functioning is similar to AdaBoost for classification.
## 7. Other Ensembles
* **Voting methods**. The functioning of Voting is very simple: you can choose a number of base learners (these can be very different from each other: a Decision Tree, KNN, a Neural Network, and so on), and the final prediction is given by the average prediction of each single estimator. If weights are provided for each estimator, the final prediction is a weighted average (this means that the prediction of each estimator has a different influence). Learn more about [VotingClassifier](https://scikit-learn.org/stable/modules/ensemble.html#voting-classifier) and [VotingRegressor](https://scikit-learn.org/stable/modules/ensemble.html#voting-regressor) in the scikit-learn documentation.
* **Stacking**. Stacking works in a hierarchical way: on a first level, several estimators (base learners) are trained on the training dataset. On a second level, another estimator (called meta-regressor, or meta-classifier) is trained by taking as input the predictions at the previous level.
<img src="./img/ensembles/stacking.png" width="500"/>
The base estimators can be very diverse from each other: one can be a Decision Tree, another one a linear model, another one a Neural Network, and so on. Stacking can be implemented in scikit-learn. Found out more [in the documentation](https://scikit-learn.org/stable/modules/ensemble.html#stacked-generalization).
* **XGBoost**. XGBoost (short for extreme Gradient Boosting) is a novel version of Gradient Boosting, optimized with specific data structures that allow much faster computations than Gradient Boosting. XGBoost, furthermore, allows for more control on the regularization of the trees. This combinations allow XGBoost to provide scalable, portable, and accurate results. XGBoost has gained a lot of popularity in the last years (for example, it has won several Kaggle competitions). XGBoost is not implemented in scikit-learn, but it has its own [Python package](https://xgboost.readthedocs.io/en/latest/python/python_intro.html). The library is also available in languages other than Python. You can learn more about XGBoost in its [documentation page](https://xgboost.readthedocs.io/en/latest/get_started.html).
## 8. Example on the Heart Data
Here, we are going to implement ensembles on the Heart Dataset. We are going to compare two ensemble methods:
* RandomForest
* AdaBoost
We will use Randomized Search to perform model search and tuning. For these techniques we search across the following parameters:
* number of iterations (both for AdaBoost and RandomForest), between 50, 100, 500, and 1000
* learning rate (AdaBoost), which will be given a reciprocal distribution (between 1e-4 and 0.99)
* number of features to perform the splits (RandomForest), varied between 2, 3, and $\sqrt{p}$
As usual, we first load the data.
```
data_train = pd.read_csv("./data/heart_data/heart_train_processed.csv")
data_test = pd.read_csv("./data/heart_data/heart_test_processed.csv")
X_train = data_train.drop("y", axis=1)
X_test = data_test.drop("y", axis=1)
y_train = data_train["y"]
y_test = data_test["y"]
```
We now prepare the grid and run 10-fold-cross-validation. Since we are comparing different classifiers, we will create a Pipeline first.
```
from sklearn.pipeline import Pipeline
from scipy.stats import reciprocal # Reciprocal distribution in scipy.stats
from sklearn.model_selection import RandomizedSearchCV
pipe = Pipeline([('classifier', RandomForestClassifier())])
n_trees = [50, 100, 500, 1000]
# Create space of candidate learning algorithms and their hyperparameters
search_space = [{'classifier': [AdaBoostClassifier(random_state=1)],
'classifier__learning_rate': reciprocal(1e-4, 9.9e-1),
'classifier__n_estimators': n_trees},
{'classifier': [RandomForestClassifier(random_state=1)],
'classifier__n_estimators': n_trees,
'classifier__max_features': [2, 3, "sqrt"]}]
```
The grid is ready. Let's run RandomizedSearchCV. For the search, we are going to perform 50 iterations.
```
rnd_search_cv = RandomizedSearchCV(pipe, search_space, n_iter=50, cv=10, n_jobs=-1, iid=False,
random_state=1, verbose=2)
rnd_search_cv.fit(X_train, y_train)
print("Randomized Search: Done")
```
The best classifier was AdaBoost:
```
rnd_search_cv.best_estimator_
```
with the following hyperparameters:
```
rnd_search_cv.best_params_
```
This produced the best CV accuracy:
```
rnd_search_cv.best_score_
```
As usual, we can store the results in a dataframe (notice that the best CV scores are obtained with AdaBoost)...
```
results = pd.DataFrame(rnd_search_cv.cv_results_).sort_values(["mean_test_score"],
ascending=False)
results.head(10)
```
...and we can plot them (here we see the best 20 models):
```
# Plot accuracy of 20 best models
best = 20
fig = plt.figure(figsize=(15,5))
ax = plt.subplot(1,1,1)
ax.tick_params(axis='x', rotation=90)
plt.errorbar(range(best), results.iloc[0:best]["mean_test_score"],
yerr=results.iloc[0:best]["std_test_score"], c="blue", label="1. Std. Error", alpha=0.6,
linewidth=2)
plt.plot(range(best), results.iloc[0:best]["mean_test_score"],
"ro", label="Avg. Accuracy", markersize=9)
plt.xticks(range(best), labels=results.iloc[0:best]["params"],
fontweight='bold', fontsize=5)
plt.xlabel('Parameter Set', fontsize=12)
plt.title('Heart Data: AdaBoost vs. RandomForest (random search)', fontsize=15)
plt.ylabel("Accuracy",fontsize=12)
plt.legend(loc=3)
plt.ylim(0.5,1)
plt.show()
```
The first Random Forest classifier ranks fifth, and randomly selects $m=3$ features at each split; this forest is composed of 50 trees. The best CV accuracy for a RandomForest is 0.830, against 0.839 of the best AdaBoost model.
Let's check the feature importance of the best AdaBoost model:
```
importances = rnd_search_cv.best_estimator_['classifier'].feature_importances_
ind_sort = np.argsort(importances)
plt.figure(figsize=(8,5))
plt.barh(np.arange(1, X_train.shape[1]+1, 1), importances[ind_sort])
plt.yticks(np.arange(1, X_train.shape[1]+1, 1), labels=X_train.columns[list(ind_sort)])
plt.show()
```
(Compare with feature importances observed in the Decision Trees notebook). Last, let's assess the accuracy on the test set of the best model (AdaBoost) found by RandomizedSearch:
```
rnd_search_cv.score(X_test, y_test)
```
This result is not so far from what we obtained with the linear models (Logistic Regression and LinearSVM); probably, by increasing the number of Randomized Search iterations and expanding the hyperparameter grid, we could find an even better ensemble.
**Exercise**: try to re-run the experiment, adding Bagging with varying number of iterations (try to use KNN=1 and a Linear SVM with large value for $C$, or SVM with Polynomial Kernel with large $C$ and and large value of the degree $d$ as base learners), and Gradient Boosting with varying iterations, learning rates, and maximum depth of the decision trees. Tune the maximum depth also for AdaBoost. If you feel like, try also implementing stacking on this dataset (you can choose and tune the base learners). Increase the number of iterations of Randomized Search to search across a larger space.
|
github_jupyter
|
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
bunch_data = load_boston()
features = bunch_data.feature_names
X_boston, y_boston = bunch_data.data, bunch_data.target
X_boston_train, X_boston_test, y_boston_train, y_boston_test = train_test_split(X_boston, y_boston,
test_size=0.1, random_state=10)
from sklearn.ensemble import BaggingRegressor
from sklearn.linear_model import LinearRegression
# Try every 50 number of bootstrap replications between 20 and 1000
n_iter = np.arange(20, 1000, 50)
# Here we will store the oob scores:
oob_scores = np.zeros(len(n_iter))
i = 0
for b in n_iter:
print("n_bags = ", b)
bag_reg = BaggingRegressor(base_estimator= LinearRegression(),
n_estimators = b, oob_score=True, n_jobs=-1, random_state=1)
bag_reg.fit(X_boston_train, y_boston_train)
oob_scores[i] = bag_reg.oob_score_
i += 1
plt.figure(figsize=(10,4))
plt.plot(n_iter, oob_scores, "b-", label="OOB Scores")
plt.xlabel("# Bootrstrap Replications")
plt.ylabel("OOB Score")
plt.title("Boston Data: Bagging with Linear Regression")
plt.show()
best_B = n_iter[np.argmax(oob_scores)]
best_bag = BaggingRegressor(base_estimator= LinearRegression(),
n_estimators = best_B, n_jobs=-1, random_state=1)
best_bag.fit(X_boston_train, y_boston_train)
best_bag.score(X_boston_test, y_boston_test)
# Import Data
data = pd.read_csv("./data/ensembles/moons.csv")
X_moons = data.iloc[:,:2].to_numpy()
y_moons = data["y"].to_numpy()
X_moons_train, X_moons_test, y_moons_train, y_moons_test = train_test_split(X_moons, y_moons,
stratify=y_moons, test_size=0.2,
random_state=1)
plt.figure(figsize=(10,5))
plt.plot(X_moons_train[y_moons_train==0,0], X_moons_train[y_moons_train==0,1], "bo", label="Class 0")
plt.plot(X_moons_train[y_moons_train==1,0], X_moons_train[y_moons_train==1,1], "ro", label="Class 1")
plt.xlabel("x1")
plt.ylabel("x2")
plt.legend()
plt.show()
from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier(n_estimators=500, criterion="gini", max_features="sqrt", oob_score=True, random_state=2)
rfc.fit(X_moons_train, y_moons_train)
rfc.oob_score_
rfc.score(X_moons_test, y_moons_test)
x1_r = np.arange(X_moons_train[:,0].min()-0.1, X_moons_train[:,0].max()+0.1, 0.01)
x2_r = np.arange(X_moons_train[:,1].min()-0.1, X_moons_train[:,1].max()+0.1, 0.01)
xx1, xx2 = np.meshgrid(x1_r, x2_r)
z = rfc.predict(np.c_[xx1.ravel(), xx2.ravel()]).reshape(xx1.shape)
plt.figure(figsize=(10,5))
plt.contour(xx1, xx2, z, levels=1, colors='k', alpha=1., linewidths=1, linestyles='-')
plt.plot(X_moons_train[y_moons_train==0,0], X_moons_train[y_moons_train==0,1], "bo", label="Class 0")
plt.plot(X_moons_train[y_moons_train==1,0], X_moons_train[y_moons_train==1,1], "ro", label="Class 1")
plt.xlabel("x1")
plt.ylabel("x2")
plt.legend()
plt.show()
rfc.feature_importances_
from sklearn.ensemble import GradientBoostingRegressor
gdb = GradientBoostingRegressor(loss='ls', learning_rate=1e-1, n_estimators=500, max_depth=1, random_state=1)
gdb.fit(X_boston_train, y_boston_train)
gdb.score(X_boston_test, y_boston_test)
np.c_[features, gdb.feature_importances_]
plt.figure(figsize=(10,4))
plt.subplot(1,2, 1)
plt.plot(X_boston_train[:,12],y_boston_train, "bo")
plt.xlabel("LSTAT")
plt.ylabel("House Prices")
plt.subplot(1,2, 2)
plt.plot(X_boston_train[:,5],y_boston_train, "bo")
plt.xlabel("RM")
plt.ylabel("House Prices")
plt.show()
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
ada = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=1),
n_estimators=50, learning_rate=1., random_state=1)
ada.fit(X_moons_train, y_moons_train)
ada.score(X_moons_test, y_moons_test)
x1_r = np.arange(X_moons_train[:,0].min()-0.1, X_moons_train[:,0].max()+0.1, 0.01)
x2_r = np.arange(X_moons_train[:,1].min()-0.1, X_moons_train[:,1].max()+0.1, 0.01)
xx1, xx2 = np.meshgrid(x1_r, x2_r)
z = ada.predict(np.c_[xx1.ravel(), xx2.ravel()]).reshape(xx1.shape)
plt.figure(figsize=(10,5))
plt.contour(xx1, xx2, z, levels=1, colors='k', alpha=1., linewidths=1, linestyles='-')
plt.plot(X_moons_train[y_moons_train==0,0], X_moons_train[y_moons_train==0,1], "bo", label="Class 0")
plt.plot(X_moons_train[y_moons_train==1,0], X_moons_train[y_moons_train==1,1], "ro", label="Class 1")
plt.xlabel("x1")
plt.ylabel("x2")
plt.legend()
plt.show()
ada.feature_importances_
data_train = pd.read_csv("./data/heart_data/heart_train_processed.csv")
data_test = pd.read_csv("./data/heart_data/heart_test_processed.csv")
X_train = data_train.drop("y", axis=1)
X_test = data_test.drop("y", axis=1)
y_train = data_train["y"]
y_test = data_test["y"]
from sklearn.pipeline import Pipeline
from scipy.stats import reciprocal # Reciprocal distribution in scipy.stats
from sklearn.model_selection import RandomizedSearchCV
pipe = Pipeline([('classifier', RandomForestClassifier())])
n_trees = [50, 100, 500, 1000]
# Create space of candidate learning algorithms and their hyperparameters
search_space = [{'classifier': [AdaBoostClassifier(random_state=1)],
'classifier__learning_rate': reciprocal(1e-4, 9.9e-1),
'classifier__n_estimators': n_trees},
{'classifier': [RandomForestClassifier(random_state=1)],
'classifier__n_estimators': n_trees,
'classifier__max_features': [2, 3, "sqrt"]}]
rnd_search_cv = RandomizedSearchCV(pipe, search_space, n_iter=50, cv=10, n_jobs=-1, iid=False,
random_state=1, verbose=2)
rnd_search_cv.fit(X_train, y_train)
print("Randomized Search: Done")
rnd_search_cv.best_estimator_
rnd_search_cv.best_params_
rnd_search_cv.best_score_
results = pd.DataFrame(rnd_search_cv.cv_results_).sort_values(["mean_test_score"],
ascending=False)
results.head(10)
# Plot accuracy of 20 best models
best = 20
fig = plt.figure(figsize=(15,5))
ax = plt.subplot(1,1,1)
ax.tick_params(axis='x', rotation=90)
plt.errorbar(range(best), results.iloc[0:best]["mean_test_score"],
yerr=results.iloc[0:best]["std_test_score"], c="blue", label="1. Std. Error", alpha=0.6,
linewidth=2)
plt.plot(range(best), results.iloc[0:best]["mean_test_score"],
"ro", label="Avg. Accuracy", markersize=9)
plt.xticks(range(best), labels=results.iloc[0:best]["params"],
fontweight='bold', fontsize=5)
plt.xlabel('Parameter Set', fontsize=12)
plt.title('Heart Data: AdaBoost vs. RandomForest (random search)', fontsize=15)
plt.ylabel("Accuracy",fontsize=12)
plt.legend(loc=3)
plt.ylim(0.5,1)
plt.show()
importances = rnd_search_cv.best_estimator_['classifier'].feature_importances_
ind_sort = np.argsort(importances)
plt.figure(figsize=(8,5))
plt.barh(np.arange(1, X_train.shape[1]+1, 1), importances[ind_sort])
plt.yticks(np.arange(1, X_train.shape[1]+1, 1), labels=X_train.columns[list(ind_sort)])
plt.show()
rnd_search_cv.score(X_test, y_test)
| 0.614857 | 0.989399 |
# Setting up
Eventually, the folder for this class on your computer will look like something like this:
```
FIN377
└───LeDatSciFi-2022
│ ... <-- has lots o'stuff in it
│
└───ASGN01-donbowen <-- whatever your GH username is
│ ... <-- has lots o'stuff in it
│
└───Class Notes <-- organize as you want, here is suggestion:
│ README.md
│ .gitignore
│ Module 1 Notes.ipynb
│ Module 2 Notes.ipynb
│ │
│ └───exercises <-- a place to put worksheet files
│ │
│ └───handouts <-- you can copy handouts here
│ │
│ └───learning python <-- you can add folders place to put
│ │ some_practice_stuff.py
│ │ more_practice_stuff.py
│ │ ...
│
... <-- more future assignment and project folders
```
## Let's go!
After the steps below, you will be ready to work on assignment 1, and work on problems in class. As a bonus, doing these will also teach you a lot about using GitHub in the process, but also check out the [textbook's chapter's on it (1.3-1.4).](https://ledatascifi.github.io/ledatascifi-2022/content/01/03_github.html#necessary-skills)
Before you start these, you need to have completed [the setup steps](https://ledatascifi.github.io/ledatascifi-2022/content/01/02_Setup.html).
1. Pick a place on your computer to store your work from this class. Put a folder there called FIN377.
- It's your call where. Some students use the GitHub folder created by GitHub Desktop. Some use the desktop. Some put it inside their school folder.
1. **Let's download the textbook (ledatascifi-2022).** This will make it easy as Py for you to download handouts, lecture slides, etc:
1. Open GitHub Desktop (GH-D) and click File > "Clone repository"
1. In the pop up: Go to the URL tab. Put "ledatascifi/ledatascifi-2022" in the first line. In the second line, put the path to your FIN377 folder. Click clone.
1. After it downloads (slow the first time), you can quickly download new lecture slides, handouts etc. by clicking "Fetch Origin".
1. **Note: Don't work on handouts in this folder, "because I can overwrite it." Instead, copy the handouts to your own notes folder, and work there.**
1. [Here is a good trick](https://ledatascifi.github.io/ledatascifi-2022/content/01/05_jupyterlab.html#a-good-trick-how-do-i-copy-code-from-one-file-to-another) you can use to quickly copy code from the textbook (or anywhere) into notes (or your assignment files)
1. **Let's make a repo for your class notes inside the 377 folder.** Call it "Class Notes"
1. Copy FIN 377/LeDatSciFi-2022/Handouts/Module 1 notes.ipynb (which is on your computer now) into it
1. Open GH-D. File > New Repository. In that popup:
1. Name: Class Notes
1. Local Path: ...FIN 377 (stop at FIN 377)
1. Click box to initialize with a README
1. In the gitignore, I would select python
1. Click "publish", then "publish again" (Yes, keep this code private)
1. To modify a repo in the cloud (sometimes the fastest way to change things)
1. Go to the webpage of your class notes repo. (One way: In GH-D, make sure your class notes repo is selected in the upper left. Then click Repository > View on GitHub)
1. Click on the pencil next to the readme
2. This is the "front page" of your repo, so let's make it useful to visitors (including future you!)
3. Type your name.
4. "Commit" the changes to "save" it. See your name when you look at the README online?
5. Now go to your class notes folder _on your computer_. Open the README.md file (in a text editor like Notepad). See - your name is missing! We need to download the changes _from the website to your computer_.
6. Close the README file you just opened. Go to GH-D, and click "Fetch origin" to download any changes made. Reopen the readme file and you should see your name!
1. To work on a file on your computer and save that work to the repo in the cloud:
1. Open the README.md file from your class notes. Copy the text below into it.
```
Key links:
- [The main website](https://ledatascifi.github.io)
- [The dashboard](https://ledatascifi.github.io/ledatascifi-2022/content/about/schedule.html)
- [Tips](https://ledatascifi.github.io/ledatascifi-2022/content/about/tips.html)
- [Help](https://ledatascifi.github.io/ledatascifi-2022/content/about/help.html)
- [The LDSF org](https://github.com/orgs/LeDataSciFi)
- [Announcements, discussions, and help](https://github.com/orgs/LeDataSciFi/teams/classmates-2022)
- [Lecture files (e.g. "powerpoints")](https://github.com/LeDataSciFi/ledatascifi-2022/tree/main/lectures)
```
1. Save the file.
1. Open GH-D, and you'll see it's detected changes to that file. In the "summary" box, add a note about what you're doing (makes it easier to see contributions to work, go back in time, etc).
1. Click the blue "commit" button and then "push"
1. Look at the repo on the website (refresh the page), and you'll see the changes!
1. You can use this readme to store useful links as you wish.
1. **Let's start the assignment.**
1. Click on the assignment link in coursesite and follow the prompts.
1. Read the instructions/instructions.md file once the repo is created.
1. Open GitHub Desktop (GH-D) and click File > "Clone repository"
1. Under the "GitHub.com" tab, you should see that repo. Make sure the local path ends at you FIN377 folder.
1. Clone it.
1. Now you can begin working on the assignment!
1. Read the [GitHub workflow!](https://ledatascifi.github.io/ledatascifi-2022/content/01/03a_githubworkflow.html) You should do these three things repeatedly as you work, and it's good to get into the habit starting now.
1. Practice: Sometimes it is useful to download a single file off a repo anywhere on GitHub to your computer.
1. Go to any repo, and click on any file.
1. On the next page that opens, right click the “Raw” button and “Save Link As”.
1. You can save it to your downloads folder, doesn't matter. The point is to see how to do this.
1. Optional exercises: https://ledatascifi.github.io/ledatascifi-2022/content/01/03_github.html#optional-exercises
|
github_jupyter
|
FIN377
└───LeDatSciFi-2022
│ ... <-- has lots o'stuff in it
│
└───ASGN01-donbowen <-- whatever your GH username is
│ ... <-- has lots o'stuff in it
│
└───Class Notes <-- organize as you want, here is suggestion:
│ README.md
│ .gitignore
│ Module 1 Notes.ipynb
│ Module 2 Notes.ipynb
│ │
│ └───exercises <-- a place to put worksheet files
│ │
│ └───handouts <-- you can copy handouts here
│ │
│ └───learning python <-- you can add folders place to put
│ │ some_practice_stuff.py
│ │ more_practice_stuff.py
│ │ ...
│
... <-- more future assignment and project folders
| 0.343122 | 0.783326 |
# Artificial Intelligence Nanodegree
## Convolutional Neural Networks
---
In this notebook, we train an MLP to classify images from the MNIST database.
### 1. Load MNIST Database
```
from keras.datasets import mnist
# use Keras to import pre-shuffled MNIST database
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print("The MNIST database has a training set of %d examples." % len(X_train))
print("The MNIST database has a test set of %d examples." % len(X_test))
```
### 2. Visualize the First Six Training Images
```
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib.cm as cm
import numpy as np
# plot first six training images
fig = plt.figure(figsize=(20,20))
for i in range(6):
ax = fig.add_subplot(1, 6, i+1, xticks=[], yticks=[])
ax.imshow(X_train[i], cmap='gray')
ax.set_title(str(y_train[i]))
```
### 3. View an Image in More Detail
```
def visualize_input(img, ax):
ax.imshow(img, cmap='gray')
width, height = img.shape
thresh = img.max()/2.5
for x in range(width):
for y in range(height):
ax.annotate(str(round(img[x][y],2)), xy=(y,x),
horizontalalignment='center',
verticalalignment='center',
color='white' if img[x][y]<thresh else 'black')
fig = plt.figure(figsize = (12,12))
ax = fig.add_subplot(111)
visualize_input(X_train[0], ax)
```
### 4. Rescale the Images by Dividing Every Pixel in Every Image by 255
```
# rescale [0,255] --> [0,1]
X_train = X_train.astype('float32')/255
X_test = X_test.astype('float32')/255
```
### 5. Encode Categorical Integer Labels Using a One-Hot Scheme
```
from keras.utils import np_utils
# print first ten (integer-valued) training labels
print('Integer-valued labels:')
print(y_train[:10])
# one-hot encode the labels
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
# print first ten (one-hot) training labels
print('One-hot labels:')
print(y_train[:10])
```
### 6. Define the Model Architecture
```
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
# define the model
model = Sequential()
model.add(Flatten(input_shape=X_train.shape[1:]))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))
# summarize the model
model.summary()
```
### 7. Compile the Model
```
# compile the model
model.compile(loss='categorical_crossentropy', optimizer='rmsprop',
metrics=['accuracy'])
```
### 8. Calculate the Classification Accuracy on the Test Set (Before Training)
```
# evaluate test accuracy
score = model.evaluate(X_test, y_test, verbose=0)
accuracy = 100*score[1]
# print test accuracy
print('Test accuracy: %.4f%%' % accuracy)
```
### 9. Train the Model
```
from keras.callbacks import ModelCheckpoint
# train the model
checkpointer = ModelCheckpoint(filepath='mnist.model.best.hdf5',
verbose=1, save_best_only=True)
hist = model.fit(X_train, y_train, batch_size=128, epochs=10,
validation_split=0.2, callbacks=[checkpointer],
verbose=1, shuffle=True)
```
### 10. Load the Model with the Best Classification Accuracy on the Validation Set
```
# load the weights that yielded the best validation accuracy
model.load_weights('mnist.model.best.hdf5')
```
### 11. Calculate the Classification Accuracy on the Test Set
```
# evaluate test accuracy
score = model.evaluate(X_test, y_test, verbose=0)
accuracy = 100*score[1]
# print test accuracy
print('Test accuracy: %.4f%%' % accuracy)
```
|
github_jupyter
|
from keras.datasets import mnist
# use Keras to import pre-shuffled MNIST database
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print("The MNIST database has a training set of %d examples." % len(X_train))
print("The MNIST database has a test set of %d examples." % len(X_test))
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib.cm as cm
import numpy as np
# plot first six training images
fig = plt.figure(figsize=(20,20))
for i in range(6):
ax = fig.add_subplot(1, 6, i+1, xticks=[], yticks=[])
ax.imshow(X_train[i], cmap='gray')
ax.set_title(str(y_train[i]))
def visualize_input(img, ax):
ax.imshow(img, cmap='gray')
width, height = img.shape
thresh = img.max()/2.5
for x in range(width):
for y in range(height):
ax.annotate(str(round(img[x][y],2)), xy=(y,x),
horizontalalignment='center',
verticalalignment='center',
color='white' if img[x][y]<thresh else 'black')
fig = plt.figure(figsize = (12,12))
ax = fig.add_subplot(111)
visualize_input(X_train[0], ax)
# rescale [0,255] --> [0,1]
X_train = X_train.astype('float32')/255
X_test = X_test.astype('float32')/255
from keras.utils import np_utils
# print first ten (integer-valued) training labels
print('Integer-valued labels:')
print(y_train[:10])
# one-hot encode the labels
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
# print first ten (one-hot) training labels
print('One-hot labels:')
print(y_train[:10])
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
# define the model
model = Sequential()
model.add(Flatten(input_shape=X_train.shape[1:]))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))
# summarize the model
model.summary()
# compile the model
model.compile(loss='categorical_crossentropy', optimizer='rmsprop',
metrics=['accuracy'])
# evaluate test accuracy
score = model.evaluate(X_test, y_test, verbose=0)
accuracy = 100*score[1]
# print test accuracy
print('Test accuracy: %.4f%%' % accuracy)
from keras.callbacks import ModelCheckpoint
# train the model
checkpointer = ModelCheckpoint(filepath='mnist.model.best.hdf5',
verbose=1, save_best_only=True)
hist = model.fit(X_train, y_train, batch_size=128, epochs=10,
validation_split=0.2, callbacks=[checkpointer],
verbose=1, shuffle=True)
# load the weights that yielded the best validation accuracy
model.load_weights('mnist.model.best.hdf5')
# evaluate test accuracy
score = model.evaluate(X_test, y_test, verbose=0)
accuracy = 100*score[1]
# print test accuracy
print('Test accuracy: %.4f%%' % accuracy)
| 0.686055 | 0.980375 |
# Understanding Deepfakes with Keras

# Task 1: Importing Libraries and Helper Functions
Please note: If you haven't already, please install the required packages by executing the code cell below.
```
!pip3 install tensorflow
!pip3 install git+https://github.com/am1tyadav/tfutils.git
#!pip install tfutils
%matplotlib notebook
import tensorflow as tf
import numpy as np
import os
import tfutils
from matplotlib import pyplot as plt
from tensorflow.keras.layers import Dense, Flatten, Conv2D, BatchNormalization
from tensorflow.keras.layers import Conv2DTranspose, Reshape, LeakyReLU
from tensorflow.keras.models import Model, Sequential
from PIL import Image
print('TensorFlow version:', tf.__version__)
```
# Task 2: Importing and Plotting the Data
```
(x_train, y_train), (x_test, y_test) = tfutils.datasets.mnist.load_data(one_hot=False)
x_train = tfutils.datasets.mnist.load_subset([0], x_train, y_train)
x_test = tfutils.datasets.mnist.load_subset([0], x_test, y_test)
x = np.concatenate([x_train, x_test], axis=0)
tfutils.datasets.mnist.plot_ten_random_examples(plt, x, np.zeros((x.shape[0], 1))).show()
```
# Task 3: Discriminator

```
size = 28
noise_dim = 1
discriminator = Sequential([
Conv2D(64, 3, strides=2, input_shape=(28, 28, 1)),
LeakyReLU(),
BatchNormalization(),
Conv2D(128, 5, strides=2),
LeakyReLU(),
BatchNormalization(),
Conv2D(256, 5, strides=2),
LeakyReLU(),
BatchNormalization(),
Flatten(),
Dense(1, activation='sigmoid')
])
opt = tf.keras.optimizers.Adam(lr=2e-4, beta_1=0.5)
discriminator.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
discriminator.summary()
```
# Task 4: Generator
```
generator = Sequential([
Dense(256, activation='relu', input_shape=(noise_dim,)),
Reshape((1, 1, 256)),
Conv2DTranspose(256, 5, activation='relu'),
BatchNormalization(),
Conv2DTranspose(128, 5, activation='relu'),
BatchNormalization(),
Conv2DTranspose(64, 5, strides=2, activation='relu'),
BatchNormalization(),
Conv2DTranspose(32, 5, activation='relu'),
BatchNormalization(),
Conv2DTranspose(1, 4, activation='sigmoid')
])
generator.summary()
noise = np.random.randn(1, noise_dim)
gen_image = generator.predict(noise)[0]
plt.figure()
plt.imshow(np.reshape(gen_image, (28, 28)), cmap='binary')
```
# Task 5: Generative Adversarial Network (GAN)
```
input_layer = tf.keras.layers.Input(shape=(noise_dim,))
gen_out = generator(input_layer)
disc_out = discriminator(gen_out)
gan = Model(
input_layer,
disc_out
)
discriminator.trainable = False
gan.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
gan.summary()
```
# Tasks 6 and 7: Training the GAN
```
%%time
epochs = 25
batch_size = 128
steps_per_epoch = int(2 * x.shape[0]/batch_size)
print('Steps per epoch=', steps_per_epoch)
dp = tfutils.plotting.DynamicPlot(plt, 5, 5, (8, 8))
for e in range(0, epochs):
dp.start_of_epoch(e)
for step in range(0, steps_per_epoch):
true_examples = x[int(batch_size/2)*step: int(batch_size/2)*(step + 1)]
true_examples = np.reshape(true_examples, (true_examples.shape[0], 28, 28, 1))
noise = np.random.randn(int(batch_size/2), noise_dim)
generated_examples = generator.predict(noise)
x_batch = np.concatenate([generated_examples, true_examples], axis=0)
y_batch = np.array([0] * int(batch_size/2) + [1] * int(batch_size/2))
indices = np.random.choice(range(batch_size), batch_size, replace=False)
x_batch = x_batch[indices]
y_batch = y_batch[indices]
# train the discriminator
discriminator.trainable = True
discriminator.train_on_batch(x_batch, y_batch)
discriminator.trainable = False
# train the generator
loss, _ = gan.train_on_batch(noise, np.ones((int(batch_size/2), 1)))
_, acc = discriminator.evaluate(x_batch, y_batch, verbose=False)
noise = np.random.randn(1, noise_dim)
generated_example = generator.predict(noise)[0]
dp.end_of_epoch(np.reshape(generated_example, (28, 28)), 'binary',
'DiscAcc:{:.2f}'.format(acc), 'GANLoss:{:.2f}'.format(loss))
```
|
github_jupyter
|
!pip3 install tensorflow
!pip3 install git+https://github.com/am1tyadav/tfutils.git
#!pip install tfutils
%matplotlib notebook
import tensorflow as tf
import numpy as np
import os
import tfutils
from matplotlib import pyplot as plt
from tensorflow.keras.layers import Dense, Flatten, Conv2D, BatchNormalization
from tensorflow.keras.layers import Conv2DTranspose, Reshape, LeakyReLU
from tensorflow.keras.models import Model, Sequential
from PIL import Image
print('TensorFlow version:', tf.__version__)
(x_train, y_train), (x_test, y_test) = tfutils.datasets.mnist.load_data(one_hot=False)
x_train = tfutils.datasets.mnist.load_subset([0], x_train, y_train)
x_test = tfutils.datasets.mnist.load_subset([0], x_test, y_test)
x = np.concatenate([x_train, x_test], axis=0)
tfutils.datasets.mnist.plot_ten_random_examples(plt, x, np.zeros((x.shape[0], 1))).show()
size = 28
noise_dim = 1
discriminator = Sequential([
Conv2D(64, 3, strides=2, input_shape=(28, 28, 1)),
LeakyReLU(),
BatchNormalization(),
Conv2D(128, 5, strides=2),
LeakyReLU(),
BatchNormalization(),
Conv2D(256, 5, strides=2),
LeakyReLU(),
BatchNormalization(),
Flatten(),
Dense(1, activation='sigmoid')
])
opt = tf.keras.optimizers.Adam(lr=2e-4, beta_1=0.5)
discriminator.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
discriminator.summary()
generator = Sequential([
Dense(256, activation='relu', input_shape=(noise_dim,)),
Reshape((1, 1, 256)),
Conv2DTranspose(256, 5, activation='relu'),
BatchNormalization(),
Conv2DTranspose(128, 5, activation='relu'),
BatchNormalization(),
Conv2DTranspose(64, 5, strides=2, activation='relu'),
BatchNormalization(),
Conv2DTranspose(32, 5, activation='relu'),
BatchNormalization(),
Conv2DTranspose(1, 4, activation='sigmoid')
])
generator.summary()
noise = np.random.randn(1, noise_dim)
gen_image = generator.predict(noise)[0]
plt.figure()
plt.imshow(np.reshape(gen_image, (28, 28)), cmap='binary')
input_layer = tf.keras.layers.Input(shape=(noise_dim,))
gen_out = generator(input_layer)
disc_out = discriminator(gen_out)
gan = Model(
input_layer,
disc_out
)
discriminator.trainable = False
gan.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
gan.summary()
%%time
epochs = 25
batch_size = 128
steps_per_epoch = int(2 * x.shape[0]/batch_size)
print('Steps per epoch=', steps_per_epoch)
dp = tfutils.plotting.DynamicPlot(plt, 5, 5, (8, 8))
for e in range(0, epochs):
dp.start_of_epoch(e)
for step in range(0, steps_per_epoch):
true_examples = x[int(batch_size/2)*step: int(batch_size/2)*(step + 1)]
true_examples = np.reshape(true_examples, (true_examples.shape[0], 28, 28, 1))
noise = np.random.randn(int(batch_size/2), noise_dim)
generated_examples = generator.predict(noise)
x_batch = np.concatenate([generated_examples, true_examples], axis=0)
y_batch = np.array([0] * int(batch_size/2) + [1] * int(batch_size/2))
indices = np.random.choice(range(batch_size), batch_size, replace=False)
x_batch = x_batch[indices]
y_batch = y_batch[indices]
# train the discriminator
discriminator.trainable = True
discriminator.train_on_batch(x_batch, y_batch)
discriminator.trainable = False
# train the generator
loss, _ = gan.train_on_batch(noise, np.ones((int(batch_size/2), 1)))
_, acc = discriminator.evaluate(x_batch, y_batch, verbose=False)
noise = np.random.randn(1, noise_dim)
generated_example = generator.predict(noise)[0]
dp.end_of_epoch(np.reshape(generated_example, (28, 28)), 'binary',
'DiscAcc:{:.2f}'.format(acc), 'GANLoss:{:.2f}'.format(loss))
| 0.874339 | 0.959687 |
# MNIST Example
In this notebook we'll use the `vegans` library to generate some fake handwritten digits, using a generator and discriminator of our choice.
### Initial Setup
First, some imports:
```
import os
import torch
import pickle
import numpy as np
import torch.nn as nn
import matplotlib.pyplot as plt
import vegans.utils.loading as loading
from vegans.GAN import WassersteinGAN, WassersteinGANGP
from vegans.utils.utils import plot_losses, plot_images
# do we have cuda?
print('Cuda is available: {}'.format(torch.cuda.is_available()))
device = "cuda" if torch.cuda.is_available() else "cpu"
```
Now download the mnist dataset and set the parameters below (To get exactly the same format as in this tutorial download from [here](https://github.com/tneuer/GAN-pytorch/tree/main/data/mnist), but of course you can load it from anywhere you want):
```
# This directory will contain the MNIST data
datapath = "./data"
# Size of z latent vector (i.e. size of generator input)
z_dim = [1, 4, 4]
# Input channels
nc = 1
# Padding for mnist images (28x28) -> (32x32)
pad = 2
```
Now load and preprocess the data:
- The images are saved in gray scale from 0-255, so we scale it to 0-1. Then we can use a Sigmoid as the last layer of the generator.
- The original image shape is (28, 28) but when working with convolutional layers it is often beneficial to have a power of two. Therefore we pad two empty rows and columns to every image.
- Finally we reshape the images because we need the images in the shape of (nr_channels, nr_heiht_pixels, nr_width_pixels). In out case this results in [1, 32, 32]
```
""" Create dataset
"""
X_train, y_train, X_test, y_test = loading.load_data(datapath, which="mnist", download=True)
X_train = X_train.reshape((-1, 1, 32, 32))
X_test = X_test.reshape((-1, 1, 32, 32))
X_train = X_train / np.max(X_train)
X_test = X_test / np.max(X_test)
print(X_train.shape, X_test.shape)
x_dim = X_train.shape[1:]
```
Plot some of the training images:
```
fig, axs = plot_images(images=X_train.reshape(-1, 32, 32))
```
### Definition of Generator and Discriminator / Critic
We'll specify the architecture of the generator and discriminator / critic networks. It's difficult to know which architectures to choose before training. Here we used a architecture which proved to work.
Since we want to train a Wasserstein GAN, the output of the critic should be a real number and not a probability. Therefore we drop the last sigmoid and use the identity function. If you want to switch to a architecture that uses a discriminator switch the `nn.Identity` with `nn.Sigmoid` for the adversary.
```
""" Generator
"""
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
ngf = 20
self.hidden_part = nn.Sequential(
nn.ConvTranspose2d(in_channels=z_dim[0], out_channels=ngf * 8, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(ngf * 8),
nn.LeakyReLU(0.1),
# state size. (ngf*8) x 4 x 4
nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1),
nn.BatchNorm2d(ngf * 4),
nn.LeakyReLU(0.1),
# state size. (ngf*4) x 8 x 8
nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1),
nn.BatchNorm2d(ngf * 2),
nn.LeakyReLU(0.1),
nn.Conv2d(ngf * 2, ngf * 2, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(ngf * 2),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ngf*2) x 16 x 16
nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1),
nn.BatchNorm2d(ngf),
nn.LeakyReLU(0.1),
nn.Conv2d(ngf, ngf, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(ngf),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ngf) x 32 x 32
nn.ConvTranspose2d(ngf, nc, 5, 1, 2),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(nc, nc, kernel_size=3, stride=1, padding=1),
)
self.output = nn.Sigmoid()
def forward(self, x):
x = self.hidden_part(x)
x = self.output(x)
return x
""" Adversary
"""
class Critic(nn.Module):
def __init__(self):
super(Critic, self).__init__()
ncf = 8
self.hidden_part = nn.Sequential(
# input is (nc) x 32 x 32
nn.Conv2d(in_channels=nc, out_channels=ncf, kernel_size=3, stride=2, padding=1),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ncf) x 16 x 16
nn.Conv2d(ncf, ncf * 2, 4, 2, 1),
nn.BatchNorm2d(ncf * 2),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ncf*2) x 8 x 8
nn.Conv2d(ncf * 2, ncf * 4, 4, 2, 1),
nn.BatchNorm2d(ncf * 4),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ncf*4) x 4 x 4
nn.Conv2d(ncf * 4, ncf * 8, 4, 2, 1),
nn.BatchNorm2d(ncf * 8),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ncf*8) x 2 x 2
nn.Flatten(),
nn.Linear(in_features=ncf*8*2*2, out_features=32),
nn.ReLU(),
nn.Linear(in_features=32, out_features=1)
)
self.output = nn.Identity()
def forward(self, x):
x = self.hidden_part(x)
x = self.output(x)
return x
generator = Generator()
critic = Critic()
```
### Train our GAN
Build a Wasserstein GAN trainer, using default optimizers (we can also specify our own). To use a different GAN algorithm, just use the corresponding class (e.g., `VanillaGAN` for original GAN).
Here you can specify some optional GAN parameters, such as the latent space dimension `z_dim`, the number of samples to save (`fixed_noise_size`) and the optimizer keyword arguments (`optim_kwargs`). We set `folder=None` so that no folder is created where all results would be stored. Otherwise we could give a path like `folder="TrainedModels/GAN"`. All results (summary, images, loss functions, tensorboard information, models) would be saved in that folder. You can control what should be saved in the `fit` method. This folder will never overwrite an existing folder. If the path already exists a new path of the form `folder=path_{TimeStamp}` is created.
We also decrease the learning rate of the critic a little.
```
optim_kwargs = {"Generator": {"lr": 0.0005}, "Adversary": {"lr": 0.0001}}
gan = WassersteinGAN(
generator, critic, z_dim=z_dim, x_dim=x_dim,
optim_kwargs=optim_kwargs, fixed_noise_size=20, folder=None
)
gan.summary()
```
Train the networks by calling the `fit()` method. Here you can specify some parameters for training like `eochs`, `batch_size`, `save_model_every`, `save_images_every`, `print_every`, `enable_tensorboard` and others.
You can interrupt training at any time and still access train stats from within the `gan` object. You can resume training later. Note that we increase the number of steps the critic (adversary) is trained, which is common for Wasserstein GANs but not VanillaGANs so take care when switching out algorithms.
```
steps = {"Adversary": 5}
gan.fit(
X_train, epochs=5, steps=steps,
print_every="0.25e", save_losses_every=10, enable_tensorboard=False
)
samples, losses = gan.get_training_results()
fig, axs = plot_losses(losses)
print(samples.shape)
fig, axs = plot_images(samples.reshape(-1, 32, 32), n=9)
```
Now we want to generate new images and have control over the number of generated images. Note that the `get_training_results` returns as many images as were specified with the `fixed_noise_size` argument in the constructor when creating the GAN.
```
new_samples = gan.generate(n=100)
print(new_samples.shape)
fig, axs = plot_images(samples.reshape(-1, 32, 32))
```
|
github_jupyter
|
import os
import torch
import pickle
import numpy as np
import torch.nn as nn
import matplotlib.pyplot as plt
import vegans.utils.loading as loading
from vegans.GAN import WassersteinGAN, WassersteinGANGP
from vegans.utils.utils import plot_losses, plot_images
# do we have cuda?
print('Cuda is available: {}'.format(torch.cuda.is_available()))
device = "cuda" if torch.cuda.is_available() else "cpu"
# This directory will contain the MNIST data
datapath = "./data"
# Size of z latent vector (i.e. size of generator input)
z_dim = [1, 4, 4]
# Input channels
nc = 1
# Padding for mnist images (28x28) -> (32x32)
pad = 2
""" Create dataset
"""
X_train, y_train, X_test, y_test = loading.load_data(datapath, which="mnist", download=True)
X_train = X_train.reshape((-1, 1, 32, 32))
X_test = X_test.reshape((-1, 1, 32, 32))
X_train = X_train / np.max(X_train)
X_test = X_test / np.max(X_test)
print(X_train.shape, X_test.shape)
x_dim = X_train.shape[1:]
fig, axs = plot_images(images=X_train.reshape(-1, 32, 32))
""" Generator
"""
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
ngf = 20
self.hidden_part = nn.Sequential(
nn.ConvTranspose2d(in_channels=z_dim[0], out_channels=ngf * 8, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(ngf * 8),
nn.LeakyReLU(0.1),
# state size. (ngf*8) x 4 x 4
nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1),
nn.BatchNorm2d(ngf * 4),
nn.LeakyReLU(0.1),
# state size. (ngf*4) x 8 x 8
nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1),
nn.BatchNorm2d(ngf * 2),
nn.LeakyReLU(0.1),
nn.Conv2d(ngf * 2, ngf * 2, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(ngf * 2),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ngf*2) x 16 x 16
nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1),
nn.BatchNorm2d(ngf),
nn.LeakyReLU(0.1),
nn.Conv2d(ngf, ngf, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(ngf),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ngf) x 32 x 32
nn.ConvTranspose2d(ngf, nc, 5, 1, 2),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(nc, nc, kernel_size=3, stride=1, padding=1),
)
self.output = nn.Sigmoid()
def forward(self, x):
x = self.hidden_part(x)
x = self.output(x)
return x
""" Adversary
"""
class Critic(nn.Module):
def __init__(self):
super(Critic, self).__init__()
ncf = 8
self.hidden_part = nn.Sequential(
# input is (nc) x 32 x 32
nn.Conv2d(in_channels=nc, out_channels=ncf, kernel_size=3, stride=2, padding=1),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ncf) x 16 x 16
nn.Conv2d(ncf, ncf * 2, 4, 2, 1),
nn.BatchNorm2d(ncf * 2),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ncf*2) x 8 x 8
nn.Conv2d(ncf * 2, ncf * 4, 4, 2, 1),
nn.BatchNorm2d(ncf * 4),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ncf*4) x 4 x 4
nn.Conv2d(ncf * 4, ncf * 8, 4, 2, 1),
nn.BatchNorm2d(ncf * 8),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ncf*8) x 2 x 2
nn.Flatten(),
nn.Linear(in_features=ncf*8*2*2, out_features=32),
nn.ReLU(),
nn.Linear(in_features=32, out_features=1)
)
self.output = nn.Identity()
def forward(self, x):
x = self.hidden_part(x)
x = self.output(x)
return x
generator = Generator()
critic = Critic()
optim_kwargs = {"Generator": {"lr": 0.0005}, "Adversary": {"lr": 0.0001}}
gan = WassersteinGAN(
generator, critic, z_dim=z_dim, x_dim=x_dim,
optim_kwargs=optim_kwargs, fixed_noise_size=20, folder=None
)
gan.summary()
steps = {"Adversary": 5}
gan.fit(
X_train, epochs=5, steps=steps,
print_every="0.25e", save_losses_every=10, enable_tensorboard=False
)
samples, losses = gan.get_training_results()
fig, axs = plot_losses(losses)
print(samples.shape)
fig, axs = plot_images(samples.reshape(-1, 32, 32), n=9)
new_samples = gan.generate(n=100)
print(new_samples.shape)
fig, axs = plot_images(samples.reshape(-1, 32, 32))
| 0.906078 | 0.991628 |
This notebook prepares data extracted by the 01_get_training_data notebook from the HDF5 file contaning simulation data for ML, and trains and evaluates several ML models (decision trees, random forest, polynomial SVM and MLP).
Author: Mariia Lundvall ([email protected]) <br>
Date: 01/21/2019
```
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.svm import LinearSVC
from sklearn import metrics
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from pandas import Series
from matplotlib import pyplot
from tqdm import tqdm_notebook as tqdm
```
<b> NOTE: Update the paths prior to running this notebook. <b>
```
# path to temporal training data
# these files are created by the 01_get_training_data notebook
temp_path = '/home/NETID/lundvm/data/train_data/temp_'
# path to spacial training data
# these files are created by the 01_get_training_data notebook
space_path = '/home/NETID/lundvm/data/train_data/space_'
def prepare_data(path, window_size, data_type):
"""
Prepares data for training. Creates training and test sets (80%/20%).
Args:
path(str): path to the csv containing data
window_size(int): window size
data_type(str): data type, must be 'temp' for temporal and 'space' for spacial.
Returns:
X_train, X_test, y_train, y_test: training and test sets for sklearn machine learning models.
"""
file_name = path + str(window_size) + '.csv'
data = pd.read_csv(file_name, header=None, dtype='int')
if data_type == 'space':
window_size = window_size*2
y = data[window_size]
X = data.drop(window_size, axis=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
return X_train, X_test, y_train, y_test
def train_model(model, X_train, X_test, y_train, y_test):
"""
Trains and tests the given model on the given data. Returns the mean of
cross-validation scores and the test score.
Args:
model(sklearn classifier): model to train and test
X_train, X_test, y_train, y_test: training and test data
Returns:
cv_score(float): mean of the model cross-validation scores (10-fold)
test_score(float): model test score
"""
cv_score = cross_val_score(model, X_train, y_train, cv=10).mean()
model.fit(X_train, y_train)
y_pred_ = model.predict(X_train)
test_score = model.score(X_test, y_test)
return cv_score, test_score
def run_ML(path, windows, models, data_type):
"""
Runs ML.
Args:
path(str): path to the csv containing data
windows(list of ints): window sizes
models(list of sklearn classifiers): list of models to train
data_type(str): data type, must be 'temp' for temporal and 'space' for spacial.
Returns:
none
"""
for w in tqdm(windows):
results = pd.DataFrame(index=['Desicion Tree', 'Random Forest', 'Poly SVM', 'MLP'], columns=[
'CV Score', 'Test Score'])
cv_scores = []
test_scores = []
X_train, X_test, y_train, y_test = prepare_data(path, w, data_type)
for m in models:
cv_score, test_score = train_model(m, X_train, X_test, y_train, y_test)
cv_scores.append(cv_score)
test_scores.append(test_score)
results['CV Score'] = cv_scores
results['Test Score'] = test_scores
print("Window size: " + str(w))
print(results)
print('')
print('Running ML on temporal data\n')
windows=[5, 10, 50, 100, 500]
models=[DecisionTreeClassifier(), RandomForestClassifier(max_depth=2, random_state=0, n_estimators=10),
SVC(degree=2, gamma='scale'), MLPClassifier(hidden_layer_sizes=(100), alpha=0.0001, random_state=0)]
run_ML(temp_path, windows, models, 'temp')
print('Running ML on spacial data\n')
windows=[5, 10, 50, 100, 500]
models=[DecisionTreeClassifier(), RandomForestClassifier(max_depth=2, random_state=0, n_estimators=10),
SVC(degree=2, gamma='scale'), MLPClassifier(hidden_layer_sizes=(100), alpha=0.0001, random_state=0)]
run_ML(space_path, windows, models, 'space')
```
|
github_jupyter
|
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.svm import LinearSVC
from sklearn import metrics
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from pandas import Series
from matplotlib import pyplot
from tqdm import tqdm_notebook as tqdm
# path to temporal training data
# these files are created by the 01_get_training_data notebook
temp_path = '/home/NETID/lundvm/data/train_data/temp_'
# path to spacial training data
# these files are created by the 01_get_training_data notebook
space_path = '/home/NETID/lundvm/data/train_data/space_'
def prepare_data(path, window_size, data_type):
"""
Prepares data for training. Creates training and test sets (80%/20%).
Args:
path(str): path to the csv containing data
window_size(int): window size
data_type(str): data type, must be 'temp' for temporal and 'space' for spacial.
Returns:
X_train, X_test, y_train, y_test: training and test sets for sklearn machine learning models.
"""
file_name = path + str(window_size) + '.csv'
data = pd.read_csv(file_name, header=None, dtype='int')
if data_type == 'space':
window_size = window_size*2
y = data[window_size]
X = data.drop(window_size, axis=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
return X_train, X_test, y_train, y_test
def train_model(model, X_train, X_test, y_train, y_test):
"""
Trains and tests the given model on the given data. Returns the mean of
cross-validation scores and the test score.
Args:
model(sklearn classifier): model to train and test
X_train, X_test, y_train, y_test: training and test data
Returns:
cv_score(float): mean of the model cross-validation scores (10-fold)
test_score(float): model test score
"""
cv_score = cross_val_score(model, X_train, y_train, cv=10).mean()
model.fit(X_train, y_train)
y_pred_ = model.predict(X_train)
test_score = model.score(X_test, y_test)
return cv_score, test_score
def run_ML(path, windows, models, data_type):
"""
Runs ML.
Args:
path(str): path to the csv containing data
windows(list of ints): window sizes
models(list of sklearn classifiers): list of models to train
data_type(str): data type, must be 'temp' for temporal and 'space' for spacial.
Returns:
none
"""
for w in tqdm(windows):
results = pd.DataFrame(index=['Desicion Tree', 'Random Forest', 'Poly SVM', 'MLP'], columns=[
'CV Score', 'Test Score'])
cv_scores = []
test_scores = []
X_train, X_test, y_train, y_test = prepare_data(path, w, data_type)
for m in models:
cv_score, test_score = train_model(m, X_train, X_test, y_train, y_test)
cv_scores.append(cv_score)
test_scores.append(test_score)
results['CV Score'] = cv_scores
results['Test Score'] = test_scores
print("Window size: " + str(w))
print(results)
print('')
print('Running ML on temporal data\n')
windows=[5, 10, 50, 100, 500]
models=[DecisionTreeClassifier(), RandomForestClassifier(max_depth=2, random_state=0, n_estimators=10),
SVC(degree=2, gamma='scale'), MLPClassifier(hidden_layer_sizes=(100), alpha=0.0001, random_state=0)]
run_ML(temp_path, windows, models, 'temp')
print('Running ML on spacial data\n')
windows=[5, 10, 50, 100, 500]
models=[DecisionTreeClassifier(), RandomForestClassifier(max_depth=2, random_state=0, n_estimators=10),
SVC(degree=2, gamma='scale'), MLPClassifier(hidden_layer_sizes=(100), alpha=0.0001, random_state=0)]
run_ML(space_path, windows, models, 'space')
| 0.827793 | 0.946101 |
```
# load in the libraries we will use
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.model_selection import ShuffleSplit
from sklearn.metrics import make_scorer
from sklearn.metrics import r2_score
import visuals as vs
%matplotlib inline
train = pd.read_csv('houseTrain.csv')
test = pd.read_csv('houseTest.csv')
print len(train)
print len(test)
# First split the training data into the features and the target
features = train.drop('SalePrice', axis=1)
target = train.SalePrice
# How many features are there?
print len(features.columns.values)
# Which columns are missing values?
nan_columns = features.columns[pd.isnull(features).any()].tolist()
for i in nan_columns:
print '{0}: {1} {2}'.format(i, features[i].isnull().sum(), features[i].dtypes)
# Let's turn the above into a function
def missing_data_info(df):
'''
Takes: a pandas dataframe which is checked for missing data in the columns. Uses any() method to check for
missing data.
Returns: prints out the name of columns with missing data, the number of missing values, and the dtype of the column
and returns a dictionary of the printed data in the form column_name: [#_missing_values, col_dtype]'''
nan_columns = df.columns[pd.isnull(df).any()].tolist()
nan_dict = {}
for i in nan_columns:
print '{0}: {1} {2}'.format(i, df[i].isnull().sum(), features[i].dtypes)
nan_dict[i] = [df[i].isnull().sum(), features[i].dtypes]
return nan_dict
# The Alley, FireplaceQu, PoolQC, Fence, MiscFeatures objects should be dropped
variables_to_drop = ['Alley', 'FireplaceQu', 'PoolQC', 'Fence', 'MiscFeature']
def graph_mean_on_scatter(df, x_name, y_name):
'''
Input:
df: the pandas data frame the data is contained in
x_name: the name of the df column to plot on the x-axis
y_name: the name of the df column to plot on the y-axis
Dependencies:
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
Returns:
A regplot which has any missing values plotted separately in order to evaluate the usefullness of
substituting in the mean for the missing data.'''
missing = pd.DataFrame(data=df[x_name][df[x_name].isnull()], columns=[x_name])
missing[y_name] = df[y_name][df[x_name].isnull()]
missing[x_name].fillna(value=np.nanmean(df[x_name]), inplace=True)
sns.regplot(x=x_name, y=y_name, data=df)
plt.plot(missing[x_name], missing[y_name], 's')
plt.show()
return
# Now need to decide how to fill the missing values from the remaining factors
# Let's start with LotFrontage
graph_mean_on_scatter(train, 'LotFrontage', 'SalePrice')
# The mean LotFrontage values fit right in with the rest of the data. Let's fill in the missing data using these values
mean_LotFrontage = np.nanmean(features.LotFrontage)
features.LotFrontage.fillna(value=mean_LotFrontage, inplace=True)
# check that LotFrontage column isn't missing any daya
missing_data_info(features)
#success!
# Let's try the same strategy above for MasVnrArea which is the Masonry Veneer Area
graph_mean_on_scatter(train, 'MasVnrArea', 'SalePrice')
# I'm going to use the mean value to fill the missing data
mean_MasVnrArea = np.nanmean(features.MasVnrArea)
features.MasVnrArea.fillna(value=mean_MasVnrArea, inplace=True)
# Look at how using the mean value works for GarageYrBlt
graph_mean_on_scatter(train, 'GarageYrBlt', 'SalePrice')
# I don't like that so much of imputed data is weighted down below the trend line.
# It might be that the value for GarageYrBlt doens't exists is because there is no garage!
# Looking back at the number of values of missing data for the garage features,
# there are an equal number of missing features. This would suggest that those homes don't have a garage.
# And in fact, the same pattern is true for the basement features.
# We can test this hypothesis by looking at the comparison between GarageYrBlt and YearBlt
graph_mean_on_scatter(train, 'GarageYrBlt', 'YearBuilt')
# Looks like most of the garages were built when the house was built, so this likely isn't going to add much information
# I'll add the garage features to the variables_to_drop list
variables_to_drop.extend(['GarageType', 'GarageYrBlt', 'GarageFinish', 'GarageQual', 'GarageCond'])
features.drop(variables_to_drop, axis=1, inplace=True)
missing_data_info(features)
# Let's look through the remaining columns that are missing data points. These are all categorical variables
# We'll start with MasVnrType
sns.boxplot(x='MasVnrType', y='SalePrice', data=train)
sns.stripplot(x="MasVnrType", y="SalePrice", data=train,
size=2, jitter=True, edgecolor="gray", alpha=0.5)
# The BrkFace veneer type looks like it is right in the middle. Since we used the mean values to for the
# MasVnrArea, I'll use BrkFace as the "mean" value to use as the replacement for this feaure
features.MasVnrType.fillna(value='BrkFace', inplace=True)
```
### Basement Condition
The BsmtCond feature documentation says that NA values mean there is no basement. I want to see if it shows up as a factor
```
sns.boxplot(x='BsmtCond', y='SalePrice', data=train)
sns.stripplot(x='BsmtCond', y='SalePrice', data=train, size=2, jitter=True, edgecolor="gray", alpha=0.5)
# Since 'Na' string in the basement features doesn't count as a category, I'm going to replace the Na values with the
# string 'None'
for i in ['BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'BsmtQual']:
features.loc[:,i].fillna(value='NoBsmt', inplace=True)
missing_data_info(features)
# only 1 feature left with null values! This feature ranks the circuit breaker/fuse box quality of the house
# let's take a look at it
sns.boxplot(x='Electrical', y='SalePrice', data=train)
sns.stripplot(x='Electrical', y='SalePrice', data=train, size = 2, jitter=True, alpha=0.5)
train.SalePrice[train.Electrical.isnull()]
# Since so many of the values are SBrkr and the price of the house missing the data is pretty close to the median of
# the SBrkr values, I'm going to assign the missing value to SBrkr
features.Electrical.fillna(value="SBrkr", inplace=True)
#and check that it worked
missing_data_info(features)
# success! That was a good pratice of investigating and filling missing features. Now I will use just the numeric
# data to train a DecisionTreeRegressor model and make another submission
# Ben Hamner: "The best data scientists rapidly iterate."
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
numeric_features = features.select_dtypes(include=numerics)
vs.ModelLearning(numeric_features, target)
vs.ModelComplexity(numeric_features, target)
# I'm going with a max depth of 7
reg = DecisionTreeRegressor(max_depth = 7)
reg.fit(numeric_features, target)
# prepare the test data
test.drop(variables_to_drop, axis=1, inplace=True)
numeric_test_features = test.select_dtypes(include=numerics)
# need to impute the missing data
the_missing_test_data = missing_data_info(numeric_test_features)
for k in the_missing_test_data.keys():
numeric_test_features[k].fillna(value=np.nanmean(numeric_test_features[k]), inplace=True)
missing_data_info(numeric_test_features)
# No missing data points in the test set so:
DTRegressor = reg.predict(numeric_test_features)
print len(DTRegressor)
test_id = test.Id
print len(test_id)
DTR_submission = pd.DataFrame(data=DTRegressor, index=test_id, columns=['SalePrice'])
print DTR_submission.head()
DTR_submission.to_csv('DTR_submission3.csv')
def performance_metric(y_true, y_predict):
""" Calculates and returns the performance score between
true and predicted values based on the metric chosen. """
# TODO: Calculate the performance score between 'y_true' and 'y_predict'
score = r2_score(y_true, y_predict)
# Return the score
return score
# this was worse than the first model!
# Let's do hyperparameter tuning
# split the data into training and testing
X_train, X_test, y_train, y_test = train_test_split(numeric_features, target, test_size = 0.2, random_state=0)
# make the scorer
r2_scorer = make_scorer(performance_metric)
parameters = {'max_depth':[1,3,6,10,20], 'min_samples_split':[2,5,10,15,18,20,23,25,28,30,40,50,100],
'min_samples_leaf':[1,5,10,12,15,17,20,40]}
reg = DecisionTreeRegressor()
clf = GridSearchCV(reg, parameters)
clf.fit(X_train, y_train)
clf.best_score_
clf.best_params_
GS_results = pd.DataFrame(clf.cv_results_).sort_values('mean_test_score', axis=0, ascending=False)
GS_results.head()
clf.score(X_test, y_test)
DTR = clf.predict(numeric_test_features)
print len(DTRegressor)
test_id = test.Id
print len(test_id)
DTR_submission = pd.DataFrame(data=DTR, index=test_id, columns=['SalePrice'])
print DTR_submission.head()
DTR_submission.to_csv('DTR_submission4.csv')
# The decision tree with the hypertuned parameters increased my score by 188 positions (0.03 decrease in
# the root mean squared error of my predictions).
categorical_variables = features.select_dtypes(include= ['object'])
categorical_variables.head()
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
le = LabelEncoder()
categorical_encoded = categorical_variables.apply(le.fit_transform)
cat_reg = DecisionTreeRegressor()
cat_reg.fit(categorical_encoded, target)
numeric_categorical_test = test.select_dtypes(['object'])
numeric_categorical_test = numeric_categorical_test.apply(le.fit_transform)
numeric_categorical_test.head()
DTR = cat_reg.predict(numeric_categorical_test)
print len(DTRegressor)
test_id = test.Id
print len(test_id)
DTR_submission = pd.DataFrame(data=DTR, index=test_id, columns=['SalePrice'])
print DTR_submission.head()
DTR_submission.to_csv('DTR_submission5.csv')
# submission score of 0.39 - pretty bad!
def make_submission(test_data, test_data_index, predictor, k):
'''
test_data = a pandas dataframe containing the test data
predictor = a trained classifier
k = the number of the entry. Used to keep older entries from being overwritten
output: writes a csv file to the current directory'''
predictions = predictor.predict(test_data)
test_id = test_data_index
submission = pd.DataFrame(data=predictions, index=test_id, columns=['SalePrice'])
print submission.head()
submission.to_csv('DTR_submission{}.csv'.format(k))
make_submission(numeric_categorical_test, test.Id, cat_reg, 6)
# concatenate the categorical_encoded and the numeric_features dataframes
all_features = pd.concat([categorical_encoded, numeric_features], axis=1)
all_features.head()
X_train, X_test, y_train, y_test = train_test_split(all_features, target, test_size = 0.2, random_state=0)
reg = DecisionTreeRegressor()
clf = GridSearchCV(reg, parameters)
clf.fit(X_train, y_train)
print clf.best_score_
print clf.best_params_
print clf.score(X_test, y_test)
all_features_test = pd.concat([numeric_categorical_test, numeric_test_features], axis=1)
make_submission(all_features_test, test.Id, clf, 6)
# these predictions are worse than the hypertuned submission using only the numeric features (submission 4)
# this is not what I was expecting because this model gave higher scores on the hold-out set duing the
# GridSearchCV and gave a better score on the held out test data
# I think the next thing to do is clean up this notebook and then go through the categorical variables to determine
# which are ordinal and which are not, determine how to replace eadh variable type and then use one hot encoding on
# the non-ordinal categorical variables and label encoding on the ordinal ones
```
|
github_jupyter
|
# load in the libraries we will use
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.model_selection import ShuffleSplit
from sklearn.metrics import make_scorer
from sklearn.metrics import r2_score
import visuals as vs
%matplotlib inline
train = pd.read_csv('houseTrain.csv')
test = pd.read_csv('houseTest.csv')
print len(train)
print len(test)
# First split the training data into the features and the target
features = train.drop('SalePrice', axis=1)
target = train.SalePrice
# How many features are there?
print len(features.columns.values)
# Which columns are missing values?
nan_columns = features.columns[pd.isnull(features).any()].tolist()
for i in nan_columns:
print '{0}: {1} {2}'.format(i, features[i].isnull().sum(), features[i].dtypes)
# Let's turn the above into a function
def missing_data_info(df):
'''
Takes: a pandas dataframe which is checked for missing data in the columns. Uses any() method to check for
missing data.
Returns: prints out the name of columns with missing data, the number of missing values, and the dtype of the column
and returns a dictionary of the printed data in the form column_name: [#_missing_values, col_dtype]'''
nan_columns = df.columns[pd.isnull(df).any()].tolist()
nan_dict = {}
for i in nan_columns:
print '{0}: {1} {2}'.format(i, df[i].isnull().sum(), features[i].dtypes)
nan_dict[i] = [df[i].isnull().sum(), features[i].dtypes]
return nan_dict
# The Alley, FireplaceQu, PoolQC, Fence, MiscFeatures objects should be dropped
variables_to_drop = ['Alley', 'FireplaceQu', 'PoolQC', 'Fence', 'MiscFeature']
def graph_mean_on_scatter(df, x_name, y_name):
'''
Input:
df: the pandas data frame the data is contained in
x_name: the name of the df column to plot on the x-axis
y_name: the name of the df column to plot on the y-axis
Dependencies:
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
Returns:
A regplot which has any missing values plotted separately in order to evaluate the usefullness of
substituting in the mean for the missing data.'''
missing = pd.DataFrame(data=df[x_name][df[x_name].isnull()], columns=[x_name])
missing[y_name] = df[y_name][df[x_name].isnull()]
missing[x_name].fillna(value=np.nanmean(df[x_name]), inplace=True)
sns.regplot(x=x_name, y=y_name, data=df)
plt.plot(missing[x_name], missing[y_name], 's')
plt.show()
return
# Now need to decide how to fill the missing values from the remaining factors
# Let's start with LotFrontage
graph_mean_on_scatter(train, 'LotFrontage', 'SalePrice')
# The mean LotFrontage values fit right in with the rest of the data. Let's fill in the missing data using these values
mean_LotFrontage = np.nanmean(features.LotFrontage)
features.LotFrontage.fillna(value=mean_LotFrontage, inplace=True)
# check that LotFrontage column isn't missing any daya
missing_data_info(features)
#success!
# Let's try the same strategy above for MasVnrArea which is the Masonry Veneer Area
graph_mean_on_scatter(train, 'MasVnrArea', 'SalePrice')
# I'm going to use the mean value to fill the missing data
mean_MasVnrArea = np.nanmean(features.MasVnrArea)
features.MasVnrArea.fillna(value=mean_MasVnrArea, inplace=True)
# Look at how using the mean value works for GarageYrBlt
graph_mean_on_scatter(train, 'GarageYrBlt', 'SalePrice')
# I don't like that so much of imputed data is weighted down below the trend line.
# It might be that the value for GarageYrBlt doens't exists is because there is no garage!
# Looking back at the number of values of missing data for the garage features,
# there are an equal number of missing features. This would suggest that those homes don't have a garage.
# And in fact, the same pattern is true for the basement features.
# We can test this hypothesis by looking at the comparison between GarageYrBlt and YearBlt
graph_mean_on_scatter(train, 'GarageYrBlt', 'YearBuilt')
# Looks like most of the garages were built when the house was built, so this likely isn't going to add much information
# I'll add the garage features to the variables_to_drop list
variables_to_drop.extend(['GarageType', 'GarageYrBlt', 'GarageFinish', 'GarageQual', 'GarageCond'])
features.drop(variables_to_drop, axis=1, inplace=True)
missing_data_info(features)
# Let's look through the remaining columns that are missing data points. These are all categorical variables
# We'll start with MasVnrType
sns.boxplot(x='MasVnrType', y='SalePrice', data=train)
sns.stripplot(x="MasVnrType", y="SalePrice", data=train,
size=2, jitter=True, edgecolor="gray", alpha=0.5)
# The BrkFace veneer type looks like it is right in the middle. Since we used the mean values to for the
# MasVnrArea, I'll use BrkFace as the "mean" value to use as the replacement for this feaure
features.MasVnrType.fillna(value='BrkFace', inplace=True)
sns.boxplot(x='BsmtCond', y='SalePrice', data=train)
sns.stripplot(x='BsmtCond', y='SalePrice', data=train, size=2, jitter=True, edgecolor="gray", alpha=0.5)
# Since 'Na' string in the basement features doesn't count as a category, I'm going to replace the Na values with the
# string 'None'
for i in ['BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'BsmtQual']:
features.loc[:,i].fillna(value='NoBsmt', inplace=True)
missing_data_info(features)
# only 1 feature left with null values! This feature ranks the circuit breaker/fuse box quality of the house
# let's take a look at it
sns.boxplot(x='Electrical', y='SalePrice', data=train)
sns.stripplot(x='Electrical', y='SalePrice', data=train, size = 2, jitter=True, alpha=0.5)
train.SalePrice[train.Electrical.isnull()]
# Since so many of the values are SBrkr and the price of the house missing the data is pretty close to the median of
# the SBrkr values, I'm going to assign the missing value to SBrkr
features.Electrical.fillna(value="SBrkr", inplace=True)
#and check that it worked
missing_data_info(features)
# success! That was a good pratice of investigating and filling missing features. Now I will use just the numeric
# data to train a DecisionTreeRegressor model and make another submission
# Ben Hamner: "The best data scientists rapidly iterate."
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
numeric_features = features.select_dtypes(include=numerics)
vs.ModelLearning(numeric_features, target)
vs.ModelComplexity(numeric_features, target)
# I'm going with a max depth of 7
reg = DecisionTreeRegressor(max_depth = 7)
reg.fit(numeric_features, target)
# prepare the test data
test.drop(variables_to_drop, axis=1, inplace=True)
numeric_test_features = test.select_dtypes(include=numerics)
# need to impute the missing data
the_missing_test_data = missing_data_info(numeric_test_features)
for k in the_missing_test_data.keys():
numeric_test_features[k].fillna(value=np.nanmean(numeric_test_features[k]), inplace=True)
missing_data_info(numeric_test_features)
# No missing data points in the test set so:
DTRegressor = reg.predict(numeric_test_features)
print len(DTRegressor)
test_id = test.Id
print len(test_id)
DTR_submission = pd.DataFrame(data=DTRegressor, index=test_id, columns=['SalePrice'])
print DTR_submission.head()
DTR_submission.to_csv('DTR_submission3.csv')
def performance_metric(y_true, y_predict):
""" Calculates and returns the performance score between
true and predicted values based on the metric chosen. """
# TODO: Calculate the performance score between 'y_true' and 'y_predict'
score = r2_score(y_true, y_predict)
# Return the score
return score
# this was worse than the first model!
# Let's do hyperparameter tuning
# split the data into training and testing
X_train, X_test, y_train, y_test = train_test_split(numeric_features, target, test_size = 0.2, random_state=0)
# make the scorer
r2_scorer = make_scorer(performance_metric)
parameters = {'max_depth':[1,3,6,10,20], 'min_samples_split':[2,5,10,15,18,20,23,25,28,30,40,50,100],
'min_samples_leaf':[1,5,10,12,15,17,20,40]}
reg = DecisionTreeRegressor()
clf = GridSearchCV(reg, parameters)
clf.fit(X_train, y_train)
clf.best_score_
clf.best_params_
GS_results = pd.DataFrame(clf.cv_results_).sort_values('mean_test_score', axis=0, ascending=False)
GS_results.head()
clf.score(X_test, y_test)
DTR = clf.predict(numeric_test_features)
print len(DTRegressor)
test_id = test.Id
print len(test_id)
DTR_submission = pd.DataFrame(data=DTR, index=test_id, columns=['SalePrice'])
print DTR_submission.head()
DTR_submission.to_csv('DTR_submission4.csv')
# The decision tree with the hypertuned parameters increased my score by 188 positions (0.03 decrease in
# the root mean squared error of my predictions).
categorical_variables = features.select_dtypes(include= ['object'])
categorical_variables.head()
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
le = LabelEncoder()
categorical_encoded = categorical_variables.apply(le.fit_transform)
cat_reg = DecisionTreeRegressor()
cat_reg.fit(categorical_encoded, target)
numeric_categorical_test = test.select_dtypes(['object'])
numeric_categorical_test = numeric_categorical_test.apply(le.fit_transform)
numeric_categorical_test.head()
DTR = cat_reg.predict(numeric_categorical_test)
print len(DTRegressor)
test_id = test.Id
print len(test_id)
DTR_submission = pd.DataFrame(data=DTR, index=test_id, columns=['SalePrice'])
print DTR_submission.head()
DTR_submission.to_csv('DTR_submission5.csv')
# submission score of 0.39 - pretty bad!
def make_submission(test_data, test_data_index, predictor, k):
'''
test_data = a pandas dataframe containing the test data
predictor = a trained classifier
k = the number of the entry. Used to keep older entries from being overwritten
output: writes a csv file to the current directory'''
predictions = predictor.predict(test_data)
test_id = test_data_index
submission = pd.DataFrame(data=predictions, index=test_id, columns=['SalePrice'])
print submission.head()
submission.to_csv('DTR_submission{}.csv'.format(k))
make_submission(numeric_categorical_test, test.Id, cat_reg, 6)
# concatenate the categorical_encoded and the numeric_features dataframes
all_features = pd.concat([categorical_encoded, numeric_features], axis=1)
all_features.head()
X_train, X_test, y_train, y_test = train_test_split(all_features, target, test_size = 0.2, random_state=0)
reg = DecisionTreeRegressor()
clf = GridSearchCV(reg, parameters)
clf.fit(X_train, y_train)
print clf.best_score_
print clf.best_params_
print clf.score(X_test, y_test)
all_features_test = pd.concat([numeric_categorical_test, numeric_test_features], axis=1)
make_submission(all_features_test, test.Id, clf, 6)
# these predictions are worse than the hypertuned submission using only the numeric features (submission 4)
# this is not what I was expecting because this model gave higher scores on the hold-out set duing the
# GridSearchCV and gave a better score on the held out test data
# I think the next thing to do is clean up this notebook and then go through the categorical variables to determine
# which are ordinal and which are not, determine how to replace eadh variable type and then use one hot encoding on
# the non-ordinal categorical variables and label encoding on the ordinal ones
| 0.553143 | 0.920039 |
# Explainer for Iris model with Poetry-defined Environment
## Prerequisites
* A kubernetes cluster with kubectl configured
* poetry
* rclone
* curl
## Setup Seldon Core
Use the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Setup-Cluster) with [Ambassador Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Ambassador) and [Install Seldon Core](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Install-Seldon-Core). Instructions [also online](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html).
We will assume that ambassador (or Istio) ingress is port-forwarded to `localhost:8003`
## Setup MinIO
Use the provided [notebook](https://docs.seldon.io/projects/seldon-core/en/latest/examples/minio_setup.html) to install Minio in your cluster.
Instructions [also online](https://docs.seldon.io/projects/seldon-core/en/latest/examples/minio_setup.html).
We will assume that MinIO service is port-forwarded to `localhost:8090`
```
%%writefile rclone.conf
[s3]
type = s3
provider = minio
env_auth = false
access_key_id = minioadmin
secret_access_key = minioadmin
endpoint = http://localhost:8090
%%writefile secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: seldon-rclone-secret
type: Opaque
stringData:
RCLONE_CONFIG_S3_TYPE: s3
RCLONE_CONFIG_S3_PROVIDER: minio
RCLONE_CONFIG_S3_ENV_AUTH: "false"
RCLONE_CONFIG_S3_ACCESS_KEY_ID: minioadmin
RCLONE_CONFIG_S3_SECRET_ACCESS_KEY: minioadmin
RCLONE_CONFIG_S3_ENDPOINT: http://minio.minio-system.svc.cluster.local:9000
!kubectl apply -f secret.yaml
```
## Poetry
We will use `poetry.lock` to fully define the explainer environment. Install poetry following official [documentation](https://python-poetry.org/docs/#installation). Usually this goes down to
```bash
curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3 -
```
# Deploy Iris Model
```
%%writefile iris.yaml
apiVersion: machinelearning.seldon.io/v1alpha2
kind: SeldonDeployment
metadata:
name: iris
spec:
predictors:
- name: default
replicas: 1
graph:
name: classifier
implementation: SKLEARN_SERVER
modelUri: gs://seldon-models/v1.11.0-dev/sklearn/iris
!kubectl apply -f iris.yaml
!kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=iris -o jsonpath='{.items[0].metadata.name}')
%%bash
curl -s -X POST -H 'Content-Type: application/json' \
-d '{"data":{"ndarray":[[5.964, 4.006, 2.081, 1.031]]}}' \
http://localhost:8003/seldon/seldon/iris/api/v1.0/predictions | jq .
```
# Train Explainer
## Prepare Training Environment
We are going to use `pyproject.toml` and `poetry.lock` files from [Alibi Explain Server](https://github.com/SeldonIO/seldon-core/tree/master/components/alibi-explain-server). This will allow us to create environment that will match the runtime one.
```
%%bash
cp ../../../components/alibi-explain-server/pyproject.toml .
cp ../../../components/alibi-explain-server/poetry.lock .
conda create --yes --prefix ./venv python=3.7.10
%%bash
source ~/miniconda3/etc/profile.d/conda.sh
conda activate ./venv
poetry install
```
## Prepare Training Script
```
%%writefile train.py
import numpy as np
from sklearn.datasets import load_iris
from alibi.explainers import AnchorTabular
import requests
dataset = load_iris()
feature_names = dataset.feature_names
iris_data = dataset.data
model_url = "http://localhost:8003/seldon/seldon/iris/api/v1.0/predictions"
def predict_fn(X):
data = {"data": {"ndarray": X.tolist()}}
r = requests.post(model_url, json={"data": {"ndarray": [[1, 2, 3, 4]]}})
return np.array(r.json()["data"]["ndarray"])
explainer = AnchorTabular(predict_fn, feature_names)
explainer.fit(iris_data, disc_perc=(25, 50, 75))
explainer.save("./explainer/")
!./venv/bin/python3 train.py
!tree explainer/
```
# Save and deploy Explainer
```
!rclone --config="rclone.conf" copy explainer/ s3:explainers/iris/
%%writefile iris-with-explainer.yaml
apiVersion: machinelearning.seldon.io/v1alpha2
kind: SeldonDeployment
metadata:
name: iris
spec:
predictors:
- name: default
replicas: 1
graph:
name: classifier
implementation: SKLEARN_SERVER
modelUri: gs://seldon-models/v1.11.0-dev/sklearn/iris
explainer:
type: AnchorTabular
modelUri: s3:explainers/iris/
envSecretRefName: seldon-rclone-secret
replicas: 1
!kubectl apply -f iris-with-explainer.yaml
```
# Test Deployed explainer
```
import numpy as np
import requests
model_url = (
"http://localhost:8003/seldon/seldon/iris-explainer/default/api/v1.0/explain"
)
def explain_fn(X):
data = {"data": {"ndarray": X.tolist()}}
r = requests.post(model_url, json={"data": {"ndarray": [[1, 2, 3, 4]]}})
return r.json()
explanation = explain_fn(np.array([[5.964, 4.006, 2.081, 1.031]]))
print("Anchor: %s" % (" AND ".join(explanation["data"]["anchor"])))
print("Precision: %.2f" % explanation["data"]["precision"])
print("Coverage: %.2f" % explanation["data"]["coverage"])
```
|
github_jupyter
|
%%writefile rclone.conf
[s3]
type = s3
provider = minio
env_auth = false
access_key_id = minioadmin
secret_access_key = minioadmin
endpoint = http://localhost:8090
%%writefile secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: seldon-rclone-secret
type: Opaque
stringData:
RCLONE_CONFIG_S3_TYPE: s3
RCLONE_CONFIG_S3_PROVIDER: minio
RCLONE_CONFIG_S3_ENV_AUTH: "false"
RCLONE_CONFIG_S3_ACCESS_KEY_ID: minioadmin
RCLONE_CONFIG_S3_SECRET_ACCESS_KEY: minioadmin
RCLONE_CONFIG_S3_ENDPOINT: http://minio.minio-system.svc.cluster.local:9000
!kubectl apply -f secret.yaml
curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3 -
%%writefile iris.yaml
apiVersion: machinelearning.seldon.io/v1alpha2
kind: SeldonDeployment
metadata:
name: iris
spec:
predictors:
- name: default
replicas: 1
graph:
name: classifier
implementation: SKLEARN_SERVER
modelUri: gs://seldon-models/v1.11.0-dev/sklearn/iris
!kubectl apply -f iris.yaml
!kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=iris -o jsonpath='{.items[0].metadata.name}')
%%bash
curl -s -X POST -H 'Content-Type: application/json' \
-d '{"data":{"ndarray":[[5.964, 4.006, 2.081, 1.031]]}}' \
http://localhost:8003/seldon/seldon/iris/api/v1.0/predictions | jq .
%%bash
cp ../../../components/alibi-explain-server/pyproject.toml .
cp ../../../components/alibi-explain-server/poetry.lock .
conda create --yes --prefix ./venv python=3.7.10
%%bash
source ~/miniconda3/etc/profile.d/conda.sh
conda activate ./venv
poetry install
%%writefile train.py
import numpy as np
from sklearn.datasets import load_iris
from alibi.explainers import AnchorTabular
import requests
dataset = load_iris()
feature_names = dataset.feature_names
iris_data = dataset.data
model_url = "http://localhost:8003/seldon/seldon/iris/api/v1.0/predictions"
def predict_fn(X):
data = {"data": {"ndarray": X.tolist()}}
r = requests.post(model_url, json={"data": {"ndarray": [[1, 2, 3, 4]]}})
return np.array(r.json()["data"]["ndarray"])
explainer = AnchorTabular(predict_fn, feature_names)
explainer.fit(iris_data, disc_perc=(25, 50, 75))
explainer.save("./explainer/")
!./venv/bin/python3 train.py
!tree explainer/
!rclone --config="rclone.conf" copy explainer/ s3:explainers/iris/
%%writefile iris-with-explainer.yaml
apiVersion: machinelearning.seldon.io/v1alpha2
kind: SeldonDeployment
metadata:
name: iris
spec:
predictors:
- name: default
replicas: 1
graph:
name: classifier
implementation: SKLEARN_SERVER
modelUri: gs://seldon-models/v1.11.0-dev/sklearn/iris
explainer:
type: AnchorTabular
modelUri: s3:explainers/iris/
envSecretRefName: seldon-rclone-secret
replicas: 1
!kubectl apply -f iris-with-explainer.yaml
import numpy as np
import requests
model_url = (
"http://localhost:8003/seldon/seldon/iris-explainer/default/api/v1.0/explain"
)
def explain_fn(X):
data = {"data": {"ndarray": X.tolist()}}
r = requests.post(model_url, json={"data": {"ndarray": [[1, 2, 3, 4]]}})
return r.json()
explanation = explain_fn(np.array([[5.964, 4.006, 2.081, 1.031]]))
print("Anchor: %s" % (" AND ".join(explanation["data"]["anchor"])))
print("Precision: %.2f" % explanation["data"]["precision"])
print("Coverage: %.2f" % explanation["data"]["coverage"])
| 0.39129 | 0.90686 |
Lambda School Data Science
*Unit 2, Sprint 3, Module 4*
---
# Model Interpretation
You will use your portfolio project dataset for all assignments this sprint.
## Assignment
Complete these tasks for your project, and document your work.
- [ ] Continue to iterate on your project: data cleaning, exploratory visualization, feature engineering, modeling.
- [ ] Make at least 1 partial dependence plot to explain your model.
- [ ] Make at least 1 Shapley force plot to explain an individual prediction.
- [ ] **Share at least 1 visualization (of any type) on Slack!**
If you aren't ready to make these plots with your own dataset, you can practice these objectives with any dataset you've worked with previously. Example solutions are available for Partial Dependence Plots with the Tanzania Waterpumps dataset, and Shapley force plots with the Titanic dataset. (These datasets are available in the data directory of this repository.)
Please be aware that **multi-class classification** will result in multiple Partial Dependence Plots (one for each class), and multiple sets of Shapley Values (one for each class).
## Stretch Goals
#### Partial Dependence Plots
- [ ] Make multiple PDPs with 1 feature in isolation.
- [ ] Make multiple PDPs with 2 features in interaction.
- [ ] Use Plotly to make a 3D PDP.
- [ ] Make PDPs with categorical feature(s). Use Ordinal Encoder, outside of a pipeline, to encode your data first. If there is a natural ordering, then take the time to encode it that way, instead of random integers. Then use the encoded data with pdpbox. Get readable category names on your plot, instead of integer category codes.
#### Shap Values
- [ ] Make Shapley force plots to explain at least 4 individual predictions.
- If your project is Binary Classification, you can do a True Positive, True Negative, False Positive, False Negative.
- If your project is Regression, you can do a high prediction with low error, a low prediction with low error, a high prediction with high error, and a low prediction with high error.
- [ ] Use Shapley values to display verbal explanations of individual predictions.
- [ ] Use the SHAP library for other visualization types.
The [SHAP repo](https://github.com/slundberg/shap) has examples for many visualization types, including:
- Force Plot, individual predictions
- Force Plot, multiple predictions
- Dependence Plot
- Summary Plot
- Summary Plot, Bar
- Interaction Values
- Decision Plots
We just did the first type during the lesson. The [Kaggle microcourse](https://www.kaggle.com/dansbecker/advanced-uses-of-shap-values) shows two more. Experiment and see what you can learn!
### Links
#### Partial Dependence Plots
- [Kaggle / Dan Becker: Machine Learning Explainability — Partial Dependence Plots](https://www.kaggle.com/dansbecker/partial-plots)
- [Christoph Molnar: Interpretable Machine Learning — Partial Dependence Plots](https://christophm.github.io/interpretable-ml-book/pdp.html) + [animated explanation](https://twitter.com/ChristophMolnar/status/1066398522608635904)
- [pdpbox repo](https://github.com/SauceCat/PDPbox) & [docs](https://pdpbox.readthedocs.io/en/latest/)
- [Plotly: 3D PDP example](https://plot.ly/scikit-learn/plot-partial-dependence/#partial-dependence-of-house-value-on-median-age-and-average-occupancy)
#### Shapley Values
- [Kaggle / Dan Becker: Machine Learning Explainability — SHAP Values](https://www.kaggle.com/learn/machine-learning-explainability)
- [Christoph Molnar: Interpretable Machine Learning — Shapley Values](https://christophm.github.io/interpretable-ml-book/shapley.html)
- [SHAP repo](https://github.com/slundberg/shap) & [docs](https://shap.readthedocs.io/en/latest/)
```
%%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/'
!pip install category_encoders==2.*
!pip install eli5
!pip install pdpbox
!pip install shap
# If you're working locally:
else:
DATA_PATH = '../data/'
import pandas as pd
test=pd.read_csv(r"C:\Users\Aarons\Downloads\airline-passenger-satisfaction\test.csv")
train=pd.read_csv(r"C:\Users\Aarons\Downloads\airline-passenger-satisfaction\train.csv")
train.shape, test.shape
train = train.drop(columns=['Unnamed: 0', 'id' ])
train = train.dropna(subset=['Cleanliness'])
train['Clean'] = (train['Cleanliness'] >= 4)
y = train['Clean'].unique()
y
train['Clean'].value_counts(normalize=True)
train = train.fillna("Missing")
from sklearn.model_selection import train_test_split
train, val = train_test_split(train, train_size=0.80, test_size=0.20,
stratify=train['Clean'], random_state=42)
test = test.drop(columns=['Unnamed: 0'])
train.shape, val.shape, test.shape
train.head()
target = "Clean"
features = train.columns.drop([target, 'Flight Distance', 'Cleanliness'])
X_train = train[features]
y_train = train[target]
X_val = val[features]
y_val = val[target]
%matplotlib inline
import seaborn as sns
sns.distplot(y_train);
import category_encoders as ce
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
pipeline = make_pipeline(
ce.OrdinalEncoder(),
SimpleImputer(strategy='median'),
RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
)
# Fit on train, score on val
pipeline.fit(X_train, y_train)
print('Validation Accuracy', pipeline.score(X_val, y_val))
rf = pipeline.named_steps['randomforestclassifier']
importances = pd.Series(rf.feature_importances_, X_train.columns)
# Plot feature importances
%matplotlib inline
import matplotlib.pyplot as plt
n = 10
plt.figure(figsize=(10,n/2))
plt.title(f'Top {n} features')
importances.sort_values()[-n:].plot.barh(color='orange');
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = 72
from pdpbox.pdp import pdp_isolate, pdp_plot
feature = 'Inflight entertainment'
isolated = pdp_isolate(
model = gb,
dataset = X_val,
model_features = X_val.columns,
feature= feature
)
pdp_plot(isolated, feature);
pdp_plot(isolated, feature_name=feature, plot_lines=True, frac_to_plot=0.01);
plt.xlim([0, 5])
```
|
github_jupyter
|
%%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/'
!pip install category_encoders==2.*
!pip install eli5
!pip install pdpbox
!pip install shap
# If you're working locally:
else:
DATA_PATH = '../data/'
import pandas as pd
test=pd.read_csv(r"C:\Users\Aarons\Downloads\airline-passenger-satisfaction\test.csv")
train=pd.read_csv(r"C:\Users\Aarons\Downloads\airline-passenger-satisfaction\train.csv")
train.shape, test.shape
train = train.drop(columns=['Unnamed: 0', 'id' ])
train = train.dropna(subset=['Cleanliness'])
train['Clean'] = (train['Cleanliness'] >= 4)
y = train['Clean'].unique()
y
train['Clean'].value_counts(normalize=True)
train = train.fillna("Missing")
from sklearn.model_selection import train_test_split
train, val = train_test_split(train, train_size=0.80, test_size=0.20,
stratify=train['Clean'], random_state=42)
test = test.drop(columns=['Unnamed: 0'])
train.shape, val.shape, test.shape
train.head()
target = "Clean"
features = train.columns.drop([target, 'Flight Distance', 'Cleanliness'])
X_train = train[features]
y_train = train[target]
X_val = val[features]
y_val = val[target]
%matplotlib inline
import seaborn as sns
sns.distplot(y_train);
import category_encoders as ce
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
pipeline = make_pipeline(
ce.OrdinalEncoder(),
SimpleImputer(strategy='median'),
RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
)
# Fit on train, score on val
pipeline.fit(X_train, y_train)
print('Validation Accuracy', pipeline.score(X_val, y_val))
rf = pipeline.named_steps['randomforestclassifier']
importances = pd.Series(rf.feature_importances_, X_train.columns)
# Plot feature importances
%matplotlib inline
import matplotlib.pyplot as plt
n = 10
plt.figure(figsize=(10,n/2))
plt.title(f'Top {n} features')
importances.sort_values()[-n:].plot.barh(color='orange');
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = 72
from pdpbox.pdp import pdp_isolate, pdp_plot
feature = 'Inflight entertainment'
isolated = pdp_isolate(
model = gb,
dataset = X_val,
model_features = X_val.columns,
feature= feature
)
pdp_plot(isolated, feature);
pdp_plot(isolated, feature_name=feature, plot_lines=True, frac_to_plot=0.01);
plt.xlim([0, 5])
| 0.417509 | 0.945851 |
```
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/data_loader.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/extractNet_connected.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/extractNet_connected_v2.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/extractNet_connected_vgg.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/extractNet_connected_vgg19.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/extractNet_simple.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/helper.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/metrics.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/trainer.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/visualizer.py
import numpy as np
import os
import matplotlib.pyplot as plt
import random
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import skimage.io as io
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
from helper import *
from visualizer import *
from metrics import *
from extractNet_simple import *
from extractNet_connected import *
from extractNet_connected_vgg19 import *
from trainer import *
from data_loader import *
!rm -rf __MACOSX
!rm -rf *.zip
!wget https://github.com/MNRKhan/aps360-project/raw/master/datasets/train2014/data_vehicle.zip
!rm -rf ./data
!unzip data_vehicle.zip
!rm -rf __MACOSX
!rm -rf *.zip
batch_size = 64
lr = 0.001
# Set random seeds
torch.manual_seed(360)
np.random.seed(360)
random.seed(360)
# Form dataset
transform = transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
dataset = ImageMaskDataset("/home/sp98sp/train/data", transform)
# Dataset sizes
size = len(dataset)
train_size = int(0.6 * size)
valid_size = int(0.2 * size)
test_size = size - train_size - valid_size
# Splitting datasets
train_data, valid_data, test_data = torch.utils.data.random_split(dataset, [train_size, valid_size, test_size])
# Making dataloader
train = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=0)
valid = DataLoader(valid_data, batch_size=batch_size, shuffle=True, num_workers=0)
print("Size of dataset:", size)
# Empty cache
torch.cuda.empty_cache()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net = extractNet_connected_vgg19()
net.to(device)
print("Model is being trained on:", device)
trainModel(net, train, valid, batch_size=batch_size, lr=lr, num_epochs=100, checkpoint=False, device=device)
torch.save(net.state_dict(), "try1")
trainModel(net, train, valid, batch_size=batch_size, lr=lr, num_epochs=100, checkpoint=False, device=device)
torch.save(net.state_dict(), "try2")
trainModel(net, train, valid, batch_size=batch_size, lr=lr, num_epochs=100, checkpoint=False, device=device)
torch.save(net.state_dict(), "try3")
# After training
net.to("cpu")
img, target = train_data[0]
out = net(img.unsqueeze(0))
out = out.squeeze(0).squeeze(0).detach().numpy()
target = target.squeeze(0).detach().numpy()
plt.imshow(target)
plt.show()
plt.imshow(out)
plt.show()
result = torch.sigmoid(net(img.unsqueeze(0)))
result = thresholdProbMask(result.squeeze(0).squeeze(0).detach())
plt.imshow(result)
plt.show()
```
|
github_jupyter
|
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/data_loader.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/extractNet_connected.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/extractNet_connected_v2.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/extractNet_connected_vgg.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/extractNet_connected_vgg19.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/extractNet_simple.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/helper.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/metrics.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/trainer.py
!wget https://github.com/MNRKhan/aps360-project/raw/master/modules/visualizer.py
import numpy as np
import os
import matplotlib.pyplot as plt
import random
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import skimage.io as io
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
from helper import *
from visualizer import *
from metrics import *
from extractNet_simple import *
from extractNet_connected import *
from extractNet_connected_vgg19 import *
from trainer import *
from data_loader import *
!rm -rf __MACOSX
!rm -rf *.zip
!wget https://github.com/MNRKhan/aps360-project/raw/master/datasets/train2014/data_vehicle.zip
!rm -rf ./data
!unzip data_vehicle.zip
!rm -rf __MACOSX
!rm -rf *.zip
batch_size = 64
lr = 0.001
# Set random seeds
torch.manual_seed(360)
np.random.seed(360)
random.seed(360)
# Form dataset
transform = transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
dataset = ImageMaskDataset("/home/sp98sp/train/data", transform)
# Dataset sizes
size = len(dataset)
train_size = int(0.6 * size)
valid_size = int(0.2 * size)
test_size = size - train_size - valid_size
# Splitting datasets
train_data, valid_data, test_data = torch.utils.data.random_split(dataset, [train_size, valid_size, test_size])
# Making dataloader
train = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=0)
valid = DataLoader(valid_data, batch_size=batch_size, shuffle=True, num_workers=0)
print("Size of dataset:", size)
# Empty cache
torch.cuda.empty_cache()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net = extractNet_connected_vgg19()
net.to(device)
print("Model is being trained on:", device)
trainModel(net, train, valid, batch_size=batch_size, lr=lr, num_epochs=100, checkpoint=False, device=device)
torch.save(net.state_dict(), "try1")
trainModel(net, train, valid, batch_size=batch_size, lr=lr, num_epochs=100, checkpoint=False, device=device)
torch.save(net.state_dict(), "try2")
trainModel(net, train, valid, batch_size=batch_size, lr=lr, num_epochs=100, checkpoint=False, device=device)
torch.save(net.state_dict(), "try3")
# After training
net.to("cpu")
img, target = train_data[0]
out = net(img.unsqueeze(0))
out = out.squeeze(0).squeeze(0).detach().numpy()
target = target.squeeze(0).detach().numpy()
plt.imshow(target)
plt.show()
plt.imshow(out)
plt.show()
result = torch.sigmoid(net(img.unsqueeze(0)))
result = thresholdProbMask(result.squeeze(0).squeeze(0).detach())
plt.imshow(result)
plt.show()
| 0.813387 | 0.2783 |
# Multilayer Perceptron in TensorFlow
Credits: Forked from [TensorFlow-Examples](https://github.com/aymericdamien/TensorFlow-Examples) by Aymeric Damien
## Setup
Refer to the [setup instructions](http://nbviewer.ipython.org/github/donnemartin/data-science-ipython-notebooks/blob/master/deep-learning/tensor-flow-examples/Setup_TensorFlow.md)
```
# Import MINST data
import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
import tensorflow as tf
# Parameters
learning_rate = 0.001
training_epochs = 15
batch_size = 100
display_step = 1
# Network Parameters
n_hidden_1 = 256 # 1st layer num features
n_hidden_2 = 256 # 2nd layer num features
n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 10 # MNIST total classes (0-9 digits)
# tf Graph input
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])
# Create model
def multilayer_perceptron(_X, _weights, _biases):
#Hidden layer with RELU activation
layer_1 = tf.nn.relu(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1']))
#Hidden layer with RELU activation
layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2']))
return tf.matmul(layer_2, weights['out']) + biases['out']
# Store layers weight & bias
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# Construct model
pred = multilayer_perceptron(x, weights, biases)
# Define loss and optimizer
# Softmax loss
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
# Adam Optimizer
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Initializing the variables
init = tf.initialize_all_variables()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Fit training using batch data
sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
# Compute average loss
avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch
# Display logs per epoch step
if epoch % display_step == 0:
print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)
print "Optimization Finished!"
# Test model
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
```
|
github_jupyter
|
# Import MINST data
import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
import tensorflow as tf
# Parameters
learning_rate = 0.001
training_epochs = 15
batch_size = 100
display_step = 1
# Network Parameters
n_hidden_1 = 256 # 1st layer num features
n_hidden_2 = 256 # 2nd layer num features
n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 10 # MNIST total classes (0-9 digits)
# tf Graph input
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])
# Create model
def multilayer_perceptron(_X, _weights, _biases):
#Hidden layer with RELU activation
layer_1 = tf.nn.relu(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1']))
#Hidden layer with RELU activation
layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2']))
return tf.matmul(layer_2, weights['out']) + biases['out']
# Store layers weight & bias
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# Construct model
pred = multilayer_perceptron(x, weights, biases)
# Define loss and optimizer
# Softmax loss
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
# Adam Optimizer
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Initializing the variables
init = tf.initialize_all_variables()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Fit training using batch data
sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
# Compute average loss
avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch
# Display logs per epoch step
if epoch % display_step == 0:
print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)
print "Optimization Finished!"
# Test model
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
| 0.743075 | 0.982457 |
```
import glob
import nltk
import pandas as pd
from sklearn import svm
from sklearn import metrics
from sklearn import naive_bayes
from gensim.models import KeyedVectors
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
```
<div class="alert alert-block alert-warning">
1. Reading & PreProcessing Training & Testing Data
</div>
```
model = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
li = []
Cols = ['ID','Label', 'Tweet']
path = r'C:\\Users\\khled\\Downloads\\Model\\'
all_files = glob.glob(path + "/twitter-201*.txt")
#Reading all files:
for file in all_files:
df = pd.read_csv(file, names=Cols, delimiter='\t')
li.append(df)
DF = pd.concat(li, axis=0, ignore_index=True)
Data = DF.drop('ID', axis=1)
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()
stop = stopwords.words('english')
Data['Tweet'] = Data['Tweet'].replace({r'\\':'',r'\'':'',r'\,':'','&':'',r'\"':'','!':'','\.':'','u2019':'\'','u002c':',','(@[A-Za-z0-9]+)|(\w+:\/\/\S+)':''}, regex=True)
Data['Tweet'] = [ tweet.casefold() for tweet in Data['Tweet'] ]
Data['Tweet'] = Data['Tweet'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))
Data['Tweet'] = Data['Tweet'].apply(lambda x: ' '.join([porter.stem(word) for word in x.split()]))
def cond(i):
if i == 0: return 'neutral'
elif i == 1: return 'positive'
elif i == 2: return 'negative'
return i
#Reading Test and Test Labels for evaluating results
Test = pd.read_csv("C:\\Users\\khled\\Downloads\\Model\\test.csv")
test_labels = pd.read_csv("C:\\Users\\khled\\Downloads\\Model\\answer_key.csv")
test_labels['vlabels'] = [cond(label) for label in test_labels['label']]
Test['tweet'] = Test['tweet'].replace({r'\\':'',r'\'':'',r'\,':'','&':'',r'\"':'','!':'','\.':'','u2019':'\'','u002c':',','(@[A-Za-z0-9]+)|(\w+:\/\/\S+)':''}, regex=True)
Test['tweet'] = [ tweet.casefold() for tweet in Test['tweet'] ]
Test['tweet'] = Test['tweet'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))
Test['tweet'] = Test['tweet'].apply(lambda x: ' '.join([porter.stem(word) for word in x.split()]))
print(len(Data['Tweet']))
```
<div class="alert alert-block alert-warning">
2. Transform Training & Testing Data to vectors
</div>
```
#Transform tweets to array
Tweets_wv = []
for i in range(0,16041):
F = 1
Sentince = [0]*300
for x in Data['Tweet'][i].split():
found = x in model.wv
if found:
F += 1
Sentince = Sentince + model[x]
Sentince = [ e / F-1 for e in Sentince ]
Tweets_wv.append(Sentince)
print(len(Tweets_wv[0]))
Test_wv = []
for i in range(0,3096):
F = 1
Sentince = [0]*300
for x in Test['tweet'][i].split():
found = x in model.wv
if found:
F += 1
Sentince = Sentince + model[x]
Sentince = [ e / F-1 for e in Sentince ]
Test_wv.append(Sentince)
print(len(Test_wv[0]))
```
<div class="alert alert-block alert-warning">
3. Normalizing the vectors
</div>
```
Scaler = MinMaxScaler()
Tweets_wv = Scaler.fit_transform(Tweets_wv)
Test_wv = Scaler.fit_transform(Test_wv)
#print(Tweets_wv[0])
```
<div class="alert alert-block alert-warning">
4. Testing
</div>
```
#Naïve Bayes Multinomial
Clf = naive_bayes.MultinomialNB()
Clf.fit(Tweets_wv,Data['Label'])
Pred = Clf.predict(Test_wv)
acc = metrics.accuracy_score(test_labels['vlabels'],Pred)
print ('accuracy = '+str(acc*100)+'%')
print (metrics.classification_report(test_labels['vlabels'],Pred))
#SVM (Linear Kernel)
Clf = svm.SVC(kernel='linear', C=1)
Clf.fit(Tweets_wv,Data['Label'])
Pred = Clf.predict(Test_wv)
acc = metrics.accuracy_score(test_labels['vlabels'],Pred)
print ('accuracy = '+str(acc*100)+'%')
print (metrics.classification_report(test_labels['vlabels'],Pred))
#Logistic Regression
Clf = LogisticRegression()
Clf.fit(Tweets_wv,Data['Label'])
Pred = Clf.predict(Test_wv)
acc = metrics.accuracy_score(test_labels['vlabels'],Pred)
print ('accuracy = '+str(acc*100)+'%')
print (metrics.classification_report(test_labels['vlabels'],Pred))
```
|
github_jupyter
|
import glob
import nltk
import pandas as pd
from sklearn import svm
from sklearn import metrics
from sklearn import naive_bayes
from gensim.models import KeyedVectors
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
model = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
li = []
Cols = ['ID','Label', 'Tweet']
path = r'C:\\Users\\khled\\Downloads\\Model\\'
all_files = glob.glob(path + "/twitter-201*.txt")
#Reading all files:
for file in all_files:
df = pd.read_csv(file, names=Cols, delimiter='\t')
li.append(df)
DF = pd.concat(li, axis=0, ignore_index=True)
Data = DF.drop('ID', axis=1)
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()
stop = stopwords.words('english')
Data['Tweet'] = Data['Tweet'].replace({r'\\':'',r'\'':'',r'\,':'','&':'',r'\"':'','!':'','\.':'','u2019':'\'','u002c':',','(@[A-Za-z0-9]+)|(\w+:\/\/\S+)':''}, regex=True)
Data['Tweet'] = [ tweet.casefold() for tweet in Data['Tweet'] ]
Data['Tweet'] = Data['Tweet'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))
Data['Tweet'] = Data['Tweet'].apply(lambda x: ' '.join([porter.stem(word) for word in x.split()]))
def cond(i):
if i == 0: return 'neutral'
elif i == 1: return 'positive'
elif i == 2: return 'negative'
return i
#Reading Test and Test Labels for evaluating results
Test = pd.read_csv("C:\\Users\\khled\\Downloads\\Model\\test.csv")
test_labels = pd.read_csv("C:\\Users\\khled\\Downloads\\Model\\answer_key.csv")
test_labels['vlabels'] = [cond(label) for label in test_labels['label']]
Test['tweet'] = Test['tweet'].replace({r'\\':'',r'\'':'',r'\,':'','&':'',r'\"':'','!':'','\.':'','u2019':'\'','u002c':',','(@[A-Za-z0-9]+)|(\w+:\/\/\S+)':''}, regex=True)
Test['tweet'] = [ tweet.casefold() for tweet in Test['tweet'] ]
Test['tweet'] = Test['tweet'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))
Test['tweet'] = Test['tweet'].apply(lambda x: ' '.join([porter.stem(word) for word in x.split()]))
print(len(Data['Tweet']))
#Transform tweets to array
Tweets_wv = []
for i in range(0,16041):
F = 1
Sentince = [0]*300
for x in Data['Tweet'][i].split():
found = x in model.wv
if found:
F += 1
Sentince = Sentince + model[x]
Sentince = [ e / F-1 for e in Sentince ]
Tweets_wv.append(Sentince)
print(len(Tweets_wv[0]))
Test_wv = []
for i in range(0,3096):
F = 1
Sentince = [0]*300
for x in Test['tweet'][i].split():
found = x in model.wv
if found:
F += 1
Sentince = Sentince + model[x]
Sentince = [ e / F-1 for e in Sentince ]
Test_wv.append(Sentince)
print(len(Test_wv[0]))
Scaler = MinMaxScaler()
Tweets_wv = Scaler.fit_transform(Tweets_wv)
Test_wv = Scaler.fit_transform(Test_wv)
#print(Tweets_wv[0])
#Naïve Bayes Multinomial
Clf = naive_bayes.MultinomialNB()
Clf.fit(Tweets_wv,Data['Label'])
Pred = Clf.predict(Test_wv)
acc = metrics.accuracy_score(test_labels['vlabels'],Pred)
print ('accuracy = '+str(acc*100)+'%')
print (metrics.classification_report(test_labels['vlabels'],Pred))
#SVM (Linear Kernel)
Clf = svm.SVC(kernel='linear', C=1)
Clf.fit(Tweets_wv,Data['Label'])
Pred = Clf.predict(Test_wv)
acc = metrics.accuracy_score(test_labels['vlabels'],Pred)
print ('accuracy = '+str(acc*100)+'%')
print (metrics.classification_report(test_labels['vlabels'],Pred))
#Logistic Regression
Clf = LogisticRegression()
Clf.fit(Tweets_wv,Data['Label'])
Pred = Clf.predict(Test_wv)
acc = metrics.accuracy_score(test_labels['vlabels'],Pred)
print ('accuracy = '+str(acc*100)+'%')
print (metrics.classification_report(test_labels['vlabels'],Pred))
| 0.253861 | 0.517754 |
```
from pandas_datareader import data, wb
tickers_data = {}
from tqdm import tqdm
tickers = ['APBR', 'PAMP', 'YPFD', 'GGAL', 'ERAR', 'CRES', 'COME', 'ALUA', 'FRAN', 'MIRG',
'BMA', 'TRAN', 'TS', 'JMIN', 'EDN', 'TGSU2', 'SAMI', 'AGRO', 'TECO2', 'PESA',
'CEPU', 'CTIO', 'CECO2', 'AUSO', 'PETR', 'CELU', 'TGNO4']
for ticker in tqdm(tickers):
if ticker in tickers_data: continue
for method in 'get_data_google get_data_yahoo'.split():
try:
tickers_data[ticker] = {
'source': method,
'data': getattr(data, method)(ticker)
}
except Exception:
continue
import pickle
with open('tickers_data.pkl', 'w') as f:
pickle.dump(tickers_data, f, 2)
%matplotlib nbagg
%pylab
from statsmodels.tsa.filters.hp_filter import hpfilter
returns = []
for ticker, ticker_data in tickers_data.iteritems():
close = ticker_data['data']['2017-01-01':].Close
if len(close) == 0: continue
returns.append(
{
'return': (close.iloc[-1] - close.iloc[0]) / close.iloc[0],
'close': hpfilter(close, 50)[1],
'close_orig': close,
'ticker': ticker
}
)
figure()
t = choice(returns)
title(t['ticker'])
t['close'].plot()
t['close_orig'].plot()
def corr(s1, s2, start):
s1 = s1[start:]
s2 = s2[start:]
# return (s1 / s1.iloc[0]).corr(s2 / s2.iloc[0])
return (s1 / s1.iloc[0]).diff().corr((s2 / s2.iloc[0]).diff())
corrs = []
for t1 in returns:
for t2 in returns:
corrs.append(
{
't1': t1['ticker'],
't2': t2['ticker'],
'corr': corr(t1['close'], t2['close'], '2016-01-01')
}
)
import pandas as pd
returns = pd.DataFrame(returns)
returns.sort_values('return', ascending=False)[['ticker', 'return']]
corrs = pd.DataFrame(corrs)
corrs = corrs.sort_values('corr', ascending=False)
corrs[corrs.t1 == 'PAMP'].merge(returns, left_on='t2', right_on='ticker')[['t2', 'corr', 'return']]
from sklearn.cluster import k_means
figure()
plot(range(2, 10), [k_means(M, i)[-1] for i in range(2, 10)], '-o')
from sklearn.cluster import k_means
clusters = dict(zip(names, k_means(M, 5)[1]))
from collections import defaultdict
names = sorted(corrs.t1.unique(), key=lambda x:corrs['corr'][corrs.t1==x].sum())
if 'avg_cluster_distance' in globals():
avg_cluster_distance = defaultdict(list)
for name, cl_id in clusters.iteritems():
avg_cluster_distance[cl_id].append(corrs['corr'][corrs.t1==name].sum())
avg_cluster_distance = {cl_id: np.mean(v) for cl_id, v in avg_cluster_distance.iteritems()}
names = sorted(names, key=lambda x:avg_cluster_distance[clusters[x]])
M = []
for name1 in names:
row = []
for name2 in names:
if name1 == name2:
row.append(0)
else:
c = corrs[(corrs.t1 == name1) & (corrs.t2==name2)]
row.append(c['corr'].iloc[0])
M.append(row)
figure()
imshow(M, interpolation='nearest', origin='lower')
xticks(range(len(names)), names, rotation=45)
yticks(range(len(names)), names, rotation=45)
colorbar()
title('Correlacion stocks del Merval')
import networkx as nx
edges = []
for i, row in corrs.iterrows():
if row['corr'] > 0:
edges.append((row.t1, row.t2, round(float(row['corr']), 2)))
g = nx.Graph()
g.add_weighted_edges_from(edges)
nx.write_graphml(g, 'g.graphml')
!pwd
figure()
tickers_data['FRAN']['data']['2016-01-01':].Close.plot()
```
|
github_jupyter
|
from pandas_datareader import data, wb
tickers_data = {}
from tqdm import tqdm
tickers = ['APBR', 'PAMP', 'YPFD', 'GGAL', 'ERAR', 'CRES', 'COME', 'ALUA', 'FRAN', 'MIRG',
'BMA', 'TRAN', 'TS', 'JMIN', 'EDN', 'TGSU2', 'SAMI', 'AGRO', 'TECO2', 'PESA',
'CEPU', 'CTIO', 'CECO2', 'AUSO', 'PETR', 'CELU', 'TGNO4']
for ticker in tqdm(tickers):
if ticker in tickers_data: continue
for method in 'get_data_google get_data_yahoo'.split():
try:
tickers_data[ticker] = {
'source': method,
'data': getattr(data, method)(ticker)
}
except Exception:
continue
import pickle
with open('tickers_data.pkl', 'w') as f:
pickle.dump(tickers_data, f, 2)
%matplotlib nbagg
%pylab
from statsmodels.tsa.filters.hp_filter import hpfilter
returns = []
for ticker, ticker_data in tickers_data.iteritems():
close = ticker_data['data']['2017-01-01':].Close
if len(close) == 0: continue
returns.append(
{
'return': (close.iloc[-1] - close.iloc[0]) / close.iloc[0],
'close': hpfilter(close, 50)[1],
'close_orig': close,
'ticker': ticker
}
)
figure()
t = choice(returns)
title(t['ticker'])
t['close'].plot()
t['close_orig'].plot()
def corr(s1, s2, start):
s1 = s1[start:]
s2 = s2[start:]
# return (s1 / s1.iloc[0]).corr(s2 / s2.iloc[0])
return (s1 / s1.iloc[0]).diff().corr((s2 / s2.iloc[0]).diff())
corrs = []
for t1 in returns:
for t2 in returns:
corrs.append(
{
't1': t1['ticker'],
't2': t2['ticker'],
'corr': corr(t1['close'], t2['close'], '2016-01-01')
}
)
import pandas as pd
returns = pd.DataFrame(returns)
returns.sort_values('return', ascending=False)[['ticker', 'return']]
corrs = pd.DataFrame(corrs)
corrs = corrs.sort_values('corr', ascending=False)
corrs[corrs.t1 == 'PAMP'].merge(returns, left_on='t2', right_on='ticker')[['t2', 'corr', 'return']]
from sklearn.cluster import k_means
figure()
plot(range(2, 10), [k_means(M, i)[-1] for i in range(2, 10)], '-o')
from sklearn.cluster import k_means
clusters = dict(zip(names, k_means(M, 5)[1]))
from collections import defaultdict
names = sorted(corrs.t1.unique(), key=lambda x:corrs['corr'][corrs.t1==x].sum())
if 'avg_cluster_distance' in globals():
avg_cluster_distance = defaultdict(list)
for name, cl_id in clusters.iteritems():
avg_cluster_distance[cl_id].append(corrs['corr'][corrs.t1==name].sum())
avg_cluster_distance = {cl_id: np.mean(v) for cl_id, v in avg_cluster_distance.iteritems()}
names = sorted(names, key=lambda x:avg_cluster_distance[clusters[x]])
M = []
for name1 in names:
row = []
for name2 in names:
if name1 == name2:
row.append(0)
else:
c = corrs[(corrs.t1 == name1) & (corrs.t2==name2)]
row.append(c['corr'].iloc[0])
M.append(row)
figure()
imshow(M, interpolation='nearest', origin='lower')
xticks(range(len(names)), names, rotation=45)
yticks(range(len(names)), names, rotation=45)
colorbar()
title('Correlacion stocks del Merval')
import networkx as nx
edges = []
for i, row in corrs.iterrows():
if row['corr'] > 0:
edges.append((row.t1, row.t2, round(float(row['corr']), 2)))
g = nx.Graph()
g.add_weighted_edges_from(edges)
nx.write_graphml(g, 'g.graphml')
!pwd
figure()
tickers_data['FRAN']['data']['2016-01-01':].Close.plot()
| 0.382833 | 0.498779 |
**This notebook teaches how to:**
set up adaptive integration schemes, set up fail operations, set up preparation and finalization instructions, and use suggested step sizes.
[](https://mybinder.org/v2/gh/stammler/simframe/HEAD?labpath=examples%2F5_adaptive_schemes.ipynb)
# 5. Adaptive Integration Schemes
For this tutorial we revisit the problem of the first tutorial.
* $\frac{\mathrm{d}Y}{\mathrm{d}x} = b\ Y$
* $Y \left( 0 \right) = A$
* $Y \left( x \right) = A\ e^{bx}$
But this time we increase the step size, such that the numeric solution is oscillating.
**Problem parameters**
```
dx = 1.75
A = 1.
b = -1.
```
**Setting up frame**
```
from simframe import Frame
sim = Frame(description="Adaptive step sizing")
```
**Adding field and integration variable**
```
sim.addintegrationvariable("x", 0.)
sim.addfield("Y", A)
```
**Setting up writer**
```
from simframe import writers
sim.writer = writers.namespacewriter()
sim.writer.verbosity = 0
```
**Setting differential equation**
We slightly modify the differential equation and add a counter that tells us how often the function got called.
```
N = 0
def dYdx(frame, x, Y):
global N
N += 1
return b*Y
sim.Y.differentiator = dYdx
```
**Setting up the step size**
In this example we return a constant step size defined previously.
```
def fdx(frame):
return dx
sim.x.updater = fdx
```
**Setting up snapshots**
```
import numpy as np
sim.x.snapshots = np.arange(dx, 15., dx)
```
**Setting up integrator**
First we simply integrate with the known 1st-order Euler scheme with a constant step size.
```
from simframe import Integrator
from simframe import Instruction
from simframe import schemes
sim.integrator = Integrator(sim.x)
sim.integrator.instructions = [Instruction(schemes.expl_1_euler, sim.Y)]
```
**Running the simulation**
```
sim.run()
```
**Reading data**
```
data = sim.writer.read.all()
```
We store the data in a list for later comparison.
```
dataset = []
dataset.append([data, "Euler 1st-order", N])
```
**Plotting**
Function returning the exact solution used for plotting
```
def f(x):
return A*np.exp(b*x)
import matplotlib.pyplot as plt
def plot(dataset):
fig, ax = plt.subplots(dpi=150)
x = np.linspace(0, 15., 100)
ax.plot(x, f(x), c="black", label="Exact solution")
for i, val in enumerate(dataset):
ax.plot(val[0].x, val[0].Y, "o", c="C"+str(i), label="{} ({} evaluations)".format(val[1], val[2]))
ax.plot(val[0].x, val[0].Y, c="C"+str(i), lw=1)
ax.legend(fontsize="small")
fig.tight_layout()
plt.show()
plot(dataset)
```
As you can see, the calculated solution is oscillating aroung the real solution.
## Adaptive Step Sizing Schemes
Instead of a constant step size, we now want to adjust it dynamically. If the error is too large, we decrease the step size. As an estimate for the error we compare the full Euler 1st-order step to the solution we get from performing two consecutive Euler 1st-order step with half the step size. If the relative error is larger than 10 %, we repeat the integration with a smaller step size until we are withing the error.
We therefore have to set up a custom integration scheme as was shown in the previous example. The scheme has to perform the full step and two semi steps and and needs to compare them. If the error is too large, the scheme has to return `False`. If it was successful, it has to return the change `dY` of the dependent variable `Y`.
```
def adaptive(x0, Y0, dx, *args, **kwargs):
fullstep = dx*Y0.derivative(x0, Y0)
semistep1 = 0.5*fullstep
semistep2 = 0.5*dx*Y0.derivative(x0+0.5*dx, Y0+semistep1)
semisteps = semistep1 + semistep2
relerr = np.abs((semisteps-fullstep)/(Y0+semisteps))
if relerr > 0.1:
return False
else:
return semisteps
```
**Creating scheme and modifying instruction set**
```
from simframe.integration import Scheme
adaptive = Scheme(adaptive)
sim.integrator.instructions = [Instruction(adaptive, sim.Y)]
```
## The fail operation
If the integration failed, because the step size was too large, i.e., the scheme returned `False`, the integrator triggers a fail operation. This operation can be used to manipulate the step size. In our case, we want to decrease the step size by a factor of 10.
Note the `global dx` to manipule `dx` persistently outside the function.
```
def failop(frame):
global dx
dx /= 10.
```
We assign this function to the fail operation of the integrator. The fail operation needs the parent `Frame` object as positional argument. If any instruction returns `False`, the fail operation will be executed and the integrator goes through the instructions again, before updating the fields.
Note: In case you have an `update` instuction in your instruction set, you have to undo it by yourself in the fail operation.
```
sim.integrator.failop = failop
```
## Preparation and finalization
If the integration was successful, we want to increase our step size by a factor of 5. This is done via the `finalizer` of the integrator, which is called after going through the instruction set and after updating the fields to be integrated. The equivalent that is called before going through the instructions set is `<Frame>.integrator.preparator`.
```
def finalize(frame):
global dx
dx *= 5.
sim.integrator.finalizer = finalize
```
**Resetting the parameters**
```
N = 0
sim.x = 0.
sim.Y = 1.
sim.writer.reset()
```
Before running the simulation we save the inital step size for later use.
```
import copy
dx_ini = dx
```
**Running the simulation**
```
sim.run()
```
**Reading data and plotting**
```
data_adaptive = sim.writer.read.all()
dataset.append([data_adaptive, "Adaptive Euler 1st-order", N])
plot(dataset)
```
**Embedded methods**
Another technique for estimating the error is to perform a higher order method for the full step instead of the same method for two semistep as done before. In some cases the higher order method is utilizing the result of the lower order method, saving evaluations. These methods are called embedded methods.
`simframe` comes with a few embedded methods. In this example we use the embedded Bogacki-Shampine method.
```
sim.integrator.instructions = [Instruction(schemes.expl_3_bogacki_shampine_adptv, sim.Y)]
```
## Suggested step sizes
The embedded methods included in `simframe` provide an estimate for the new step size depending on the truncation error. This estimate is saved in the integration variable in `<IntVar>.suggested`. We have to modify the step size function to utilize this estimate.
```
def fdx(sim):
return sim.x.suggested
sim.x.updater = fdx
```
And we have to give an initial suggestion for the step size. We'll use the initial value as before.
```
sim.x.suggest(dx_ini)
```
**Unsetting fail operation and finalization**
The fail operation and finalization operations are not needed anymore and have to be unset.
```
sim.integrator.failop = None
sim.integrator.finalizer = None
```
**Resetting the parameters and running the simulation**
```
N = 0
sim.x = 0.
sim.Y = 1.
sim.writer.reset()
sim.run()
```
**Reading data and plotting**
```
data_bogackishampine = sim.writer.read.all()
dataset.append([data_bogackishampine, "Adaptive Bogacki-Shampine 3rd-order", N])
plot(dataset)
```
As you can see the Bogacki-Shampine method needs 32 eveluations of the derivative in this setup. That's only about half of the amount of the adaptive Euler method and it's significantly more accurate.
Change the stepsize to `dx = 2.25` and run the notebook again. For this step size the Euler 1st-order method is unstable.
## Passing keyword arguments to integration scheme
It is also possible to pass key word arguments to the integrator to control its behaviour. We could for example increase the accuracy by changing the desired relative error. This is done by passing a controller dictionary to the instruction.
```
sim.integrator.instructions = [Instruction(schemes.expl_3_bogacki_shampine_adptv, sim.Y, controller={"eps": 0.01})]
```
Here we want to have maximum relative error of $1\,\%$. Default is $10\,\%$.
**Resetting the parameters and running the simulation**
Note the `reset=True` keyword when resetting the suggested step size. Suggesting step sizes takes the minimum of the suggested and the current value, which is still set from the earlier integration. We therefore have to reset the current value with the keyword.
```
N = 0
sim.x = 0.
sim.x.suggest(dx_ini, reset=True)
sim.Y = 1.
sim.Y._buffer = None
sim.writer.reset()
sim.run()
```
**Reading and plotting data**
```
data_bogackishampine_accurate = sim.writer.read.all()
dataset.append([data_bogackishampine_accurate, "Adaptive Bogacki-Shampine 3rd-order ($\epsilon=0.01$)", N])
plot(dataset)
```
With this settings it takes slightly longer to approach the analytical solution, but the overshooting in the beginning is prevented.
|
github_jupyter
|
dx = 1.75
A = 1.
b = -1.
from simframe import Frame
sim = Frame(description="Adaptive step sizing")
sim.addintegrationvariable("x", 0.)
sim.addfield("Y", A)
from simframe import writers
sim.writer = writers.namespacewriter()
sim.writer.verbosity = 0
N = 0
def dYdx(frame, x, Y):
global N
N += 1
return b*Y
sim.Y.differentiator = dYdx
def fdx(frame):
return dx
sim.x.updater = fdx
import numpy as np
sim.x.snapshots = np.arange(dx, 15., dx)
from simframe import Integrator
from simframe import Instruction
from simframe import schemes
sim.integrator = Integrator(sim.x)
sim.integrator.instructions = [Instruction(schemes.expl_1_euler, sim.Y)]
sim.run()
data = sim.writer.read.all()
dataset = []
dataset.append([data, "Euler 1st-order", N])
def f(x):
return A*np.exp(b*x)
import matplotlib.pyplot as plt
def plot(dataset):
fig, ax = plt.subplots(dpi=150)
x = np.linspace(0, 15., 100)
ax.plot(x, f(x), c="black", label="Exact solution")
for i, val in enumerate(dataset):
ax.plot(val[0].x, val[0].Y, "o", c="C"+str(i), label="{} ({} evaluations)".format(val[1], val[2]))
ax.plot(val[0].x, val[0].Y, c="C"+str(i), lw=1)
ax.legend(fontsize="small")
fig.tight_layout()
plt.show()
plot(dataset)
def adaptive(x0, Y0, dx, *args, **kwargs):
fullstep = dx*Y0.derivative(x0, Y0)
semistep1 = 0.5*fullstep
semistep2 = 0.5*dx*Y0.derivative(x0+0.5*dx, Y0+semistep1)
semisteps = semistep1 + semistep2
relerr = np.abs((semisteps-fullstep)/(Y0+semisteps))
if relerr > 0.1:
return False
else:
return semisteps
from simframe.integration import Scheme
adaptive = Scheme(adaptive)
sim.integrator.instructions = [Instruction(adaptive, sim.Y)]
def failop(frame):
global dx
dx /= 10.
sim.integrator.failop = failop
def finalize(frame):
global dx
dx *= 5.
sim.integrator.finalizer = finalize
N = 0
sim.x = 0.
sim.Y = 1.
sim.writer.reset()
import copy
dx_ini = dx
sim.run()
data_adaptive = sim.writer.read.all()
dataset.append([data_adaptive, "Adaptive Euler 1st-order", N])
plot(dataset)
sim.integrator.instructions = [Instruction(schemes.expl_3_bogacki_shampine_adptv, sim.Y)]
def fdx(sim):
return sim.x.suggested
sim.x.updater = fdx
sim.x.suggest(dx_ini)
sim.integrator.failop = None
sim.integrator.finalizer = None
N = 0
sim.x = 0.
sim.Y = 1.
sim.writer.reset()
sim.run()
data_bogackishampine = sim.writer.read.all()
dataset.append([data_bogackishampine, "Adaptive Bogacki-Shampine 3rd-order", N])
plot(dataset)
sim.integrator.instructions = [Instruction(schemes.expl_3_bogacki_shampine_adptv, sim.Y, controller={"eps": 0.01})]
N = 0
sim.x = 0.
sim.x.suggest(dx_ini, reset=True)
sim.Y = 1.
sim.Y._buffer = None
sim.writer.reset()
sim.run()
data_bogackishampine_accurate = sim.writer.read.all()
dataset.append([data_bogackishampine_accurate, "Adaptive Bogacki-Shampine 3rd-order ($\epsilon=0.01$)", N])
plot(dataset)
| 0.444806 | 0.987532 |
# **Data Understanding**
---
## **Prepare Environment**
<br/>
### Imports
```
# Data analysis and data wrangling
import numpy as np
import pandas as pd
# Plotting
import seaborn as sns
import matplotlib.pyplot as plt
# Other
import configparser
import subprocess
import warnings
import pprint
import time
import os
```
<br/>
### Prepare Principal Directory
```
def path_to_work(end_directory: str='notebooks'):
curr_dir = os.path.dirname(os.path.realpath ("__file__"))
if curr_dir.endswith(end_directory):
os.chdir('..')
return f'Change directory to: {curr_dir}'
return f'Current working directory: {curr_dir}'
path_to_work('notebooks')
```
<br/>
### Set Config
```
# Visualization inside the jupyter
%matplotlib inline
# Load the "autoreload" extension so that code can change
%load_ext autoreload
# ----------
# Plot
# ----------
# graph style
sns.set_style("darkgrid")
plt.style.use('fivethirtyeight')
# ----------
# Seaborn rcParams
# ----------
rc={'savefig.dpi': 500,
'figure.autolayout': True,
'figure.figsize': [17, 12],
'axes.labelsize': 18,
'axes.titlesize': 18,
'font.size': 10,
'lines.linewidth': 1.0,
'lines.markersize': 8,
'legend.fontsize': 15,
'xtick.labelsize': 15,
'ytick.labelsize': 15}
sns.set(context='notebook', # notebook
style='darkgrid',
palette='deep',
color_codes=True,
rc=rc)
# ----------
# Pandas
# ----------
# Floating point
pd.options.display.float_format = '{:.2f}'.format
# Print xxxx rows and all columns
pd.set_option('display.max_rows', 300)
pd.set_option('display.max_columns', None)
# ----------
# Python
# ----------
# pretty print
pp = pprint.PrettyPrinter(indent=4)
# Supress unnecessary warnings so that presentation looks clean
warnings.filterwarnings('ignore')
```
<br/>
### Load Data
```
df = pd.read_csv('data/cleansing/dados_limpos_ceaps_cleansing.csv',
encoding='utf-8',
delimiter=',',
verbose=True)
dict_map_senadores = dict(pd.read_csv('data/cleansing/map_senadores.csv',
encoding='utf-8',
delimiter=',',
verbose=True))
type(dict_map_senadores)
# Primeiras linhas do dataset
df.head()
```
### Seleção condicional onde pegamos todos as linhas cujo o valor reembolsado é R$ 0,01
```
df[df['VALOR_REEMBOLSADO'] == 0.01]
```
---
```
plot_tipo_despesa = sns.countplot(data=df,
x='TIPO_DESPESA',
color='blue')
plt.title('QUANTIDADE DE DESPESAS LANÇADAS')
plt.xlabel('TIPO DE DESPESA')
plt.ylabel('Valor em R$')
plt.xticks(rotation=45);
```
<br/>
### Check Values by `SENADOR`
```
df['SENADOR'].value_counts().plot(kind='bar', color='blue')
plt.xticks(rotation=90)
plt.title("Valor Total por Senador")
plt.ylabel('Valor em R$')
plt.legend()
plt.show()
```
<br/>
### Top Values Received
```
valores_senadores = df.groupby('SENADOR')['VALOR_REEMBOLSADO'].sum().sort_values(ascending=False)
valores_senadores.plot(kind='bar', color='green')
plt.xticks(rotation=90)
plt.title("Valor de Reembolso por Senador")
plt.ylabel('Valor em R$')
plt.legend()
plt.autoscale()
plt.show()
```
### Verificando o quanto que foi pedido de reembolso durante cada mês
```
gastos_por_mes = df.pivot_table(index='MES', values='VALOR_REEMBOLSADO', aggfunc=np.sum)
display(gastos_por_mes)
gastos_por_mes = df.pivot_table(index='MES', values='VALOR_REEMBOLSADO', aggfunc=np.sum)
gastos_por_mes = gastos_por_mes.rename(index={1:"janeiro",
2:"fevereiro",
3:"março",
4:"abril",
5:"maio",
6:"junho",
7:"julho",
8:"agosto",
9:"setembro",
10:"outubro",
11:"novembro",
12:"dezembro"})
display(gastos_por_mes)
gastos_por_mes.plot(kind='bar', color='blue', fontsize=18)
# visualização do gráfico
plt.ylabel('Valor em R$')
plt.xlabel('Meses')
plt.title("Valor de Reembolso por Mês")
plt.legend(loc="upper right")
plt.legend()
plt.xticks(rotation=45)
plt.autoscale()
plt.show()
```
### Verificando a média e mediana dos valores reembolsados
```
#Geração dos dados para o mapa de calor
#Criando uma Pivot Table
mapa_de_calor = df.pivot_table(index='MES', values='VALOR_REEMBOLSADO', columns='TIPO_DESPESA', aggfunc=np.sum)
mapa_de_calor = mapa_de_calor.rename(index={1:"janeiro",
2:"fevereiro",
3:"março",
4:"abril",
5:"maio",
6:"junho",
7:"julho",
8:"agosto",
9:"setembro",
10:"outubro",
11:"novembro",
12:"dezembro"})
mapa_de_calor.head()
#Gerando o mapa de calor
sns.heatmap(mapa_de_calor, annot=True, fmt='g', cmap='Reds')
plt.title("\nMapa de Calor sobre os Tipos de Despesas\n\n")
plt.xticks(rotation=75)
plt.yticks(rotation=0)
plt.autoscale()
plt.show()
```
---
|
github_jupyter
|
# Data analysis and data wrangling
import numpy as np
import pandas as pd
# Plotting
import seaborn as sns
import matplotlib.pyplot as plt
# Other
import configparser
import subprocess
import warnings
import pprint
import time
import os
def path_to_work(end_directory: str='notebooks'):
curr_dir = os.path.dirname(os.path.realpath ("__file__"))
if curr_dir.endswith(end_directory):
os.chdir('..')
return f'Change directory to: {curr_dir}'
return f'Current working directory: {curr_dir}'
path_to_work('notebooks')
# Visualization inside the jupyter
%matplotlib inline
# Load the "autoreload" extension so that code can change
%load_ext autoreload
# ----------
# Plot
# ----------
# graph style
sns.set_style("darkgrid")
plt.style.use('fivethirtyeight')
# ----------
# Seaborn rcParams
# ----------
rc={'savefig.dpi': 500,
'figure.autolayout': True,
'figure.figsize': [17, 12],
'axes.labelsize': 18,
'axes.titlesize': 18,
'font.size': 10,
'lines.linewidth': 1.0,
'lines.markersize': 8,
'legend.fontsize': 15,
'xtick.labelsize': 15,
'ytick.labelsize': 15}
sns.set(context='notebook', # notebook
style='darkgrid',
palette='deep',
color_codes=True,
rc=rc)
# ----------
# Pandas
# ----------
# Floating point
pd.options.display.float_format = '{:.2f}'.format
# Print xxxx rows and all columns
pd.set_option('display.max_rows', 300)
pd.set_option('display.max_columns', None)
# ----------
# Python
# ----------
# pretty print
pp = pprint.PrettyPrinter(indent=4)
# Supress unnecessary warnings so that presentation looks clean
warnings.filterwarnings('ignore')
df = pd.read_csv('data/cleansing/dados_limpos_ceaps_cleansing.csv',
encoding='utf-8',
delimiter=',',
verbose=True)
dict_map_senadores = dict(pd.read_csv('data/cleansing/map_senadores.csv',
encoding='utf-8',
delimiter=',',
verbose=True))
type(dict_map_senadores)
# Primeiras linhas do dataset
df.head()
df[df['VALOR_REEMBOLSADO'] == 0.01]
plot_tipo_despesa = sns.countplot(data=df,
x='TIPO_DESPESA',
color='blue')
plt.title('QUANTIDADE DE DESPESAS LANÇADAS')
plt.xlabel('TIPO DE DESPESA')
plt.ylabel('Valor em R$')
plt.xticks(rotation=45);
df['SENADOR'].value_counts().plot(kind='bar', color='blue')
plt.xticks(rotation=90)
plt.title("Valor Total por Senador")
plt.ylabel('Valor em R$')
plt.legend()
plt.show()
valores_senadores = df.groupby('SENADOR')['VALOR_REEMBOLSADO'].sum().sort_values(ascending=False)
valores_senadores.plot(kind='bar', color='green')
plt.xticks(rotation=90)
plt.title("Valor de Reembolso por Senador")
plt.ylabel('Valor em R$')
plt.legend()
plt.autoscale()
plt.show()
gastos_por_mes = df.pivot_table(index='MES', values='VALOR_REEMBOLSADO', aggfunc=np.sum)
display(gastos_por_mes)
gastos_por_mes = df.pivot_table(index='MES', values='VALOR_REEMBOLSADO', aggfunc=np.sum)
gastos_por_mes = gastos_por_mes.rename(index={1:"janeiro",
2:"fevereiro",
3:"março",
4:"abril",
5:"maio",
6:"junho",
7:"julho",
8:"agosto",
9:"setembro",
10:"outubro",
11:"novembro",
12:"dezembro"})
display(gastos_por_mes)
gastos_por_mes.plot(kind='bar', color='blue', fontsize=18)
# visualização do gráfico
plt.ylabel('Valor em R$')
plt.xlabel('Meses')
plt.title("Valor de Reembolso por Mês")
plt.legend(loc="upper right")
plt.legend()
plt.xticks(rotation=45)
plt.autoscale()
plt.show()
#Geração dos dados para o mapa de calor
#Criando uma Pivot Table
mapa_de_calor = df.pivot_table(index='MES', values='VALOR_REEMBOLSADO', columns='TIPO_DESPESA', aggfunc=np.sum)
mapa_de_calor = mapa_de_calor.rename(index={1:"janeiro",
2:"fevereiro",
3:"março",
4:"abril",
5:"maio",
6:"junho",
7:"julho",
8:"agosto",
9:"setembro",
10:"outubro",
11:"novembro",
12:"dezembro"})
mapa_de_calor.head()
#Gerando o mapa de calor
sns.heatmap(mapa_de_calor, annot=True, fmt='g', cmap='Reds')
plt.title("\nMapa de Calor sobre os Tipos de Despesas\n\n")
plt.xticks(rotation=75)
plt.yticks(rotation=0)
plt.autoscale()
plt.show()
| 0.591605 | 0.774839 |
```
BRANCH='main'
"""
You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.
Instructions for setting up Colab are as follows:
1. Open a new Python 3 notebook.
2. Import this notebook from GitHub (File -> Upload Notebook -> "GITHUB" tab -> copy/paste GitHub URL)
3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select "GPU" for hardware accelerator)
4. Run this cell to set up dependencies.
"""
# If you're using Google Colab and not running locally, run this cell
# install NeMo
!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]
import os
import wget
import torch
import pytorch_lightning as pl
from omegaconf import OmegaConf
```
# Task Description
In this tutorial, we are going to describe how to export NeMo NLP models with BERT based models as the pre-trained model.
## Convert the Megatron-LM Weights to Nemo file
If you prefer to use the Huggingface BERT models, please skip this section and refer to `Setting up a NeMo Experiment` section to load a model from `nemo_nlp.modules.get_pretrained_lm_models_list()`
NeMo Megatron BERT can [load from a pretrained model](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/core/core.html?highlight=nemo%20file#restore) using `.nemo` file. We can convert the Megatron-LM checkpoint to the `.nemo` file. Let's first download the pretrained model weights and vocabulary file.
```
from nemo.collections.nlp.modules.common.megatron.megatron_utils import MEGATRON_CONFIG_MAP
import pathlib
PRETRAINED_BERT_MODEL = "megatron-bert-345m-uncased" # specify BERT-like model from MEGATRON_CONFIG_MAP.keys()
nemo_out_path = "qa_pretrained.nemo" # the nemo output file name
checkpoint_url = MEGATRON_CONFIG_MAP[PRETRAINED_BERT_MODEL]['checkpoint']
vocab_url = MEGATRON_CONFIG_MAP[PRETRAINED_BERT_MODEL]['vocab']
checkpoint_filename = pathlib.Path(checkpoint_url).name
vocab_filename = pathlib.Path(vocab_url).name
if not pathlib.Path(checkpoint_filename).exists():
print('downloading from checkpoint url', checkpoint_url)
!wget $checkpoint_url
if not pathlib.Path(vocab_filename).exists():
print('downloading from vocab url', vocab_url)
!wget $vocab_url
WORK_DIR = "WORK_DIR"
os.makedirs(WORK_DIR, exist_ok=True)
# Prepare the model parameters
# download the model's configuration file
config_dir = WORK_DIR + '/configs/'
MODEL_CONFIG = "megatron_bert_config.yaml"
os.makedirs(config_dir, exist_ok=True)
if not os.path.exists(config_dir + MODEL_CONFIG):
print('Downloading config file...')
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/language_modeling/conf/' + MODEL_CONFIG, config_dir)
else:
print ('config file is already exists')
# this line will print the entire config of the model
config_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}'
print(config_path)
config = OmegaConf.load(config_path)
config.model.megatron_legacy = True # set to true if you trained the NLP model on NeMo < 1.5.0
config.model.bias_gelu_fusion = False # set to true if you want the MegatronLM to NeMo conversion for training; and set to false to use the converted model at time of export
config.model.masked_softmax_fusion = False # set to true if you want the MegatronLM to NeMo conversion for training; and set to false to use the converted model at time of export
config.model.num_layers = 24
config.model.hidden_size = 1024
config.model.ffn_hidden_size = 4096
config.model.num_attention_heads = 16
config.model.tokenizer.vocab_file = vocab_filename
config.model.tokenizer.type = 'BertWordPieceLowerCase' # change this to BertWordPieceCase if you are using a cased pretrained model
config.model.tensor_model_parallel_size = 1
config.model.data.data_prefix = ''
config.model.max_position_embeddings = 512
config.model.data.seq_length = 512
config.cfg = {}
config.cfg.cfg = config.model
with open('hparams.yaml', 'w') as f:
f.write(OmegaConf.to_yaml(config.cfg))
if(config.model.megatron_legacy):
checkpoint_filename = "model_optim_rng_ca.pt" #provide path to the pretrained pt file you used during training on NeMo < 1.5.0, for NeMo >= 1.5.0
print(checkpoint_filename)
import os
PWD = os.getcwd()
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/language_modeling/megatron_lm_ckpt_to_nemo.py')
!python -m torch.distributed.run --nproc_per_node=1 megatron_lm_ckpt_to_nemo.py --checkpoint_folder=$PWD --checkpoint_name=$checkpoint_filename --hparams_file=$PWD/hparams.yaml --nemo_file_path=$PWD/$nemo_out_path --model_type=bert --tensor_model_parallel_size=1
```
# Legacy NLP Bert based model conversion
Step 1: Convert legacy nemo checkpoint to a checkpoint which is currently supported by nemo
Step 2: Use the converted model from step 1 to export the nemo file to the required format
```
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/nemo_legacy_import/nlp_checkpoint_port.py')
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/export.py')
legacy_nemo_file_path = "/NeMo/megatron_multiqa.nemo" #path to you model trained on NeMo < 1.5
nemo_converted_out_path = "converted_megatron_multiqa.nemo"
megatron_absolute_language_model_path = "/NeMo/tutorials/nlp/qa_pretrained.nemo" # Give the absolute path of the model you obtained using megatron_lm_ckpt_to_nemo
onnx_export_out_path = "onnx_megatron_multiqa.onnx"
os.system(f"python nlp_checkpoint_port.py {legacy_nemo_file_path} {nemo_converted_out_path} --megatron-legacy=True --megatron-checkpoint {megatron_absolute_language_model_path}")
os.system(f"python export.py {nemo_converted_out_path} {onnx_export_out_path} --autocast --runtime-check")
```
# Convert a NLP model with BERT based pre-trained model trained on NeMo >= 1.5.0
For models trained on NeMo >= 1.5.0, you just run the export script and skip the legacy conversion part
```
nemo_file_path = ""
onnx_export_out_path =
python export.py $nemo_converted_out_path $onnx_export_out_path --autocast --runtime-check
```
|
github_jupyter
|
BRANCH='main'
"""
You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.
Instructions for setting up Colab are as follows:
1. Open a new Python 3 notebook.
2. Import this notebook from GitHub (File -> Upload Notebook -> "GITHUB" tab -> copy/paste GitHub URL)
3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select "GPU" for hardware accelerator)
4. Run this cell to set up dependencies.
"""
# If you're using Google Colab and not running locally, run this cell
# install NeMo
!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]
import os
import wget
import torch
import pytorch_lightning as pl
from omegaconf import OmegaConf
from nemo.collections.nlp.modules.common.megatron.megatron_utils import MEGATRON_CONFIG_MAP
import pathlib
PRETRAINED_BERT_MODEL = "megatron-bert-345m-uncased" # specify BERT-like model from MEGATRON_CONFIG_MAP.keys()
nemo_out_path = "qa_pretrained.nemo" # the nemo output file name
checkpoint_url = MEGATRON_CONFIG_MAP[PRETRAINED_BERT_MODEL]['checkpoint']
vocab_url = MEGATRON_CONFIG_MAP[PRETRAINED_BERT_MODEL]['vocab']
checkpoint_filename = pathlib.Path(checkpoint_url).name
vocab_filename = pathlib.Path(vocab_url).name
if not pathlib.Path(checkpoint_filename).exists():
print('downloading from checkpoint url', checkpoint_url)
!wget $checkpoint_url
if not pathlib.Path(vocab_filename).exists():
print('downloading from vocab url', vocab_url)
!wget $vocab_url
WORK_DIR = "WORK_DIR"
os.makedirs(WORK_DIR, exist_ok=True)
# Prepare the model parameters
# download the model's configuration file
config_dir = WORK_DIR + '/configs/'
MODEL_CONFIG = "megatron_bert_config.yaml"
os.makedirs(config_dir, exist_ok=True)
if not os.path.exists(config_dir + MODEL_CONFIG):
print('Downloading config file...')
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/language_modeling/conf/' + MODEL_CONFIG, config_dir)
else:
print ('config file is already exists')
# this line will print the entire config of the model
config_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}'
print(config_path)
config = OmegaConf.load(config_path)
config.model.megatron_legacy = True # set to true if you trained the NLP model on NeMo < 1.5.0
config.model.bias_gelu_fusion = False # set to true if you want the MegatronLM to NeMo conversion for training; and set to false to use the converted model at time of export
config.model.masked_softmax_fusion = False # set to true if you want the MegatronLM to NeMo conversion for training; and set to false to use the converted model at time of export
config.model.num_layers = 24
config.model.hidden_size = 1024
config.model.ffn_hidden_size = 4096
config.model.num_attention_heads = 16
config.model.tokenizer.vocab_file = vocab_filename
config.model.tokenizer.type = 'BertWordPieceLowerCase' # change this to BertWordPieceCase if you are using a cased pretrained model
config.model.tensor_model_parallel_size = 1
config.model.data.data_prefix = ''
config.model.max_position_embeddings = 512
config.model.data.seq_length = 512
config.cfg = {}
config.cfg.cfg = config.model
with open('hparams.yaml', 'w') as f:
f.write(OmegaConf.to_yaml(config.cfg))
if(config.model.megatron_legacy):
checkpoint_filename = "model_optim_rng_ca.pt" #provide path to the pretrained pt file you used during training on NeMo < 1.5.0, for NeMo >= 1.5.0
print(checkpoint_filename)
import os
PWD = os.getcwd()
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/language_modeling/megatron_lm_ckpt_to_nemo.py')
!python -m torch.distributed.run --nproc_per_node=1 megatron_lm_ckpt_to_nemo.py --checkpoint_folder=$PWD --checkpoint_name=$checkpoint_filename --hparams_file=$PWD/hparams.yaml --nemo_file_path=$PWD/$nemo_out_path --model_type=bert --tensor_model_parallel_size=1
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/nemo_legacy_import/nlp_checkpoint_port.py')
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/export.py')
legacy_nemo_file_path = "/NeMo/megatron_multiqa.nemo" #path to you model trained on NeMo < 1.5
nemo_converted_out_path = "converted_megatron_multiqa.nemo"
megatron_absolute_language_model_path = "/NeMo/tutorials/nlp/qa_pretrained.nemo" # Give the absolute path of the model you obtained using megatron_lm_ckpt_to_nemo
onnx_export_out_path = "onnx_megatron_multiqa.onnx"
os.system(f"python nlp_checkpoint_port.py {legacy_nemo_file_path} {nemo_converted_out_path} --megatron-legacy=True --megatron-checkpoint {megatron_absolute_language_model_path}")
os.system(f"python export.py {nemo_converted_out_path} {onnx_export_out_path} --autocast --runtime-check")
nemo_file_path = ""
onnx_export_out_path =
python export.py $nemo_converted_out_path $onnx_export_out_path --autocast --runtime-check
| 0.708213 | 0.726729 |
# DAT210x - Programming with Python for DS
## Module4- Lab1
```
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
from plyfile import PlyData, PlyElement
# Look pretty...
# matplotlib.style.use('ggplot')
plt.style.use('ggplot')
```
Every `100` samples in the dataset, we save `1`. If things run too slow, try increasing this number. If things run too fast, try decreasing it... =)
```
reduce_factor = 100
```
Load up the scanned armadillo:
```
plyfile = PlyData.read('Datasets/stanford_armadillo.ply')
armadillo = pd.DataFrame({
'x':plyfile['vertex']['z'][::reduce_factor],
'y':plyfile['vertex']['x'][::reduce_factor],
'z':plyfile['vertex']['y'][::reduce_factor]
})
```
### PCA
In the method below, write code to import the libraries required for PCA.
Then, train a PCA model on the passed in `armadillo` dataframe parameter. Lastly, project the armadillo down to the two principal components, by dropping one dimension.
**NOTE-1**: Be sure to RETURN your projected armadillo rather than `None`! This projection will be stored in a NumPy NDArray rather than a Pandas dataframe. This is something Pandas does for you automatically =).
**NOTE-2**: Regarding the `svd_solver` parameter, simply pass that into your PCA model constructor as-is, e.g. `svd_solver=svd_solver`.
For additional details, please read through [Decomposition - PCA](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html).
```
armadillo.tail(10)
def do_PCA(armadillo, svd_solver):
from sklearn.decomposition import PCA
svd_solver = svd_solver
pca = PCA(n_components=2, svd_solver=svd_solver)
pca.fit(armadillo)
t = pca.transform(armadillo)
return t
```
### Preview the Data
```
# Render the Original Armadillo
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_title('Armadillo 3D')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.scatter(armadillo.x, armadillo.y, armadillo.z, c='green', marker='.', alpha=0.75)
plt.show()
```
### Time Execution Speeds
Let's see how long it takes PCA to execute:
```
%timeit transform = do_PCA(armadillo, 'full')
transform = do_PCA(armadillo, 'full')
```
```
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('Full PCA')
ax.scatter(transform[:,0], transform[:,1], c='blue', marker='.', alpha=0.75)
plt.show()
```
Let's also take a look at the speed of the randomized solver on the same dataset. It might be faster, it might be slower, or it might take exactly the same amount of time to execute:
```
%timeit rpca = do_PCA(armadillo, 'randomized')
trpca = do_PCA(armadillo, 'randomized')
```
Let's see what the results look like:
```
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('Randomized PCA')
ax.scatter(trpca[:,0], trpca[:,1], c='red', marker='.', alpha=0.75)
plt.show()
```
|
github_jupyter
|
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
from plyfile import PlyData, PlyElement
# Look pretty...
# matplotlib.style.use('ggplot')
plt.style.use('ggplot')
reduce_factor = 100
plyfile = PlyData.read('Datasets/stanford_armadillo.ply')
armadillo = pd.DataFrame({
'x':plyfile['vertex']['z'][::reduce_factor],
'y':plyfile['vertex']['x'][::reduce_factor],
'z':plyfile['vertex']['y'][::reduce_factor]
})
armadillo.tail(10)
def do_PCA(armadillo, svd_solver):
from sklearn.decomposition import PCA
svd_solver = svd_solver
pca = PCA(n_components=2, svd_solver=svd_solver)
pca.fit(armadillo)
t = pca.transform(armadillo)
return t
# Render the Original Armadillo
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_title('Armadillo 3D')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.scatter(armadillo.x, armadillo.y, armadillo.z, c='green', marker='.', alpha=0.75)
plt.show()
%timeit transform = do_PCA(armadillo, 'full')
transform = do_PCA(armadillo, 'full')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('Full PCA')
ax.scatter(transform[:,0], transform[:,1], c='blue', marker='.', alpha=0.75)
plt.show()
%timeit rpca = do_PCA(armadillo, 'randomized')
trpca = do_PCA(armadillo, 'randomized')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('Randomized PCA')
ax.scatter(trpca[:,0], trpca[:,1], c='red', marker='.', alpha=0.75)
plt.show()
| 0.712532 | 0.947137 |
<img src="images/logo.jpg" style="display: block; margin-left: auto; margin-right: auto;" alt="לוגו של מיזם לימוד הפייתון. נחש מצויר בצבעי צהוב וכחול, הנע בין האותיות של שם הקורס: לומדים פייתון. הסלוגן המופיע מעל לשם הקורס הוא מיזם חינמי ללימוד תכנות בעברית.">
# <span style="text-align: right; direction: rtl; float: right;">פונקציות – חלק 2</span>
## <span style="text-align: right; direction: rtl; float: right; clear: both;">הקדמה</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
עד כה למדנו להכיר את עולמן של הפונקציות מקרוב:
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li>פונקציות הן כלי שימושי שמאפשר לנו לחלק את הקוד לתתי־משימות מוגדרות, ולשמור עליו מסודר וקל לתחזוק.</li>
<li>לפונקציה יש "קלט" שהוא הפרמטרים שלה, ו"פלט" שהוא ערך ההחזרה שלה.</li>
<li>אפשר לקרוא לפונקציה בציון שמה, סוגריים, ורשימת הארגומנטים שרוצים להעביר לפרמטרים שלה.</li>
</ul>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
במחברת זו נרכוש כלים נוספים שיאפשרו לנו גמישות רבה יותר בהגדרת פונקציות ובשימוש בהן.
</p>
## <span style="text-align: right; direction: rtl; float: right; clear: both;">שימוש מתקדם בפונקציות</span>
### <span style="text-align: right; direction: rtl; float: right; clear: both;">העברת ארגומנטים בעזרת שם<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כאשר אנחנו קוראים לפונקציה, יישלחו לפי הסדר הארגומנטים שנעביר אל הפרמטרים שמוגדרים בכותרת הפונקציה.<br>
מצב כזה נקרא <dfn>positional arguments</dfn> ("<dfn>ארגומנטים לפי מיקום</dfn>").<br>
נסתכל על פונקציה שמקבלת טווח (סוף והתחלה, בסדר הזה) ומחזירה רשימה של כל המספרים השלמים בטווח:
</p>
```
def my_range(end, start):
numbers = []
i = start
while i < end:
numbers.append(i)
i += 1
return numbers
my_range(5, 0)
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
לפעמים נרצה לשנות את סדר הארגומנטים שאנחנו שולחים לפונקציה.<br>
נעשה זאת בקריאה לפונקציה, על־ידי העברת שם הארגומנט ולאחר מכן העברת הערך שאנחנו רוצים להעביר אליו:
</p>
```
my_range(start=0, end=5)
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בשורה הזו הפכנו את סדר הארגומנטים.<br>
כיוון שבקריאה כתבנו את שמות הפרמטרים התואמים לכותרת הפונקציה, הערכים נשלחו למקום הנכון.<br>
השיטה הזו נקראת <dfn>keyword arguments</dfn> (<dfn>"ארגומנטים לפי שם"</dfn>), ובה אנחנו מעבירים את הארגומנטים שלנו לפי שמות הפרמטרים בכותרת הפונקציה.<br>
אנחנו משתמשים בשיטה הזו אפילו כשאנחנו לא רוצים לשנות את סדר הארגומנטים, אלא רק לעשות קצת סדר בקוד.<br>
נבחן, לדוגמה, את המקרה של הפונקציה <code>random.randrange</code> – נעים יותר לראות קריאה לפונקציה עם שמות הפרמטרים:
</p>
```
import random
random.randrange(100, 200) # מובן פחות
random.randrange(start=100, stop=200) # מובן יותר
```
<div class="align-center" style="display: flex; text-align: right; direction: rtl;">
<div style="display: flex; width: 10%; float: right; ">
<img src="images/warning.png" style="height: 50px !important;" alt="אזהרה!">
</div>
<div style="width: 90%">
<p style="text-align: right; direction: rtl;">
למרות השימוש בסימן <code>=</code>, לא מדובר פה בהשמה במובן הקלאסי שלה.<br>
זוהי צורת כתיבה מיוחדת בקריאה לפונקציות שהמטרה שלה היא לסמן "העבר לפרמטר ששמו כך־וכך את הערך כך־וכך".
</p>
</div>
</div>
### <span style="text-align: right; direction: rtl; float: right; clear: both;">פרמטרים עם ערכי ברירת מחדל<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נזכר בפונקציה <code>get</code> של מילון, שמאפשרת לקבל ממנו ערך לפי מפתח מסוים.<br>
אם המפתח שאנחנו מחפשים לא קיים במילון, הפונקציה מחזירה <samp>None</samp>:
</p>
```
ghibli_release_dates = {
'Castle in the Sky': '1986-08-02',
'My Neighbor Totoro': '1988-04-16',
'Spirited Away': '2001-07-20',
'Ponyo': '2008-07-19',
}
ponyo_release_date = ghibli_release_dates.get('Ponyo')
men_in_black_release_date = ghibli_release_dates.get('Men in Black')
print(f"Ponyo release date: {ponyo_release_date}")
print(f"Men in Black release date: {men_in_black_release_date}")
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נממש את הפונקציה <code>get</code> בעצמנו. לשם הנוחות, ייראה השימוש שונה במקצת:<br>
</p>
```
def get(dictionary, key):
if key in dictionary:
return dictionary[key]
return None
ponyo_release_date = get(ghibli_release_dates, 'Ponyo')
men_in_black_release_date = get(ghibli_release_dates, 'Men in Black')
print(f"Ponyo release date: {ponyo_release_date}")
print(f"Men in Black release date: {men_in_black_release_date}")
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
המימוש שלנו לא מושלם. הפעולה המקורית, <code>get</code> על מילון, פועלת בצורה מתוחכמת יותר.<br>
אפשר להעביר לה פרמטר נוסף, שקובע מה יחזור אם המפתח שהעברנו בפרמטר הראשון לא נמצא במילון:
</p>
```
ponyo_release_date = ghibli_release_dates.get('Ponyo', '???')
men_in_black_release_date = ghibli_release_dates.get('Men in Black', '???')
print(f"Ponyo release date: {ponyo_release_date}")
print(f"Men in Black release date: {men_in_black_release_date}")
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
שימו לב להתנהגות המיוחדת של הפעולה <code>get</code>!<br>
אם המפתח שהעברנו בארגומנט הראשון לא קיים במילון, היא מחזירה את הערך שכתוב בארגומנט השני.<br>
אפשר להעביר לה ארגומנט אחד, ואפשר להעביר לה שני ארגומנטים. היא מתפקדת כראוי בשני המצבים.<br>
זו לא פעם ראשונה שאנחנו רואים פונקציות כאלו. למעשה, בשבוע שעבר למדנו על פעולות builtins רבות שמתנהגות כך:<br>
<code>range</code>, <code>enumerate</code> ו־<code>round</code>, כולן יודעות לקבל מספר משתנה של ארגומנטים.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נניח לפעולה <code>get</code> בינתיים. אל דאגה, נחזור אליה בקרוב.<br>
בזמן שאנחנו נחים מפעולות על מילונים יום האהבה מתקרב, וחנות הוורדים הקרובה מעוניינת להעלות את מחירי כל מוצריה בשקל אחד.<br>
התבקשנו לבנות עבורם פונקציה שמקבלת רשימת מחירים, ומחזירה רשימה שבה כל איבר גדול ב־1 מרשימת המחירים המקורית.<br>
ניגש לעבודה:
</p>
```
def get_new_prices(l):
l2 = []
for item in l:
l2.append(item + 1)
return l2
prices = [42, 73, 300]
print(get_new_prices(prices))
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בתוך זמן קצר הפונקציה שבנינו הופכת ללהיט היסטרי בחנויות הוורדים.<br>
מנהל קרטל הוורדים הבין־לאומי ג'וזפה ורדי יוצר איתנו קשר, ומבקש לשכלל התוכנה כך שיוכל להעלות את מחירי המוצרים כרצונו.<br>
כדי לעמוד בדרישה, נבנה פונקציה שמקבלת רשימה, ובנוסף אליה את המחיר שיתווסף לכל איבר ברשימה זו.<br>
כך, אם הקורא לפונקציה יעביר כארגומנט השני את הערך 2, כל איבר ברשימה יגדל ב־2.<br>
נממש בקלילות:
</p>
```
def get_new_prices(l, increment_by):
l2 = []
for item in l:
l2.append(item + increment_by)
return l2
prices = [42, 73, 300]
print(get_new_prices(prices, 1))
print(get_new_prices(prices, 2))
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ורדי פוצח בשירה מרוב אושר, ומבקש שכלול אחרון לפונקציה, אם אפשר.<br>
אם הקורא לפונקציה העביר לה רק את רשימת המחירים, העלו את כל המחירים בשקל, כברירת מחדל.<br>
אם כן הועבר הארגומנט השני, העלו את המחיר לפי הערך שצוין באותו ארגומנט.<br>
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הפעם אנחנו מתחבטים קצת יותר, מגרדים בראש, קוראים כמה מדריכי פייתון ומגיעים לבסוף לתשובה הבאה:
</p>
```
def get_new_prices(l, increment_by=1):
l2 = []
for item in l:
l2.append(item + increment_by)
return l2
prices = [42, 73, 300]
print(prices)
print(get_new_prices(prices))
print(get_new_prices(prices, 5))
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כשאנחנו רוצים להגדיר פרמטר עם ערך ברירת מחדל, נוכל לקבוע את ערך ברירת המחדל שלו בכותרת הפונקציה.<br>
אם יועבר ארגומנט שכזה לפונקציה – פייתון תשתמש בערך שהועבר.<br>
אם לא – יילקח ערך ברירת המחדל שהוגדר בכותרת הפונקציה.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
במקרה שלנו הגדרנו את הפרמטר <code>increment_by</code> עם ערך ברירת המחדל 1.<br>
קריאה לפונקציה עם ארגומנט אחד בלבד (רשימת המחירים) תגדיל את כל המחירים ב־1, שהרי הוא ערך ברירת המחדל.<br>
קריאה לפונקציה עם שני ארגומנטים (רשימת המחירים, סכום ההעלאה) תגדיל את כל המחירים בסכום ההעלאה שהועבר.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
חשוב להבין שקריאה לפונקציה עם ערכים במקום ערכי ברירת המחדל, לא תשנה את ערך ברירת המחדל בקריאות הבאות:
</p>
```
print(get_new_prices(prices, 5))
print(get_new_prices(prices))
```
<div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;">
<div style="display: flex; width: 10%; float: right; clear: both;">
<img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול">
</div>
<div style="width: 70%">
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ממשו את פונקציית <code>get</code> המלאה. הפונקציה תקבל מילון, מפתח ו"ערך לשעת חירום".<br>
החזירו את הערך השייך למפתח שהתקבל. אחרת – החזירו את הערך לשעת החירום שהועבר לפונקציה.<br>
אם לא הועבר ערך לשעת חירום והמפתח לא נמצא במילון, החזירו <samp>None</samp>.
</p>
</div>
<div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;">
<p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;">
<strong>חשוב!</strong><br>
פתרו לפני שתמשיכו!
</p>
</div>
</div>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נדגים את אותו עיקרון עם כמה ערכי ברירת מחדל.<br>
אם הדרישה הייתה, לדוגמה, להוסיף לפונקציה גם אפשרות להנחה במחירי הפרחים, היינו יכולים לממש זאת כך:
</p>
```
def get_new_prices(l, increment_by=1, discount=0):
l2 = []
for item in l:
new_price = item + increment_by - discount
l2.append(new_price)
return l2
prices = [42, 73, 300]
print(prices)
print(get_new_prices(prices, 10, 1)) # העלאה של 10, הנחה של 1
print(get_new_prices(prices, 5)) # העלאה של 5
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
אך מה יקרה כשנרצה לתת רק הנחה?<br>
במקרה כזה, כשנרצה "לדלג" מעל אחד מערכי ברירת המחדל, נצטרך להעביר את שמות הפרמטרים בקריאה לפונקציה.<br>
בדוגמה הבאה אנחנו מעלים את המחיר ב־1 (כי זו ברירת המחדל), ומורידים אותו ב־5:
</p>
```
prices = [42, 73, 300]
print(prices)
print(get_new_prices(prices, discount=5))
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
זה אמנם עניין של סגנון, אבל יש יופי וסדר בציון שמות הפרמטרים גם כשלא חייבים:
</p>
```
print(get_new_prices(prices, increment_by=10, discount=1))
```
### <span style="text-align: right; direction: rtl; float: right; clear: both;">מספר משתנה של ארגומנטים<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הפונקציה הפייתונית <code>max</code>, למשל, מתנהגת באופן משונה.<br>
היא יודעת לקבל כל מספר שהוא של ארגומנטים, ולהחליט מי מהם הוא הגדול ביותר.<br>
ראו בעצמכם!
</p>
```
max(13, 256, 278, 887, 989, 457, 6510, 18, 865, 901, 401, 704, 640)
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נוכל גם אנחנו לממש פונקציה שמקבלת מספר משתנה של פרמטרים די בקלות.<br>
נתחיל מלממש פונקציה טיפשית למדי, שמקבלת מספר משתנה של פרמטרים ומדפיסה אותם:
</p>
```
def silly_function(*parameters):
print(parameters)
print(type(parameters))
print('-' * 20)
silly_function('Shmulik', 'Shlomo')
silly_function('Shmulik', 1, 1, 2, 3, 5, 8, 13)
silly_function()
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
מה התרחש בדוגמה האחרונה, בעצם?<br>
כשפרמטר מוגדר בכותרת הפונקציה עם הסימן כוכבית, אפשר לשלוח אל אותו פרמטר מספר בלתי מוגבל של ארגומנטים.<br>
הערך שייכנס לפרמטר יהיה מסוג <code>tuple</code>, שאיבריו הם כל האיברים שהועברו כארגומנטים.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
לצורך ההדגמה, נבנה פונקציה שמקבלת פרמטרים ומדפיסה אותם בזה אחר זה:
</p>
```
def silly_function2(*parameters):
print(f"Printing all the items in {parameters}:")
for parameter in parameters:
print(parameter)
print("-" * 20)
silly_function2('Shmulik', 'Shlomo')
silly_function2('Shmulik', 1, 1, 2, 3, 5, 8, 13)
silly_function2()
```
<div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;">
<div style="display: flex; width: 10%; float: right; clear: both;">
<img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול">
</div>
<div style="width: 70%">
<p style="text-align: right; direction: rtl; float: right; clear: both;">
שחקו עם הפונקציה <code>silly_function2</code> וודאו שהבנתם מה מתרחש בה.<br>
כשתסיימו, נסו לממש את הפונקציה <code>max</code> בעצמכם.
</p>
</div>
<div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;">
<p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;">
<strong>חשוב!</strong><br>
פתרו לפני שתמשיכו!
</p>
</div>
</div>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נממש את <code>max</code>:
</p>
```
def my_max(*numbers):
if not numbers: # אם לא סופקו ארגומנטים, אין מקסימום
return None
maximum = numbers[0]
for number in numbers:
if number > maximum:
maximum = number
return maximum
my_max(13, 256, 278, 887, 989, 457, 6510, 18, 865, 901, 401, 704, 640)
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כותרת הפונקציה יכולה לכלול משתנים נוספים לפני הכוכבית.<br>
נראה לדוגמה פונקציה שמקבלת גובה הנחה ואת מחירי כל המוצרים שקנינו, ומחזירה את הסכום הסופי שעלינו לשלם:
</p>
```
def get_final_price(discount, *prices):
return sum(prices) - discount
get_final_price(10000, 3.141, 90053)
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
אף שבמבט ראשון הפונקציה <code>get_final_price</code> עשויה להיראות מגניבה, כדאי להיזהר משימוש מוגזם בתכונה הזו של פייתון.<br>
הדוגמה הזו אמנם מדגימה גמישות יוצאת דופן של פייתון, אבל ככלל היא דוגמה גרועה מאוד לשימוש בכוכבית.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
שימו לב כמה נוח יותר להבין את המימוש הבא ל־<code>get_final_price</code>, וכמה נוח יותר להבין את הקריאה לפונקציה הזו:
</p>
```
def get_final_price(prices, discount):
return sum(prices) - discount
get_final_price(prices=(3.141, 90053), discount=10000)
```
### <span style="text-align: right; direction: rtl; float: right; clear: both;">תרגול ביניים: סולל דרך<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כתבו פונקציה בשם <code>create_path</code> שיכולה לקבל מספר בלתי מוגבל של ארגומנטים.<br>
הפרמטר הראשון יהיה אות הכונן שבו הקבצים מאוחסנים (לרוב "C"), והפרמטרים שאחריו יהיו שמות של תיקיות וקבצים.<br>
שרשרו אותם בעזרת התו <code>\</code> כדי ליצור מהם מחרוזת המייצגת נתיב במחשב. אחרי האות של הכונן שימו נקודתיים.<br>
הניחו שהקלט שהמשתמש הכניס הוא תקין.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הנה כמה דוגמאות לקריאות לפונקציה ולערכי ההחזרה שלה:
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li>הקריאה <code dir="ltr">create_path("C", "Users", "Yam")</code> תחזיר <samp dir="ltr">"C:\Users\Yam"</samp></li>
<li>הקריאה <code dir="ltr">create_path("C", "Users", "Yam", "HaimonLimon.mp4")</code> תחזיר <samp dir="ltr">"C:\Users\Yam\HaimonLimon.mp4"</samp></li>
<li>הקריאה <code dir="ltr">create_path("D", "1337.png")</code> תחזיר <samp dir="ltr">"D:\1337.png"</samp></li>
<li>הקריאה <code dir="ltr">create_path("C")</code> תחזיר <samp dir="ltr">"C:"</samp></li>
<li>הקריאה <code dir="ltr">create_path()</code> תגרום לשגיאה</li>
</ul>
### <span style="text-align: right; direction: rtl; float: right; clear: both;">מספר משתנה של ארגומנטים עם שמות<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בתחילת המחברת למדנו כיצד מעבירים לפונקציות ארגומנטים בעזרת שם:
</p>
```
def print_introduction(name, age):
return f"My name is {name} and I am {age} years old."
print_introduction(age=2019, name="Gandalf")
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
אבל מה אם נרצה להעביר לפונקציה שלנו מספר בלתי מוגבל של ארגומנטים לפי שם?<br>
נביא כדוגמה את הפעולה <code>format</code> על מחרוזות.<br>
<code>format</code> היא פונקציה גמישה בכל הנוגע לכמות ולשמות של הארגומנטים שמועברים לה לפי שם.<br>
נראה שתי דוגמאות לשימוש בה, שימוש שבמבט ראשון עשוי להיראות קסום:
</p>
```
message = "My name is {name} and I am {age} years old"
formatted_message = message.format(name="Gandalf", age=2019)
print(formatted_message)
song = "I'll {action} a story of a {animal}.\nA {animal} who's {key} is {value}."
formatted_song = song.format(action="sing", animal="duck", key="name", value="Alfred Kwak")
print(formatted_song)
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נכתוב גם אנחנו פונקציה שמסוגלת לקבל מספר בלתי מוגבל של ארגומנטים לפי שם.<br>
ניעזר תחילה בידידתנו הוותיקה, <code>silly_function</code>, כדי לראות איך הקסם קורה:
</p>
```
def silly_function(**kwargs):
print(kwargs)
print(type(kwargs))
silly_function(a=5, b=6, address="221B Baker St, London, England.")
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ההתנהגות הזו מתרחשת כיוון שהשתמשנו בשתי כוכביות לפני שם המשתנה.<br>
השימוש בשתי כוכביות מאפשר לנו להעביר מספר בלתי מוגבל של ארגומנטים עם שם, באופן שמזכיר קצת את השימוש בכוכבית שראינו קודם.<br>
המשתנה שבו נשמרים הנתונים הוא מסוג מילון, ובו המפתחות יהיו שמות הארגומנטים שהועברו, והערכים – הערכים שהועברו לאותם שמות.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
אחרי שהבנו איך הסיפור הזה עובד, בואו ננסה ליצור פונקציה מעניינת יותר.<br>
הפונקציה שנכתוב תקבל כארגומנטים כמה גרם מכל רכיב צריך כדי להכין סושי, ותדפיס לנו מתכון:
</p>
```
def print_sushi_recipe(**ingredients_and_amounts):
for ingredient, amount in ingredients_and_amounts.items():
print(f"{amount} grams of {ingredient}")
print_sushi_recipe(rice=300, water=300, vinegar=15, sugar=10, salt=3, fish=600)
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בדוגמה זו השתמשנו בעובדה שהפרמטר שמוגדר בעזרת שתי כוכביות הוא בהכרח מילון.<br>
עברנו על כל המפתחות והערכים שבו בעזרת הפעולה <code>items</code>, והדפסנו את המתכון, רכיב אחר רכיב.
</p>
<div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;">
<div style="display: flex; width: 10%; float: right; clear: both;">
<img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול">
</div>
<div style="width: 70%">
<p style="text-align: right; direction: rtl; float: right; clear: both;">
גרמו לפונקציה <code>print_sushi_recipe</code> להדפיס את הרכיבים לפי סדר משקלם, מהנמוך לגבוה.
</p>
</div>
</div>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
פרמטר המוגדר בעזרת שתי כוכביות תמיד יופיע בסוף רשימת הפרמטרים.
</p>
### <span style="text-align: right; direction: rtl; float: right; clear: both;">תרגול ביניים: גזור פזורפ<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כתבו פונקציה בשם <code>my_format</code> שמקבלת מחרוזת, ומספר בלתי מוגבל של פרמטרים עם שמות.<br>
הפונקציה תחליף כל הופעה של <code>{key}</code> במחרוזת, אם <code>key</code> הועבר כפרמטר לפונקציה.<br>
הערך שבו <code>{key}</code> יוחלף הוא הערך שהועבר ל־<code>key</code> במסגרת העברת הארגומנטים לפונקציה.<br>
הפונקציה לא תשתמש בפעולה <code>format</code> של מחרוזות או בפונקציות שלא למדנו עד כה.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הנה כמה דוגמאות לקריאות לפונקציה ולערכי ההחזרה שלה:
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li>
הקריאה <code dir="ltr">my_format("I'm Mr. {name}, look at me!", name="Meeseeks")</code><br>
תחזיר <samp dir="ltr">"I'm Mr. Meeseeks, look at me!"</samp>
</li>
<li>
הקריאה <code dir="ltr">my_format("{a} {b} {c} {c}", a="wubba", b="lubba", c="dub")</code><br>
תחזיר <samp dir="ltr">"wubba lubba dub dub"</samp>
</li>
<li>
הקריאה <code dir="ltr">my_format("The universe is basically an animal", animal="Chicken")</code><br>
תחזיר <samp dir="ltr">"The universe is basically an animal"</samp>
</li>
<li>
הקריאה <code dir="ltr">my_format("The universe is basically an animal")</code><br>
תחזיר <samp dir="ltr">"The universe is basically an animal"</samp>
</li>
</ul>
### <span style="text-align: right; direction: rtl; float: right; clear: both;">חוק וסדר<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נוכל לשלב יחד את כל הטכניקות שלמדנו עד עכשיו לפונקציה אחת.<br>
ניצור, לדוגמה, פונקציה שמחשבת עלות הכנה של עוגה.<br>
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הפונקציה תקבל:
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li>את רשימת הרכיבים הקיימים בסופר ואת המחירים שלהם.</li>
<li>את רשימת הרכיבים הדרושים כדי להכין עוגה (נניח ששם כל רכיב הוא מילה בודדת).</li>
<li>אם ללקוח מגיעה הנחה.</li>
<li>שיעור ההנחה, באחוזים. כברירת מחדל, אם ללקוח מגיעה הנחה – שיעורה הוא 10%.</li>
</ul>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
לצורך פישוט התרגיל, נתעלם לרגע מעניין הכמויות במתכון :)
</p>
```
def calculate_cake_price(apply_discount, *ingredients, discount_rate=10, **prices):
if not apply_discount:
discount_rate = 0
final_price = 0
for ingredient in ingredients:
final_price = final_price + prices.get(ingredient)
final_price = final_price - (final_price * discount_rate / 100)
return final_price
calculate_cake_price(True, 'chocolate', 'cream', chocolate=30, cream=20, water=5)
```
<div class="align-center" style="display: flex; text-align: right; direction: rtl;">
<div style="display: flex; width: 10%; float: right; ">
<img src="images/warning.png" style="height: 50px !important;" alt="אזהרה!">
</div>
<div style="width: 90%">
<p style="text-align: right; direction: rtl;">
הפונקציה נכתבה כדי להדגים את הטכניקה, והיא נראית די רע.<br>
ראו כמה קשה להבין איזה ארגומנט שייך לאיזה פרמטר בקריאה לפונקציה.<br>
יש להפעיל שיקול דעת לפני שימוש בטכניקות של קבלת פרמטרים מרובים.
</p>
</div>
</div>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
שימו לב לסדר הפרמטרים בכותרת הפונקציה:
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li>הארגומנטים שמיקומם קבוע ואנחנו יודעים מי הם הולכים להיות (<code>apply_discount</code>).</li>
<li>הארגומנטים שמיקומם קבוע ואנחנו לא יודעים מי הם הולכים להיות (<code>ingredients</code>).</li>
<li>הארגומנטים ששמותיהם ידועים וערך ברירת המחדל שלהם נקבע בראש הפונקציה (<code>discount_rate</code>).</li>
<li>ערכים נוספים ששמותיהם לא ידועים מראש (<code>prices</code>).</li>
</ul>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נסו לחשוב: למה נקבע דווקא הסדר הזה?
</p>
<div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;">
<div style="display: flex; width: 10%; float: right; clear: both;">
<img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול">
</div>
<div style="width: 70%">
<p style="text-align: right; direction: rtl; float: right; clear: both;">
איך הייתם כותבים את אותה הפונקציה בדיוק בלי שימוש בטכניקות שלמדנו?<br>
השימוש בערכי ברירת מחדל מותר.
</p>
</div>
<div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;">
<p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;">
<strong>חשוב!</strong><br>
פתרו לפני שתמשיכו!
</p>
</div>
</div>
### <span style="text-align: right; direction: rtl; float: right; clear: both;">ערכי ברירת מחדל שאפשר לשנותם<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
יש מקרה קצה של ערכי ברירת מחדל שגורם לפייתון להתנהג קצת מוזר.<br>
זה קורה כשערך ברירת המחדל שהוגדר בכותרת הפונקציה הוא mutable:
</p>
```
def append(item, l=[]):
l.append(item)
return l
print(append(4, [1, 2, 3]))
print(append('a'))
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
עד כאן נראה כאילו הפונקציה פועלת באופן שהיינו מצפים ממנה.<br>
ערך ברירת המחדל של הפרמטר <code>l</code> הוא רשימה ריקה, ולכן בקריאה השנייה חוזרת רשימה עם איבר בודד, <samp>['a']</samp>.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נקרא לפונקציה עוד כמה פעמים, ונגלה משהו מוזר:
</p>
```
print(append('b'))
print(append('c'))
print(append('d'))
print(append(4, [1, 2, 3]))
print(append('e'))
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
משונה ולא הגיוני! ציפינו לקבל את הרשימה <samp>['b']</samp> ואז את הרשימה <samp>['c']</samp> וכן הלאה.<br>
במקום זה בכל פעם מצטרף איבר חדש לרשימה. למה?
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הסיבה לכך היא שפייתון קוראת את כותרת הפונקציה רק פעם אחת – בשלב ההגדרה של הפונקציה.<br>
בשלב הזה שבו פייתון תקרא את כותרת הפונקציה, ערך ברירת המחדל של <code>l</code> יצביע לרשימה ריקה.<br>
מאותו רגע, בכל פעם שלא נעביר ל־<code>l</code> ערך, <code>l</code> תהיה אותה רשימת ברירת מחדל שהגדרנו בהתחלה.<br>
נדגים זאת בעזרת הדפסת ה־<code>id</code> של הרשימה:
</p>
```
def view_memory_of_l(item, l=[]):
l.append(item)
print(f"{l} --> {id(l)}")
return l
same_list1 = view_memory_of_l('a')
same_list2 = view_memory_of_l('b')
same_list3 = view_memory_of_l('c')
new_list1 = view_memory_of_l(4, [1, 2, 3])
new_list2 = view_memory_of_l(5, [1, 2, 3])
new_list3 = view_memory_of_l(6, [1, 2, 3])
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כיצד נפתור את הבעיה?<br>
דבר ראשון – נשתדל שלא להגדיר משתנים מטיפוס שהוא mutable בתוך כותרת הפונקציה.<br>
אם נרצה בכל זאת שהפרמטר יקבל רשימה כברירת מחדל, נעשה זאת כך:
</p>
```
def append(item, l=None):
if l == None:
l = []
l.append(item)
return l
print(append(4, [1, 2, 3]))
print(append('a'))
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
שימו לב שהתופעה לא משתחזרת במבנים שהם immutable, כיוון שכשמם כן הם – אי אפשר לשנותם:
</p>
```
def increment(i=0):
i = i + 1
return i
print(increment(100))
print(increment())
print(increment())
print(increment())
print(increment(100))
```
### <span style="text-align: right; direction: rtl; float: right; clear: both;">דוגמאות נוספות<span>
#### <span style="text-align: right; direction: rtl; float: right; clear: both;">חיקוי מדויק של פונקציית get למילונים:<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נרענן את זיכרוננו בנוגע ל־unpacking:
</p>
```
range_arguments = [1, 10, 3]
range_result = range(*range_arguments)
print(list(range_result))
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
או:
</p>
```
preformatted_message = "My name is {me}, and my sister is {sister}"
parameters = {'me': 'Mei', 'sister': 'Satsuki'}
message = preformatted_message.format(**parameters)
print(message)
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
אם כך, נוכל לכתוב:
</p>
```
def get(dictionary, *args, **kwargs):
return dictionary.get(*args, **kwargs)
```
<p style="text-align: right; direction: rtl; float: right; clear: both;">
שימו לב שהכוכביות בשורה הראשונה עוזרות לנו לקבל מספר משתנה של ארגומנטים.<br>
הכוכביות בשורה השנייה הן unpacking, כפי שלמדנו בשבוע שעבר.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
החיקוי הזה לא מועיל לנו במיוחד כרגע, אבל הוא יעבוד עבור כל סוג של פעולה.
</p>
## <span style="align: right; direction: rtl; float: right; clear: both;">מונחים</span>
<dl style="text-align: right; direction: rtl; float: right; clear: both;">
<dt>ערכי ברירת מחדל</dt><dd>Default Parameters. פרמטרים שנקבע להם ערך ברירת מחדל בכותרת הפונקציה.</dd>
<dt>ארגומנטים לפי מיקום</dt><dd>Positional Arguments. ערכים המועברים כארגומנטים בקריאה לפונקציה לפי המיקום שלהם, וללא שם לידם.</dd>
<dt>ארגומנטים לפי שם</dt><dd>Keyword Arguments. ערכים המועברים כארגומנטים בקריאה לפונקציה לפי השם שלהם שנמצא לפני השווה.</dd>
<dt>מספר משתנה של ארגומנטים</dt><dd>נקרא לרוב <code dir="ltr">*args</code>. מאפשר לנו לקבל מספר בלתי מוגבל של ארגומנטים לפי מיקום.</dd>
<dt>מספר משתנה של ארגומנטים עם שמות</dt><dd>נקרא לרוב <code dir="ltr">**kwargs</code>. מאפשר לנו לקבל מספר בלתי מוגבל של ארגומנטים לפי שם.</dd>
</dl>
## <span style="text-align: right; direction: rtl; float: right; clear: both;">תרגילים<span>
### <span style="text-align: right; direction: rtl; float: right; clear: both;">כפלו לי שתו לי<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כתבו פונקציה בשם <var>avg</var> שמקבלת מספר בלתי מוגבל של ארגומנטים, ומדפיסה את הממוצע שלהם.
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li>
הקריאה <code dir="ltr">avg(5, 6)</code>
תחזיר <samp dir="ltr">5.5</samp>
</li>
<li>
הקריאה <code dir="ltr">avg(10, 5, 3)</code>
תחזיר <samp dir="ltr">6</samp>
</li>
<li>
הקריאה <code dir="ltr">avg(2)</code>
תחזיר <samp dir="ltr">2</samp>
</li>
<li>
הקריאה <code dir="ltr">avg()</code>
תחזיר <samp dir="ltr">None</samp> או שגיאה, לבחירתכם
</li>
</ul>
### <span style="text-align: right; direction: rtl; float: right; clear: both;">Cup of join<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כתבו פונקציה בשם <var>join</var>, שמקבלת מספר בלתי מוגבל של רשימות, כל רשימה כפרמטר.<br>
על הפונקציה להיות מסוגלת לקבל פרמטר נוסף בשם <code>sep</code>.<br>
על הפונקציה להחזיר רשימה אחת המורכבת מכלל הרשימות שהתקבלו כפרמטרים.<br>
אם סופק הפרמטר <var>sep</var>, יש לשרשר אותו כאיבר בין כל שתי רשימות. אם הוא לא סופק, יש לשרשר את התו <code>"-"</code> במקום.
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li>
הקריאה <code dir="ltr">join([1, 2], [8], [9, 5, 6], sep='@')</code>
תחזיר <samp dir="ltr">[1, 2, '@', 8, '@', 9, 5, 6]</samp>
</li>
<li>
הקריאה <code dir="ltr">join([1, 2], [8], [9, 5, 6])</code>
תחזיר <samp dir="ltr">[1, 2, '-', 8, '-', 9, 5, 6]</samp>
</li>
<li>
הקריאה <code dir="ltr">join([1])</code>
תחזיר <samp dir="ltr">[1]</samp>
</li>
<li>
הקריאה <code dir="ltr">join()</code>
תחזיר <samp dir="ltr">None</samp> או שגיאה, לבחירתכם
</li>
</ul>
### <span style="text-align: right; direction: rtl; float: right; clear: both;">חתכת עוגה<span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ממשו פונקציה בשם <var>get_recipe_price</var>, שלה יש:<br>
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li>
פרמטר בשם <var>prices</var>, שיקבל מילון של מצרכים הדרושים כדי להכין מתכון מסוים.<br>
מפתח המילון יהיה שם המוצר, וערך המילון יהיה המחיר שלו ל־100 גרם.<br>
הניחו ששמו של כל רכיב הוא מילה אחת, ללא רווחים וללא תווים מיוחדים.
</li>
<li>
פרמטר רשות בשם <var>optionals</var> שיקבל רשימה של רכיבים שנתעלם מהם, משמע – לא נקנה מהם בכלל.<br>
אם הפרמטר לא יצוין, יש להתייחס לכל הרכיבים שהועברו.
</li>
<li>
עבור כל רכיב שהועבר ב־<var>ingredients</var>, יש להעביר ארגומנט הנושא את שמו של הרכיב.<br>
ערך הארגומנט צריך להיות כמות הרכיב (בגרמים) שממנה אנחנו רוצים לקנות עבור המתכון.
</li>
</ul>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הפונקציה תחזיר את המחיר שעלינו לשלם על קניית כל המצרכים.
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li>
הקריאה <code dir="ltr">get_recipe_price({'chocolate': 18, 'milk': 8}, chocolate=200, milk=100)</code><br>
תחזיר <samp dir="ltr">44</samp>
</li>
<li>
הקריאה <code dir="ltr">get_recipe_price({'chocolate': 18, 'milk': 8}, optionals=['milk'], chocolate=300)</code><br>
תחזיר <samp dir="ltr">54</samp>
</li>
<li>
הקריאה <code dir="ltr">get_recipe_price({})</code><br>
תחזיר <samp dir="ltr">0</samp>
</li>
</ul>
|
github_jupyter
|
def my_range(end, start):
numbers = []
i = start
while i < end:
numbers.append(i)
i += 1
return numbers
my_range(5, 0)
my_range(start=0, end=5)
import random
random.randrange(100, 200) # מובן פחות
random.randrange(start=100, stop=200) # מובן יותר
ghibli_release_dates = {
'Castle in the Sky': '1986-08-02',
'My Neighbor Totoro': '1988-04-16',
'Spirited Away': '2001-07-20',
'Ponyo': '2008-07-19',
}
ponyo_release_date = ghibli_release_dates.get('Ponyo')
men_in_black_release_date = ghibli_release_dates.get('Men in Black')
print(f"Ponyo release date: {ponyo_release_date}")
print(f"Men in Black release date: {men_in_black_release_date}")
def get(dictionary, key):
if key in dictionary:
return dictionary[key]
return None
ponyo_release_date = get(ghibli_release_dates, 'Ponyo')
men_in_black_release_date = get(ghibli_release_dates, 'Men in Black')
print(f"Ponyo release date: {ponyo_release_date}")
print(f"Men in Black release date: {men_in_black_release_date}")
ponyo_release_date = ghibli_release_dates.get('Ponyo', '???')
men_in_black_release_date = ghibli_release_dates.get('Men in Black', '???')
print(f"Ponyo release date: {ponyo_release_date}")
print(f"Men in Black release date: {men_in_black_release_date}")
def get_new_prices(l):
l2 = []
for item in l:
l2.append(item + 1)
return l2
prices = [42, 73, 300]
print(get_new_prices(prices))
def get_new_prices(l, increment_by):
l2 = []
for item in l:
l2.append(item + increment_by)
return l2
prices = [42, 73, 300]
print(get_new_prices(prices, 1))
print(get_new_prices(prices, 2))
def get_new_prices(l, increment_by=1):
l2 = []
for item in l:
l2.append(item + increment_by)
return l2
prices = [42, 73, 300]
print(prices)
print(get_new_prices(prices))
print(get_new_prices(prices, 5))
print(get_new_prices(prices, 5))
print(get_new_prices(prices))
def get_new_prices(l, increment_by=1, discount=0):
l2 = []
for item in l:
new_price = item + increment_by - discount
l2.append(new_price)
return l2
prices = [42, 73, 300]
print(prices)
print(get_new_prices(prices, 10, 1)) # העלאה של 10, הנחה של 1
print(get_new_prices(prices, 5)) # העלאה של 5
prices = [42, 73, 300]
print(prices)
print(get_new_prices(prices, discount=5))
print(get_new_prices(prices, increment_by=10, discount=1))
max(13, 256, 278, 887, 989, 457, 6510, 18, 865, 901, 401, 704, 640)
def silly_function(*parameters):
print(parameters)
print(type(parameters))
print('-' * 20)
silly_function('Shmulik', 'Shlomo')
silly_function('Shmulik', 1, 1, 2, 3, 5, 8, 13)
silly_function()
def silly_function2(*parameters):
print(f"Printing all the items in {parameters}:")
for parameter in parameters:
print(parameter)
print("-" * 20)
silly_function2('Shmulik', 'Shlomo')
silly_function2('Shmulik', 1, 1, 2, 3, 5, 8, 13)
silly_function2()
def my_max(*numbers):
if not numbers: # אם לא סופקו ארגומנטים, אין מקסימום
return None
maximum = numbers[0]
for number in numbers:
if number > maximum:
maximum = number
return maximum
my_max(13, 256, 278, 887, 989, 457, 6510, 18, 865, 901, 401, 704, 640)
def get_final_price(discount, *prices):
return sum(prices) - discount
get_final_price(10000, 3.141, 90053)
def get_final_price(prices, discount):
return sum(prices) - discount
get_final_price(prices=(3.141, 90053), discount=10000)
def print_introduction(name, age):
return f"My name is {name} and I am {age} years old."
print_introduction(age=2019, name="Gandalf")
message = "My name is {name} and I am {age} years old"
formatted_message = message.format(name="Gandalf", age=2019)
print(formatted_message)
song = "I'll {action} a story of a {animal}.\nA {animal} who's {key} is {value}."
formatted_song = song.format(action="sing", animal="duck", key="name", value="Alfred Kwak")
print(formatted_song)
def silly_function(**kwargs):
print(kwargs)
print(type(kwargs))
silly_function(a=5, b=6, address="221B Baker St, London, England.")
def print_sushi_recipe(**ingredients_and_amounts):
for ingredient, amount in ingredients_and_amounts.items():
print(f"{amount} grams of {ingredient}")
print_sushi_recipe(rice=300, water=300, vinegar=15, sugar=10, salt=3, fish=600)
def calculate_cake_price(apply_discount, *ingredients, discount_rate=10, **prices):
if not apply_discount:
discount_rate = 0
final_price = 0
for ingredient in ingredients:
final_price = final_price + prices.get(ingredient)
final_price = final_price - (final_price * discount_rate / 100)
return final_price
calculate_cake_price(True, 'chocolate', 'cream', chocolate=30, cream=20, water=5)
def append(item, l=[]):
l.append(item)
return l
print(append(4, [1, 2, 3]))
print(append('a'))
print(append('b'))
print(append('c'))
print(append('d'))
print(append(4, [1, 2, 3]))
print(append('e'))
def view_memory_of_l(item, l=[]):
l.append(item)
print(f"{l} --> {id(l)}")
return l
same_list1 = view_memory_of_l('a')
same_list2 = view_memory_of_l('b')
same_list3 = view_memory_of_l('c')
new_list1 = view_memory_of_l(4, [1, 2, 3])
new_list2 = view_memory_of_l(5, [1, 2, 3])
new_list3 = view_memory_of_l(6, [1, 2, 3])
def append(item, l=None):
if l == None:
l = []
l.append(item)
return l
print(append(4, [1, 2, 3]))
print(append('a'))
def increment(i=0):
i = i + 1
return i
print(increment(100))
print(increment())
print(increment())
print(increment())
print(increment(100))
range_arguments = [1, 10, 3]
range_result = range(*range_arguments)
print(list(range_result))
preformatted_message = "My name is {me}, and my sister is {sister}"
parameters = {'me': 'Mei', 'sister': 'Satsuki'}
message = preformatted_message.format(**parameters)
print(message)
def get(dictionary, *args, **kwargs):
return dictionary.get(*args, **kwargs)
| 0.314577 | 0.967318 |
# Import Libraries
```
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import random
import argparse
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import set_random_seed
from keras import regularizers
from keras import backend as K
from keras.models import Model
from keras.utils import plot_model
from keras.losses import mse, binary_crossentropy
from keras.layers import Lambda, Input, Dense, Dropout
import pandas as pd
import seaborn as sns
from keras.utils import np_utils
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
from keras.objectives import mse
from keras.models import Sequential
from keras.layers.core import Dropout, Dense
from keras.regularizers import l1, l2
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from collections import defaultdict
GLOBAL_SEED = 1
LOCAL_SEED = 42
set_random_seed(GLOBAL_SEED)
np.random.seed(GLOBAL_SEED)
random.seed(GLOBAL_SEED)
%matplotlib inline
%pylab inline
rcParams['figure.figsize'] = [10, 8]
```
# Read Data
```
# Define PATH to file
path = '/DataSets/Selected/breast-cancer-wisconsin/wdbc.data'
# Dataset will be generated with the prefix:
dest = '/Dataset/wdbc'
from sklearn.utils import shuffle
set_random_seed(GLOBAL_SEED)
np.random.seed(GLOBAL_SEED)
random.seed(GLOBAL_SEED)
import pandas as pd
na_values = {'?', np.nan}
df = pd.read_csv(path,
sep=',',
header=None,
na_filter=True,
verbose=False,
skip_blank_lines=True,
na_values=na_values,
keep_default_na=False)
print('Origin dataset:')
print(df.head())
# Drop N/A
df.replace('U', np.nan, inplace=True)
df.dropna(axis='rows', how='all', inplace=True)
df = shuffle(df, random_state=GLOBAL_SEED)
df.drop([0], axis=1, inplace=True)
print(df.head())
col_names = list(df)
new_names = {}
for i, name in enumerate(col_names):
new_names[name] = 'X' + str(i)
df.rename(columns=new_names, inplace=True)
df = df.reindex(sorted(df.columns), axis=1)
print(df.head())
```
## Handling categorical columns
```
# For breast cancer
# df['X9'] = df['X9'].astype('category')
# For Pima Diabetes
cat_cols = ['X0']
df[cat_cols] = df[cat_cols].astype('category')
colnums = len(df.columns)
for i in df.columns:
try:
if df[i].dtype.name == 'object' or df[i].dtype.name == 'category':
df[i] = df[i].astype('category')
else:
df[i] = df[i].astype('float32')
except:
continue
df.dropna(axis='rows', how='any', inplace=True)
print(df.head())
print(df.describe())
print(df.info())
df_non_null = df
```
# Make data become missing
```
from sklearn.utils import resample
# make 50% of the data becoming missing
prob_missing = 0.5
df_incomplete = df_non_null.copy()
ix = [(row, col) for row in range(df_non_null.shape[0]) for col in range(df_non_null.shape[1])]
L = resample(ix, n_samples = int(prob_missing*len(ix)),
random_state=LOCAL_SEED)
for row, col in L:
df_incomplete.iat[row, col] = np.nan
df_incomplete.info()
missing_encoded = pd.get_dummies(df_incomplete)
for col in df.columns:
missing_cols = missing_encoded.columns.str.startswith(str(col) + "_")
missing_encoded.loc[df_incomplete[col].isnull(), missing_cols] = np.nan
missing_encoded.head()
hidden_size = 1000
n_epochs = 100
n_batch_size=1024
def masked_mae(X_true, X_pred, mask):
masked_diff = X_true[mask] - X_pred[mask]
return np.mean(np.abs(masked_diff))
def reverse_encoding(df_test_dummies):
names = list(df_test_dummies)
c_dict = {}
for n in names:
if '_' in n:
index = n.index('_')
c_dict[n[:index]] = [c for c in names if n[:index+1] in c]
values = []
for key, items in c_dict.items():
dummies = df_test_dummies[items]
d_names = list(dummies)
c_dict = {}
for n in d_names:
c_dict[n] = n[n.index('_')+1:]
dummies.rename(columns=c_dict,
inplace=True)
df_test_dummies[key] = dummies.idxmax(axis=1)
df_test_dummies.drop(items, axis=1, inplace=True)
print(df_test_dummies.head())
return df_test_dummies
```
# AutoEncoder with Dropout
```
class AutoEncoderDropout:
def __init__(self,
n_dims,
recurrent_weight=0.5,
optimizer="adam",
dropout_probability=0.5,
hidden_activation="relu",
output_activation="sigmoid",
init="glorot_normal",
l1_penalty=1e-3,
l2_penalty=1e-3,
hidden_size=hidden_size):
self.n_dims = n_dims
self.recurrent_weight = recurrent_weight
self.optimizer = optimizer
self.dropout_probability = dropout_probability
self.hidden_activation = hidden_activation
self.output_activation = output_activation
self.init = init
self.l1_penalty = l1_penalty
self.l2_penalty = l2_penalty
self.hidden_size = hidden_size
def make_reconstruction_loss(self, n_features):
def reconstruction_loss(input_and_mask, y_pred):
X_values = input_and_mask[:, :n_features]
missing_mask = input_and_mask[:, n_features:]
observed_mask = 1 - missing_mask
X_values_observed = X_values * observed_mask
pred_observed = y_pred * observed_mask
return binary_crossentropy(y_true=X_values_observed,
y_pred=pred_observed)
return reconstruction_loss
def _create_model(self):
latent_dim = int(np.ceil(self.n_dims*0.5))
inputs = Input(shape=(2*self.n_dims, ),
name='encoder_input')
x = inputs
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
encoded = Dense(latent_dim, name='encoding')(x)
self.encoder = Model(inputs, encoded, name='encoder')
latent_inputs = Input(shape=(latent_dim,), name='decoder_input')
x = latent_inputs
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
outputs = Dense(self.n_dims, activation=self.output_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
self.decoder = Model(latent_inputs,
outputs,
name='decoder')
outputs = self.decoder(self.encoder(inputs))
self.model = Model(inputs, outputs, name='ae_mlp')
loss_function = self.make_reconstruction_loss(self.n_dims)
self.model.compile(optimizer=self.optimizer,
loss=loss_function)
def fill(self, data, missing_mask):
data[missing_mask] = -1
return data
def _create_missing_mask(self, data):
if data.dtype != "f" and data.dtype != "d":
data = data.astype(float)
return np.isnan(data)
def _train_epoch(self, data, missing_mask, batch_size):
input_with_mask = np.hstack([data, missing_mask])
n_samples = len(input_with_mask)
n_batches = int(np.ceil(n_samples / batch_size))
indices = np.arange(n_samples)
np.random.shuffle(indices)
X_shuffled = input_with_mask[indices]
for batch_idx in range(n_batches):
batch_start = batch_idx * batch_size
batch_end = (batch_idx + 1) * batch_size
batch_data = X_shuffled[batch_start:batch_end, :]
self.model.train_on_batch(batch_data, batch_data)
return self.model.predict(input_with_mask)
def predict(self, x_test_with_mask):
predict_stochastic = K.function([self.decoder.layers[0].input,
K.learning_phase()],
[self.decoder.layers[-1].output])
latent_input = self.encoder.predict(x_test_with_mask)
outputs = np.array([np.array(predict_stochastic([latent_input,
1])).reshape((x_test_with_mask.shape[0],
x_test_with_mask.shape[1]//2)) for _ in range(50)])
return np.mean(outputs, axis=0)
def train(self, x_train, x_test, batch_size=256, train_epochs=100):
missing_mask = self._create_missing_mask(x_train)
x_train = self.fill(x_train, missing_mask)
x_test_missing_mask = self._create_missing_mask(x_test)
x_test = self.fill(x_test, x_test_missing_mask)
self._create_model()
observed_mask = ~missing_mask
x_test_observed_mask = ~x_test_missing_mask
input_with_mask = np.hstack([x_train, missing_mask])
for epoch in range(train_epochs):
X_pred = self._train_epoch(x_train, missing_mask, batch_size)
x_test_with_mask = np.hstack([x_test, x_test_missing_mask])
X_test_pred = self.predict(x_test_with_mask)
observed_mae = masked_mae(X_true=x_train,
X_pred=X_pred,
mask=observed_mask)
test_observed_mae = masked_mae(X_true=x_test,
X_pred = X_test_pred,
mask=x_test_observed_mask)
if epoch % 50 == 0:
print("observed mae:", observed_mae)
print("Test mae:", test_observed_mae)
old_weight = (1.0 - self.recurrent_weight)
x_train[missing_mask] *= old_weight
x_test[x_test_missing_mask] *= old_weight
pred_missing = X_pred[missing_mask]
x_test_pred_missing = X_test_pred[x_test_missing_mask]
x_train[missing_mask] += self.recurrent_weight * pred_missing
x_test[x_test_missing_mask] += self.recurrent_weight * x_test_pred_missing
return x_train.copy(), x_test.copy()
import math
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
seeds = [LOCAL_SEED+2, LOCAL_SEED+1, LOCAL_SEED+4, LOCAL_SEED+6, LOCAL_SEED+8]
rmses = []
cols = df_non_null.columns
non_null_values = df_non_null.values.copy()
for seed_number in seeds:
values = missing_encoded.values.copy()
train, test, comp_train, comp_test = train_test_split(values.copy(),
non_null_values.copy(),
test_size=0.1,
random_state=seed_number)
df_test_complete = pd.DataFrame(columns=cols,
data=comp_test.copy())
scaler = MinMaxScaler().fit(train)
x_train = scaler.transform(train)
x_test = scaler.transform(test)
n_dims = x_train.shape[1]
aedropout = AutoEncoderDropout(n_dims=n_dims)
complete_encoded = aedropout.train(x_train.copy(),
x_test.copy(),
train_epochs=n_epochs,
batch_size=n_batch_size)
train_encoded, test_encoded = complete_encoded
missing_cols = list(missing_encoded)
inverse_test_encoded = scaler.inverse_transform(test_encoded)
df_test_dummies = pd.DataFrame(columns=missing_cols,
data=inverse_test_encoded)
df_test_dummies = reverse_encoding(df_test_dummies.copy())
df_test_dummies.drop(cat_cols, axis=1,
inplace=True)
df_test_complete.drop(cat_cols, axis=1,
inplace=True)
true_vals = df_test_complete.values.copy()
test_vals = df_test_dummies.values.copy()
scaler2 = MinMaxScaler().fit(true_vals)
scaled_true_vales = scaler2.transform(true_vals)
scaled_test_vales = scaler2.transform(test_vals)
rmse = math.sqrt(mean_squared_error(scaled_true_vales,
scaled_test_vales))
rmses.append(rmse)
print(np.mean(rmses), np.std(rmses))
```
# VAE MCD
```
class VAEDropout:
def __init__(self, n_dims,
recurrent_weight=0.5,
optimizer="adam",
dropout_probability=0.5,
hidden_activation="relu",
output_activation="sigmoid",
init="glorot_normal",
l2_penalty=1e-3,
hidden_size=hidden_size):
self.n_dims = n_dims
self.recurrent_weight = recurrent_weight
self.optimizer = optimizer
self.dropout_probability = dropout_probability
self.hidden_activation = hidden_activation
self.output_activation = output_activation
self.init = init
self.l2_penalty = l2_penalty
self.hidden_size = hidden_size
self._create_model()
def _create_model(self):
latent_dim = int(np.ceil(self.n_dims*0.5))
inputs = Input(shape=(2*n_dims, ), name='encoder_input')
x = inputs
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)
self.encoder = Model(inputs, [z_mean,
z_log_var], name='encoder')
latent_inputs = Input(shape=(latent_dim,), name='z_sampling')
x = latent_inputs
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
outputs = Dense(self.n_dims, activation=self.output_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
self.decoder = Model(latent_inputs,
outputs,
name='decoder')
outputs = self.decoder(self.encoder(inputs)[0])
self.model = Model(inputs, outputs,
name='vae_mlp')
reconstruction_loss = self.make_vae_reconstruction_loss(n_dims,
z_mean,
z_log_var)
self.model.compile(optimizer=self.optimizer,
loss=reconstruction_loss)
def make_vae_reconstruction_loss(self, n_features, z_mean, z_log_var):
def reconstruction_loss(input_and_mask, y_pred):
X_values = input_and_mask[:, :n_features]
missing_mask = input_and_mask[:, n_features:]
observed_mask = 1 - missing_mask
X_values_observed = X_values * observed_mask
pred_observed = y_pred * observed_mask
reconstruction_loss = binary_crossentropy(y_true=X_values_observed,
y_pred=pred_observed)
reconstruction_loss*=n_features
kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
kl_loss = K.sum(kl_loss, axis=-1)
kl_loss *= -0.5
vae_loss = K.mean(reconstruction_loss + kl_loss)
return vae_loss
return reconstruction_loss
def fill(self, data, missing_mask):
data[missing_mask] = -1
return data
def _create_missing_mask(self, data):
if data.dtype != "f" and data.dtype != "d":
data = data.astype(float)
return np.isnan(data)
def predict(self, x_test_with_mask):
predict_stochastic = K.function([self.decoder.layers[0].input,
K.learning_phase()],
[self.decoder.layers[-1].output])
latent_input = self.encoder.predict(x_test_with_mask)
outputs = np.array([np.array(predict_stochastic([latent_input,
1])).reshape((x_test_with_mask.shape[0],
x_test_with_mask.shape[1]//2)) for _ in range(50)])
return np.mean(outputs, axis=0)
def _train_epoch(self, data, missing_mask, batch_size):
input_with_mask = np.hstack([data, missing_mask])
n_samples = len(input_with_mask)
n_batches = int(np.ceil(n_samples / batch_size))
indices = np.arange(n_samples)
np.random.shuffle(indices)
X_shuffled = input_with_mask[indices]
for batch_idx in range(n_batches):
batch_start = batch_idx * batch_size
batch_end = (batch_idx + 1) * batch_size
batch_data = X_shuffled[batch_start:batch_end, :]
self.model.train_on_batch(batch_data, batch_data)
return self.model.predict(input_with_mask)
def train(self, x_train, x_test, batch_size=256, train_epochs=100):
missing_mask = self._create_missing_mask(x_train)
x_train = self.fill(x_train, missing_mask)
x_test_missing_mask = self._create_missing_mask(x_test)
x_test = self.fill(x_test, x_test_missing_mask)
observed_mask = ~missing_mask
x_test_observed_mask = ~x_test_missing_mask
for epoch in range(train_epochs):
X_pred = self._train_epoch(x_train, missing_mask, batch_size)
x_test_with_mask = np.hstack([x_test, x_test_missing_mask])
X_test_pred = self.predict(x_test_with_mask)
observed_mae = masked_mae(X_true=x_train,
X_pred=X_pred,
mask=observed_mask)
test_observed_mae = masked_mae(X_true=x_test,
X_pred = X_test_pred,
mask=x_test_observed_mask)
if epoch % 50 == 0:
print("Traing observed mae:", observed_mae)
print("Test observed mae:", test_observed_mae)
old_weight = (1.0 - self.recurrent_weight)
x_train[missing_mask] *= old_weight
x_test[x_test_missing_mask] *= old_weight
pred_missing = X_pred[missing_mask]
x_test_pred_missing = X_test_pred[x_test_missing_mask]
x_train[missing_mask] += self.recurrent_weight * pred_missing
x_test[x_test_missing_mask] += self.recurrent_weight*x_test_pred_missing
return x_train.copy(), x_test.copy()
import math
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
seeds = [LOCAL_SEED+2, LOCAL_SEED+1, LOCAL_SEED+4, LOCAL_SEED+6, LOCAL_SEED+8]
rmses = []
cols = df_non_null.columns
non_null_values = df_non_null.values.copy()
for seed_number in seeds:
values = missing_encoded.values.copy()
train, test, comp_train, comp_test = train_test_split(values.copy(),
non_null_values.copy(),
test_size=0.1,
random_state=seed_number)
df_test_complete = pd.DataFrame(columns=cols,
data=comp_test.copy())
scaler = MinMaxScaler().fit(train)
x_train = scaler.transform(train)
x_test = scaler.transform(test)
n_dims = x_train.shape[1]
aedropout = VAEDropout(n_dims=n_dims)
complete_encoded = aedropout.train(x_train.copy(),
x_test.copy(),
train_epochs=n_epochs,
batch_size=n_batch_size)
train_encoded, test_encoded = complete_encoded
missing_cols = list(missing_encoded)
inverse_test_encoded = scaler.inverse_transform(test_encoded)
df_test_dummies = pd.DataFrame(columns=missing_cols,
data=inverse_test_encoded)
df_test_dummies = reverse_encoding(df_test_dummies.copy())
df_test_dummies.drop(cat_cols, axis=1,
inplace=True)
df_test_complete.drop(cat_cols, axis=1,
inplace=True)
true_vals = df_test_complete.values.copy()
test_vals = df_test_dummies.values.copy()
scaler2 = MinMaxScaler().fit(true_vals)
scaled_true_vales = scaler2.transform(true_vals)
scaled_test_vales = scaler2.transform(test_vals)
rmse = math.sqrt(mean_squared_error(scaled_true_vales,
scaled_test_vales))
rmses.append(rmse)
print(np.mean(rmses))
print(np.std(rmses))
```
# AutoEncoder
```
class Autoencoder:
def __init__(self, n_dims,
recurrent_weight=0.5,
optimizer="adam",
dropout_probability=0.1,
hidden_activation="relu",
output_activation="sigmoid",
init="glorot_normal",
l1_penalty=0,
l2_penalty=1e-3,
hidden_size=hidden_size):
self.n_dims = n_dims
self.recurrent_weight = recurrent_weight
self.optimizer = optimizer
self.dropout_probability = dropout_probability
self.hidden_activation = hidden_activation
self.output_activation = output_activation
self.init = init
self.l1_penalty = l1_penalty
self.l2_penalty = l2_penalty
self.hidden_size = hidden_size
def make_reconstruction_loss(self, n_features):
def reconstruction_loss(input_and_mask, y_pred):
X_values = input_and_mask[:, :n_features]
missing_mask = input_and_mask[:, n_features:]
observed_mask = 1 - missing_mask
X_values_observed = X_values * observed_mask
pred_observed = y_pred * observed_mask
return binary_crossentropy(y_true=X_values_observed,
y_pred=pred_observed)
return reconstruction_loss
def _create_model(self):
latent_dim = int(np.ceil(self.n_dims*0.5))
inputs = Input(shape=(2*n_dims, ), name='encoder_input')
x = inputs
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
encoded = Dense(latent_dim, name='encoding')(x)
self.encoder = Model(inputs, encoded, name='encoder')
latent_inputs = Input(shape=(latent_dim,), name='z_sampling')
x = latent_inputs
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
outputs = Dense(n_dims, activation=self.output_activation)(x)
self.decoder = Model(latent_inputs,
outputs,
name='decoder')
outputs = self.decoder(self.encoder(inputs))
self.model = Model(inputs, outputs, name='vae_mlp')
loss_function = self.make_reconstruction_loss(n_dims)
self.model.compile(optimizer=self.optimizer,
loss=loss_function)
def fill(self, data, missing_mask):
data[missing_mask] = -1
return data
def _create_missing_mask(self, data):
if data.dtype != "f" and data.dtype != "d":
data = data.astype(float)
return np.isnan(data)
def _train_epoch(self, data, missing_mask, batch_size):
input_with_mask = np.hstack([data, missing_mask])
n_samples = len(input_with_mask)
n_batches = int(np.ceil(n_samples / batch_size))
indices = np.arange(n_samples)
np.random.shuffle(indices)
X_shuffled = input_with_mask[indices]
for batch_idx in range(n_batches):
batch_start = batch_idx * batch_size
batch_end = (batch_idx + 1) * batch_size
batch_data = X_shuffled[batch_start:batch_end, :]
self.model.train_on_batch(batch_data, batch_data)
return self.model.predict(input_with_mask)
def train(self, x_train, x_test, batch_size=256, train_epochs=100):
missing_mask = self._create_missing_mask(x_train)
x_train = self.fill(x_train, missing_mask)
x_test_missing_mask = self._create_missing_mask(x_test)
x_test = self.fill(x_test, x_test_missing_mask)
self._create_model()
self.encoder.summary()
self.decoder.summary()
self.model.summary()
observed_mask = ~missing_mask
x_test_observed_mask = ~x_test_missing_mask
input_with_mask = np.hstack([x_train, missing_mask])
for epoch in range(train_epochs):
X_pred = self._train_epoch(x_train, missing_mask, batch_size)
x_test_with_mask = np.hstack([x_test, x_test_missing_mask])
X_test_pred = self.model.predict(x_test_with_mask)
observed_mae = masked_mae(X_true=x_train,
X_pred=X_pred,
mask=observed_mask)
test_observed_mae = masked_mae(X_true=x_test,
X_pred = X_test_pred,
mask=x_test_observed_mask)
if epoch % 50 == 0:
print("observed mae:", observed_mae)
print("Test mae:", test_observed_mae)
old_weight = (1.0 - self.recurrent_weight)
x_train[missing_mask] *= old_weight
x_test[x_test_missing_mask] *= old_weight
pred_missing = X_pred[missing_mask]
x_test_pred_missing = X_test_pred[x_test_missing_mask]
x_train[missing_mask] += self.recurrent_weight * pred_missing
x_test[x_test_missing_mask] += self.recurrent_weight * x_test_pred_missing
return x_train.copy(), x_test.copy()
import math
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
seeds = [LOCAL_SEED+2, LOCAL_SEED+1, LOCAL_SEED+4, LOCAL_SEED+6, LOCAL_SEED+8]
rmses = []
cols = df_non_null.columns
non_null_values = df_non_null.values.copy()
for seed_number in seeds:
values = missing_encoded.values.copy()
train, test, comp_train, comp_test = train_test_split(values.copy(),
non_null_values.copy(),
test_size=0.1,
random_state=seed_number)
df_test_complete = pd.DataFrame(columns=cols,
data=comp_test.copy())
scaler = MinMaxScaler().fit(train)
x_train = scaler.transform(train)
x_test = scaler.transform(test)
n_dims = x_train.shape[1]
aedropout = Autoencoder(n_dims=n_dims)
complete_encoded = aedropout.train(x_train.copy(),
x_test.copy(),
train_epochs=n_epochs,
batch_size=n_batch_size)
train_encoded, test_encoded = complete_encoded
missing_cols = list(missing_encoded)
inverse_test_encoded = scaler.inverse_transform(test_encoded)
df_test_dummies = pd.DataFrame(columns=missing_cols,
data=inverse_test_encoded)
df_test_dummies = reverse_encoding(df_test_dummies.copy())
df_test_dummies.drop(cat_cols, axis=1,
inplace=True)
df_test_complete.drop(cat_cols, axis=1,
inplace=True)
true_vals = df_test_complete.values.copy()
test_vals = df_test_dummies.values.copy()
scaler2 = MinMaxScaler().fit(true_vals)
scaled_true_vales = scaler2.transform(true_vals)
scaled_test_vales = scaler2.transform(test_vals)
rmse = math.sqrt(mean_squared_error(scaled_true_vales,
scaled_test_vales))
rmses.append(rmse)
print(np.mean(rmses))
print(np.std(rmses))
```
# VAE
```
class VAE:
def __init__(self, n_dims,
recurrent_weight=0.5,
optimizer="adam",
dropout_probability=0.1,
hidden_activation="relu",
output_activation="sigmoid",
init="glorot_normal",
l2_penalty=1e-3):
self.n_dims = n_dims
self.recurrent_weight = recurrent_weight
self.optimizer = optimizer
self.dropout_probability = dropout_probability
self.hidden_activation = hidden_activation
self.output_activation = output_activation
self.init = init
self.l2_penalty = l2_penalty
self.hidden_size = hidden_size
self._create_model()
def make_reconstruction_loss(self, n_features, z_mean, z_log_var):
def reconstruction_loss(input_and_mask, y_pred):
X_values = input_and_mask[:, :n_features]
missing_mask = input_and_mask[:, n_features:]
observed_mask = 1 - missing_mask
X_values_observed = X_values * observed_mask
pred_observed = y_pred * observed_mask
reconstruction_loss = binary_crossentropy(y_true=X_values_observed,
y_pred=pred_observed)
reconstruction_loss*=n_features
kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
kl_loss = K.sum(kl_loss, axis=-1)
kl_loss *= -0.5
vae_loss = K.mean(reconstruction_loss + kl_loss)
return vae_loss
return reconstruction_loss
def sampling(self, args):
"""Reparameterization trick by sampling from an isotropic unit Gaussian.
# Arguments
args (tensor): mean and log of variance of Q(z|X)
# Returns
z (tensor): sampled latent vector
"""
z_mean, z_log_var = args
batch = K.shape(z_mean)[0]
dim = K.int_shape(z_mean)[1]
# by default, random_normal has mean = 0 and std = 1.0
epsilon = K.random_normal(shape=(batch, dim))
return z_mean + K.exp(0.5 * z_log_var) * epsilon
def _create_model(self):
latent_dim = (int(np.ceil(self.n_dims*0.5)))
inputs = Input(shape=(2*self.n_dims, ), name='encoder_input')
x = inputs
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)
z = Lambda(self.sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])
self.encoder = Model(inputs, [z_mean,
z_log_var, z], name='encoder')
latent_inputs = Input(shape=(latent_dim,), name='z_sampling')
x = latent_inputs
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
outputs = Dense(self.n_dims, activation=self.output_activation)(x)
self.decoder = Model(latent_inputs,
outputs,
name='decoder')
outputs = self.decoder(self.encoder(inputs)[2])
self.model = Model(inputs, outputs,
name='vae_mlp')
reconstruction_loss = self.make_reconstruction_loss(n_dims,
z_mean,
z_log_var)
self.model.compile(optimizer=self.optimizer,
loss=reconstruction_loss)
def fill(self, data, missing_mask):
data[missing_mask] = -1
return data
def _create_missing_mask(self, data):
if data.dtype != "f" and data.dtype != "d":
data = data.astype(float)
return np.isnan(data)
def _train_epoch(self, data, missing_mask, batch_size):
input_with_mask = np.hstack([data, missing_mask])
n_samples = len(input_with_mask)
n_batches = int(np.ceil(n_samples / batch_size))
indices = np.arange(n_samples)
np.random.shuffle(indices)
X_shuffled = input_with_mask[indices]
for batch_idx in range(n_batches):
batch_start = batch_idx * batch_size
batch_end = (batch_idx + 1) * batch_size
batch_data = X_shuffled[batch_start:batch_end, :]
self.model.train_on_batch(batch_data, batch_data)
return self.model.predict(input_with_mask)
def train(self, x_train, x_test, batch_size=256, train_epochs=100):
missing_mask = self._create_missing_mask(x_train)
x_train = self.fill(x_train, missing_mask)
x_test_missing_mask = self._create_missing_mask(x_test)
x_test = self.fill(x_test, x_test_missing_mask)
observed_mask = ~missing_mask
x_test_observed_mask = ~x_test_missing_mask
for epoch in range(train_epochs):
X_pred = self._train_epoch(x_train, missing_mask, batch_size)
x_test_with_mask = np.hstack([x_test, x_test_missing_mask])
X_test_pred = self.model.predict(x_test_with_mask)
observed_mae = masked_mae(X_true=x_train,
X_pred=X_pred,
mask=observed_mask)
test_observed_mae = masked_mae(X_true=x_test,
X_pred = X_test_pred,
mask=x_test_observed_mask)
if epoch % 50 == 0:
print("Traing observed mae:", observed_mae)
print("Test observed mae:", test_observed_mae)
old_weight = (1.0 - self.recurrent_weight)
x_train[missing_mask] *= old_weight
x_test[x_test_missing_mask] *= old_weight
pred_missing = X_pred[missing_mask]
x_test_pred_missing = X_test_pred[x_test_missing_mask]
x_train[missing_mask] += self.recurrent_weight * pred_missing
x_test[x_test_missing_mask] += self.recurrent_weight*x_test_pred_missing
return x_train.copy(), x_test.copy()
import math
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
seeds = [LOCAL_SEED+2, LOCAL_SEED+1, LOCAL_SEED+4, LOCAL_SEED+6, LOCAL_SEED+8]
rmses = []
cols = df_non_null.columns
non_null_values = df_non_null.values.copy()
for seed_number in seeds:
values = missing_encoded.values.copy()
train, test, comp_train, comp_test = train_test_split(values.copy(),
non_null_values.copy(),
test_size=0.1,
random_state=seed_number)
df_test_complete = pd.DataFrame(columns=cols,
data=comp_test.copy())
scaler = MinMaxScaler().fit(train)
x_train = scaler.transform(train)
x_test = scaler.transform(test)
n_dims = x_train.shape[1]
aedropout = VAE(n_dims=n_dims)
complete_encoded = aedropout.train(x_train.copy(),
x_test.copy(),
train_epochs=n_epochs,
batch_size=n_batch_size)
train_encoded, test_encoded = complete_encoded
missing_cols = list(missing_encoded)
inverse_test_encoded = scaler.inverse_transform(test_encoded)
df_test_dummies = pd.DataFrame(columns=missing_cols,
data=inverse_test_encoded)
df_test_dummies = reverse_encoding(df_test_dummies.copy())
df_test_dummies.drop(cat_cols, axis=1,
inplace=True)
df_test_complete.drop(cat_cols, axis=1,
inplace=True)
true_vals = df_test_complete.values.copy()
test_vals = df_test_dummies.values.copy()
scaler2 = MinMaxScaler().fit(true_vals)
scaled_true_vales = scaler2.transform(true_vals)
scaled_test_vales = scaler2.transform(test_vals)
rmse = math.sqrt(mean_squared_error(scaled_true_vales,
scaled_test_vales))
rmses.append(rmse)
print(np.mean(rmses))
print(np.std(rmses))
```
|
github_jupyter
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import random
import argparse
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import set_random_seed
from keras import regularizers
from keras import backend as K
from keras.models import Model
from keras.utils import plot_model
from keras.losses import mse, binary_crossentropy
from keras.layers import Lambda, Input, Dense, Dropout
import pandas as pd
import seaborn as sns
from keras.utils import np_utils
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
from keras.objectives import mse
from keras.models import Sequential
from keras.layers.core import Dropout, Dense
from keras.regularizers import l1, l2
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from collections import defaultdict
GLOBAL_SEED = 1
LOCAL_SEED = 42
set_random_seed(GLOBAL_SEED)
np.random.seed(GLOBAL_SEED)
random.seed(GLOBAL_SEED)
%matplotlib inline
%pylab inline
rcParams['figure.figsize'] = [10, 8]
# Define PATH to file
path = '/DataSets/Selected/breast-cancer-wisconsin/wdbc.data'
# Dataset will be generated with the prefix:
dest = '/Dataset/wdbc'
from sklearn.utils import shuffle
set_random_seed(GLOBAL_SEED)
np.random.seed(GLOBAL_SEED)
random.seed(GLOBAL_SEED)
import pandas as pd
na_values = {'?', np.nan}
df = pd.read_csv(path,
sep=',',
header=None,
na_filter=True,
verbose=False,
skip_blank_lines=True,
na_values=na_values,
keep_default_na=False)
print('Origin dataset:')
print(df.head())
# Drop N/A
df.replace('U', np.nan, inplace=True)
df.dropna(axis='rows', how='all', inplace=True)
df = shuffle(df, random_state=GLOBAL_SEED)
df.drop([0], axis=1, inplace=True)
print(df.head())
col_names = list(df)
new_names = {}
for i, name in enumerate(col_names):
new_names[name] = 'X' + str(i)
df.rename(columns=new_names, inplace=True)
df = df.reindex(sorted(df.columns), axis=1)
print(df.head())
# For breast cancer
# df['X9'] = df['X9'].astype('category')
# For Pima Diabetes
cat_cols = ['X0']
df[cat_cols] = df[cat_cols].astype('category')
colnums = len(df.columns)
for i in df.columns:
try:
if df[i].dtype.name == 'object' or df[i].dtype.name == 'category':
df[i] = df[i].astype('category')
else:
df[i] = df[i].astype('float32')
except:
continue
df.dropna(axis='rows', how='any', inplace=True)
print(df.head())
print(df.describe())
print(df.info())
df_non_null = df
from sklearn.utils import resample
# make 50% of the data becoming missing
prob_missing = 0.5
df_incomplete = df_non_null.copy()
ix = [(row, col) for row in range(df_non_null.shape[0]) for col in range(df_non_null.shape[1])]
L = resample(ix, n_samples = int(prob_missing*len(ix)),
random_state=LOCAL_SEED)
for row, col in L:
df_incomplete.iat[row, col] = np.nan
df_incomplete.info()
missing_encoded = pd.get_dummies(df_incomplete)
for col in df.columns:
missing_cols = missing_encoded.columns.str.startswith(str(col) + "_")
missing_encoded.loc[df_incomplete[col].isnull(), missing_cols] = np.nan
missing_encoded.head()
hidden_size = 1000
n_epochs = 100
n_batch_size=1024
def masked_mae(X_true, X_pred, mask):
masked_diff = X_true[mask] - X_pred[mask]
return np.mean(np.abs(masked_diff))
def reverse_encoding(df_test_dummies):
names = list(df_test_dummies)
c_dict = {}
for n in names:
if '_' in n:
index = n.index('_')
c_dict[n[:index]] = [c for c in names if n[:index+1] in c]
values = []
for key, items in c_dict.items():
dummies = df_test_dummies[items]
d_names = list(dummies)
c_dict = {}
for n in d_names:
c_dict[n] = n[n.index('_')+1:]
dummies.rename(columns=c_dict,
inplace=True)
df_test_dummies[key] = dummies.idxmax(axis=1)
df_test_dummies.drop(items, axis=1, inplace=True)
print(df_test_dummies.head())
return df_test_dummies
class AutoEncoderDropout:
def __init__(self,
n_dims,
recurrent_weight=0.5,
optimizer="adam",
dropout_probability=0.5,
hidden_activation="relu",
output_activation="sigmoid",
init="glorot_normal",
l1_penalty=1e-3,
l2_penalty=1e-3,
hidden_size=hidden_size):
self.n_dims = n_dims
self.recurrent_weight = recurrent_weight
self.optimizer = optimizer
self.dropout_probability = dropout_probability
self.hidden_activation = hidden_activation
self.output_activation = output_activation
self.init = init
self.l1_penalty = l1_penalty
self.l2_penalty = l2_penalty
self.hidden_size = hidden_size
def make_reconstruction_loss(self, n_features):
def reconstruction_loss(input_and_mask, y_pred):
X_values = input_and_mask[:, :n_features]
missing_mask = input_and_mask[:, n_features:]
observed_mask = 1 - missing_mask
X_values_observed = X_values * observed_mask
pred_observed = y_pred * observed_mask
return binary_crossentropy(y_true=X_values_observed,
y_pred=pred_observed)
return reconstruction_loss
def _create_model(self):
latent_dim = int(np.ceil(self.n_dims*0.5))
inputs = Input(shape=(2*self.n_dims, ),
name='encoder_input')
x = inputs
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
encoded = Dense(latent_dim, name='encoding')(x)
self.encoder = Model(inputs, encoded, name='encoder')
latent_inputs = Input(shape=(latent_dim,), name='decoder_input')
x = latent_inputs
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
outputs = Dense(self.n_dims, activation=self.output_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
self.decoder = Model(latent_inputs,
outputs,
name='decoder')
outputs = self.decoder(self.encoder(inputs))
self.model = Model(inputs, outputs, name='ae_mlp')
loss_function = self.make_reconstruction_loss(self.n_dims)
self.model.compile(optimizer=self.optimizer,
loss=loss_function)
def fill(self, data, missing_mask):
data[missing_mask] = -1
return data
def _create_missing_mask(self, data):
if data.dtype != "f" and data.dtype != "d":
data = data.astype(float)
return np.isnan(data)
def _train_epoch(self, data, missing_mask, batch_size):
input_with_mask = np.hstack([data, missing_mask])
n_samples = len(input_with_mask)
n_batches = int(np.ceil(n_samples / batch_size))
indices = np.arange(n_samples)
np.random.shuffle(indices)
X_shuffled = input_with_mask[indices]
for batch_idx in range(n_batches):
batch_start = batch_idx * batch_size
batch_end = (batch_idx + 1) * batch_size
batch_data = X_shuffled[batch_start:batch_end, :]
self.model.train_on_batch(batch_data, batch_data)
return self.model.predict(input_with_mask)
def predict(self, x_test_with_mask):
predict_stochastic = K.function([self.decoder.layers[0].input,
K.learning_phase()],
[self.decoder.layers[-1].output])
latent_input = self.encoder.predict(x_test_with_mask)
outputs = np.array([np.array(predict_stochastic([latent_input,
1])).reshape((x_test_with_mask.shape[0],
x_test_with_mask.shape[1]//2)) for _ in range(50)])
return np.mean(outputs, axis=0)
def train(self, x_train, x_test, batch_size=256, train_epochs=100):
missing_mask = self._create_missing_mask(x_train)
x_train = self.fill(x_train, missing_mask)
x_test_missing_mask = self._create_missing_mask(x_test)
x_test = self.fill(x_test, x_test_missing_mask)
self._create_model()
observed_mask = ~missing_mask
x_test_observed_mask = ~x_test_missing_mask
input_with_mask = np.hstack([x_train, missing_mask])
for epoch in range(train_epochs):
X_pred = self._train_epoch(x_train, missing_mask, batch_size)
x_test_with_mask = np.hstack([x_test, x_test_missing_mask])
X_test_pred = self.predict(x_test_with_mask)
observed_mae = masked_mae(X_true=x_train,
X_pred=X_pred,
mask=observed_mask)
test_observed_mae = masked_mae(X_true=x_test,
X_pred = X_test_pred,
mask=x_test_observed_mask)
if epoch % 50 == 0:
print("observed mae:", observed_mae)
print("Test mae:", test_observed_mae)
old_weight = (1.0 - self.recurrent_weight)
x_train[missing_mask] *= old_weight
x_test[x_test_missing_mask] *= old_weight
pred_missing = X_pred[missing_mask]
x_test_pred_missing = X_test_pred[x_test_missing_mask]
x_train[missing_mask] += self.recurrent_weight * pred_missing
x_test[x_test_missing_mask] += self.recurrent_weight * x_test_pred_missing
return x_train.copy(), x_test.copy()
import math
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
seeds = [LOCAL_SEED+2, LOCAL_SEED+1, LOCAL_SEED+4, LOCAL_SEED+6, LOCAL_SEED+8]
rmses = []
cols = df_non_null.columns
non_null_values = df_non_null.values.copy()
for seed_number in seeds:
values = missing_encoded.values.copy()
train, test, comp_train, comp_test = train_test_split(values.copy(),
non_null_values.copy(),
test_size=0.1,
random_state=seed_number)
df_test_complete = pd.DataFrame(columns=cols,
data=comp_test.copy())
scaler = MinMaxScaler().fit(train)
x_train = scaler.transform(train)
x_test = scaler.transform(test)
n_dims = x_train.shape[1]
aedropout = AutoEncoderDropout(n_dims=n_dims)
complete_encoded = aedropout.train(x_train.copy(),
x_test.copy(),
train_epochs=n_epochs,
batch_size=n_batch_size)
train_encoded, test_encoded = complete_encoded
missing_cols = list(missing_encoded)
inverse_test_encoded = scaler.inverse_transform(test_encoded)
df_test_dummies = pd.DataFrame(columns=missing_cols,
data=inverse_test_encoded)
df_test_dummies = reverse_encoding(df_test_dummies.copy())
df_test_dummies.drop(cat_cols, axis=1,
inplace=True)
df_test_complete.drop(cat_cols, axis=1,
inplace=True)
true_vals = df_test_complete.values.copy()
test_vals = df_test_dummies.values.copy()
scaler2 = MinMaxScaler().fit(true_vals)
scaled_true_vales = scaler2.transform(true_vals)
scaled_test_vales = scaler2.transform(test_vals)
rmse = math.sqrt(mean_squared_error(scaled_true_vales,
scaled_test_vales))
rmses.append(rmse)
print(np.mean(rmses), np.std(rmses))
class VAEDropout:
def __init__(self, n_dims,
recurrent_weight=0.5,
optimizer="adam",
dropout_probability=0.5,
hidden_activation="relu",
output_activation="sigmoid",
init="glorot_normal",
l2_penalty=1e-3,
hidden_size=hidden_size):
self.n_dims = n_dims
self.recurrent_weight = recurrent_weight
self.optimizer = optimizer
self.dropout_probability = dropout_probability
self.hidden_activation = hidden_activation
self.output_activation = output_activation
self.init = init
self.l2_penalty = l2_penalty
self.hidden_size = hidden_size
self._create_model()
def _create_model(self):
latent_dim = int(np.ceil(self.n_dims*0.5))
inputs = Input(shape=(2*n_dims, ), name='encoder_input')
x = inputs
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)
self.encoder = Model(inputs, [z_mean,
z_log_var], name='encoder')
latent_inputs = Input(shape=(latent_dim,), name='z_sampling')
x = latent_inputs
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
x = Dropout(self.dropout_probability)(x)
outputs = Dense(self.n_dims, activation=self.output_activation,
init=self.init,
kernel_regularizer=l2(self.l2_penalty),
bias_regularizer=l2(self.l2_penalty))(x)
self.decoder = Model(latent_inputs,
outputs,
name='decoder')
outputs = self.decoder(self.encoder(inputs)[0])
self.model = Model(inputs, outputs,
name='vae_mlp')
reconstruction_loss = self.make_vae_reconstruction_loss(n_dims,
z_mean,
z_log_var)
self.model.compile(optimizer=self.optimizer,
loss=reconstruction_loss)
def make_vae_reconstruction_loss(self, n_features, z_mean, z_log_var):
def reconstruction_loss(input_and_mask, y_pred):
X_values = input_and_mask[:, :n_features]
missing_mask = input_and_mask[:, n_features:]
observed_mask = 1 - missing_mask
X_values_observed = X_values * observed_mask
pred_observed = y_pred * observed_mask
reconstruction_loss = binary_crossentropy(y_true=X_values_observed,
y_pred=pred_observed)
reconstruction_loss*=n_features
kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
kl_loss = K.sum(kl_loss, axis=-1)
kl_loss *= -0.5
vae_loss = K.mean(reconstruction_loss + kl_loss)
return vae_loss
return reconstruction_loss
def fill(self, data, missing_mask):
data[missing_mask] = -1
return data
def _create_missing_mask(self, data):
if data.dtype != "f" and data.dtype != "d":
data = data.astype(float)
return np.isnan(data)
def predict(self, x_test_with_mask):
predict_stochastic = K.function([self.decoder.layers[0].input,
K.learning_phase()],
[self.decoder.layers[-1].output])
latent_input = self.encoder.predict(x_test_with_mask)
outputs = np.array([np.array(predict_stochastic([latent_input,
1])).reshape((x_test_with_mask.shape[0],
x_test_with_mask.shape[1]//2)) for _ in range(50)])
return np.mean(outputs, axis=0)
def _train_epoch(self, data, missing_mask, batch_size):
input_with_mask = np.hstack([data, missing_mask])
n_samples = len(input_with_mask)
n_batches = int(np.ceil(n_samples / batch_size))
indices = np.arange(n_samples)
np.random.shuffle(indices)
X_shuffled = input_with_mask[indices]
for batch_idx in range(n_batches):
batch_start = batch_idx * batch_size
batch_end = (batch_idx + 1) * batch_size
batch_data = X_shuffled[batch_start:batch_end, :]
self.model.train_on_batch(batch_data, batch_data)
return self.model.predict(input_with_mask)
def train(self, x_train, x_test, batch_size=256, train_epochs=100):
missing_mask = self._create_missing_mask(x_train)
x_train = self.fill(x_train, missing_mask)
x_test_missing_mask = self._create_missing_mask(x_test)
x_test = self.fill(x_test, x_test_missing_mask)
observed_mask = ~missing_mask
x_test_observed_mask = ~x_test_missing_mask
for epoch in range(train_epochs):
X_pred = self._train_epoch(x_train, missing_mask, batch_size)
x_test_with_mask = np.hstack([x_test, x_test_missing_mask])
X_test_pred = self.predict(x_test_with_mask)
observed_mae = masked_mae(X_true=x_train,
X_pred=X_pred,
mask=observed_mask)
test_observed_mae = masked_mae(X_true=x_test,
X_pred = X_test_pred,
mask=x_test_observed_mask)
if epoch % 50 == 0:
print("Traing observed mae:", observed_mae)
print("Test observed mae:", test_observed_mae)
old_weight = (1.0 - self.recurrent_weight)
x_train[missing_mask] *= old_weight
x_test[x_test_missing_mask] *= old_weight
pred_missing = X_pred[missing_mask]
x_test_pred_missing = X_test_pred[x_test_missing_mask]
x_train[missing_mask] += self.recurrent_weight * pred_missing
x_test[x_test_missing_mask] += self.recurrent_weight*x_test_pred_missing
return x_train.copy(), x_test.copy()
import math
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
seeds = [LOCAL_SEED+2, LOCAL_SEED+1, LOCAL_SEED+4, LOCAL_SEED+6, LOCAL_SEED+8]
rmses = []
cols = df_non_null.columns
non_null_values = df_non_null.values.copy()
for seed_number in seeds:
values = missing_encoded.values.copy()
train, test, comp_train, comp_test = train_test_split(values.copy(),
non_null_values.copy(),
test_size=0.1,
random_state=seed_number)
df_test_complete = pd.DataFrame(columns=cols,
data=comp_test.copy())
scaler = MinMaxScaler().fit(train)
x_train = scaler.transform(train)
x_test = scaler.transform(test)
n_dims = x_train.shape[1]
aedropout = VAEDropout(n_dims=n_dims)
complete_encoded = aedropout.train(x_train.copy(),
x_test.copy(),
train_epochs=n_epochs,
batch_size=n_batch_size)
train_encoded, test_encoded = complete_encoded
missing_cols = list(missing_encoded)
inverse_test_encoded = scaler.inverse_transform(test_encoded)
df_test_dummies = pd.DataFrame(columns=missing_cols,
data=inverse_test_encoded)
df_test_dummies = reverse_encoding(df_test_dummies.copy())
df_test_dummies.drop(cat_cols, axis=1,
inplace=True)
df_test_complete.drop(cat_cols, axis=1,
inplace=True)
true_vals = df_test_complete.values.copy()
test_vals = df_test_dummies.values.copy()
scaler2 = MinMaxScaler().fit(true_vals)
scaled_true_vales = scaler2.transform(true_vals)
scaled_test_vales = scaler2.transform(test_vals)
rmse = math.sqrt(mean_squared_error(scaled_true_vales,
scaled_test_vales))
rmses.append(rmse)
print(np.mean(rmses))
print(np.std(rmses))
class Autoencoder:
def __init__(self, n_dims,
recurrent_weight=0.5,
optimizer="adam",
dropout_probability=0.1,
hidden_activation="relu",
output_activation="sigmoid",
init="glorot_normal",
l1_penalty=0,
l2_penalty=1e-3,
hidden_size=hidden_size):
self.n_dims = n_dims
self.recurrent_weight = recurrent_weight
self.optimizer = optimizer
self.dropout_probability = dropout_probability
self.hidden_activation = hidden_activation
self.output_activation = output_activation
self.init = init
self.l1_penalty = l1_penalty
self.l2_penalty = l2_penalty
self.hidden_size = hidden_size
def make_reconstruction_loss(self, n_features):
def reconstruction_loss(input_and_mask, y_pred):
X_values = input_and_mask[:, :n_features]
missing_mask = input_and_mask[:, n_features:]
observed_mask = 1 - missing_mask
X_values_observed = X_values * observed_mask
pred_observed = y_pred * observed_mask
return binary_crossentropy(y_true=X_values_observed,
y_pred=pred_observed)
return reconstruction_loss
def _create_model(self):
latent_dim = int(np.ceil(self.n_dims*0.5))
inputs = Input(shape=(2*n_dims, ), name='encoder_input')
x = inputs
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
encoded = Dense(latent_dim, name='encoding')(x)
self.encoder = Model(inputs, encoded, name='encoder')
latent_inputs = Input(shape=(latent_dim,), name='z_sampling')
x = latent_inputs
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
outputs = Dense(n_dims, activation=self.output_activation)(x)
self.decoder = Model(latent_inputs,
outputs,
name='decoder')
outputs = self.decoder(self.encoder(inputs))
self.model = Model(inputs, outputs, name='vae_mlp')
loss_function = self.make_reconstruction_loss(n_dims)
self.model.compile(optimizer=self.optimizer,
loss=loss_function)
def fill(self, data, missing_mask):
data[missing_mask] = -1
return data
def _create_missing_mask(self, data):
if data.dtype != "f" and data.dtype != "d":
data = data.astype(float)
return np.isnan(data)
def _train_epoch(self, data, missing_mask, batch_size):
input_with_mask = np.hstack([data, missing_mask])
n_samples = len(input_with_mask)
n_batches = int(np.ceil(n_samples / batch_size))
indices = np.arange(n_samples)
np.random.shuffle(indices)
X_shuffled = input_with_mask[indices]
for batch_idx in range(n_batches):
batch_start = batch_idx * batch_size
batch_end = (batch_idx + 1) * batch_size
batch_data = X_shuffled[batch_start:batch_end, :]
self.model.train_on_batch(batch_data, batch_data)
return self.model.predict(input_with_mask)
def train(self, x_train, x_test, batch_size=256, train_epochs=100):
missing_mask = self._create_missing_mask(x_train)
x_train = self.fill(x_train, missing_mask)
x_test_missing_mask = self._create_missing_mask(x_test)
x_test = self.fill(x_test, x_test_missing_mask)
self._create_model()
self.encoder.summary()
self.decoder.summary()
self.model.summary()
observed_mask = ~missing_mask
x_test_observed_mask = ~x_test_missing_mask
input_with_mask = np.hstack([x_train, missing_mask])
for epoch in range(train_epochs):
X_pred = self._train_epoch(x_train, missing_mask, batch_size)
x_test_with_mask = np.hstack([x_test, x_test_missing_mask])
X_test_pred = self.model.predict(x_test_with_mask)
observed_mae = masked_mae(X_true=x_train,
X_pred=X_pred,
mask=observed_mask)
test_observed_mae = masked_mae(X_true=x_test,
X_pred = X_test_pred,
mask=x_test_observed_mask)
if epoch % 50 == 0:
print("observed mae:", observed_mae)
print("Test mae:", test_observed_mae)
old_weight = (1.0 - self.recurrent_weight)
x_train[missing_mask] *= old_weight
x_test[x_test_missing_mask] *= old_weight
pred_missing = X_pred[missing_mask]
x_test_pred_missing = X_test_pred[x_test_missing_mask]
x_train[missing_mask] += self.recurrent_weight * pred_missing
x_test[x_test_missing_mask] += self.recurrent_weight * x_test_pred_missing
return x_train.copy(), x_test.copy()
import math
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
seeds = [LOCAL_SEED+2, LOCAL_SEED+1, LOCAL_SEED+4, LOCAL_SEED+6, LOCAL_SEED+8]
rmses = []
cols = df_non_null.columns
non_null_values = df_non_null.values.copy()
for seed_number in seeds:
values = missing_encoded.values.copy()
train, test, comp_train, comp_test = train_test_split(values.copy(),
non_null_values.copy(),
test_size=0.1,
random_state=seed_number)
df_test_complete = pd.DataFrame(columns=cols,
data=comp_test.copy())
scaler = MinMaxScaler().fit(train)
x_train = scaler.transform(train)
x_test = scaler.transform(test)
n_dims = x_train.shape[1]
aedropout = Autoencoder(n_dims=n_dims)
complete_encoded = aedropout.train(x_train.copy(),
x_test.copy(),
train_epochs=n_epochs,
batch_size=n_batch_size)
train_encoded, test_encoded = complete_encoded
missing_cols = list(missing_encoded)
inverse_test_encoded = scaler.inverse_transform(test_encoded)
df_test_dummies = pd.DataFrame(columns=missing_cols,
data=inverse_test_encoded)
df_test_dummies = reverse_encoding(df_test_dummies.copy())
df_test_dummies.drop(cat_cols, axis=1,
inplace=True)
df_test_complete.drop(cat_cols, axis=1,
inplace=True)
true_vals = df_test_complete.values.copy()
test_vals = df_test_dummies.values.copy()
scaler2 = MinMaxScaler().fit(true_vals)
scaled_true_vales = scaler2.transform(true_vals)
scaled_test_vales = scaler2.transform(test_vals)
rmse = math.sqrt(mean_squared_error(scaled_true_vales,
scaled_test_vales))
rmses.append(rmse)
print(np.mean(rmses))
print(np.std(rmses))
class VAE:
def __init__(self, n_dims,
recurrent_weight=0.5,
optimizer="adam",
dropout_probability=0.1,
hidden_activation="relu",
output_activation="sigmoid",
init="glorot_normal",
l2_penalty=1e-3):
self.n_dims = n_dims
self.recurrent_weight = recurrent_weight
self.optimizer = optimizer
self.dropout_probability = dropout_probability
self.hidden_activation = hidden_activation
self.output_activation = output_activation
self.init = init
self.l2_penalty = l2_penalty
self.hidden_size = hidden_size
self._create_model()
def make_reconstruction_loss(self, n_features, z_mean, z_log_var):
def reconstruction_loss(input_and_mask, y_pred):
X_values = input_and_mask[:, :n_features]
missing_mask = input_and_mask[:, n_features:]
observed_mask = 1 - missing_mask
X_values_observed = X_values * observed_mask
pred_observed = y_pred * observed_mask
reconstruction_loss = binary_crossentropy(y_true=X_values_observed,
y_pred=pred_observed)
reconstruction_loss*=n_features
kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
kl_loss = K.sum(kl_loss, axis=-1)
kl_loss *= -0.5
vae_loss = K.mean(reconstruction_loss + kl_loss)
return vae_loss
return reconstruction_loss
def sampling(self, args):
"""Reparameterization trick by sampling from an isotropic unit Gaussian.
# Arguments
args (tensor): mean and log of variance of Q(z|X)
# Returns
z (tensor): sampled latent vector
"""
z_mean, z_log_var = args
batch = K.shape(z_mean)[0]
dim = K.int_shape(z_mean)[1]
# by default, random_normal has mean = 0 and std = 1.0
epsilon = K.random_normal(shape=(batch, dim))
return z_mean + K.exp(0.5 * z_log_var) * epsilon
def _create_model(self):
latent_dim = (int(np.ceil(self.n_dims*0.5)))
inputs = Input(shape=(2*self.n_dims, ), name='encoder_input')
x = inputs
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)
z = Lambda(self.sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])
self.encoder = Model(inputs, [z_mean,
z_log_var, z], name='encoder')
latent_inputs = Input(shape=(latent_dim,), name='z_sampling')
x = latent_inputs
x = Dense(self.hidden_size//4, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
x = Dense(self.hidden_size, activation=self.hidden_activation,
init=self.init)(x)
x = Dropout(self.dropout_probability)(x)
outputs = Dense(self.n_dims, activation=self.output_activation)(x)
self.decoder = Model(latent_inputs,
outputs,
name='decoder')
outputs = self.decoder(self.encoder(inputs)[2])
self.model = Model(inputs, outputs,
name='vae_mlp')
reconstruction_loss = self.make_reconstruction_loss(n_dims,
z_mean,
z_log_var)
self.model.compile(optimizer=self.optimizer,
loss=reconstruction_loss)
def fill(self, data, missing_mask):
data[missing_mask] = -1
return data
def _create_missing_mask(self, data):
if data.dtype != "f" and data.dtype != "d":
data = data.astype(float)
return np.isnan(data)
def _train_epoch(self, data, missing_mask, batch_size):
input_with_mask = np.hstack([data, missing_mask])
n_samples = len(input_with_mask)
n_batches = int(np.ceil(n_samples / batch_size))
indices = np.arange(n_samples)
np.random.shuffle(indices)
X_shuffled = input_with_mask[indices]
for batch_idx in range(n_batches):
batch_start = batch_idx * batch_size
batch_end = (batch_idx + 1) * batch_size
batch_data = X_shuffled[batch_start:batch_end, :]
self.model.train_on_batch(batch_data, batch_data)
return self.model.predict(input_with_mask)
def train(self, x_train, x_test, batch_size=256, train_epochs=100):
missing_mask = self._create_missing_mask(x_train)
x_train = self.fill(x_train, missing_mask)
x_test_missing_mask = self._create_missing_mask(x_test)
x_test = self.fill(x_test, x_test_missing_mask)
observed_mask = ~missing_mask
x_test_observed_mask = ~x_test_missing_mask
for epoch in range(train_epochs):
X_pred = self._train_epoch(x_train, missing_mask, batch_size)
x_test_with_mask = np.hstack([x_test, x_test_missing_mask])
X_test_pred = self.model.predict(x_test_with_mask)
observed_mae = masked_mae(X_true=x_train,
X_pred=X_pred,
mask=observed_mask)
test_observed_mae = masked_mae(X_true=x_test,
X_pred = X_test_pred,
mask=x_test_observed_mask)
if epoch % 50 == 0:
print("Traing observed mae:", observed_mae)
print("Test observed mae:", test_observed_mae)
old_weight = (1.0 - self.recurrent_weight)
x_train[missing_mask] *= old_weight
x_test[x_test_missing_mask] *= old_weight
pred_missing = X_pred[missing_mask]
x_test_pred_missing = X_test_pred[x_test_missing_mask]
x_train[missing_mask] += self.recurrent_weight * pred_missing
x_test[x_test_missing_mask] += self.recurrent_weight*x_test_pred_missing
return x_train.copy(), x_test.copy()
import math
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
seeds = [LOCAL_SEED+2, LOCAL_SEED+1, LOCAL_SEED+4, LOCAL_SEED+6, LOCAL_SEED+8]
rmses = []
cols = df_non_null.columns
non_null_values = df_non_null.values.copy()
for seed_number in seeds:
values = missing_encoded.values.copy()
train, test, comp_train, comp_test = train_test_split(values.copy(),
non_null_values.copy(),
test_size=0.1,
random_state=seed_number)
df_test_complete = pd.DataFrame(columns=cols,
data=comp_test.copy())
scaler = MinMaxScaler().fit(train)
x_train = scaler.transform(train)
x_test = scaler.transform(test)
n_dims = x_train.shape[1]
aedropout = VAE(n_dims=n_dims)
complete_encoded = aedropout.train(x_train.copy(),
x_test.copy(),
train_epochs=n_epochs,
batch_size=n_batch_size)
train_encoded, test_encoded = complete_encoded
missing_cols = list(missing_encoded)
inverse_test_encoded = scaler.inverse_transform(test_encoded)
df_test_dummies = pd.DataFrame(columns=missing_cols,
data=inverse_test_encoded)
df_test_dummies = reverse_encoding(df_test_dummies.copy())
df_test_dummies.drop(cat_cols, axis=1,
inplace=True)
df_test_complete.drop(cat_cols, axis=1,
inplace=True)
true_vals = df_test_complete.values.copy()
test_vals = df_test_dummies.values.copy()
scaler2 = MinMaxScaler().fit(true_vals)
scaled_true_vales = scaler2.transform(true_vals)
scaled_test_vales = scaler2.transform(test_vals)
rmse = math.sqrt(mean_squared_error(scaled_true_vales,
scaled_test_vales))
rmses.append(rmse)
print(np.mean(rmses))
print(np.std(rmses))
| 0.520009 | 0.657951 |
# CSV & EXCEL
```
import pandas as pd
pd.read_csv("./data/microbiome.csv", header='infer', sep=',', encoding="utf-8").head()
dx1 = pd.read_excel('./data/Sample_xls.xlsx', sheet_name='sheet1', header=None)
dx2 = pd.read_excel('./data/Sample_xls.xlsx', sheet_name='sheet2', header=None)
print(dx1.head())
print('-'*100)
print(dx2.head())
population_dict = {'California': 38332521,'Texas': 26448193,'New York': 19651127,'Florida': 19552860,
'Illinois': 12882135}
population = pd.Series(population_dict)
area_dict = {'California': 423967, 'Texas': 695662, 'Illinois': 149995, 'New York': 141297,'Florida': 170312}
area = pd.Series(area_dict)
income_dict = {'California': 75277, 'Texas': 60629, 'Illinois': 65030, 'New York': 71855,'Florida': 53267}
income = pd.Series(area_dict)
data=pd.DataFrame({'pop': population,'area': area, 'income': income})
display(data)
data.to_csv('./data/output/to_csv_eg.csv',index=False,header=False)
data.to_excel('./data/output/to_xls_eg.xlsx',index=False,header=False,sheet_name='sheet_name')
```
# DataFrame select & indexing
<details>
<summary>dataframe結構圖</summary>
<img src = './img/creating_dataframe1.png'>
</details>
<details>
<summary>dataframe的Series結構圖</summary>
<details>
<summary>columns' series</summary>
<img src = './img/dataSER-1.png'>
</details>
<details>
<summary>index lables' series</summary>
<img src = './img/Untitled.png'>
</details>
</details>
#### 使用 Dictionary 風格來存取(透過欄名稱索引)
```
data['area']
```
#### Dictionary 風格的語法也可以用來修改物件,或是建立⼀個新欄位
```
data['density'] = data['pop'] / data['area']
```
#### DataFrame的屬性
```
data.columns
data.index
data.values
```
#### loc
```
data.loc['Texas']
data.loc['Illinois', 'pop']
data.loc[:'Texas', :'pop']
```
#### iloc
```
data.iloc[-1]
data.iloc[1,2]
data.iloc[:3, :2]
```
#### Masking indexing
```
data['density'] > 100
data[data['density'] > 100]
```
#### Fancy indexing
```
data[['pop','income','density']]
```
#### combine masking and fancy indexing as in the following:
```
data.loc[(data.density > 100).values, ['pop', 'density']]
data.iloc[(data.density > 100).values, [0,2]]
```
# JSON & xml
```
dj = pd.read_json('./data/data.json')
dj.head(10)
import xml.etree.ElementTree as XET
tree = XET.parse('./data/County_h_10906.xml') # 以XET套件載入XML檔案
root = tree.getroot() # 取得XML表格
for (i,tag_lv1) in enumerate(root):
print(tag_lv1.tag)
for tag_lv2 in tag_lv1:
print(tag_lv2.tag)
if i == 2:
break
print([(node.find('欄位1').text, node.find('欄位2').text, node.find('欄位3').text) for node in root.findall('County_h_10906')][:3])
```
# MySQL
```
import sqlalchemy as db
import pandas.io.sql as sql
import pandas as pd
#連接資料庫
username = 'root' # 資料庫帳號
password = '' # 資料庫密碼
host = 'localhost' # 資料庫位址
port = '3306' # 資料庫埠號
database = 'classicmodels' # 資料庫名稱
table = 'offices' # 表格名稱
# 建立資料庫引擎
engine = db.create_engine(f'mysql+pymysql://{username}:{password}@{host}:{port}/{database}')
# 建立資料庫連線
# con = engine.raw_connection()
con = engine.connect()
#readinto dataframe
df = sql.read_sql(f'SELECT * FROM `{database}`.`{table}`;', con)
df.tail()
df_append = pd.DataFrame([{'officeCode': 8,'city':'Taipei',
'phone':'1234567891','addressLine1':'Taipei DaAn',
'addressLine2':'Taipei DaAn2','state':'Taipei',
'country':'Taiwan','postalCode':'123','territory':'Asia'}])
df_append.tail()
sql.to_sql(df_append, name=table, con=con, if_exists='append',index=False)
df = sql.read_sql(f'SELECT * FROM `{database}`.`{table}`;', con)
df.tail()
```
# 補充
```
metadata = db.MetaData()
# 取得 test 資料表的 Python 對應操作物件
tableoffices = db.Table('offices', metadata, autoload=True, autoload_with=engine)
# DELETE
query = db.delete(tableoffices).where(tableoffices.c.officeCode == 8)
proxy = con.execute(query)
```
|
github_jupyter
|
import pandas as pd
pd.read_csv("./data/microbiome.csv", header='infer', sep=',', encoding="utf-8").head()
dx1 = pd.read_excel('./data/Sample_xls.xlsx', sheet_name='sheet1', header=None)
dx2 = pd.read_excel('./data/Sample_xls.xlsx', sheet_name='sheet2', header=None)
print(dx1.head())
print('-'*100)
print(dx2.head())
population_dict = {'California': 38332521,'Texas': 26448193,'New York': 19651127,'Florida': 19552860,
'Illinois': 12882135}
population = pd.Series(population_dict)
area_dict = {'California': 423967, 'Texas': 695662, 'Illinois': 149995, 'New York': 141297,'Florida': 170312}
area = pd.Series(area_dict)
income_dict = {'California': 75277, 'Texas': 60629, 'Illinois': 65030, 'New York': 71855,'Florida': 53267}
income = pd.Series(area_dict)
data=pd.DataFrame({'pop': population,'area': area, 'income': income})
display(data)
data.to_csv('./data/output/to_csv_eg.csv',index=False,header=False)
data.to_excel('./data/output/to_xls_eg.xlsx',index=False,header=False,sheet_name='sheet_name')
data['area']
data['density'] = data['pop'] / data['area']
data.columns
data.index
data.values
data.loc['Texas']
data.loc['Illinois', 'pop']
data.loc[:'Texas', :'pop']
data.iloc[-1]
data.iloc[1,2]
data.iloc[:3, :2]
data['density'] > 100
data[data['density'] > 100]
data[['pop','income','density']]
data.loc[(data.density > 100).values, ['pop', 'density']]
data.iloc[(data.density > 100).values, [0,2]]
dj = pd.read_json('./data/data.json')
dj.head(10)
import xml.etree.ElementTree as XET
tree = XET.parse('./data/County_h_10906.xml') # 以XET套件載入XML檔案
root = tree.getroot() # 取得XML表格
for (i,tag_lv1) in enumerate(root):
print(tag_lv1.tag)
for tag_lv2 in tag_lv1:
print(tag_lv2.tag)
if i == 2:
break
print([(node.find('欄位1').text, node.find('欄位2').text, node.find('欄位3').text) for node in root.findall('County_h_10906')][:3])
import sqlalchemy as db
import pandas.io.sql as sql
import pandas as pd
#連接資料庫
username = 'root' # 資料庫帳號
password = '' # 資料庫密碼
host = 'localhost' # 資料庫位址
port = '3306' # 資料庫埠號
database = 'classicmodels' # 資料庫名稱
table = 'offices' # 表格名稱
# 建立資料庫引擎
engine = db.create_engine(f'mysql+pymysql://{username}:{password}@{host}:{port}/{database}')
# 建立資料庫連線
# con = engine.raw_connection()
con = engine.connect()
#readinto dataframe
df = sql.read_sql(f'SELECT * FROM `{database}`.`{table}`;', con)
df.tail()
df_append = pd.DataFrame([{'officeCode': 8,'city':'Taipei',
'phone':'1234567891','addressLine1':'Taipei DaAn',
'addressLine2':'Taipei DaAn2','state':'Taipei',
'country':'Taiwan','postalCode':'123','territory':'Asia'}])
df_append.tail()
sql.to_sql(df_append, name=table, con=con, if_exists='append',index=False)
df = sql.read_sql(f'SELECT * FROM `{database}`.`{table}`;', con)
df.tail()
metadata = db.MetaData()
# 取得 test 資料表的 Python 對應操作物件
tableoffices = db.Table('offices', metadata, autoload=True, autoload_with=engine)
# DELETE
query = db.delete(tableoffices).where(tableoffices.c.officeCode == 8)
proxy = con.execute(query)
| 0.114889 | 0.678853 |
```
from time import time # To time our operations
from collections import defaultdict # For word frequency
from pathlib import Path
import logging # Setting up the loggings to monitor gensim
logging.basicConfig(format="%(levelname)s - %(asctime)s: %(message)s", datefmt= '%H:%M:%S', level=logging.INFO)
```
# Dataset
```
data_fn = Path('../input/tokenized_paragraphs.txt')
tokenized_paras = [para.split(' ') for para in data_fn.read_text().split('\n')]
tokenized_paras[0]
word_freq = defaultdict(int)
for para in tokenized_paras:
for i in para:
word_freq[i] += 1
len(word_freq)
sorted(word_freq, key=word_freq.get, reverse=True)[:10]
```
# Training the Model
```
import multiprocessing
from gensim.models import Word2Vec
```
## Why I seperate the training of the model in 3 steps:
I prefer to separate the training in 3 distinctive steps for clarity and monitoring.
1. `Word2Vec()`:
>In this first step, I set up the parameters of the model one-by-one. <br>I do not supply the parameter `sentences`, and therefore leave the model uninitialized, purposefully.
2. `.build_vocab()`:
>Here it builds the vocabulary from a sequence of sentences and thus initialized the model. <br>With the loggings, I can follow the progress and even more important, the effect of `min_count` and `sample` on the word corpus. I noticed that these two parameters, and in particular `sample`, have a great influence over the performance of a model. Displaying both allows for a more accurate and an easier management of their influence.
3. `.train()`:
>Finally, trains the model.<br>
The loggings here are mainly useful for monitoring, making sure that no threads are executed instantaneously.
```
cores = multiprocessing.cpu_count() # Count the number of cores in a computer
```
## The parameters:
* `min_count` <font color='purple'>=</font> <font color='green'>int</font> - Ignores all words with total absolute frequency lower than this - (2, 100)
* `window` <font color='purple'>=</font> <font color='green'>int</font> - The maximum distance between the current and predicted word within a sentence. E.g. `window` words on the left and `window` words on the left of our target - (2, 10)
* `size` <font color='purple'>=</font> <font color='green'>int</font> - Dimensionality of the feature vectors. - (50, 300)
* `sample` <font color='purple'>=</font> <font color='green'>float</font> - The threshold for configuring which higher-frequency words are randomly downsampled. Highly influencial. - (0, 1e-5)
* `alpha` <font color='purple'>=</font> <font color='green'>float</font> - The initial learning rate - (0.01, 0.05)
* `min_alpha` <font color='purple'>=</font> <font color='green'>float</font> - Learning rate will linearly drop to `min_alpha` as training progresses. To set it: alpha - (min_alpha * epochs) ~ 0.00
* `negative` <font color='purple'>=</font> <font color='green'>int</font> - If > 0, negative sampling will be used, the int for negative specifies how many "noise words" should be drown. If set to 0, no negative sampling is used. - (5, 20)
* `workers` <font color='purple'>=</font> <font color='green'>int</font> - Use these many worker threads to train the model (=faster training with multicore machines)
### Dimension of word embedding
The optimal dimensionality of word embeddings is mostly task-dependent: a smaller dimensionality works better for more syntactic tasks such as named entity recognition (Melamud et al., 2016) [3] or part-of-speech (POS) tagging (Plank et al., 2016) [4], while a larger dimensionality is more useful for more semantic tasks such as sentiment analysis (Ruder et al., 2016) [5].
- [3] -> http://arxiv.org/abs/1601.00893
- [4] -> Plank, B., Søgaard, A., & Goldberg, Y. (2016). Multilingual Part-of-Speech Tagging with Bidirectional Long Short-Term Memory Models and Auxiliary Loss. In Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics.
- [5] -> http://arxiv.org/abs/1609.02745
```
w2v_model = Word2Vec(min_count=20,
window=5,
size=150,
sample=6e-5,
alpha=0.03,
min_alpha=0.0007,
negative=20,
workers=cores-1)
```
## Building the Vocabulary Table:
Word2Vec requires us to build the vocabulary table (simply digesting all the words and filtering out the unique words, and doing some basic counts on them):
```
t = time()
w2v_model.build_vocab(tokenized_paras, progress_per=10000)
print('Time to build vocab: {} mins'.format(round((time() - t) / 60, 2)))
```
## Training of the model:
_Parameters of the training:_
* `total_examples` <font color='purple'>=</font> <font color='green'>int</font> - Count of sentences;
* `epochs` <font color='purple'>=</font> <font color='green'>int</font> - Number of iterations (epochs) over the corpus - [10, 20, 30]
```
t = time()
w2v_model.train(tokenized_paras, total_examples=w2v_model.corpus_count, epochs=30, report_delay=1)
print('Time to train the model: {} mins'.format(round((time() - t) / 60, 2)))
w2v_model.wv['ཞུགས']
```
# Save the word2vec
```
w2v_model.wv.save_word2vec_format("./bo_word2vec",
"./vocab",
binary=False)
!ls
from gensim.models import KeyedVectors
wv_from_text = KeyedVectors.load_word2vec_format('word2vec_org', binary=False)
wv_from_text['ཞུགས']
!head vocabulary
import gensim
gensim.__version__
```
|
github_jupyter
|
from time import time # To time our operations
from collections import defaultdict # For word frequency
from pathlib import Path
import logging # Setting up the loggings to monitor gensim
logging.basicConfig(format="%(levelname)s - %(asctime)s: %(message)s", datefmt= '%H:%M:%S', level=logging.INFO)
data_fn = Path('../input/tokenized_paragraphs.txt')
tokenized_paras = [para.split(' ') for para in data_fn.read_text().split('\n')]
tokenized_paras[0]
word_freq = defaultdict(int)
for para in tokenized_paras:
for i in para:
word_freq[i] += 1
len(word_freq)
sorted(word_freq, key=word_freq.get, reverse=True)[:10]
import multiprocessing
from gensim.models import Word2Vec
cores = multiprocessing.cpu_count() # Count the number of cores in a computer
w2v_model = Word2Vec(min_count=20,
window=5,
size=150,
sample=6e-5,
alpha=0.03,
min_alpha=0.0007,
negative=20,
workers=cores-1)
t = time()
w2v_model.build_vocab(tokenized_paras, progress_per=10000)
print('Time to build vocab: {} mins'.format(round((time() - t) / 60, 2)))
t = time()
w2v_model.train(tokenized_paras, total_examples=w2v_model.corpus_count, epochs=30, report_delay=1)
print('Time to train the model: {} mins'.format(round((time() - t) / 60, 2)))
w2v_model.wv['ཞུགས']
w2v_model.wv.save_word2vec_format("./bo_word2vec",
"./vocab",
binary=False)
!ls
from gensim.models import KeyedVectors
wv_from_text = KeyedVectors.load_word2vec_format('word2vec_org', binary=False)
wv_from_text['ཞུགས']
!head vocabulary
import gensim
gensim.__version__
| 0.480235 | 0.854035 |
<a href="https://colab.research.google.com/github/oskumd2/explaining-in-style/blob/main/Explaining_in_Style_AttFind.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
#@title Imports
from typing import Optional, Tuple, List
import six.moves.cPickle as cPickle
import tensorflow as tf
import numpy as np
import requests
import tqdm
import collections
import os
import zipfile
from matplotlib import pyplot as plt
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from io import BytesIO
import IPython.display
#@title Load the encoder, the discriminator, the generator and the classifier (slow!)
path = '/tmp/celab_a_age/' #@param {type: 'string'}
bucket_path = 'https://storage.googleapis.com/explaining-in-style/celeb_a_age/'
if not os.path.exists(path):
os.mkdir(path)
def get_path_from_bucket(bucket_url, path):
r = requests.get(bucket_url)
filename = os.path.split(bucket_url)[-1].replace('.zip', '')
zip_ref = zipfile.ZipFile(BytesIO(r.content))
zip_ref.extractall(path)
return os.path.join(path, filename)
num_layers = 14
label_size = 2
resolution = 256
generator = tf.keras.models.load_model(get_path_from_bucket(bucket_path + 'generator.savedmodel.zip', path))
encoder = tf.keras.models.load_model(get_path_from_bucket(bucket_path + 'encoder.savedmodel.zip', path))
discriminator = tf.keras.models.load_model(get_path_from_bucket(bucket_path + 'discriminator.savedmodel.zip', path))
classifier = tf.keras.models.load_model(get_path_from_bucket(bucket_path + 'mobilenet.savedmodel.zip', path))
#@title Utils {form-width: '20%'}
def make_animation(image: np.ndarray,
resolution: int,
figsize: Tuple[int, int] = (20, 8)):
fig = plt.figure(1, figsize=figsize)
_ = plt.gca()
def transpose_image(image):
image_reshape = image.reshape([-1, resolution, resolution, 3])
return image_reshape.transpose([1, 0, 2, 3]).reshape([resolution, -1, 3])
im = plt.imshow(transpose_image(image[:, :resolution, :]),
interpolation='none')
def animate_func(i):
im.set_array(transpose_image(image[:, resolution*i:resolution*(i+1), :]))
return [im]
animation = matplotlib.animation.FuncAnimation(
fig, animate_func, frames=image.shape[1] // resolution, interval=600)
plt.close(1)
return animation
def show_image(image, fmt='png'):
if image.dtype == np.float32:
image = np.uint8(image * 127.5 + 127.5)
if image.shape[0] == 3:
image = np.transpose(image, (1, 2, 0))
bytes_io = BytesIO()
Image.fromarray(image).save(bytes_io, fmt)
IPython.display.display(IPython.display.Image(data=bytes_io.getvalue()))
def filter_unstable_images(style_change_effect: np.ndarray,
effect_threshold: float = 0.3,
num_indices_threshold: int = 750) -> np.ndarray:
"""Filters out images which are affected by too many S values."""
unstable_images = (
np.sum(np.abs(style_change_effect) > effect_threshold, axis=(1, 2, 3)) >
num_indices_threshold)
style_change_effect[unstable_images] = 0
return style_change_effect
@tf.function
def call_synthesis(generator: tf.keras.models.Model,
dlatents_in: tf.Tensor,
conditioning_in: Optional[tf.Tensor] = None,
labels_in: Optional[tf.Tensor] = None,
training: bool = False,
num_layers: int = 14,
dlatent_size: int = 512) -> tf.Tensor:
"""Calls the synthesis.
Args:
dlatents_in: the intermediate latent representation of shape [batch size,
num_layers, dlatent_size].
conditioning_in: Conditioning input to the synthesis network (can be an
image or output from an encoder) of shape [minibatch, channels,
resolution, resolution]. Set to None if unused.
labels_in: of shape [batch_size, label_size]. Set to None if unused.
training: Whether this is a training call.
Returns:
The output images and optional latent vector.
"""
if labels_in is not None:
zero_labels = tf.zeros_like(labels_in)
dlatents_labels = tf.tile(tf.expand_dims(labels, 1), [1, num_layers, 1])
if dlatent_size > 0:
dlatents_expanded = tf.concat([dlatents_in, dlatents_labels], axis=2)
else:
dlatents_expanded = dlatents_labels
else:
if dlatent_size == 0:
raise ValueError('Dlatents are empty and no labels were provided.')
dlatents_expanded = dlatents_in
# Evaluate synthesis network.
style_vector_blocks, style_vector_torgb = generator.style_vector_calculator(
dlatents_expanded[:, 0], training=training)
if conditioning_in is not None:
network_inputs = (style_vector_blocks, style_vector_torgb,
conditioning_in)
else:
network_inputs = (style_vector_blocks, style_vector_torgb)
synthesis_results = generator.g_synthesis(network_inputs, training=training)
# Return requested outputs.
return tf.maximum(tf.minimum(synthesis_results, 1), -1)
def discriminator_filter(style_change_effect: np.ndarray,
all_dlatents: np.ndarray,
generator: tf.keras.models.Model,
discriminator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
sindex: int,
style_min: float,
style_max: float,
class_index: int,
num_images: int = 10,
label_size: int = 2,
change_threshold: float = 0.5,
shift_size: float = 2,
effect_threshold: float = 0.2,
sindex_offset: int = 0) -> bool:
"""Returns false if changing the style index adds artifacts to the images.
Args:
style_change_effect: A shape of [num_images, 2, style_size, num_classes].
The effect of each change of style on specific direction on each image.
all_dlatents: The dlatents of each image, shape of [num_images,
dlatent_size].
generator: The generator model. Either StyleGAN or GLO.
discriminator: The discriminator model.
sindex: The style index.
style_min: The style min value in all images.
style_max: The style max value in all images.
class_index: The index of the class to check.
num_images: The number of images to do the disciminator_filter test.
label_size: The label size.
change_threshold: The maximal change allowed in the discriminator
prediction.
shift_size: The size to shift the style index.
effect_threshold: Used for choosing images that the classification was
changed enough.
sindex_offset: The offset of the style index if style_change_effect contains
some of the layers and not all styles.
"""
for style_sign_index in range(2):
images_idx = ((style_change_effect[:, style_sign_index, sindex,
class_index]) >
effect_threshold).nonzero()[0]
images_idx = images_idx[:num_images]
dlatents = all_dlatents[images_idx]
for i in range(len(images_idx)):
cur_dlatent = dlatents[i:i + 1]
(discriminator_orig,
discriminator_change) = get_discriminator_results_given_dlatent(
dlatent=cur_dlatent,
generator=generator,
discriminator=discriminator,
classifier=classifier,
class_index=class_index,
sindex=sindex + sindex_offset,
s_style_min=style_min,
s_style_max=style_max,
style_direction_index=style_sign_index,
shift_size=shift_size,
label_size=label_size)
if np.abs(discriminator_orig - discriminator_change) > change_threshold:
return False
return True
def find_significant_styles_image_fraction(
style_change_effect: np.ndarray,
num_indices: int,
class_index: int,
generator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
all_dlatents: np.ndarray,
style_min: np.ndarray,
style_max: np.ndarray,
effect_threshold: float = 0.2,
min_changed_images_fraction: float = 0.03,
label_size: int = 2,
sindex_offset: int = 0,
discriminator: Optional[tf.keras.models.Model] = None,
discriminator_threshold: float = 0.2) -> List[Tuple[int, int]]:
"""Returns indices in the style vector which affect the classifier.
Args:
style_change_effect: A shape of [num_images, 2, style_size, num_classes].
The effect of each change of style on specific direction on each image.
num_indices: Number of styles in the result.
class_index: The index of the class to visualize.
generator: The generator model. Either StyleGAN or GLO.
all_dlatents: The dlatents of each image, shape of [num_images,
dlatent_size].
style_min: An array with the min value for each style index.
style_max: An array with the max value for each style index.
effect_threshold: Minimal change of classifier output to be considered.
min_changed_images_fraction: Minimal fraction of images which are changed.
label_size: The label size.
sindex_offset: The offset of the style index if style_change_effect contains
some of the layers and not all styles.
discriminator: The discriminator model. If None, don't filter style indices.
discriminator_threshold: Used in discriminator_filter to define the maximal
change allowed in the discriminator prediction.
"""
effect_positive = np.sum(
style_change_effect[:, :, :, class_index] > effect_threshold, axis=0)
effect_positive = effect_positive.flatten()
all_sindices = []
sindices = np.argsort(effect_positive)[::-1]
if discriminator is not None:
print('Using discriminator...')
for sindex in sindices[:num_indices*2]:
if (effect_positive[sindex] <
min_changed_images_fraction * style_change_effect.shape[0]):
break
if discriminator is not None:
s_index = sindex % style_change_effect.shape[2]
if not discriminator_filter(
style_change_effect,
all_dlatents,
generator,
discriminator,
classifier,
s_index,
style_min[s_index + sindex_offset],
style_max[s_index + sindex_offset],
class_index,
label_size=label_size,
change_threshold=discriminator_threshold,
sindex_offset=sindex_offset):
continue
all_sindices.append(sindex)
if len(all_sindices) == num_indices:
break
return [(x // style_change_effect.shape[2],
(x % style_change_effect.shape[2]) + sindex_offset)
for x in all_sindices]
def find_significant_styles(
style_change_effect: np.ndarray,
num_indices: int,
class_index: int,
discriminator: Optional[tf.keras.models.Model],
generator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
all_dlatents: np.ndarray,
style_min: np.ndarray,
style_max: np.ndarray,
max_image_effect: float = 0.2,
label_size: int = 2,
discriminator_threshold: float = 0.2,
sindex_offset: int = 0) -> List[Tuple[int, int]]:
"""Returns indices in the style vector which affect the classifier.
Args:
style_change_effect: A shape of [num_images, 2, style_size, num_classes].
The effect of each change of style on specific direction on each image.
num_indices: Number of styles in the result.
class_index: The index of the class to visualize.
discriminator: The discriminator model. If None, don't filter style indices.
generator: The generator model. Either StyleGAN or GLO.
all_dlatents: The dlatents of each image, shape of [num_images,
dlatent_size].
style_min: An array with the min value for each style index.
style_max: An array with the max value for each style index.
max_image_effect: Ignore contributions of styles if the previously found
styles changed the probability of the image by more than this threshold.
label_size: The label size.
discriminator_threshold: Used in discriminator_filter to define the maximal
change allowed in the discriminator prediction.
sindex_offset: The offset of the style index if style_change_effect contains
some of the layers and not all styles.
"""
num_images = style_change_effect.shape[0]
style_effect_direction = np.maximum(
0, style_change_effect[:, :, :, class_index].reshape((num_images, -1)))
images_effect = np.zeros(num_images)
all_sindices = []
discriminator_removed = []
while len(all_sindices) < num_indices:
next_s = np.argmax(
np.mean(
style_effect_direction[images_effect < max_image_effect], axis=0))
if discriminator is not None:
sindex = next_s % style_change_effect.shape[2]
if sindex == 0:
break
if not discriminator_filter(
style_change_effect=style_change_effect,
all_dlatents=all_dlatents,
generator=generator,
discriminator=discriminator,
classifier=classifier,
sindex=sindex,
style_min=style_min[sindex + sindex_offset],
style_max=style_max[sindex + sindex_offset],
class_index=class_index,
label_size=label_size,
change_threshold=discriminator_threshold,
sindex_offset=sindex_offset):
style_effect_direction[:, next_s] = np.zeros(num_images)
discriminator_removed.append(sindex)
continue
all_sindices.append(next_s)
images_effect += style_effect_direction[:, next_s]
style_effect_direction[:, next_s] = 0
return [(x // style_change_effect.shape[2],
(x % style_change_effect.shape[2]) + sindex_offset)
for x in all_sindices]
def _float_features(values):
"""Returns a float_list from a float / double."""
return tf.train.Feature(float_list=tf.train.FloatList(value=values))
LAYER_SHAPES = []
for dense in generator.style_vector_calculator.style_dense_blocks:
LAYER_SHAPES.append(dense.dense_bias.weights[0].shape[1])
def sindex_to_layer_idx_and_index(generator: tf.keras.models.Model,
sindex: int) -> Tuple[int, int]:
global LAYER_SHAPES
layer_shapes_cumsum = np.concatenate([[0], np.cumsum(LAYER_SHAPES)])
layer_idx = (layer_shapes_cumsum <= sindex).nonzero()[0][-1]
return layer_idx, sindex - layer_shapes_cumsum[layer_idx]
def get_classifier_results(generator: tf.keras.models.Model,
expanded_dlatent: tf.Tensor,
use_softmax: bool = False):
image = call_synthesis(generator, expanded_dlatent)
image = tf.transpose(image, (0, 2, 3, 1))
results = classifier(image, training=False)
if use_softmax:
return tf.nn.softmax(results).numpy()[0]
else:
return results.numpy()[0]
def draw_on_image(image: np.ndarray, number: float,
font_file: str,
font_fill: Tuple[int, int, int] = (0, 0, 255)) -> np.ndarray:
"""Draws a number on the top left corner of the image."""
fnt = ImageFont.truetype(font_file, 20)
out_image = Image.fromarray((image * 127.5 + 127.5).astype(np.uint8))
draw = ImageDraw.Draw(out_image)
draw.multiline_text((10, 10), ('%.3f' % number), font=fnt, fill=font_fill)
return np.array(out_image)
def generate_change_image_given_dlatent(
dlatent: np.ndarray,
generator: tf.keras.models.Model,
classifier: Optional[tf.keras.models.Model],
class_index: int,
sindex: int,
s_style_min: float,
s_style_max: float,
style_direction_index: int,
shift_size: float,
label_size: int = 2,
) -> Tuple[np.ndarray, float, float]:
"""Modifies an image given the dlatent on a specific S-index.
Args:
dlatent: The image dlatent, with sape [dlatent_size].
generator: The generator model. Either StyleGAN or GLO.
classifier: The classifier to visualize.
class_index: The index of the class to visualize.
sindex: The specific style index to visualize.
s_style_min: The minimal value of the style index.
s_style_max: The maximal value of the style index.
style_direction_index: If 0 move s to it's min value otherwise to it's max
value.
shift_size: Factor of the shift of the style vector.
label_size: The size of the label.
Returns:
The image after the style index modification, and the output of
the classifier on this image.
"""
network_inputs = generator.style_vector_calculator(dlatent)
style_vector = tf.concat(
generator.style_vector_calculator(dlatent, training=False)[0],
axis=1).numpy()
orig_value = style_vector[0, sindex]
target_value = (s_style_min if style_direction_index == 0 else s_style_max)
weight_shift = shift_size * (target_value - orig_value)
layer_idx, in_idx = sindex_to_layer_idx_and_index(generator, sindex)
layer_one_hot = tf.expand_dims(
tf.one_hot(in_idx, network_inputs[0][layer_idx].shape[1]), 0)
network_inputs[0][layer_idx] += (weight_shift * layer_one_hot)
images_out = generator.g_synthesis(network_inputs, training=False)
images_out = tf.maximum(tf.minimum(images_out, 1), -1)
change_image = tf.transpose(images_out, [0, 2, 3, 1])
result = classifier(change_image, training=False)
change_prob = tf.nn.softmax(result).numpy()[0, class_index]
return change_image, change_prob
def get_discriminator_results_given_dlatent(
dlatent: np.ndarray,
generator: tf.keras.models.Model,
discriminator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
class_index: int,
sindex: int,
s_style_min: float,
s_style_max: float,
style_direction_index: int,
shift_size: float = 2,
label_size: int = 2,
) -> Tuple[float, float]:
"""Modifies an image given the dlatent on a specific S-index.
Args:
dlatent: The image dlatent, with sape [dlatent_size].
generator: The generator model. Either StyleGAN or GLO.
class_index: The index of the class to visualize.
sindex: The specific style index to visualize.
s_style_min: The minimal value of the style index.
s_style_max: The maximal value of the style index.
style_direction_index: If 0 move s to it's min value otherwise to it's max
value.
shift_size: Factor of the shift of the style vector.
label_size: The size of the label.
Returns:
The discriminator before and after.
"""
network_inputs = generator.style_vector_calculator(dlatent)
images_out = generator.g_synthesis(network_inputs, training=False)
images_out = tf.maximum(tf.minimum(images_out, 1), -1)
labels = tf.constant(dlatent[:, -label_size:], dtype=tf.float32)
discriminator_before = discriminator([images_out, labels], training=False)
# I am not using the classifier output here, because it is only one.
change_image, _ = (
generate_change_image_given_dlatent(dlatent, generator, classifier,
class_index, sindex,
s_style_min, s_style_max,
style_direction_index, shift_size,
label_size))
labels = tf.nn.softmax(classifier(change_image, training=False))
change_image_for_disc = tf.transpose(change_image, (0, 3, 1, 2))
discriminator_after = discriminator([change_image_for_disc, labels],
training=False)
return (discriminator_before, discriminator_after)
def generate_images_given_dlatent(
dlatent: np.ndarray,
generator: tf.keras.models.Model,
classifier: Optional[tf.keras.models.Model],
class_index: int,
sindex: int,
s_style_min: float,
s_style_max: float,
style_direction_index: int,
font_file: Optional[str],
shift_size: float = 2,
label_size: int = 2,
draw_results_on_image: bool = True,
resolution: int = 256,
) -> Tuple[np.ndarray, float, float, float, float]:
"""Modifies an image given the dlatent on a specific S-index.
Args:
dlatent: The image dlatent, with sape [dlatent_size].
generator: The generator model. Either StyleGAN or GLO.
classifier: The classifier to visualize.
class_index: The index of the class to visualize.
sindex: The specific style index to visualize.
s_style_min: The minimal value of the style index.
s_style_max: The maximal value of the style index.
style_direction_index: If 0 move s to it's min value otherwise to it's max
value.
font_file: A path to the font file for writing the probability on the image.
shift_size: Factor of the shift of the style vector.
label_size: The size of the label.
draw_results_on_image: Whether to draw the classifier outputs on the images.
Returns:
The image before and after the style index modification, and the outputs of
the classifier before and after the
modification.
"""
network_inputs = generator.style_vector_calculator(dlatent)
result_image = np.zeros((resolution, 2 * resolution, 3), np.uint8)
images_out = generator.g_synthesis(network_inputs, training=False)
images_out = tf.maximum(tf.minimum(images_out, 1), -1)
base_image = tf.transpose(images_out, [0, 2, 3, 1])
result = classifier(base_image, training=False)
base_prob = tf.nn.softmax(result).numpy()[0, class_index]
if draw_results_on_image:
result_image[:, :resolution, :] = draw_on_image(
base_image[0].numpy(), base_prob, font_file)
else:
result_image[:, :resolution, :] = (base_image[0].numpy() * 127.5 +
127.5).astype(np.uint8)
change_image, change_prob = (
generate_change_image_given_dlatent(dlatent, generator, classifier,
class_index, sindex,
s_style_min, s_style_max,
style_direction_index, shift_size,
label_size))
if draw_results_on_image:
result_image[:, resolution:, :] = draw_on_image(
change_image[0].numpy(), change_prob, font_file)
else:
result_image[:, resolution:, :] = (
np.maxiumum(np.minimum(change_image[0].numpy(), 1), -1) * 127.5 +
127.5).astype(np.uint8)
return (result_image, change_prob, base_prob)
def visualize_style(generator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
all_dlatents: np.ndarray,
style_change_effect: np.ndarray,
style_min: np.ndarray,
style_max: np.ndarray,
sindex: int,
style_direction_index: int,
max_images: int,
shift_size: float,
font_file: str,
label_size: int = 2,
class_index: int = 0,
effect_threshold: float = 0.3,
seed: Optional[int] = None,
allow_both_directions_change: bool = False,
draw_results_on_image: bool = True) -> np.ndarray:
"""Returns an image visualizing the effect of a specific S-index.
Args:
generator: The generator model. Either StyleGAN or GLO.
classifier: The classifier to visualize.
all_dlatents: An array with shape [num_images, dlatent_size].
style_change_effect: A shape of [num_images, 2, style_size, num_classes].
The effect of each change of style on specific direction on each image.
style_min: The minimal value of each style, with shape [style_size].
style_max: The maximal value of each style, with shape [style_size].
sindex: The specific style index to visualize.
style_direction_index: If 0 move s to its min value otherwise to its max
value.
max_images: Maximal number of images to visualize.
shift_size: Factor of the shift of the style vector.
font_file: A path to the font file for writing the probability on the image.
label_size: The size of the label.
class_index: The index of the class to visualize.
effect_threshold: Choose images whose effect was at least this number.
seed: If given, use this as a seed to the random shuffling of the images.
allow_both_directions_change: Whether to allow both increasing and
decreasing the classifiaction (used for age).
draw_results_on_image: Whether to draw the classifier outputs on the images.
"""
# Choose the dlatent indices to visualize
if allow_both_directions_change:
images_idx = (np.abs(style_change_effect[:, style_direction_index, sindex,
class_index]) >
effect_threshold).nonzero()[0]
else:
images_idx = ((style_change_effect[:, style_direction_index, sindex,
class_index]) >
effect_threshold).nonzero()[0]
if images_idx.size == 0:
return np.array([])
if seed is not None:
np.random.seed(seed)
np.random.shuffle(images_idx)
images_idx = images_idx[:min(max_images*10, len(images_idx))]
dlatents = all_dlatents[images_idx]
result_images = []
for i in range(len(images_idx)):
cur_dlatent = dlatents[i:i + 1]
(result_image, base_prob, change_prob) = generate_images_given_dlatent(
dlatent=cur_dlatent,
generator=generator,
classifier=classifier,
class_index=class_index,
sindex=sindex,
s_style_min=style_min[sindex],
s_style_max=style_max[sindex],
style_direction_index=style_direction_index,
font_file=font_file,
shift_size=shift_size,
label_size=label_size,
draw_results_on_image=draw_results_on_image)
if np.abs(change_prob - base_prob) < effect_threshold:
continue
result_images.append(result_image)
if len(result_images) == max_images:
break
if len(result_images) < 3:
# No point in returning results with very little images
return np.array([])
return np.concatenate(result_images[:max_images], axis=0)
def visualize_style_by_distance_in_s(
generator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
all_dlatents: np.ndarray,
all_style_vectors_distances: np.ndarray,
style_min: np.ndarray,
style_max: np.ndarray,
sindex: int,
style_sign_index: int,
max_images: int,
shift_size: float,
font_file: str,
label_size: int = 2,
class_index: int = 0,
draw_results_on_image: bool = True,
effect_threshold: float = 0.1) -> np.ndarray:
"""Returns an image visualizing the effect of a specific S-index.
Args:
generator: The generator model. Either StyleGAN or GLO.
classifier: The classifier to visualize.
all_dlatents: An array with shape [num_images, dlatent_size].
all_style_vectors_distances: A shape of [num_images, style_size, 2].
The distance each style from the min and max values on each image.
style_min: The minimal value of each style, with shape [style_size].
style_max: The maximal value of each style, with shape [style_size].
sindex: The specific style index to visualize.
style_sign_index: If 0 move s to its min value otherwise to its max
value.
max_images: Maximal number of images to visualize.
shift_size: Factor of the shift of the style vector.
font_file: A path to the font file for writing the probability on the image.
label_size: The size of the label.
class_index: The index of the class to visualize.
draw_results_on_image: Whether to draw the classifier outputs on the images.
"""
# Choose the dlatent indices to visualize
images_idx = np.argsort(
all_style_vectors_distances[:, sindex, style_sign_index])[::-1]
if images_idx.size == 0:
return np.array([])
images_idx = images_idx[:min(max_images*10, len(images_idx))]
dlatents = all_dlatents[images_idx]
result_images = []
for i in range(len(images_idx)):
cur_dlatent = dlatents[i:i + 1]
(result_image, change_prob, base_prob) = generate_images_given_dlatent(
dlatent=cur_dlatent,
generator=generator,
classifier=classifier,
class_index=class_index,
sindex=sindex,
s_style_min=style_min[sindex],
s_style_max=style_max[sindex],
style_direction_index=style_sign_index,
font_file=font_file,
shift_size=shift_size,
label_size=label_size,
draw_results_on_image=draw_results_on_image)
if (change_prob - base_prob) < effect_threshold:
continue
result_images.append(result_image)
if len(result_images) < 3:
# No point in returning results with very little images
return np.array([])
return np.concatenate(result_images[:max_images], axis=0)
```
# Latents extraction:
We don't provide the dataset_provider, so we will load the dlatents from a precomputed np.array.
Here we present how to run the encoder on one image, to calculate one dlatent (we pre-calculate for 250)
`TODO:` remove this code (or replace the image with a better reconstruction)
```
#@title Load the precomputed dlatents (already concatenated to the labels)
dlatents_url = bucket_path + 'dlatents.pkl'
r = requests.get(dlatents_url)
dlatents = cPickle.loads(r.content)
#@title Generate image from the dlatent
dlatent_index = 4#@param {type: "integer"}
expanded_dlatent_tmp = tf.tile(
tf.expand_dims(dlatents[dlatent_index][1], 1),
[1, num_layers, 1])
rec_image = call_synthesis(generator,
expanded_dlatent_tmp,
num_layers=num_layers)
image = rec_image.numpy()[0]
show_image(image)
```
## Run the Generation step of AttFind
Do not run if loaded from precomputed dlatents.
```
#@title Generate SSpace per index (min and max)
values_per_index = collections.defaultdict(list)
for _, dlatent in dlatents:
# Get the style vector:
s_img = tf.concat(generator.style_vector_calculator(
dlatent, training=False)[0], axis=1).numpy()[0]
for i, s_val in enumerate(s_img):
values_per_index[i].append(s_val)
values_per_index = dict(values_per_index)
s_indices_num = len(values_per_index.keys())
minimums = [min(values_per_index[i]) for i in range(s_indices_num)]
maximums = [max(values_per_index[i]) for i in range(s_indices_num)]
#@title SSpace calculation (this is also very heavy, skip to next cell to load precomputed ones) {form-width: '20%'}
s_shift_size = 1 # @param
data_path = '/tmp/celab_a_age/examples_1.tfrecord' #@param {type: 'string'}
with tf.io.TFRecordWriter(data_path) as writer:
for dlatent_index, dlatent in dlatents:
print(dlatent_index)
expanded_dlatent = tf.tile(
tf.expand_dims(dlatent, 1),
[1, num_layers, 1])
base_prob = get_classifier_results(generator, expanded_dlatent)
classifier_results = []
for sindex in tqdm.tqdm(range(0, s_indices_num)):
layer_idx, weight_idx = sindex_to_layer_idx_and_index(generator, sindex)
layer = generator.style_vector_calculator.style_dense_blocks[layer_idx]
layer_size = layer.dense_bias.weights[0].shape[1]
# Get the style vector.
s_vals = tf.concat(
generator.style_vector_calculator(dlatent, training=False)[0],
axis=1).numpy()[0]
s_shift_down = (minimums[sindex] - s_vals[sindex]) * s_shift_size
s_shift_up = (maximums[sindex] - s_vals[sindex]) * s_shift_size
s_shift_d = s_shift_down * tf.expand_dims(tf.one_hot(weight_idx,
layer_size), axis=0)
layer.dense_bias.weights[0].assign_add(s_shift_d)
classifier_results.extend(
get_classifier_results(generator, expanded_dlatent) - base_prob)
layer.dense_bias.weights[0].assign_add(-s_shift_d)
s_shift_u = s_shift_up * tf.expand_dims(
tf.one_hot(weight_idx, layer_size), axis=0)
layer.dense_bias.weights[0].assign_add(s_shift_u)
classifier_results.extend(
get_classifier_results(generator, expanded_dlatent) - base_prob)
layer.dense_bias.weights[0].assign_add(-s_shift_u)
feature = {}
feature['base_prob'] = _float_features(base_prob.flatten())
feature['dlatent'] = _float_features(dlatent.flatten())
feature['result'] = _float_features(np.array(classifier_results).flatten())
example_proto = tf.train.Example(features=tf.train.Features(feature=feature))
writer.write(example_proto.SerializeToString())
```
## Run the extraction step of AttFind
```
#@title Load effect data from the tfrecord {form-width: '20%'}
examples_url = bucket_path + 'examples_1.tfrecord'
r = requests.get(examples_url)
data_path = path + 'examples_1.tfrecord'
open(data_path, 'wb').write(r.content)
num_classes = 2
print(f'Loaded dataset: {data_path}')
table = tf.data.TFRecordDataset([data_path])
# Read sspace tfrecord unwrapped:
style_change_effect = []
dlatents = []
base_probs = []
for raw_record in table:
example = tf.train.Example()
example.ParseFromString(raw_record.numpy())
dlatents.append(
np.array(example.features.feature['dlatent'].float_list.value))
seffect = np.array(
example.features.feature['result'].float_list.value).reshape(
(-1, 2, num_classes))
style_change_effect.append(seffect.transpose([1, 0, 2]))
base_probs.append(
np.array(example.features.feature['base_prob'].float_list.value))
style_change_effect = np.array(style_change_effect)
dlatents = np.array(dlatents)
W_values, style_change_effect, base_probs = dlatents, style_change_effect, np.array(base_probs)
style_change_effect = filter_unstable_images(style_change_effect, effect_threshold=2)
all_style_vectors = tf.concat(generator.style_vector_calculator(W_values, training=False)[0], axis=1).numpy()
style_min = np.min(all_style_vectors, axis=0)
style_max = np.max(all_style_vectors, axis=0)
all_style_vectors_distances = np.zeros((all_style_vectors.shape[0], all_style_vectors.shape[1], 2))
all_style_vectors_distances[:,:, 0] = all_style_vectors - np.tile(style_min, (all_style_vectors.shape[0], 1))
all_style_vectors_distances[:,:, 1] = np.tile(style_max, (all_style_vectors.shape[0], 1)) - all_style_vectors
#@title Split by class
all_labels = np.argmax(base_probs, axis=1)
style_effect_classes = {}
W_classes = {}
style_vectors_distances_classes = {}
all_style_vectors_classes = {}
for img_ind in range(label_size):
img_inx = np.array([i for i in range(all_labels.shape[0])
if all_labels[i] == img_ind])
curr_style_effect = np.zeros((len(img_inx), style_change_effect.shape[1],
style_change_effect.shape[2], style_change_effect.shape[3]))
curr_w = np.zeros((len(img_inx), W_values.shape[1]))
curr_style_vector_distances = np.zeros((len(img_inx), style_change_effect.shape[2], 2))
for k, i in enumerate(img_inx):
curr_style_effect[k, :, :] = style_change_effect[i, :, :, :]
curr_w[k, :] = W_values[i, :]
curr_style_vector_distances[k, :, :] = all_style_vectors_distances[i, :, :]
style_effect_classes[img_ind] = curr_style_effect
W_classes[img_ind] = curr_w
style_vectors_distances_classes[img_ind] = curr_style_vector_distances
all_style_vectors_classes[img_ind] = all_style_vectors[img_inx]
print(f'Class {img_ind}, {len(img_inx)} images.')
#@title Significant S values - combined {form-width: '20%'}
label_size_clasifier = 2 #@param
num_indices = 8 #@param
effect_threshold = 0.2 #@param
use_discriminator = False #@param {type: 'boolean'}
discriminator_model = discriminator if use_discriminator else None
s_indices_and_signs_dict = {}
for class_index in [0, 1]:
split_ind = 1 - class_index
all_s = style_effect_classes[split_ind]
all_w = W_classes[split_ind]
# Find s indicies
s_indices_and_signs = find_significant_styles(
style_change_effect=all_s,
num_indices=num_indices,
class_index=class_index,
discriminator=discriminator_model,
generator=generator,
classifier=classifier,
all_dlatents=all_w,
style_min=style_min,
style_max=style_max,
max_image_effect=effect_threshold*5,
label_size=label_size_clasifier,
discriminator_threshold=0.2,
sindex_offset=0)
s_indices_and_signs_dict[class_index] = s_indices_and_signs
# Combine the style indicies for the two classes.
sindex_class_0 = [sindex for _, sindex in s_indices_and_signs_dict[0]]
all_sindex_joined_class_0 = [(1 - direction, sindex) for direction, sindex in
s_indices_and_signs_dict[1] if sindex not in sindex_class_0]
all_sindex_joined_class_0 += s_indices_and_signs_dict[0]
scores = []
for direction, sindex in all_sindex_joined_class_0:
other_direction = 1 if direction == 0 else 0
curr_score = np.mean(style_change_effect[:, direction, sindex, 0]) + np.mean(style_change_effect[:, other_direction, sindex, 1])
scores.append(curr_score)
s_indices_and_signs = [all_sindex_joined_class_0[i] for i in np.argsort(scores)[::-1]]
print('Directions and style indices for moving from class 1 to class 0 = ', s_indices_and_signs[:num_indices])
print('Use the other direction to move for class 0 to 1.')
#@title Significant S values - multi class one vs. all (this can also be used as one vs. one, using split_by_class=True and define class_index_from) {form-width: '20%'}
label_size_clasifier = 2 #@param {type:"integer"}
num_indices = 8#@param
effect_threshold = 0.1 #@param
use_discriminator = False #@param {type: 'boolean'}
class_index_to = 0 #@param {type:"integer"}
discriminator_model = discriminator if use_discriminator else None
split_by_class = False #@param {type: 'boolean'}
class_index_from = 1 #@param {type:"integer"}
if split_by_class:
split_ind = class_index_from
all_s = style_effect_classes[split_ind]
all_w = W_classes[split_ind]
else:
all_s = style_change_effect
all_w = W_values
# Find s indicies
s_indices_and_signs = find_significant_styles(
style_change_effect=all_s,
num_indices=num_indices,
class_index=class_index_to,
discriminator=discriminator_model,
generator=generator,
classifier=classifier,
all_dlatents=all_w,
style_min=style_min,
style_max=style_max,
max_image_effect=effect_threshold*5,
label_size=label_size_clasifier,
discriminator_threshold=0.2,
sindex_offset=0)
print(f'Directions and style indices for moving from all classes to class {class_index_to} = ', s_indices_and_signs[:num_indices])
#@title Visualize s-index {form-width: '20%'}
max_images = 10 #@param
sindex = 5300#@param
class_index = 0#@param {type: "integer"}
shift_sign = "1" #@param [0, 1]
wsign_index = int(shift_sign)
shift_size = 1#@param
effect_threshold = 0.2#@param
split_by_class = True #@param {type:"boolean"}
select_images_by_s_distance = True #@param {type:"boolean"}
draw_results_on_image = True #@param {type:"boolean"}
if split_by_class:
split_ind = 1 if class_index == 0 else 0
all_s = style_effect_classes[split_ind]
all_w = W_classes[split_ind]
all_s_distances = style_vectors_distances_classes[split_ind]
else:
all_s = style_change_effect
all_w = W_values
all_s_distances = all_style_vectors_distances
font_file = '/tmp/arialuni.ttf'
if not os.path.exists(font_file):
r = requests.get('https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/ipwn/arialuni.ttf')
open(font_file, 'wb').write(r.content)
if not select_images_by_s_distance:
yy = visualize_style(generator,
classifier,
all_w,
all_s,
style_min,
style_max,
sindex,
wsign_index,
max_images=max_images,
shift_size=shift_size,
font_file=font_file,
label_size=label_size,
class_index=class_index,
effect_threshold=effect_threshold,
draw_results_on_image=draw_results_on_image)
else:
yy = visualize_style_by_distance_in_s(
generator,
classifier,
all_w,
all_s_distances,
style_min,
style_max,
sindex,
wsign_index,
max_images=max_images,
shift_size=shift_size,
font_file=font_file,
label_size=label_size,
class_index=class_index,
effect_threshold=effect_threshold,
draw_results_on_image=draw_results_on_image)
if yy.size > 0:
show_image(yy)
else:
print('no images found')
#@title Show animation {form-width: '20%'}
import matplotlib.animation
from IPython.display import HTML
ani = make_animation(yy, resolution)
HTML(ani.to_jshtml())
#@title Show the 4 top attributes - as displayed in Fig.4 (b)
draw_probabilities_on_image = True #@param {type: "boolean"}
index_to_naming = {0: "Skin Pigminatation", 1: "Eyebrow Thickness", 2: "Add/Remove Glasses", 3: "Dark/White Hair"}
images_list = [[0, 4], [16, 17], [18, 18], [3, 14]]
max_images = 20
shift_sizes = [(2, 1.5),(1, 1),(1, 1),(1.5, 2)]
effect_threshold = 0.05
font_file = '/tmp/arialuni.ttf'
if not os.path.exists(font_file):
gfile.Copy('/google_src/head/depot/google3/googledata/third_party/fonts/ascender/arialuni.ttf', font_file)
for i, (direction, sindex) in enumerate(s_indices_and_signs[:4]):
images_s = np.zeros((resolution * 2, resolution * 2, 3)).astype(np.uint8)
for d in [direction, 1 - direction]:
# Take only images from the offsite class
class_index = 0 if d == direction else 1
split_ind = 1 if d == direction else 0
all_s = style_effect_classes[split_ind]
all_w = W_classes[split_ind]
all_s_distances = style_vectors_distances_classes[split_ind]
# Generate images
yy = visualize_style_by_distance_in_s(
generator,
classifier,
all_w,
all_s_distances,
style_min,
style_max,
sindex,
d,
max_images=max_images,
shift_size=shift_sizes[i][class_index],
font_file=font_file,
label_size=label_size,
class_index=class_index,
effect_threshold=effect_threshold,
draw_results_on_image=draw_probabilities_on_image)
for n in range(2):
images_s[n * resolution: (n + 1) * resolution, class_index * resolution: (class_index + 1) * resolution, :] = yy[(images_list[i][class_index]) * resolution: (images_list[i][class_index] + 1) * resolution, n * resolution: (n + 1) * resolution, :]
print(f'Attribute {i} {index_to_naming[i]}: \n(Original images are on the first row, the probabilities displayed are for the other class - left column for being old, write column for being young)')
show_image(images_s)
```
|
github_jupyter
|
#@title Imports
from typing import Optional, Tuple, List
import six.moves.cPickle as cPickle
import tensorflow as tf
import numpy as np
import requests
import tqdm
import collections
import os
import zipfile
from matplotlib import pyplot as plt
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from io import BytesIO
import IPython.display
#@title Load the encoder, the discriminator, the generator and the classifier (slow!)
path = '/tmp/celab_a_age/' #@param {type: 'string'}
bucket_path = 'https://storage.googleapis.com/explaining-in-style/celeb_a_age/'
if not os.path.exists(path):
os.mkdir(path)
def get_path_from_bucket(bucket_url, path):
r = requests.get(bucket_url)
filename = os.path.split(bucket_url)[-1].replace('.zip', '')
zip_ref = zipfile.ZipFile(BytesIO(r.content))
zip_ref.extractall(path)
return os.path.join(path, filename)
num_layers = 14
label_size = 2
resolution = 256
generator = tf.keras.models.load_model(get_path_from_bucket(bucket_path + 'generator.savedmodel.zip', path))
encoder = tf.keras.models.load_model(get_path_from_bucket(bucket_path + 'encoder.savedmodel.zip', path))
discriminator = tf.keras.models.load_model(get_path_from_bucket(bucket_path + 'discriminator.savedmodel.zip', path))
classifier = tf.keras.models.load_model(get_path_from_bucket(bucket_path + 'mobilenet.savedmodel.zip', path))
#@title Utils {form-width: '20%'}
def make_animation(image: np.ndarray,
resolution: int,
figsize: Tuple[int, int] = (20, 8)):
fig = plt.figure(1, figsize=figsize)
_ = plt.gca()
def transpose_image(image):
image_reshape = image.reshape([-1, resolution, resolution, 3])
return image_reshape.transpose([1, 0, 2, 3]).reshape([resolution, -1, 3])
im = plt.imshow(transpose_image(image[:, :resolution, :]),
interpolation='none')
def animate_func(i):
im.set_array(transpose_image(image[:, resolution*i:resolution*(i+1), :]))
return [im]
animation = matplotlib.animation.FuncAnimation(
fig, animate_func, frames=image.shape[1] // resolution, interval=600)
plt.close(1)
return animation
def show_image(image, fmt='png'):
if image.dtype == np.float32:
image = np.uint8(image * 127.5 + 127.5)
if image.shape[0] == 3:
image = np.transpose(image, (1, 2, 0))
bytes_io = BytesIO()
Image.fromarray(image).save(bytes_io, fmt)
IPython.display.display(IPython.display.Image(data=bytes_io.getvalue()))
def filter_unstable_images(style_change_effect: np.ndarray,
effect_threshold: float = 0.3,
num_indices_threshold: int = 750) -> np.ndarray:
"""Filters out images which are affected by too many S values."""
unstable_images = (
np.sum(np.abs(style_change_effect) > effect_threshold, axis=(1, 2, 3)) >
num_indices_threshold)
style_change_effect[unstable_images] = 0
return style_change_effect
@tf.function
def call_synthesis(generator: tf.keras.models.Model,
dlatents_in: tf.Tensor,
conditioning_in: Optional[tf.Tensor] = None,
labels_in: Optional[tf.Tensor] = None,
training: bool = False,
num_layers: int = 14,
dlatent_size: int = 512) -> tf.Tensor:
"""Calls the synthesis.
Args:
dlatents_in: the intermediate latent representation of shape [batch size,
num_layers, dlatent_size].
conditioning_in: Conditioning input to the synthesis network (can be an
image or output from an encoder) of shape [minibatch, channels,
resolution, resolution]. Set to None if unused.
labels_in: of shape [batch_size, label_size]. Set to None if unused.
training: Whether this is a training call.
Returns:
The output images and optional latent vector.
"""
if labels_in is not None:
zero_labels = tf.zeros_like(labels_in)
dlatents_labels = tf.tile(tf.expand_dims(labels, 1), [1, num_layers, 1])
if dlatent_size > 0:
dlatents_expanded = tf.concat([dlatents_in, dlatents_labels], axis=2)
else:
dlatents_expanded = dlatents_labels
else:
if dlatent_size == 0:
raise ValueError('Dlatents are empty and no labels were provided.')
dlatents_expanded = dlatents_in
# Evaluate synthesis network.
style_vector_blocks, style_vector_torgb = generator.style_vector_calculator(
dlatents_expanded[:, 0], training=training)
if conditioning_in is not None:
network_inputs = (style_vector_blocks, style_vector_torgb,
conditioning_in)
else:
network_inputs = (style_vector_blocks, style_vector_torgb)
synthesis_results = generator.g_synthesis(network_inputs, training=training)
# Return requested outputs.
return tf.maximum(tf.minimum(synthesis_results, 1), -1)
def discriminator_filter(style_change_effect: np.ndarray,
all_dlatents: np.ndarray,
generator: tf.keras.models.Model,
discriminator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
sindex: int,
style_min: float,
style_max: float,
class_index: int,
num_images: int = 10,
label_size: int = 2,
change_threshold: float = 0.5,
shift_size: float = 2,
effect_threshold: float = 0.2,
sindex_offset: int = 0) -> bool:
"""Returns false if changing the style index adds artifacts to the images.
Args:
style_change_effect: A shape of [num_images, 2, style_size, num_classes].
The effect of each change of style on specific direction on each image.
all_dlatents: The dlatents of each image, shape of [num_images,
dlatent_size].
generator: The generator model. Either StyleGAN or GLO.
discriminator: The discriminator model.
sindex: The style index.
style_min: The style min value in all images.
style_max: The style max value in all images.
class_index: The index of the class to check.
num_images: The number of images to do the disciminator_filter test.
label_size: The label size.
change_threshold: The maximal change allowed in the discriminator
prediction.
shift_size: The size to shift the style index.
effect_threshold: Used for choosing images that the classification was
changed enough.
sindex_offset: The offset of the style index if style_change_effect contains
some of the layers and not all styles.
"""
for style_sign_index in range(2):
images_idx = ((style_change_effect[:, style_sign_index, sindex,
class_index]) >
effect_threshold).nonzero()[0]
images_idx = images_idx[:num_images]
dlatents = all_dlatents[images_idx]
for i in range(len(images_idx)):
cur_dlatent = dlatents[i:i + 1]
(discriminator_orig,
discriminator_change) = get_discriminator_results_given_dlatent(
dlatent=cur_dlatent,
generator=generator,
discriminator=discriminator,
classifier=classifier,
class_index=class_index,
sindex=sindex + sindex_offset,
s_style_min=style_min,
s_style_max=style_max,
style_direction_index=style_sign_index,
shift_size=shift_size,
label_size=label_size)
if np.abs(discriminator_orig - discriminator_change) > change_threshold:
return False
return True
def find_significant_styles_image_fraction(
style_change_effect: np.ndarray,
num_indices: int,
class_index: int,
generator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
all_dlatents: np.ndarray,
style_min: np.ndarray,
style_max: np.ndarray,
effect_threshold: float = 0.2,
min_changed_images_fraction: float = 0.03,
label_size: int = 2,
sindex_offset: int = 0,
discriminator: Optional[tf.keras.models.Model] = None,
discriminator_threshold: float = 0.2) -> List[Tuple[int, int]]:
"""Returns indices in the style vector which affect the classifier.
Args:
style_change_effect: A shape of [num_images, 2, style_size, num_classes].
The effect of each change of style on specific direction on each image.
num_indices: Number of styles in the result.
class_index: The index of the class to visualize.
generator: The generator model. Either StyleGAN or GLO.
all_dlatents: The dlatents of each image, shape of [num_images,
dlatent_size].
style_min: An array with the min value for each style index.
style_max: An array with the max value for each style index.
effect_threshold: Minimal change of classifier output to be considered.
min_changed_images_fraction: Minimal fraction of images which are changed.
label_size: The label size.
sindex_offset: The offset of the style index if style_change_effect contains
some of the layers and not all styles.
discriminator: The discriminator model. If None, don't filter style indices.
discriminator_threshold: Used in discriminator_filter to define the maximal
change allowed in the discriminator prediction.
"""
effect_positive = np.sum(
style_change_effect[:, :, :, class_index] > effect_threshold, axis=0)
effect_positive = effect_positive.flatten()
all_sindices = []
sindices = np.argsort(effect_positive)[::-1]
if discriminator is not None:
print('Using discriminator...')
for sindex in sindices[:num_indices*2]:
if (effect_positive[sindex] <
min_changed_images_fraction * style_change_effect.shape[0]):
break
if discriminator is not None:
s_index = sindex % style_change_effect.shape[2]
if not discriminator_filter(
style_change_effect,
all_dlatents,
generator,
discriminator,
classifier,
s_index,
style_min[s_index + sindex_offset],
style_max[s_index + sindex_offset],
class_index,
label_size=label_size,
change_threshold=discriminator_threshold,
sindex_offset=sindex_offset):
continue
all_sindices.append(sindex)
if len(all_sindices) == num_indices:
break
return [(x // style_change_effect.shape[2],
(x % style_change_effect.shape[2]) + sindex_offset)
for x in all_sindices]
def find_significant_styles(
style_change_effect: np.ndarray,
num_indices: int,
class_index: int,
discriminator: Optional[tf.keras.models.Model],
generator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
all_dlatents: np.ndarray,
style_min: np.ndarray,
style_max: np.ndarray,
max_image_effect: float = 0.2,
label_size: int = 2,
discriminator_threshold: float = 0.2,
sindex_offset: int = 0) -> List[Tuple[int, int]]:
"""Returns indices in the style vector which affect the classifier.
Args:
style_change_effect: A shape of [num_images, 2, style_size, num_classes].
The effect of each change of style on specific direction on each image.
num_indices: Number of styles in the result.
class_index: The index of the class to visualize.
discriminator: The discriminator model. If None, don't filter style indices.
generator: The generator model. Either StyleGAN or GLO.
all_dlatents: The dlatents of each image, shape of [num_images,
dlatent_size].
style_min: An array with the min value for each style index.
style_max: An array with the max value for each style index.
max_image_effect: Ignore contributions of styles if the previously found
styles changed the probability of the image by more than this threshold.
label_size: The label size.
discriminator_threshold: Used in discriminator_filter to define the maximal
change allowed in the discriminator prediction.
sindex_offset: The offset of the style index if style_change_effect contains
some of the layers and not all styles.
"""
num_images = style_change_effect.shape[0]
style_effect_direction = np.maximum(
0, style_change_effect[:, :, :, class_index].reshape((num_images, -1)))
images_effect = np.zeros(num_images)
all_sindices = []
discriminator_removed = []
while len(all_sindices) < num_indices:
next_s = np.argmax(
np.mean(
style_effect_direction[images_effect < max_image_effect], axis=0))
if discriminator is not None:
sindex = next_s % style_change_effect.shape[2]
if sindex == 0:
break
if not discriminator_filter(
style_change_effect=style_change_effect,
all_dlatents=all_dlatents,
generator=generator,
discriminator=discriminator,
classifier=classifier,
sindex=sindex,
style_min=style_min[sindex + sindex_offset],
style_max=style_max[sindex + sindex_offset],
class_index=class_index,
label_size=label_size,
change_threshold=discriminator_threshold,
sindex_offset=sindex_offset):
style_effect_direction[:, next_s] = np.zeros(num_images)
discriminator_removed.append(sindex)
continue
all_sindices.append(next_s)
images_effect += style_effect_direction[:, next_s]
style_effect_direction[:, next_s] = 0
return [(x // style_change_effect.shape[2],
(x % style_change_effect.shape[2]) + sindex_offset)
for x in all_sindices]
def _float_features(values):
"""Returns a float_list from a float / double."""
return tf.train.Feature(float_list=tf.train.FloatList(value=values))
LAYER_SHAPES = []
for dense in generator.style_vector_calculator.style_dense_blocks:
LAYER_SHAPES.append(dense.dense_bias.weights[0].shape[1])
def sindex_to_layer_idx_and_index(generator: tf.keras.models.Model,
sindex: int) -> Tuple[int, int]:
global LAYER_SHAPES
layer_shapes_cumsum = np.concatenate([[0], np.cumsum(LAYER_SHAPES)])
layer_idx = (layer_shapes_cumsum <= sindex).nonzero()[0][-1]
return layer_idx, sindex - layer_shapes_cumsum[layer_idx]
def get_classifier_results(generator: tf.keras.models.Model,
expanded_dlatent: tf.Tensor,
use_softmax: bool = False):
image = call_synthesis(generator, expanded_dlatent)
image = tf.transpose(image, (0, 2, 3, 1))
results = classifier(image, training=False)
if use_softmax:
return tf.nn.softmax(results).numpy()[0]
else:
return results.numpy()[0]
def draw_on_image(image: np.ndarray, number: float,
font_file: str,
font_fill: Tuple[int, int, int] = (0, 0, 255)) -> np.ndarray:
"""Draws a number on the top left corner of the image."""
fnt = ImageFont.truetype(font_file, 20)
out_image = Image.fromarray((image * 127.5 + 127.5).astype(np.uint8))
draw = ImageDraw.Draw(out_image)
draw.multiline_text((10, 10), ('%.3f' % number), font=fnt, fill=font_fill)
return np.array(out_image)
def generate_change_image_given_dlatent(
dlatent: np.ndarray,
generator: tf.keras.models.Model,
classifier: Optional[tf.keras.models.Model],
class_index: int,
sindex: int,
s_style_min: float,
s_style_max: float,
style_direction_index: int,
shift_size: float,
label_size: int = 2,
) -> Tuple[np.ndarray, float, float]:
"""Modifies an image given the dlatent on a specific S-index.
Args:
dlatent: The image dlatent, with sape [dlatent_size].
generator: The generator model. Either StyleGAN or GLO.
classifier: The classifier to visualize.
class_index: The index of the class to visualize.
sindex: The specific style index to visualize.
s_style_min: The minimal value of the style index.
s_style_max: The maximal value of the style index.
style_direction_index: If 0 move s to it's min value otherwise to it's max
value.
shift_size: Factor of the shift of the style vector.
label_size: The size of the label.
Returns:
The image after the style index modification, and the output of
the classifier on this image.
"""
network_inputs = generator.style_vector_calculator(dlatent)
style_vector = tf.concat(
generator.style_vector_calculator(dlatent, training=False)[0],
axis=1).numpy()
orig_value = style_vector[0, sindex]
target_value = (s_style_min if style_direction_index == 0 else s_style_max)
weight_shift = shift_size * (target_value - orig_value)
layer_idx, in_idx = sindex_to_layer_idx_and_index(generator, sindex)
layer_one_hot = tf.expand_dims(
tf.one_hot(in_idx, network_inputs[0][layer_idx].shape[1]), 0)
network_inputs[0][layer_idx] += (weight_shift * layer_one_hot)
images_out = generator.g_synthesis(network_inputs, training=False)
images_out = tf.maximum(tf.minimum(images_out, 1), -1)
change_image = tf.transpose(images_out, [0, 2, 3, 1])
result = classifier(change_image, training=False)
change_prob = tf.nn.softmax(result).numpy()[0, class_index]
return change_image, change_prob
def get_discriminator_results_given_dlatent(
dlatent: np.ndarray,
generator: tf.keras.models.Model,
discriminator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
class_index: int,
sindex: int,
s_style_min: float,
s_style_max: float,
style_direction_index: int,
shift_size: float = 2,
label_size: int = 2,
) -> Tuple[float, float]:
"""Modifies an image given the dlatent on a specific S-index.
Args:
dlatent: The image dlatent, with sape [dlatent_size].
generator: The generator model. Either StyleGAN or GLO.
class_index: The index of the class to visualize.
sindex: The specific style index to visualize.
s_style_min: The minimal value of the style index.
s_style_max: The maximal value of the style index.
style_direction_index: If 0 move s to it's min value otherwise to it's max
value.
shift_size: Factor of the shift of the style vector.
label_size: The size of the label.
Returns:
The discriminator before and after.
"""
network_inputs = generator.style_vector_calculator(dlatent)
images_out = generator.g_synthesis(network_inputs, training=False)
images_out = tf.maximum(tf.minimum(images_out, 1), -1)
labels = tf.constant(dlatent[:, -label_size:], dtype=tf.float32)
discriminator_before = discriminator([images_out, labels], training=False)
# I am not using the classifier output here, because it is only one.
change_image, _ = (
generate_change_image_given_dlatent(dlatent, generator, classifier,
class_index, sindex,
s_style_min, s_style_max,
style_direction_index, shift_size,
label_size))
labels = tf.nn.softmax(classifier(change_image, training=False))
change_image_for_disc = tf.transpose(change_image, (0, 3, 1, 2))
discriminator_after = discriminator([change_image_for_disc, labels],
training=False)
return (discriminator_before, discriminator_after)
def generate_images_given_dlatent(
dlatent: np.ndarray,
generator: tf.keras.models.Model,
classifier: Optional[tf.keras.models.Model],
class_index: int,
sindex: int,
s_style_min: float,
s_style_max: float,
style_direction_index: int,
font_file: Optional[str],
shift_size: float = 2,
label_size: int = 2,
draw_results_on_image: bool = True,
resolution: int = 256,
) -> Tuple[np.ndarray, float, float, float, float]:
"""Modifies an image given the dlatent on a specific S-index.
Args:
dlatent: The image dlatent, with sape [dlatent_size].
generator: The generator model. Either StyleGAN or GLO.
classifier: The classifier to visualize.
class_index: The index of the class to visualize.
sindex: The specific style index to visualize.
s_style_min: The minimal value of the style index.
s_style_max: The maximal value of the style index.
style_direction_index: If 0 move s to it's min value otherwise to it's max
value.
font_file: A path to the font file for writing the probability on the image.
shift_size: Factor of the shift of the style vector.
label_size: The size of the label.
draw_results_on_image: Whether to draw the classifier outputs on the images.
Returns:
The image before and after the style index modification, and the outputs of
the classifier before and after the
modification.
"""
network_inputs = generator.style_vector_calculator(dlatent)
result_image = np.zeros((resolution, 2 * resolution, 3), np.uint8)
images_out = generator.g_synthesis(network_inputs, training=False)
images_out = tf.maximum(tf.minimum(images_out, 1), -1)
base_image = tf.transpose(images_out, [0, 2, 3, 1])
result = classifier(base_image, training=False)
base_prob = tf.nn.softmax(result).numpy()[0, class_index]
if draw_results_on_image:
result_image[:, :resolution, :] = draw_on_image(
base_image[0].numpy(), base_prob, font_file)
else:
result_image[:, :resolution, :] = (base_image[0].numpy() * 127.5 +
127.5).astype(np.uint8)
change_image, change_prob = (
generate_change_image_given_dlatent(dlatent, generator, classifier,
class_index, sindex,
s_style_min, s_style_max,
style_direction_index, shift_size,
label_size))
if draw_results_on_image:
result_image[:, resolution:, :] = draw_on_image(
change_image[0].numpy(), change_prob, font_file)
else:
result_image[:, resolution:, :] = (
np.maxiumum(np.minimum(change_image[0].numpy(), 1), -1) * 127.5 +
127.5).astype(np.uint8)
return (result_image, change_prob, base_prob)
def visualize_style(generator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
all_dlatents: np.ndarray,
style_change_effect: np.ndarray,
style_min: np.ndarray,
style_max: np.ndarray,
sindex: int,
style_direction_index: int,
max_images: int,
shift_size: float,
font_file: str,
label_size: int = 2,
class_index: int = 0,
effect_threshold: float = 0.3,
seed: Optional[int] = None,
allow_both_directions_change: bool = False,
draw_results_on_image: bool = True) -> np.ndarray:
"""Returns an image visualizing the effect of a specific S-index.
Args:
generator: The generator model. Either StyleGAN or GLO.
classifier: The classifier to visualize.
all_dlatents: An array with shape [num_images, dlatent_size].
style_change_effect: A shape of [num_images, 2, style_size, num_classes].
The effect of each change of style on specific direction on each image.
style_min: The minimal value of each style, with shape [style_size].
style_max: The maximal value of each style, with shape [style_size].
sindex: The specific style index to visualize.
style_direction_index: If 0 move s to its min value otherwise to its max
value.
max_images: Maximal number of images to visualize.
shift_size: Factor of the shift of the style vector.
font_file: A path to the font file for writing the probability on the image.
label_size: The size of the label.
class_index: The index of the class to visualize.
effect_threshold: Choose images whose effect was at least this number.
seed: If given, use this as a seed to the random shuffling of the images.
allow_both_directions_change: Whether to allow both increasing and
decreasing the classifiaction (used for age).
draw_results_on_image: Whether to draw the classifier outputs on the images.
"""
# Choose the dlatent indices to visualize
if allow_both_directions_change:
images_idx = (np.abs(style_change_effect[:, style_direction_index, sindex,
class_index]) >
effect_threshold).nonzero()[0]
else:
images_idx = ((style_change_effect[:, style_direction_index, sindex,
class_index]) >
effect_threshold).nonzero()[0]
if images_idx.size == 0:
return np.array([])
if seed is not None:
np.random.seed(seed)
np.random.shuffle(images_idx)
images_idx = images_idx[:min(max_images*10, len(images_idx))]
dlatents = all_dlatents[images_idx]
result_images = []
for i in range(len(images_idx)):
cur_dlatent = dlatents[i:i + 1]
(result_image, base_prob, change_prob) = generate_images_given_dlatent(
dlatent=cur_dlatent,
generator=generator,
classifier=classifier,
class_index=class_index,
sindex=sindex,
s_style_min=style_min[sindex],
s_style_max=style_max[sindex],
style_direction_index=style_direction_index,
font_file=font_file,
shift_size=shift_size,
label_size=label_size,
draw_results_on_image=draw_results_on_image)
if np.abs(change_prob - base_prob) < effect_threshold:
continue
result_images.append(result_image)
if len(result_images) == max_images:
break
if len(result_images) < 3:
# No point in returning results with very little images
return np.array([])
return np.concatenate(result_images[:max_images], axis=0)
def visualize_style_by_distance_in_s(
generator: tf.keras.models.Model,
classifier: tf.keras.models.Model,
all_dlatents: np.ndarray,
all_style_vectors_distances: np.ndarray,
style_min: np.ndarray,
style_max: np.ndarray,
sindex: int,
style_sign_index: int,
max_images: int,
shift_size: float,
font_file: str,
label_size: int = 2,
class_index: int = 0,
draw_results_on_image: bool = True,
effect_threshold: float = 0.1) -> np.ndarray:
"""Returns an image visualizing the effect of a specific S-index.
Args:
generator: The generator model. Either StyleGAN or GLO.
classifier: The classifier to visualize.
all_dlatents: An array with shape [num_images, dlatent_size].
all_style_vectors_distances: A shape of [num_images, style_size, 2].
The distance each style from the min and max values on each image.
style_min: The minimal value of each style, with shape [style_size].
style_max: The maximal value of each style, with shape [style_size].
sindex: The specific style index to visualize.
style_sign_index: If 0 move s to its min value otherwise to its max
value.
max_images: Maximal number of images to visualize.
shift_size: Factor of the shift of the style vector.
font_file: A path to the font file for writing the probability on the image.
label_size: The size of the label.
class_index: The index of the class to visualize.
draw_results_on_image: Whether to draw the classifier outputs on the images.
"""
# Choose the dlatent indices to visualize
images_idx = np.argsort(
all_style_vectors_distances[:, sindex, style_sign_index])[::-1]
if images_idx.size == 0:
return np.array([])
images_idx = images_idx[:min(max_images*10, len(images_idx))]
dlatents = all_dlatents[images_idx]
result_images = []
for i in range(len(images_idx)):
cur_dlatent = dlatents[i:i + 1]
(result_image, change_prob, base_prob) = generate_images_given_dlatent(
dlatent=cur_dlatent,
generator=generator,
classifier=classifier,
class_index=class_index,
sindex=sindex,
s_style_min=style_min[sindex],
s_style_max=style_max[sindex],
style_direction_index=style_sign_index,
font_file=font_file,
shift_size=shift_size,
label_size=label_size,
draw_results_on_image=draw_results_on_image)
if (change_prob - base_prob) < effect_threshold:
continue
result_images.append(result_image)
if len(result_images) < 3:
# No point in returning results with very little images
return np.array([])
return np.concatenate(result_images[:max_images], axis=0)
#@title Load the precomputed dlatents (already concatenated to the labels)
dlatents_url = bucket_path + 'dlatents.pkl'
r = requests.get(dlatents_url)
dlatents = cPickle.loads(r.content)
#@title Generate image from the dlatent
dlatent_index = 4#@param {type: "integer"}
expanded_dlatent_tmp = tf.tile(
tf.expand_dims(dlatents[dlatent_index][1], 1),
[1, num_layers, 1])
rec_image = call_synthesis(generator,
expanded_dlatent_tmp,
num_layers=num_layers)
image = rec_image.numpy()[0]
show_image(image)
#@title Generate SSpace per index (min and max)
values_per_index = collections.defaultdict(list)
for _, dlatent in dlatents:
# Get the style vector:
s_img = tf.concat(generator.style_vector_calculator(
dlatent, training=False)[0], axis=1).numpy()[0]
for i, s_val in enumerate(s_img):
values_per_index[i].append(s_val)
values_per_index = dict(values_per_index)
s_indices_num = len(values_per_index.keys())
minimums = [min(values_per_index[i]) for i in range(s_indices_num)]
maximums = [max(values_per_index[i]) for i in range(s_indices_num)]
#@title SSpace calculation (this is also very heavy, skip to next cell to load precomputed ones) {form-width: '20%'}
s_shift_size = 1 # @param
data_path = '/tmp/celab_a_age/examples_1.tfrecord' #@param {type: 'string'}
with tf.io.TFRecordWriter(data_path) as writer:
for dlatent_index, dlatent in dlatents:
print(dlatent_index)
expanded_dlatent = tf.tile(
tf.expand_dims(dlatent, 1),
[1, num_layers, 1])
base_prob = get_classifier_results(generator, expanded_dlatent)
classifier_results = []
for sindex in tqdm.tqdm(range(0, s_indices_num)):
layer_idx, weight_idx = sindex_to_layer_idx_and_index(generator, sindex)
layer = generator.style_vector_calculator.style_dense_blocks[layer_idx]
layer_size = layer.dense_bias.weights[0].shape[1]
# Get the style vector.
s_vals = tf.concat(
generator.style_vector_calculator(dlatent, training=False)[0],
axis=1).numpy()[0]
s_shift_down = (minimums[sindex] - s_vals[sindex]) * s_shift_size
s_shift_up = (maximums[sindex] - s_vals[sindex]) * s_shift_size
s_shift_d = s_shift_down * tf.expand_dims(tf.one_hot(weight_idx,
layer_size), axis=0)
layer.dense_bias.weights[0].assign_add(s_shift_d)
classifier_results.extend(
get_classifier_results(generator, expanded_dlatent) - base_prob)
layer.dense_bias.weights[0].assign_add(-s_shift_d)
s_shift_u = s_shift_up * tf.expand_dims(
tf.one_hot(weight_idx, layer_size), axis=0)
layer.dense_bias.weights[0].assign_add(s_shift_u)
classifier_results.extend(
get_classifier_results(generator, expanded_dlatent) - base_prob)
layer.dense_bias.weights[0].assign_add(-s_shift_u)
feature = {}
feature['base_prob'] = _float_features(base_prob.flatten())
feature['dlatent'] = _float_features(dlatent.flatten())
feature['result'] = _float_features(np.array(classifier_results).flatten())
example_proto = tf.train.Example(features=tf.train.Features(feature=feature))
writer.write(example_proto.SerializeToString())
#@title Load effect data from the tfrecord {form-width: '20%'}
examples_url = bucket_path + 'examples_1.tfrecord'
r = requests.get(examples_url)
data_path = path + 'examples_1.tfrecord'
open(data_path, 'wb').write(r.content)
num_classes = 2
print(f'Loaded dataset: {data_path}')
table = tf.data.TFRecordDataset([data_path])
# Read sspace tfrecord unwrapped:
style_change_effect = []
dlatents = []
base_probs = []
for raw_record in table:
example = tf.train.Example()
example.ParseFromString(raw_record.numpy())
dlatents.append(
np.array(example.features.feature['dlatent'].float_list.value))
seffect = np.array(
example.features.feature['result'].float_list.value).reshape(
(-1, 2, num_classes))
style_change_effect.append(seffect.transpose([1, 0, 2]))
base_probs.append(
np.array(example.features.feature['base_prob'].float_list.value))
style_change_effect = np.array(style_change_effect)
dlatents = np.array(dlatents)
W_values, style_change_effect, base_probs = dlatents, style_change_effect, np.array(base_probs)
style_change_effect = filter_unstable_images(style_change_effect, effect_threshold=2)
all_style_vectors = tf.concat(generator.style_vector_calculator(W_values, training=False)[0], axis=1).numpy()
style_min = np.min(all_style_vectors, axis=0)
style_max = np.max(all_style_vectors, axis=0)
all_style_vectors_distances = np.zeros((all_style_vectors.shape[0], all_style_vectors.shape[1], 2))
all_style_vectors_distances[:,:, 0] = all_style_vectors - np.tile(style_min, (all_style_vectors.shape[0], 1))
all_style_vectors_distances[:,:, 1] = np.tile(style_max, (all_style_vectors.shape[0], 1)) - all_style_vectors
#@title Split by class
all_labels = np.argmax(base_probs, axis=1)
style_effect_classes = {}
W_classes = {}
style_vectors_distances_classes = {}
all_style_vectors_classes = {}
for img_ind in range(label_size):
img_inx = np.array([i for i in range(all_labels.shape[0])
if all_labels[i] == img_ind])
curr_style_effect = np.zeros((len(img_inx), style_change_effect.shape[1],
style_change_effect.shape[2], style_change_effect.shape[3]))
curr_w = np.zeros((len(img_inx), W_values.shape[1]))
curr_style_vector_distances = np.zeros((len(img_inx), style_change_effect.shape[2], 2))
for k, i in enumerate(img_inx):
curr_style_effect[k, :, :] = style_change_effect[i, :, :, :]
curr_w[k, :] = W_values[i, :]
curr_style_vector_distances[k, :, :] = all_style_vectors_distances[i, :, :]
style_effect_classes[img_ind] = curr_style_effect
W_classes[img_ind] = curr_w
style_vectors_distances_classes[img_ind] = curr_style_vector_distances
all_style_vectors_classes[img_ind] = all_style_vectors[img_inx]
print(f'Class {img_ind}, {len(img_inx)} images.')
#@title Significant S values - combined {form-width: '20%'}
label_size_clasifier = 2 #@param
num_indices = 8 #@param
effect_threshold = 0.2 #@param
use_discriminator = False #@param {type: 'boolean'}
discriminator_model = discriminator if use_discriminator else None
s_indices_and_signs_dict = {}
for class_index in [0, 1]:
split_ind = 1 - class_index
all_s = style_effect_classes[split_ind]
all_w = W_classes[split_ind]
# Find s indicies
s_indices_and_signs = find_significant_styles(
style_change_effect=all_s,
num_indices=num_indices,
class_index=class_index,
discriminator=discriminator_model,
generator=generator,
classifier=classifier,
all_dlatents=all_w,
style_min=style_min,
style_max=style_max,
max_image_effect=effect_threshold*5,
label_size=label_size_clasifier,
discriminator_threshold=0.2,
sindex_offset=0)
s_indices_and_signs_dict[class_index] = s_indices_and_signs
# Combine the style indicies for the two classes.
sindex_class_0 = [sindex for _, sindex in s_indices_and_signs_dict[0]]
all_sindex_joined_class_0 = [(1 - direction, sindex) for direction, sindex in
s_indices_and_signs_dict[1] if sindex not in sindex_class_0]
all_sindex_joined_class_0 += s_indices_and_signs_dict[0]
scores = []
for direction, sindex in all_sindex_joined_class_0:
other_direction = 1 if direction == 0 else 0
curr_score = np.mean(style_change_effect[:, direction, sindex, 0]) + np.mean(style_change_effect[:, other_direction, sindex, 1])
scores.append(curr_score)
s_indices_and_signs = [all_sindex_joined_class_0[i] for i in np.argsort(scores)[::-1]]
print('Directions and style indices for moving from class 1 to class 0 = ', s_indices_and_signs[:num_indices])
print('Use the other direction to move for class 0 to 1.')
#@title Significant S values - multi class one vs. all (this can also be used as one vs. one, using split_by_class=True and define class_index_from) {form-width: '20%'}
label_size_clasifier = 2 #@param {type:"integer"}
num_indices = 8#@param
effect_threshold = 0.1 #@param
use_discriminator = False #@param {type: 'boolean'}
class_index_to = 0 #@param {type:"integer"}
discriminator_model = discriminator if use_discriminator else None
split_by_class = False #@param {type: 'boolean'}
class_index_from = 1 #@param {type:"integer"}
if split_by_class:
split_ind = class_index_from
all_s = style_effect_classes[split_ind]
all_w = W_classes[split_ind]
else:
all_s = style_change_effect
all_w = W_values
# Find s indicies
s_indices_and_signs = find_significant_styles(
style_change_effect=all_s,
num_indices=num_indices,
class_index=class_index_to,
discriminator=discriminator_model,
generator=generator,
classifier=classifier,
all_dlatents=all_w,
style_min=style_min,
style_max=style_max,
max_image_effect=effect_threshold*5,
label_size=label_size_clasifier,
discriminator_threshold=0.2,
sindex_offset=0)
print(f'Directions and style indices for moving from all classes to class {class_index_to} = ', s_indices_and_signs[:num_indices])
#@title Visualize s-index {form-width: '20%'}
max_images = 10 #@param
sindex = 5300#@param
class_index = 0#@param {type: "integer"}
shift_sign = "1" #@param [0, 1]
wsign_index = int(shift_sign)
shift_size = 1#@param
effect_threshold = 0.2#@param
split_by_class = True #@param {type:"boolean"}
select_images_by_s_distance = True #@param {type:"boolean"}
draw_results_on_image = True #@param {type:"boolean"}
if split_by_class:
split_ind = 1 if class_index == 0 else 0
all_s = style_effect_classes[split_ind]
all_w = W_classes[split_ind]
all_s_distances = style_vectors_distances_classes[split_ind]
else:
all_s = style_change_effect
all_w = W_values
all_s_distances = all_style_vectors_distances
font_file = '/tmp/arialuni.ttf'
if not os.path.exists(font_file):
r = requests.get('https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/ipwn/arialuni.ttf')
open(font_file, 'wb').write(r.content)
if not select_images_by_s_distance:
yy = visualize_style(generator,
classifier,
all_w,
all_s,
style_min,
style_max,
sindex,
wsign_index,
max_images=max_images,
shift_size=shift_size,
font_file=font_file,
label_size=label_size,
class_index=class_index,
effect_threshold=effect_threshold,
draw_results_on_image=draw_results_on_image)
else:
yy = visualize_style_by_distance_in_s(
generator,
classifier,
all_w,
all_s_distances,
style_min,
style_max,
sindex,
wsign_index,
max_images=max_images,
shift_size=shift_size,
font_file=font_file,
label_size=label_size,
class_index=class_index,
effect_threshold=effect_threshold,
draw_results_on_image=draw_results_on_image)
if yy.size > 0:
show_image(yy)
else:
print('no images found')
#@title Show animation {form-width: '20%'}
import matplotlib.animation
from IPython.display import HTML
ani = make_animation(yy, resolution)
HTML(ani.to_jshtml())
#@title Show the 4 top attributes - as displayed in Fig.4 (b)
draw_probabilities_on_image = True #@param {type: "boolean"}
index_to_naming = {0: "Skin Pigminatation", 1: "Eyebrow Thickness", 2: "Add/Remove Glasses", 3: "Dark/White Hair"}
images_list = [[0, 4], [16, 17], [18, 18], [3, 14]]
max_images = 20
shift_sizes = [(2, 1.5),(1, 1),(1, 1),(1.5, 2)]
effect_threshold = 0.05
font_file = '/tmp/arialuni.ttf'
if not os.path.exists(font_file):
gfile.Copy('/google_src/head/depot/google3/googledata/third_party/fonts/ascender/arialuni.ttf', font_file)
for i, (direction, sindex) in enumerate(s_indices_and_signs[:4]):
images_s = np.zeros((resolution * 2, resolution * 2, 3)).astype(np.uint8)
for d in [direction, 1 - direction]:
# Take only images from the offsite class
class_index = 0 if d == direction else 1
split_ind = 1 if d == direction else 0
all_s = style_effect_classes[split_ind]
all_w = W_classes[split_ind]
all_s_distances = style_vectors_distances_classes[split_ind]
# Generate images
yy = visualize_style_by_distance_in_s(
generator,
classifier,
all_w,
all_s_distances,
style_min,
style_max,
sindex,
d,
max_images=max_images,
shift_size=shift_sizes[i][class_index],
font_file=font_file,
label_size=label_size,
class_index=class_index,
effect_threshold=effect_threshold,
draw_results_on_image=draw_probabilities_on_image)
for n in range(2):
images_s[n * resolution: (n + 1) * resolution, class_index * resolution: (class_index + 1) * resolution, :] = yy[(images_list[i][class_index]) * resolution: (images_list[i][class_index] + 1) * resolution, n * resolution: (n + 1) * resolution, :]
print(f'Attribute {i} {index_to_naming[i]}: \n(Original images are on the first row, the probabilities displayed are for the other class - left column for being old, write column for being young)')
show_image(images_s)
| 0.902864 | 0.814496 |
## Guided Hunting - Detect potential network beaconing using Apache Spark via Azure Synapse
__Notebook Version:__ 1.0<br>
__Python Version:__ Python 3.8 - AzureML<br>
__Required Packages:__ azureml-synapse, Msticpy, azure-storage-file-datalake <br>
__Platforms Supported:__ Azure Machine Learning Notebooks connected to Azure Synapse Workspace
__Data Source Required:__ Yes
__Data Source:__ CommonSecurityLogs
__Spark Version:__ 3.1 or above
### Description
In this sample guided scenario notebook, we will demonstrate how to set up continuous data pipeline to store data into azure data lake storage (ADLS) and
then hunt on that data at scale using distributed processing via Azure Synapse workspace connected to serverless Spark pool.
Once historical dataset is available in ADLS , we can start performing common hunt operations, create a baseline of normal behavior using PySpark API and also apply data transformations
to find anomalous behaviors such as periodic network beaconing as explained in the blog - [Detect Network beaconing via Intra-Request time delta patterns in Azure Sentinel - Microsoft Tech Community](https://techcommunity.microsoft.com/t5/azure-sentinel/detect-network-beaconing-via-intra-request-time-delta-patterns/ba-p/779586).
You can use various other spark API to perform other data transformation to understand the data better.
The output generated can also be further enriched to populate Geolocation information and also visualize using Msticpy capabilities to identify any anomalies.
.<br>
*** Python modules download may be needed. ***<br>
*** Please run the cells sequentially to avoid errors. Please do not use "run all cells". *** <br>
## Table of Contents
1. Warm-up
2. Authentication to Azure Resources
3. Configure Azure ML and Azure Synapse Analytics
4. Load the Historical and current data
5. Data Wrangling using Spark
6. Enrich the results
7. Conclusion
### Warm-up
> **Note**: Install below packages only for the first time and restart the kernel once done.
```
# Install AzureML Synapse package to use spark magics
import sys
!{sys.executable} -m pip install azureml-synapse
# Install Azure storage datalake library to manipulate file systems
import sys
!{sys.executable} -m pip install azure-storage-file-datalake --pre
# Install Azure storage datalake library to manipulate file systems
import sys
!{sys.executable} -m pip install msticpy
```
*** $\color{red}{Note:~After~installing~the~packages,~please~restart~the~kernel.}$ ***
```
# Load Python libraries that will be used in this notebook
from azure.common.client_factory import get_client_from_cli_profile
from azure.common.credentials import get_azure_cli_credentials
from azure.mgmt.resource import ResourceManagementClient
from azureml.core import Workspace, LinkedService, SynapseWorkspaceLinkedServiceConfiguration, Datastore
from azureml.core.compute import SynapseCompute, ComputeTarget
from datetime import timedelta, datetime
from azure.storage.filedatalake import DataLakeServiceClient
from azure.core._match_conditions import MatchConditions
from azure.storage.filedatalake._models import ContentSettings
import json
import os, uuid, sys
import IPython
import pandas as pd
from ipywidgets import widgets, Layout
from IPython.display import display, HTML
from pathlib import Path
REQ_PYTHON_VER=(3, 6)
REQ_MSTICPY_VER=(1, 4, 4)
display(HTML("<h3>Starting Notebook setup...</h3>"))
if Path("./utils/nb_check.py").is_file():
from utils.nb_check import check_python_ver, check_mp_ver
check_python_ver(min_py_ver=REQ_PYTHON_VER)
try:
check_mp_ver(min_msticpy_ver=REQ_MSTICPY_VER)
except ImportError:
!pip install --upgrade msticpy
if "msticpy" in sys.modules:
importlib.reload(sys.modules["msticpy"])
else:
import msticpy
check_mp_ver(REQ_MSTICPY_VER)
# If not using Azure Notebooks, install msticpy with
# !pip install msticpy
from msticpy.nbtools import nbinit
extra_imports = [
"msticpy.nbtools.nbdisplay, draw_alert_entity_graph",
"msticpy.sectools.ip_utils, convert_to_ip_entities",
"msticpy.nbtools.ti_browser, browse_results",
"IPython.display, Image",
"msticpy.sectools.ip_utils, get_whois_info",
"msticpy.sectools.ip_utils, get_ip_type"
]
nbinit.init_notebook(
namespace=globals(),
# additional_packages=["azureml-synapse", "azure-cli", "azure-storage-file-datalake"],
extra_imports=extra_imports,
);
WIDGET_DEFAULTS = {
"layout": Layout(width="95%"),
"style": {"description_width": "initial"},
}
#Set pandas options
pd.get_option('max_rows',10)
pd.set_option('max_colwidth',50)
```
## Configure Azure ML and Azure Synapse Analytics
Please use notebook [Configurate Azure ML and Azure Synapse Analytics](https://github.com/Azure/Azure-Sentinel-Notebooks/blob/master/Configurate%20Azure%20ML%20and%20Azure%20Synapse%20Analytics.ipynb) to configure environment.
The notebook will configure existing Azure synapse workspace to create and connect to Spark pool. You can then create linked service and connect AML workspace to Azure Synapse workspaces.
<br>It will also configure data export rules to export data from Log analytics workspace CommonSecurityLog table to Azure Data lake storage Gen 2.
> **Note**: Specify the input parameters in below step in order to connect AML workspace to synapse workspace using linked service.
```
amlworkspace = "<aml workspace name>" # fill in your AML workspace name
subscription_id = "<subscription id>" # fill in your subscription id
resource_group = '<resource group of AML workspace>' # fill in your resource groups for AML workspace
linkedservice = '<linked service name>' # fill in your linked service created to connect to synapse workspace
```
### Authentication to Azure Resources
In this step we will connect aml workspace to linked service connected to Azure Synapse workspace
```
# Get the aml workspace
aml_workspace = Workspace.get(name=amlworkspace, subscription_id=subscription_id, resource_group=resource_group)
# Retrieve a known linked service
linked_service = LinkedService.get(aml_workspace, linkedservice)
```
## Start Spark Session
Enter your Synapse Spark compute below. To find the Spark compute, please follow these steps: </br>
1. On the AML Studio left menu, navigate to **Linked Services** </br>
2. Click on the name of the Link Service you want to use </br>
3. Select **Spark pools** tab </br>
4. Get the Name of the Spark pool you want to use. </br>
```
synapse_spark_compute = input('Synapse Spark compute:')
# Start spark session
%synapse start -s $subscription_id -w $amlworkspace -r $resource_group -c $synapse_spark_compute
```
## Data Preparation
In this step, we will define several details associated with ADLS account and specify input date and lookback period to calculate baseline. Based on the input dates and lookback period , we will load the data.
```
%%synapse
# Primary storage info
account_name = '<storage account name>' # fill in your primary account name
container_name = '<container name>' # fill in your container name
subscription_id = '<subscription if>' # fill in your subscription id
resource_group = '<resource group>' # fill in your resource groups for ADLS
workspace_name = '<azure sentinel/log analytics workspace name>' # fill in your workspace name
device_vendor = "Fortinet" # Replace your desired network vendor from commonsecuritylogs
# Datetime and lookback parameters
end_date = "<enter date in the format yyyy-MM-dd e.g.2021-09-17>" # fill in your input date
lookback_days = 21 # fill in lookback days if you want to run it on historical data. make sure you have historical data available in ADLS
%%synapse
from pyspark.sql.types import *
from pyspark.sql.window import Window
from pyspark.sql.functions import lag, col
from pyspark.sql.functions import *
from pyspark.sql import functions as F
from datetime import timedelta, datetime, date
# Compiling ADLS paths from date string
end_date_str = end_date.split("-")
current_path = f"/y={end_date_str[0]}/m={end_date_str[1]}/d={end_date_str[2]}"
def generate_adls_paths(end_date, lookback_days, adls_path):
endDate = datetime.strptime(end_date, '%Y-%m-%d')
endDate = endDate - timedelta(days=1)
startDate = endDate - timedelta(days=lookback_days)
daterange = [startDate + timedelta(days=x) for x in range((endDate-startDate).days + 1)]
pathlist = []
for day in daterange:
date_str = day.strftime('%Y-%m-%d').split("-")
day_path = adls_path + f"/y={date_str[0]}/m={date_str[1]}/d={date_str[2]}"
pathlist.append(day_path)
return pathlist
adls_path = f'abfss://{container_name}@{account_name}.dfs.core.windows.net/WorkspaceResourceId=/subscriptions/{subscription_id}/resourcegroups/{resource_group}/providers/microsoft.operationalinsights/workspaces/{workspace_name}'
current_day_path = adls_path + current_path
historical_path = generate_adls_paths(end_date, lookback_days, adls_path)
```
### Load Current day
In this step, you will load the data based on the input date specified.
```
%%synapse
try:
current_df = (
spark.read.option("recursiveFileLook", "true")
.option("header", "true")
.json(current_day_path)
)
current_df = (
current_df
.select(
"TimeGenerated",
"SourceIP",
"SourcePort",
"DestinationIP",
"DestinationPort",
"Protocol",
"ReceivedBytes",
"SentBytes",
"DeviceVendor",
)
.filter(F.col("DeviceVendor") == device_vendor)
)
except Exception as e:
print(f"Could note load the data due to error:{e}")
#Display the count of records
print(f"No of records loaded from the current date specified: {current_df.count()}")
```
### Load Historical data
You can also perform the analysis on all historical data available in your ADLS account. The notebook is currently configured to run only on current date specified in input.
If you need to perform the same analysis on historical data, run the cell below and under Data Wrangling using Spark -> Filtering Data code cell, replace `current_df` with `historical_df` variable.
<br>**Otherwise SKIP running below cell as it will result in an error if you do not have historical data**
```
%%synapse
try:
#Read Previous days data
historical_df = (
spark.read.option("recursiveFileLook", "true")
.option("header", "true")
.json(historical_path[-1])
)
historical_df = historical_df.select(
"TimeGenerated",
"SourceIP",
"SourcePort",
"DestinationIP",
"DestinationPort",
"Protocol",
"ReceivedBytes",
"SentBytes",
"DeviceVendor",
).filter(F.col("DeviceVendor") == device_vendor)
#Read all historical days data per day and union them together
for path in historical_path[:-1]:
daily_table = (
spark.read.option("recursiveFileLook", "true")
.option("header", "true")
.json(path)
)
daily_table = daily_table.select(
"TimeGenerated",
"SourceIP",
"SourcePort",
"DestinationIP",
"DestinationPort",
"Protocol",
"ReceivedBytes",
"SentBytes",
"DeviceVendor",
).filter(F.col("DeviceVendor") == device_vendor)
historical_df = historical_df.union(daily_table)
except Exception as e:
print(f"Could not load the data due to error:\n {e}")
#Display the count of records
print(f"\n No of records loaded from the lookback days specified: {historical_df.count()}")
```
## Data Wrangling using Spark
### Filtering data
In this step, we will prepare dataset by filtering logs to only destination as Public/external IPs. For this, we are using regex and rlike spark API to filter internal to external network traffic.
```
%%synapse
PrivateIPregex = ("^127\.|^10\.|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-1]\.|^192\.168\.")
cooked_df = (current_df # replace historical_df if you want to use historical data
# use below filter if you have Palo Alto logs
# .filter(
# (F.col("Activity") == "TRAFFIC")
# )
.withColumn(
"DestinationIsPrivate", F.col("DestinationIP").rlike(PrivateIPregex)
)
.filter(F.col("DestinationIsPrivate") == "false")
.withColumn("TimeGenerated", F.col("TimeGenerated").cast("timestamp"))
)
cooked_df.show()
```
### Baseline data to filter known Source IP and Destination IPs
In this step, you can either analyze Historical data or current data to filter source IP and destination IP per defined criteria.
In below example, we are filtering the Source IP which has daily event count more than the specified threshold.
<br> Also, you can filter the destination IPs whom very less source IPs are connecting. This will reduce false positives be filtering destination IPs which are commonly seen from internal systems which are likely benign.
```
%%synapse
daily_event_count_threshold = 100 # Replace the threshold based on your environment or use default values
degree_of_srcip_threshold = 25 # Replace the threshold based on your environment or use default values
# Filtering IP list per TotalEventsThreshold
csl_srcip = (
cooked_df.groupBy("SourceIP")
.count()
.filter(F.col("count") > daily_event_count_threshold)
.orderBy(F.col("count"), ascending=False)
)
# Filtering Destination IP list per Degree of Source IPs threshold
csl_dstip = (
cooked_df.groupBy("DestinationIP")
.agg(F.countDistinct("SourceIP").alias("DegreeofSourceIps"))
.filter(F.col("DegreeofSourceIps") < degree_of_srcip_threshold)
)
# Filtering IP list per Daily event threshold
baseline_df = (
cooked_df.join(csl_srcip, ["SourceIP"])
.join(csl_dstip, ["DestinationIP"])
.select(
"TimeGenerated",
"SourceIP",
"SourcePort",
"DestinationIP",
"DestinationPort",
"Protocol",
"ReceivedBytes",
"SentBytes",
"DeviceVendor",
)
)
baseline_df.show()
```
### Rank the datasets and Calculate PercentageBeaconing
In this step, we will use spark to wrangle the data by applying below transformations.
- Sort the dataset per SourceIP
- Calculate the time difference between First event and next event.
- Partition dataset per Source IP, Destination IP, Destination Port
- Window dataset into consecutive 3 to Calculate the Timedeltalistcount based on cluster of 1-3 timedelta events.
- Calculate percentagebeacon between TotalEventscount and Timedeltalistcount
- Apply thresholds to further reduce false positives
** SPARK References:**
- https://spark.apache.org/docs/latest/api/python/getting_started/quickstart.html
- https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql.html#window
```
%%synapse
time_delta_threshold = 15 # Replace thresholds in seconds interval between 2 successive events. min 10 to anything maximum.
percent_beacon_threshold = 75 # Replace thresholds in percentage. Max value can be 100.
# Serialize the dataset by sorting timegenerated and partition by SourceIP and WorkspaceId
w = (
Window()
.partitionBy(F.col("SourceIP"))
.orderBy(F.col("TimeGenerated"))
)
# Calculate new timestamp column of next event
csl_beacon_df = baseline_df.select(
"*", lag("TimeGenerated").over(w).alias("prev_TimeStamp")
).na.drop()
# Calculate timedelta difference between previoud and next timestamp
timeDiff = F.unix_timestamp("TimeGenerated") - F.unix_timestamp("prev_TimeStamp")
# Add new column as timedelta
csl_beacon_df = csl_beacon_df.withColumn("Timedelta", timeDiff).filter(
F.col("Timedelta") > time_delta_threshold
)
csl_beacon_ranked = csl_beacon_df.groupBy(
"DeviceVendor",
"SourceIP",
"DestinationIP",
"DestinationPort",
"Protocol",
"Timedelta",
).agg(
F.count("Timedelta").alias("Timedeltacount"),
F.sum("SentBytes").alias("TotalSentBytes"),
F.sum("ReceivedBytes").alias("TotalReceivedBytes"),
F.count("*").alias("Totalevents"),
)
w1 = (
Window.partitionBy(
"DeviceVendor",
"SourceIP",
"DestinationIP",
"DestinationPort",
)
.orderBy(F.col("SourceIP").cast("long"))
.rowsBetween(-2, 0)
)
csl_beacon_df = (
csl_beacon_ranked
.join(csl_dstip, ["DestinationIP"])
.withColumn("Timedeltalist", F.collect_list("Timedeltacount").over(w1))
.withColumn(
"Timedeltalistcount",
F.expr("AGGREGATE(Timedeltalist, DOUBLE(0), (acc, x) -> acc + x)").cast(
"long"
),
)
.withColumn(
"Totaleventcount",
F.sum("Timedeltalistcount").over(
Window.partitionBy("SourceIP", "DestinationIP", "DestinationPort")
),
)
.withColumn(
"Percentbeacon",
(
F.col("Timedeltalistcount")
/ F.sum("Timedeltalistcount").over(
Window.partitionBy(
"DeviceVendor",
"SourceIP",
"DestinationIP",
"DestinationPort",
)
)
* 100.0
),
)
.filter(F.col("Percentbeacon") > percent_beacon_threshold)
.filter(F.col("Totaleventcount") > daily_event_count_threshold)
.orderBy(F.col("Percentbeacon"), ascending=False)
)
csl_beacon_df.show()
```
## Export results from ADLS
In this step, we will save the results from previous step as single json file in ADLS. This file can be exported from ADLS to be used with native python session outside spark pool for more data analysis, visualization etc.
```
%%synapse
dir_name = "<dir-name>" # specify desired directory name
new_path = adls_path + dir_name
csl_beacon_pd = csl_beacon_df.coalesce(1).write.format("json").save(new_path)
```
## Stop Spark Session
```
%synapse stop
```
## Export results from ADLS to local filesystem
```
def initialize_storage_account(storage_account_name, storage_account_key):
try:
global service_client
service_client = DataLakeServiceClient(
account_url="{}://{}.dfs.core.windows.net".format(
"https", storage_account_name
),
credential=storage_account_key,
)
except Exception as e:
print(e)
def list_directory_contents(container_name, input_path, file_type):
try:
file_system_client = service_client.get_file_system_client(
file_system=container_name
)
paths = file_system_client.get_paths(path=input_path)
pathlist = []
for path in paths:
pathlist.append(path.name) if path.name.endswith(file_type) else pathlist
return pathlist
except Exception as e:
print(e)
def download_file_from_directory(container_name, input_path, input_file):
try:
file_system_client = service_client.get_file_system_client(
file_system=container_name
)
directory_client = file_system_client.get_directory_client(input_path)
local_file = open("output.json", "wb")
file_client = directory_client.get_file_client(input_file)
download = file_client.download_file()
downloaded_bytes = download.readall()
local_file.write(downloaded_bytes)
local_file.close()
except Exception as e:
print(e)
def json_normalize(input_file, output_file):
nwbeaconList = []
with open(input_file) as f:
for jsonObj in f:
nwbeaconDict = json.loads(jsonObj)
nwbeaconList.append(nwbeaconDict)
with open(output_file, "w") as write_file:
json.dump(nwbeaconList, write_file)
```
### Download the files from ADLS
In below sections, we will provide input details about ADLS account ad then use functions to connect , list contents and download results locally.
If you need help in locating input details, follow below steps
- Go to the https://web.azuresynapse.net and sign in to your workspace.
- In Synapse Studio, click Data, select the Linked tab, and select the container under Azure Data Lake Storage Gen2.
- Navigate to folder from the container, right click and select Properies.
- Copy ABFSS path , extact the details and map to the input fields
You can check [View account access keys](https://docs.microsoft.com/en-us/azure/storage/common/storage-account-keys-manage?tabs=azure-portal#view-account-access-keys) doc to find and retrieve your storage account keys for ADLS account.
<p style="border: solid; padding: 5pt; color: black; background-color: #AA4000">
<b>Warning</b>: If you are storing secrets such as storage account keys in the notebook you should<br>
probably opt to store either into msticpyconfig file on the compute instance or use<br.>
Azure Key Vault to store the secrets.<br>
Read more about using KeyVault
<a href=https://msticpy.readthedocs.io/en/latest/getting_started/msticpyconfig.html#specifying-secrets-as-key-vault-secrets >in the MSTICPY docs</a>
</p>
```
# Primary storage info
account_name = "<storage account name>" # fill in your primary account name
container_name = "<container name>" # fill in your container name
subscription_id = "<subscription id>"
resource_group = "<resource-group>" # fill in your resource gropup for ADLS account
workspace_name = "<Azure sentinel/Log Analytics workspace name>" # fill in your la workspace name
input_path = f"WorkspaceResourceId=/subscriptions/{subscription_id}/resourcegroups/{resource_group}/providers/microsoft.operationalinsights/workspaces/"
adls_path = f"abfss://{container_name}@{account_name}.dfs.core.windows.net/{input_path}/{workspace_name}"
dir_name = "<dir-name>/" #Replace the dirname previously specified to store results from spark
account_key = "<storage-account-key>" # Replace your storage account key
new_path = input_path + dir_name
initialize_storage_account(account_name, account_key)
pathlist = list_directory_contents(container_name, new_path, "json")
input_file = pathlist[0].split("/")[-1]
download_file_from_directory(container_name, new_path, input_file)
json_normalize("output.json", "out_normalized.json")
```
### Display results
```
df = pd.read_json('out_normalized.json')
df.head()
```
## Enrich results
In this section, we will enrich entities retrieved from network beaconing behavior such as IP information.
Types of Enrichment which will beneficial in perfoming investigation will be IP Geolcation , Whois Registrar information and ThreatIntel lookups.
For first time users, please refer `Getting Started Guide For Azure Sentinel ML Notebooks` and section [Create your configuration file](https://docs.microsoft.com/en-us/azure/sentinel/notebook-get-started#create-your-configuration-file) to create your `mstipyconfig`.
### IP Geolocation Enrichment
In this step, we will use msticpy geolocation capabilities using maxmind database. You will need maxmind API key to download the database.
<div style="border: solid; padding: 5pt"><b>Note:</b>
You may see the GeoLite driver downloading its database the first time you run this.
</div>
<br>
<details>
<summary>Learn more about MSTICPy GeoIP providers...</summary>
<p>
<a href=https://msticpy.readthedocs.io/en/latest/data_acquisition/GeoIPLookups.html >MSTICPy GeoIP Providers</a>
</p>
</details>
<br>
```
from msticpy.sectools.geoip import GeoLiteLookup
iplocation = GeoLiteLookup()
df = iplocation.df_lookup_ip(df, column="DestinationIP")
df.head()
```
### Whois registration enrichment
In this step, we can perform whois lokup on all public destination ips and populate additional information such as ASN. You can use this output to further filter known ASNs from the results.
```
num_ips = len(df["DestinationIP"].unique())
print(f"Performing WhoIs lookups for {num_ips} IPs ", end="")
df["DestASN"] = df.apply(lambda x: get_whois_info(x.DestinationIP, True), axis=1)
df["DestASNFull"] = df.apply(lambda x: x.DestASN[1], axis=1)
df["DestASN"] = df.apply(lambda x: x.DestASN[0], axis=1)
#Display results
df.head()
```
### ThreatIntel Enrichment
In this step, we can perform threatintel lookup using msticpy and open source TI providers such as IBM Xforce, VirusTotal, Greynoise etc.
Below example shows performing lookup on single IP as well as bulk lookup on all ips using IBM Xforce TI Provider.
<br>You will need to register with IBM Xforce and enter API keys into `mstipyconfig.yaml`
<details>
<summary>Learn more...</summary>
<p>
</p>
<ul>
<li>More details are shown in the <i>A Tour of Cybersec notebook features</i> notebook</li>
<li><a href=https://msticpy.readthedocs.io/en/latest/data_acquisition/TIProviders.html >Threat Intel Lookups in MSTICPy</a></li>
<li> To learn more about adding TI sources, see the TI Provider setup in the <i>A Getting Started Guide For Azure Sentinel ML Notebooks</i> notebook
</ul>
</details>
<br>
```
ti_lookup = TILookup()
# Perform lookup on single IOC
result = ti_lookup.lookup_ioc(observable="52.183.120.194", providers=["XForce"])
ti_lookup.result_to_df(result)
# Flattening all the desnation IPs into comma separated list
ip_list = df['DestinationIP'].astype(str).values.flatten().tolist()
# Perform bulk lookup on all IPs with specified providers
ti_resp = ti_lookup.lookup_iocs(data=ip_list, providers=["AzSTI", "XForce"])
select_ti = browse_results(ti_resp, severities=['high','warning'])
select_ti
```
## Visualization
MSTICpy also includes a feature to allow you to map locations, this can be particularily useful when looking at the distribution of remote network connections or other events. Below we plot the locations of destination IPs observed in our results.
```
from msticpy.nbtools import entityschema
from msticpy.sectools.ip_utils import convert_to_ip_entities
from msticpy.nbtools.foliummap import FoliumMap, get_map_center
# Convert our IP addresses in string format into an ip address entity
ip_entity = entityschema.IpAddress()
ip_list = [convert_to_ip_entities(i)[0] for i in df['DestinationIP'].head(10)]
# Get center location of all IP locaitons to center the map on
location = get_map_center(ip_list)
logon_map = FoliumMap(location=location, zoom_start=4)
# Add location markers to our map and dsiplay it
if len(ip_list) > 0:
logon_map.add_ip_cluster(ip_entities=ip_list)
display(logon_map.folium_map)
```
## Conclusion
We originally started our hunting on very large datasets of firewall logs. Due to the sheer scale of data, we leveraged spark to load the data.
<br>We then performed baselining on historical data and use it to further filter current day dataset. In the next step we performed various data transformation by using spark features such as paritioning, windowing, ranking datatset to find outbound network beaconing like behavior.
<br> In order to analyze this data further, we enrich IP entities from result dataset with additional information such as Geolocation, whois registration and threat intel lookups.
Analysts can perform further investigation on selected IP addresses from enrichment results by correlating various data sources available.
You can then create incidents in Azure Sentinel and track investigation in it.
|
github_jupyter
|
# Install AzureML Synapse package to use spark magics
import sys
!{sys.executable} -m pip install azureml-synapse
# Install Azure storage datalake library to manipulate file systems
import sys
!{sys.executable} -m pip install azure-storage-file-datalake --pre
# Install Azure storage datalake library to manipulate file systems
import sys
!{sys.executable} -m pip install msticpy
# Load Python libraries that will be used in this notebook
from azure.common.client_factory import get_client_from_cli_profile
from azure.common.credentials import get_azure_cli_credentials
from azure.mgmt.resource import ResourceManagementClient
from azureml.core import Workspace, LinkedService, SynapseWorkspaceLinkedServiceConfiguration, Datastore
from azureml.core.compute import SynapseCompute, ComputeTarget
from datetime import timedelta, datetime
from azure.storage.filedatalake import DataLakeServiceClient
from azure.core._match_conditions import MatchConditions
from azure.storage.filedatalake._models import ContentSettings
import json
import os, uuid, sys
import IPython
import pandas as pd
from ipywidgets import widgets, Layout
from IPython.display import display, HTML
from pathlib import Path
REQ_PYTHON_VER=(3, 6)
REQ_MSTICPY_VER=(1, 4, 4)
display(HTML("<h3>Starting Notebook setup...</h3>"))
if Path("./utils/nb_check.py").is_file():
from utils.nb_check import check_python_ver, check_mp_ver
check_python_ver(min_py_ver=REQ_PYTHON_VER)
try:
check_mp_ver(min_msticpy_ver=REQ_MSTICPY_VER)
except ImportError:
!pip install --upgrade msticpy
if "msticpy" in sys.modules:
importlib.reload(sys.modules["msticpy"])
else:
import msticpy
check_mp_ver(REQ_MSTICPY_VER)
# If not using Azure Notebooks, install msticpy with
# !pip install msticpy
from msticpy.nbtools import nbinit
extra_imports = [
"msticpy.nbtools.nbdisplay, draw_alert_entity_graph",
"msticpy.sectools.ip_utils, convert_to_ip_entities",
"msticpy.nbtools.ti_browser, browse_results",
"IPython.display, Image",
"msticpy.sectools.ip_utils, get_whois_info",
"msticpy.sectools.ip_utils, get_ip_type"
]
nbinit.init_notebook(
namespace=globals(),
# additional_packages=["azureml-synapse", "azure-cli", "azure-storage-file-datalake"],
extra_imports=extra_imports,
);
WIDGET_DEFAULTS = {
"layout": Layout(width="95%"),
"style": {"description_width": "initial"},
}
#Set pandas options
pd.get_option('max_rows',10)
pd.set_option('max_colwidth',50)
amlworkspace = "<aml workspace name>" # fill in your AML workspace name
subscription_id = "<subscription id>" # fill in your subscription id
resource_group = '<resource group of AML workspace>' # fill in your resource groups for AML workspace
linkedservice = '<linked service name>' # fill in your linked service created to connect to synapse workspace
# Get the aml workspace
aml_workspace = Workspace.get(name=amlworkspace, subscription_id=subscription_id, resource_group=resource_group)
# Retrieve a known linked service
linked_service = LinkedService.get(aml_workspace, linkedservice)
synapse_spark_compute = input('Synapse Spark compute:')
# Start spark session
%synapse start -s $subscription_id -w $amlworkspace -r $resource_group -c $synapse_spark_compute
%%synapse
# Primary storage info
account_name = '<storage account name>' # fill in your primary account name
container_name = '<container name>' # fill in your container name
subscription_id = '<subscription if>' # fill in your subscription id
resource_group = '<resource group>' # fill in your resource groups for ADLS
workspace_name = '<azure sentinel/log analytics workspace name>' # fill in your workspace name
device_vendor = "Fortinet" # Replace your desired network vendor from commonsecuritylogs
# Datetime and lookback parameters
end_date = "<enter date in the format yyyy-MM-dd e.g.2021-09-17>" # fill in your input date
lookback_days = 21 # fill in lookback days if you want to run it on historical data. make sure you have historical data available in ADLS
%%synapse
from pyspark.sql.types import *
from pyspark.sql.window import Window
from pyspark.sql.functions import lag, col
from pyspark.sql.functions import *
from pyspark.sql import functions as F
from datetime import timedelta, datetime, date
# Compiling ADLS paths from date string
end_date_str = end_date.split("-")
current_path = f"/y={end_date_str[0]}/m={end_date_str[1]}/d={end_date_str[2]}"
def generate_adls_paths(end_date, lookback_days, adls_path):
endDate = datetime.strptime(end_date, '%Y-%m-%d')
endDate = endDate - timedelta(days=1)
startDate = endDate - timedelta(days=lookback_days)
daterange = [startDate + timedelta(days=x) for x in range((endDate-startDate).days + 1)]
pathlist = []
for day in daterange:
date_str = day.strftime('%Y-%m-%d').split("-")
day_path = adls_path + f"/y={date_str[0]}/m={date_str[1]}/d={date_str[2]}"
pathlist.append(day_path)
return pathlist
adls_path = f'abfss://{container_name}@{account_name}.dfs.core.windows.net/WorkspaceResourceId=/subscriptions/{subscription_id}/resourcegroups/{resource_group}/providers/microsoft.operationalinsights/workspaces/{workspace_name}'
current_day_path = adls_path + current_path
historical_path = generate_adls_paths(end_date, lookback_days, adls_path)
%%synapse
try:
current_df = (
spark.read.option("recursiveFileLook", "true")
.option("header", "true")
.json(current_day_path)
)
current_df = (
current_df
.select(
"TimeGenerated",
"SourceIP",
"SourcePort",
"DestinationIP",
"DestinationPort",
"Protocol",
"ReceivedBytes",
"SentBytes",
"DeviceVendor",
)
.filter(F.col("DeviceVendor") == device_vendor)
)
except Exception as e:
print(f"Could note load the data due to error:{e}")
#Display the count of records
print(f"No of records loaded from the current date specified: {current_df.count()}")
%%synapse
try:
#Read Previous days data
historical_df = (
spark.read.option("recursiveFileLook", "true")
.option("header", "true")
.json(historical_path[-1])
)
historical_df = historical_df.select(
"TimeGenerated",
"SourceIP",
"SourcePort",
"DestinationIP",
"DestinationPort",
"Protocol",
"ReceivedBytes",
"SentBytes",
"DeviceVendor",
).filter(F.col("DeviceVendor") == device_vendor)
#Read all historical days data per day and union them together
for path in historical_path[:-1]:
daily_table = (
spark.read.option("recursiveFileLook", "true")
.option("header", "true")
.json(path)
)
daily_table = daily_table.select(
"TimeGenerated",
"SourceIP",
"SourcePort",
"DestinationIP",
"DestinationPort",
"Protocol",
"ReceivedBytes",
"SentBytes",
"DeviceVendor",
).filter(F.col("DeviceVendor") == device_vendor)
historical_df = historical_df.union(daily_table)
except Exception as e:
print(f"Could not load the data due to error:\n {e}")
#Display the count of records
print(f"\n No of records loaded from the lookback days specified: {historical_df.count()}")
%%synapse
PrivateIPregex = ("^127\.|^10\.|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-1]\.|^192\.168\.")
cooked_df = (current_df # replace historical_df if you want to use historical data
# use below filter if you have Palo Alto logs
# .filter(
# (F.col("Activity") == "TRAFFIC")
# )
.withColumn(
"DestinationIsPrivate", F.col("DestinationIP").rlike(PrivateIPregex)
)
.filter(F.col("DestinationIsPrivate") == "false")
.withColumn("TimeGenerated", F.col("TimeGenerated").cast("timestamp"))
)
cooked_df.show()
%%synapse
daily_event_count_threshold = 100 # Replace the threshold based on your environment or use default values
degree_of_srcip_threshold = 25 # Replace the threshold based on your environment or use default values
# Filtering IP list per TotalEventsThreshold
csl_srcip = (
cooked_df.groupBy("SourceIP")
.count()
.filter(F.col("count") > daily_event_count_threshold)
.orderBy(F.col("count"), ascending=False)
)
# Filtering Destination IP list per Degree of Source IPs threshold
csl_dstip = (
cooked_df.groupBy("DestinationIP")
.agg(F.countDistinct("SourceIP").alias("DegreeofSourceIps"))
.filter(F.col("DegreeofSourceIps") < degree_of_srcip_threshold)
)
# Filtering IP list per Daily event threshold
baseline_df = (
cooked_df.join(csl_srcip, ["SourceIP"])
.join(csl_dstip, ["DestinationIP"])
.select(
"TimeGenerated",
"SourceIP",
"SourcePort",
"DestinationIP",
"DestinationPort",
"Protocol",
"ReceivedBytes",
"SentBytes",
"DeviceVendor",
)
)
baseline_df.show()
%%synapse
time_delta_threshold = 15 # Replace thresholds in seconds interval between 2 successive events. min 10 to anything maximum.
percent_beacon_threshold = 75 # Replace thresholds in percentage. Max value can be 100.
# Serialize the dataset by sorting timegenerated and partition by SourceIP and WorkspaceId
w = (
Window()
.partitionBy(F.col("SourceIP"))
.orderBy(F.col("TimeGenerated"))
)
# Calculate new timestamp column of next event
csl_beacon_df = baseline_df.select(
"*", lag("TimeGenerated").over(w).alias("prev_TimeStamp")
).na.drop()
# Calculate timedelta difference between previoud and next timestamp
timeDiff = F.unix_timestamp("TimeGenerated") - F.unix_timestamp("prev_TimeStamp")
# Add new column as timedelta
csl_beacon_df = csl_beacon_df.withColumn("Timedelta", timeDiff).filter(
F.col("Timedelta") > time_delta_threshold
)
csl_beacon_ranked = csl_beacon_df.groupBy(
"DeviceVendor",
"SourceIP",
"DestinationIP",
"DestinationPort",
"Protocol",
"Timedelta",
).agg(
F.count("Timedelta").alias("Timedeltacount"),
F.sum("SentBytes").alias("TotalSentBytes"),
F.sum("ReceivedBytes").alias("TotalReceivedBytes"),
F.count("*").alias("Totalevents"),
)
w1 = (
Window.partitionBy(
"DeviceVendor",
"SourceIP",
"DestinationIP",
"DestinationPort",
)
.orderBy(F.col("SourceIP").cast("long"))
.rowsBetween(-2, 0)
)
csl_beacon_df = (
csl_beacon_ranked
.join(csl_dstip, ["DestinationIP"])
.withColumn("Timedeltalist", F.collect_list("Timedeltacount").over(w1))
.withColumn(
"Timedeltalistcount",
F.expr("AGGREGATE(Timedeltalist, DOUBLE(0), (acc, x) -> acc + x)").cast(
"long"
),
)
.withColumn(
"Totaleventcount",
F.sum("Timedeltalistcount").over(
Window.partitionBy("SourceIP", "DestinationIP", "DestinationPort")
),
)
.withColumn(
"Percentbeacon",
(
F.col("Timedeltalistcount")
/ F.sum("Timedeltalistcount").over(
Window.partitionBy(
"DeviceVendor",
"SourceIP",
"DestinationIP",
"DestinationPort",
)
)
* 100.0
),
)
.filter(F.col("Percentbeacon") > percent_beacon_threshold)
.filter(F.col("Totaleventcount") > daily_event_count_threshold)
.orderBy(F.col("Percentbeacon"), ascending=False)
)
csl_beacon_df.show()
%%synapse
dir_name = "<dir-name>" # specify desired directory name
new_path = adls_path + dir_name
csl_beacon_pd = csl_beacon_df.coalesce(1).write.format("json").save(new_path)
%synapse stop
def initialize_storage_account(storage_account_name, storage_account_key):
try:
global service_client
service_client = DataLakeServiceClient(
account_url="{}://{}.dfs.core.windows.net".format(
"https", storage_account_name
),
credential=storage_account_key,
)
except Exception as e:
print(e)
def list_directory_contents(container_name, input_path, file_type):
try:
file_system_client = service_client.get_file_system_client(
file_system=container_name
)
paths = file_system_client.get_paths(path=input_path)
pathlist = []
for path in paths:
pathlist.append(path.name) if path.name.endswith(file_type) else pathlist
return pathlist
except Exception as e:
print(e)
def download_file_from_directory(container_name, input_path, input_file):
try:
file_system_client = service_client.get_file_system_client(
file_system=container_name
)
directory_client = file_system_client.get_directory_client(input_path)
local_file = open("output.json", "wb")
file_client = directory_client.get_file_client(input_file)
download = file_client.download_file()
downloaded_bytes = download.readall()
local_file.write(downloaded_bytes)
local_file.close()
except Exception as e:
print(e)
def json_normalize(input_file, output_file):
nwbeaconList = []
with open(input_file) as f:
for jsonObj in f:
nwbeaconDict = json.loads(jsonObj)
nwbeaconList.append(nwbeaconDict)
with open(output_file, "w") as write_file:
json.dump(nwbeaconList, write_file)
# Primary storage info
account_name = "<storage account name>" # fill in your primary account name
container_name = "<container name>" # fill in your container name
subscription_id = "<subscription id>"
resource_group = "<resource-group>" # fill in your resource gropup for ADLS account
workspace_name = "<Azure sentinel/Log Analytics workspace name>" # fill in your la workspace name
input_path = f"WorkspaceResourceId=/subscriptions/{subscription_id}/resourcegroups/{resource_group}/providers/microsoft.operationalinsights/workspaces/"
adls_path = f"abfss://{container_name}@{account_name}.dfs.core.windows.net/{input_path}/{workspace_name}"
dir_name = "<dir-name>/" #Replace the dirname previously specified to store results from spark
account_key = "<storage-account-key>" # Replace your storage account key
new_path = input_path + dir_name
initialize_storage_account(account_name, account_key)
pathlist = list_directory_contents(container_name, new_path, "json")
input_file = pathlist[0].split("/")[-1]
download_file_from_directory(container_name, new_path, input_file)
json_normalize("output.json", "out_normalized.json")
df = pd.read_json('out_normalized.json')
df.head()
from msticpy.sectools.geoip import GeoLiteLookup
iplocation = GeoLiteLookup()
df = iplocation.df_lookup_ip(df, column="DestinationIP")
df.head()
num_ips = len(df["DestinationIP"].unique())
print(f"Performing WhoIs lookups for {num_ips} IPs ", end="")
df["DestASN"] = df.apply(lambda x: get_whois_info(x.DestinationIP, True), axis=1)
df["DestASNFull"] = df.apply(lambda x: x.DestASN[1], axis=1)
df["DestASN"] = df.apply(lambda x: x.DestASN[0], axis=1)
#Display results
df.head()
ti_lookup = TILookup()
# Perform lookup on single IOC
result = ti_lookup.lookup_ioc(observable="52.183.120.194", providers=["XForce"])
ti_lookup.result_to_df(result)
# Flattening all the desnation IPs into comma separated list
ip_list = df['DestinationIP'].astype(str).values.flatten().tolist()
# Perform bulk lookup on all IPs with specified providers
ti_resp = ti_lookup.lookup_iocs(data=ip_list, providers=["AzSTI", "XForce"])
select_ti = browse_results(ti_resp, severities=['high','warning'])
select_ti
from msticpy.nbtools import entityschema
from msticpy.sectools.ip_utils import convert_to_ip_entities
from msticpy.nbtools.foliummap import FoliumMap, get_map_center
# Convert our IP addresses in string format into an ip address entity
ip_entity = entityschema.IpAddress()
ip_list = [convert_to_ip_entities(i)[0] for i in df['DestinationIP'].head(10)]
# Get center location of all IP locaitons to center the map on
location = get_map_center(ip_list)
logon_map = FoliumMap(location=location, zoom_start=4)
# Add location markers to our map and dsiplay it
if len(ip_list) > 0:
logon_map.add_ip_cluster(ip_entities=ip_list)
display(logon_map.folium_map)
| 0.402157 | 0.898277 |
# Nested Lists and Nested Loops
Here is a nested list, in this case of students' grades:
```
NYU_ID_IDX = 0
FIRST_GRADE_IDX = 1
students = [
["N19914", 67.9, 82.6, 76.5],
["N23414", 87.9, 92.1, 76.5],
["N96567", 67.9, 82.4],
["N20953", 45.3, 52.1, 56.9],
["N86324", 97.9, 94.4, 96.5],
]
```
How do we loop over this?
```
for i in range(len(students)): # same as range(0, len(students), 1)
grade_sum = 0
# print(students[i][NYU_ID_IDX])
for j in range(FIRST_GRADE_IDX, len(students[i])):
# print("grade {}: {}".format(j - FIRST_GRADE_IDX, students[i][j]))
grade_sum += students[i][j]
avg = grade_sum / (len(students[i]) - FIRST_GRADE_IDX)
print("For {}, avg. is: {:.1f}".format(students[i][NYU_ID_IDX], avg))
```
Here is a triply nested list:
```
# name our constants:
CITY_NM_IDX = 0
FIRST_DAY = 1
HIGH_IDX = 0
LOW_IDX = 1
AVG_IDX = 2
weather_readings = [
["Vladivostock",
# H, L, M (high, low, mean)
[28, 12, 21], # Monday
[22, 5, 16], # Tuesday
[24, 1, 12], # Wednesday
],
["Manilla",
[92, 81, 86],
[94, 82, 87],
[91, 80, 85],
],
["Accra",
[86, 80, 83],
[88, 81, 84],
[87, 79, 83],
],
["Brooklyn",
[57, 41, 48],
[50, 36, 42],
[48, 32, 40],
[44, 28, 37],
],
]
```
Let write a program to get the average high, average low, and mean for each city.
```
for city in weather_readings:
high_sum = 0
low_sum = 0
mean_sum = 0
for day in city[FIRST_DAY:]:
for (i, temp) in enumerate(day):
if i == HIGH_IDX:
high_sum += temp
elif i == LOW_IDX:
low_sum += temp
else:
mean_sum += temp
num_days = len(city) - FIRST_DAY
high_avg = high_sum / num_days
low_avg = low_sum / num_days
mean_avg = mean_sum / num_days
print("For {}, high avg: {:4.1f}, low avg: {:4.1f}, mean: {:4.1f}".format(city[CITY_NM_IDX],
high_avg,
low_avg,
mean_avg))
# we want to name our indices with constants:
CITY_NAME_IDX = 0
HIGH_IDX = 0
LOW_IDX = 1
MEAN_IDX = 2
for city in weather_readings:
city_nm = city[CITY_NAME_IDX]
high_sum = 0
low_sum = 0
mean_sum = 0
for day in city[1:]: # same as [1:len(city):1]
for i, temp in enumerate(day):
if i == HIGH_IDX:
high_sum += temp
elif i == LOW_IDX:
low_sum += temp
elif i == MEAN_IDX:
mean_sum += temp
else:
break
num_days = len(city) - 1
high_avg = high_sum / num_days
low_avg = low_sum / num_days
mean_avg = mean_sum / num_days
print("For {}, avg. high: {:4.1f}, avg. low: {:4.1f}, mean: {:4.1f}".format(city_nm,
high_avg,
low_avg,
mean_avg))
```
|
github_jupyter
|
NYU_ID_IDX = 0
FIRST_GRADE_IDX = 1
students = [
["N19914", 67.9, 82.6, 76.5],
["N23414", 87.9, 92.1, 76.5],
["N96567", 67.9, 82.4],
["N20953", 45.3, 52.1, 56.9],
["N86324", 97.9, 94.4, 96.5],
]
for i in range(len(students)): # same as range(0, len(students), 1)
grade_sum = 0
# print(students[i][NYU_ID_IDX])
for j in range(FIRST_GRADE_IDX, len(students[i])):
# print("grade {}: {}".format(j - FIRST_GRADE_IDX, students[i][j]))
grade_sum += students[i][j]
avg = grade_sum / (len(students[i]) - FIRST_GRADE_IDX)
print("For {}, avg. is: {:.1f}".format(students[i][NYU_ID_IDX], avg))
# name our constants:
CITY_NM_IDX = 0
FIRST_DAY = 1
HIGH_IDX = 0
LOW_IDX = 1
AVG_IDX = 2
weather_readings = [
["Vladivostock",
# H, L, M (high, low, mean)
[28, 12, 21], # Monday
[22, 5, 16], # Tuesday
[24, 1, 12], # Wednesday
],
["Manilla",
[92, 81, 86],
[94, 82, 87],
[91, 80, 85],
],
["Accra",
[86, 80, 83],
[88, 81, 84],
[87, 79, 83],
],
["Brooklyn",
[57, 41, 48],
[50, 36, 42],
[48, 32, 40],
[44, 28, 37],
],
]
for city in weather_readings:
high_sum = 0
low_sum = 0
mean_sum = 0
for day in city[FIRST_DAY:]:
for (i, temp) in enumerate(day):
if i == HIGH_IDX:
high_sum += temp
elif i == LOW_IDX:
low_sum += temp
else:
mean_sum += temp
num_days = len(city) - FIRST_DAY
high_avg = high_sum / num_days
low_avg = low_sum / num_days
mean_avg = mean_sum / num_days
print("For {}, high avg: {:4.1f}, low avg: {:4.1f}, mean: {:4.1f}".format(city[CITY_NM_IDX],
high_avg,
low_avg,
mean_avg))
# we want to name our indices with constants:
CITY_NAME_IDX = 0
HIGH_IDX = 0
LOW_IDX = 1
MEAN_IDX = 2
for city in weather_readings:
city_nm = city[CITY_NAME_IDX]
high_sum = 0
low_sum = 0
mean_sum = 0
for day in city[1:]: # same as [1:len(city):1]
for i, temp in enumerate(day):
if i == HIGH_IDX:
high_sum += temp
elif i == LOW_IDX:
low_sum += temp
elif i == MEAN_IDX:
mean_sum += temp
else:
break
num_days = len(city) - 1
high_avg = high_sum / num_days
low_avg = low_sum / num_days
mean_avg = mean_sum / num_days
print("For {}, avg. high: {:4.1f}, avg. low: {:4.1f}, mean: {:4.1f}".format(city_nm,
high_avg,
low_avg,
mean_avg))
| 0.152537 | 0.841696 |
<a href="https://colab.research.google.com/github/cxbxmxcx/GenReality/blob/master/GEN_4_WGAN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
IMPORTS
```
import math
import os
import torchvision.transforms as transforms
from torchvision.utils import make_grid
from torch.utils.data import DataLoader
from torchvision import datasets
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from tqdm import tqdm
plt.ion()
from IPython.display import clear_output
```
HYPERPARAMETERS
```
class Hyperparameters(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
hp = Hyperparameters(n_epochs=200,
batch_size=64,
lr=0.00005,
n_cpu=8,
latent_dim=100,
img_size=32,
channels=1,
n_critic=25,
clip_value=.005,
sample_interval=400)
print(hp.lr)
```
SETUP
```
os.makedirs("images", exist_ok=True)
img_shape = (hp.channels, hp.img_size, hp.img_size)
cuda = True if torch.cuda.is_available() else False
def weights_init_normal(m):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
torch.nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find("BatchNorm2d") != -1:
torch.nn.init.normal_(m.weight.data, 1.0, 0.02)
torch.nn.init.constant_(m.bias.data, 0.0)
def to_img(x):
x = x.clamp(0, 1)
return x
def show_image(img):
img = to_img(img)
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
def visualise_output(images, x, y):
with torch.no_grad():
images = images.cpu()
images = to_img(images)
np_imagegrid = make_grid(images, x, y).numpy()
figure(figsize=(20,20))
plt.imshow(np.transpose(np_imagegrid, (1, 2, 0)))
plt.show()
```
GENERATOR
```
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
def block(in_feat, out_feat, normalize=True):
layers = [nn.Linear(in_feat, out_feat)]
if normalize:
layers.append(nn.BatchNorm1d(out_feat, 0.8))
layers.append(nn.LeakyReLU(0.2, inplace=True))
return layers
self.model = nn.Sequential(
*block(hp.latent_dim, 128, normalize=False),
*block(128, 256),
*block(256, 512),
*block(512, 1024),
nn.Linear(1024, int(np.prod(img_shape))),
nn.Tanh()
)
def forward(self, z):
img = self.model(z)
img = img.view(img.shape[0], *img_shape)
return img
```
DISCRIMINATOR
```
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.model = nn.Sequential(
nn.Linear(int(np.prod(img_shape)), 512),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(512, 256),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(256, 1),
)
def forward(self, img):
img_flat = img.view(img.shape[0], -1)
validity = self.model(img_flat)
return validity
```
LOSS and MODELS
```
generator = Generator()
discriminator = Discriminator()
if cuda:
generator.cuda()
discriminator.cuda()
# Initialize weights
generator.apply(weights_init_normal)
discriminator.apply(weights_init_normal)
```
OPTIMIZERS and TENSOR SETUP
```
optimizer_G = torch.optim.RMSprop(generator.parameters(), lr=hp.lr)
optimizer_D = torch.optim.RMSprop(discriminator.parameters(), lr=hp.lr)
Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor
```
GET the DATA
```
os.makedirs("../../data/mnist", exist_ok=True)
dataloader = torch.utils.data.DataLoader(
datasets.FashionMNIST(
"../../data/mnist",
train=True,
download=True,
transform=transforms.Compose(
[transforms.Resize(hp.img_size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]
),
),
batch_size=hp.batch_size,
shuffle=True,
)
```
TRAINING
```
for epoch in range(hp.n_epochs):
for i, (imgs, _) in enumerate(dataloader):
# Adversarial ground truths
valid = Variable(Tensor(imgs.shape[0], 1).fill_(1.0), requires_grad=False)
fake = Variable(Tensor(imgs.shape[0], 1).fill_(0.0), requires_grad=False)
# Configure input
real_imgs = Variable(imgs.type(Tensor))
# -----------------
# Train Discriminator
# -----------------
optimizer_G.zero_grad()
# Sample noise as generator input
z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], hp.latent_dim))))
# Generate a batch of images
fake_imgs = generator(z).detach()
d_loss = -torch.mean(discriminator(real_imgs)) + torch.mean(discriminator(fake_imgs))
d_loss.backward()
optimizer_D.step()
# Clip weights of discriminator
for p in discriminator.parameters():
p.data.clamp_(-hp.clip_value, hp.clip_value)
# Train the generator every n_critic iterations
if i % hp.n_critic == 0:
# ---------------------
# Train Generator
# ---------------------
optimizer_G.zero_grad()
# Generate a batch of images
gen_imgs = generator(z)
# Adversarial loss
g_loss = -torch.mean(discriminator(gen_imgs))
g_loss.backward()
optimizer_G.step()
batches_done = epoch * len(dataloader) + i
if batches_done % hp.sample_interval == 0:
clear_output()
print(f"Epoch:{epoch}:It{i}:DLoss{d_loss.item()}:GLoss{g_loss.item()}")
visualise_output(gen_imgs.data[:50],10, 10)
#save_image(gen_imgs.data[:25], "images/%d.png" % batches_done, nrow=5, normalize=True)
```
|
github_jupyter
|
import math
import os
import torchvision.transforms as transforms
from torchvision.utils import make_grid
from torch.utils.data import DataLoader
from torchvision import datasets
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from tqdm import tqdm
plt.ion()
from IPython.display import clear_output
class Hyperparameters(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
hp = Hyperparameters(n_epochs=200,
batch_size=64,
lr=0.00005,
n_cpu=8,
latent_dim=100,
img_size=32,
channels=1,
n_critic=25,
clip_value=.005,
sample_interval=400)
print(hp.lr)
os.makedirs("images", exist_ok=True)
img_shape = (hp.channels, hp.img_size, hp.img_size)
cuda = True if torch.cuda.is_available() else False
def weights_init_normal(m):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
torch.nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find("BatchNorm2d") != -1:
torch.nn.init.normal_(m.weight.data, 1.0, 0.02)
torch.nn.init.constant_(m.bias.data, 0.0)
def to_img(x):
x = x.clamp(0, 1)
return x
def show_image(img):
img = to_img(img)
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
def visualise_output(images, x, y):
with torch.no_grad():
images = images.cpu()
images = to_img(images)
np_imagegrid = make_grid(images, x, y).numpy()
figure(figsize=(20,20))
plt.imshow(np.transpose(np_imagegrid, (1, 2, 0)))
plt.show()
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
def block(in_feat, out_feat, normalize=True):
layers = [nn.Linear(in_feat, out_feat)]
if normalize:
layers.append(nn.BatchNorm1d(out_feat, 0.8))
layers.append(nn.LeakyReLU(0.2, inplace=True))
return layers
self.model = nn.Sequential(
*block(hp.latent_dim, 128, normalize=False),
*block(128, 256),
*block(256, 512),
*block(512, 1024),
nn.Linear(1024, int(np.prod(img_shape))),
nn.Tanh()
)
def forward(self, z):
img = self.model(z)
img = img.view(img.shape[0], *img_shape)
return img
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.model = nn.Sequential(
nn.Linear(int(np.prod(img_shape)), 512),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(512, 256),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(256, 1),
)
def forward(self, img):
img_flat = img.view(img.shape[0], -1)
validity = self.model(img_flat)
return validity
generator = Generator()
discriminator = Discriminator()
if cuda:
generator.cuda()
discriminator.cuda()
# Initialize weights
generator.apply(weights_init_normal)
discriminator.apply(weights_init_normal)
optimizer_G = torch.optim.RMSprop(generator.parameters(), lr=hp.lr)
optimizer_D = torch.optim.RMSprop(discriminator.parameters(), lr=hp.lr)
Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor
os.makedirs("../../data/mnist", exist_ok=True)
dataloader = torch.utils.data.DataLoader(
datasets.FashionMNIST(
"../../data/mnist",
train=True,
download=True,
transform=transforms.Compose(
[transforms.Resize(hp.img_size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]
),
),
batch_size=hp.batch_size,
shuffle=True,
)
for epoch in range(hp.n_epochs):
for i, (imgs, _) in enumerate(dataloader):
# Adversarial ground truths
valid = Variable(Tensor(imgs.shape[0], 1).fill_(1.0), requires_grad=False)
fake = Variable(Tensor(imgs.shape[0], 1).fill_(0.0), requires_grad=False)
# Configure input
real_imgs = Variable(imgs.type(Tensor))
# -----------------
# Train Discriminator
# -----------------
optimizer_G.zero_grad()
# Sample noise as generator input
z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], hp.latent_dim))))
# Generate a batch of images
fake_imgs = generator(z).detach()
d_loss = -torch.mean(discriminator(real_imgs)) + torch.mean(discriminator(fake_imgs))
d_loss.backward()
optimizer_D.step()
# Clip weights of discriminator
for p in discriminator.parameters():
p.data.clamp_(-hp.clip_value, hp.clip_value)
# Train the generator every n_critic iterations
if i % hp.n_critic == 0:
# ---------------------
# Train Generator
# ---------------------
optimizer_G.zero_grad()
# Generate a batch of images
gen_imgs = generator(z)
# Adversarial loss
g_loss = -torch.mean(discriminator(gen_imgs))
g_loss.backward()
optimizer_G.step()
batches_done = epoch * len(dataloader) + i
if batches_done % hp.sample_interval == 0:
clear_output()
print(f"Epoch:{epoch}:It{i}:DLoss{d_loss.item()}:GLoss{g_loss.item()}")
visualise_output(gen_imgs.data[:50],10, 10)
#save_image(gen_imgs.data[:25], "images/%d.png" % batches_done, nrow=5, normalize=True)
| 0.907355 | 0.890723 |
# Python Fundamentals 5: Tuples
Tuples is another of the built-in data types used to store collections of data in Python (along with `list`, `set` and `dictionary`. The difference between a `list` and a `tuple` is that a `list` is _changeable_ whereas a `tuple` is _unchangeable._ This means we can't add, change or remove any items after the tuple is created.
```
# Create a tuple
my_tuple = ("orange", 7, "lemon", 3.14, "mandarin", 7j, True)
print(my_tuple) # Print the tuple
print(len(my_tuple)) # Print the length of the tuple
print(type(my_tuple)) # Print the type of the tuple (to confirm it's a tuple)
```
## Accessing Tuple Elements
In much the same way as we saw with lists, we can access elements using indices:
```
my_tuple = ("orange", 7, "lemon", 3.14, "mandarin", 7j, True)
print(my_tuple[3]) # Usual index - element at position 3 (fourth element)
print(my_tuple[-2]) # Index 1 from end
print(my_tuple[2:5]) # Indexing a range
print(my_tuple[-5:-2]) # Backwards indexing a range
# Find a specified element
if 7j in my_tuple :
print("Element is in the tuple")
```
## Updating Tuples
As we mentioned, it's not possible to change the values in a tuple because they are _immutable_ (also known as _unchangeable_). However, we can effectively change the values we want by first converting the tuple to a _list,_ changing the values in the usual list ways and then converting back to a tuple.
```
my_tuple = ("orange", 7, "lemon", 3.14, "mandarin", 7j, True)
print(my_tuple)
my_list = list(my_tuple) # Converting to a list
my_list[1] = "lime" # Changing an element
my_tuple = tuple(my_list) # Convert back to a tuple
print(my_tuple)
```
## Packing and Unpacking
When we create a new tuple, we assign values to locations - this is known as _packing_ a tuple. In Python, we can also _unpack_ a tuple by extracting the values back out to variables. If we don't declare enough variable names to assign data values to, we need to use an asterisk to tell Python we want to assign several values to the variable name.
```
my_tuple = ("orange", 7, "lemon", 3.14, "mandarin", 7j, True)
(orange, seven, lemon, pi, *mandarin_complex, boolean) = my_tuple # Assign variables to data
print(orange)
print(pi)
print(mandarin_complex)
print(something)
```
## Looping Through a Tuple
As with lists, we can loop through a tuple in different ways.
```
my_tuple = ("orange", 7, "lemon", 3.14, "mandarin", 7j, True)
# Iterate through items
for x in my_tuple :
print(x)
print()
# Loop through index numbers
for i in range(len(my_tuple)) :
print(my_tuple[i])
print()
# Using a while loop
i = 0
while i < len(my_tuple) :
print(my_tuple[i])
i +=1
```
## Tuple methods
We have a few tuple methods to choose from in Python:
* `+` can be used to join two tuples together: `tuple3 = tuple1 + tuple2`
* `*` can be used to multiply tuples: `tuple2 = tuple1 * 2` is equivalent to `tuple2 = tuple1 + tuple1`
* `count(element)` returns the number of times `element` appears in the triple
* `index(element)` returns the index of `element` if it exists in the tuple. If there's more than one, it'll return the first instance.
|
github_jupyter
|
# Create a tuple
my_tuple = ("orange", 7, "lemon", 3.14, "mandarin", 7j, True)
print(my_tuple) # Print the tuple
print(len(my_tuple)) # Print the length of the tuple
print(type(my_tuple)) # Print the type of the tuple (to confirm it's a tuple)
my_tuple = ("orange", 7, "lemon", 3.14, "mandarin", 7j, True)
print(my_tuple[3]) # Usual index - element at position 3 (fourth element)
print(my_tuple[-2]) # Index 1 from end
print(my_tuple[2:5]) # Indexing a range
print(my_tuple[-5:-2]) # Backwards indexing a range
# Find a specified element
if 7j in my_tuple :
print("Element is in the tuple")
my_tuple = ("orange", 7, "lemon", 3.14, "mandarin", 7j, True)
print(my_tuple)
my_list = list(my_tuple) # Converting to a list
my_list[1] = "lime" # Changing an element
my_tuple = tuple(my_list) # Convert back to a tuple
print(my_tuple)
my_tuple = ("orange", 7, "lemon", 3.14, "mandarin", 7j, True)
(orange, seven, lemon, pi, *mandarin_complex, boolean) = my_tuple # Assign variables to data
print(orange)
print(pi)
print(mandarin_complex)
print(something)
my_tuple = ("orange", 7, "lemon", 3.14, "mandarin", 7j, True)
# Iterate through items
for x in my_tuple :
print(x)
print()
# Loop through index numbers
for i in range(len(my_tuple)) :
print(my_tuple[i])
print()
# Using a while loop
i = 0
while i < len(my_tuple) :
print(my_tuple[i])
i +=1
| 0.329607 | 0.983581 |
# Solution to Intro to NLP
Ex: Calculate the TTR for two novels in our data folder. Print the most frequent words for these two novels.
### 0. Read in text, pre-processing steps
```
import nltk
import string
from nltk import word_tokenize
from nltk.corpus import stopwords
#open and read the novels, save them as variables
austen_string = open('../Data/Austen_PrideAndPrejudice.txt', encoding='utf-8').read()
alcott_string = open('../Data/Alcott_GarlandForGirls.txt', encoding='utf-8').read()
#tokenize the text
austen_list = word_tokenize(austen_string)
alcott_list = word_tokenize(alcott_string)
print(austen_list[:10])
print(alcott_list[:10])
#pre-processing
#remove punctuation and lowercase. We can do this in one line!
punctuation = list(string.punctuation)
austen_list_clean = [word.lower() for word in austen_list if word not in punctuation]
alcott_list_clean = [word.lower() for word in alcott_list if word not in punctuation]
print(austen_list_clean[:10])
print(alcott_list_clean[:10])
```
### 1. Type-Token Ratio
Divide the length of the set of the text (the unique elements) by the length of the full list
```
print("TTR for Pride and Prejudice")
print(len(set(austen_list_clean))/len(austen_list_clean))
print("TTR for A Garland for Girls")
print(len(set(alcott_list_clean))/len(alcott_list_clean))
```
### 2. Frequent Words
```
austen_word_frequency = nltk.FreqDist(austen_list_clean)
alcott_word_frequency = nltk.FreqDist(alcott_list_clean)
print("Frequent words in Pride and Prejudice")
print(austen_word_frequency.most_common(10))
print("Frequent words in A Garland for Girls")
print(alcott_word_frequency.most_common(10))
```
### 3. Bonus: Plotting word distribution
```
austen_word_frequency.plot(50, cumulative=True)
austen_word_frequency.plot(50, cumulative=False)
```
The most frequent words are, of course, the stop words. These words do not tell us much about the content of the text.
### 4. Count word frequencies after removing stop words
```
austen_list_clean_sw = [word for word in austen_list_clean if word not in stopwords.words('english')]
alcott_list_clean_sw = [word for word in alcott_list_clean if word not in stopwords.words('english')]
austen_word_frequency_sw = nltk.FreqDist(austen_list_clean_sw)
alcott_word_frequency_sw = nltk.FreqDist(alcott_list_clean_sw)
print("Frequent words in Pride and Prejudice")
print(austen_word_frequency_sw.most_common(20))
print()
print("Frequent words in A Garland for Girls")
print(alcott_word_frequency_sw.most_common(20))
```
### 5. Bonus: Concordances (if time)
The NLTK package has many built-in functions for natural language processing. I encourage you to explore the full range of techniques available. I'll go over two more here: concordance() and similar().
The concordance() function lists out every time the specified words appears in the text along with the surrounding context.
```
marx_string = open('../Data/Marx_CommunistManifesto.txt', encoding='utf-8').read()
prince_string = open('../Data/Machiavelli_ThePrince.txt', encoding='utf-8').read()
marx_list = word_tokenize(marx_string)
prince_list = word_tokenize(prince_string)
marx_nltk = nltk.Text(marx_list)
prince_nltk = nltk.Text(prince_list)
print(prince_nltk)
marx_nltk
marx_nltk.concordance('people')
prince_nltk.concordance('people')
```
The text.similar() method takes a word w, finds all contexts w1 w w2, then finds all words w' that appear in the same context, i.e. w1 w' w2
```
print("Marx")
marx_nltk.similar('people')
print()
print("Machiavelli")
prince_nltk.similar('people')
```
|
github_jupyter
|
import nltk
import string
from nltk import word_tokenize
from nltk.corpus import stopwords
#open and read the novels, save them as variables
austen_string = open('../Data/Austen_PrideAndPrejudice.txt', encoding='utf-8').read()
alcott_string = open('../Data/Alcott_GarlandForGirls.txt', encoding='utf-8').read()
#tokenize the text
austen_list = word_tokenize(austen_string)
alcott_list = word_tokenize(alcott_string)
print(austen_list[:10])
print(alcott_list[:10])
#pre-processing
#remove punctuation and lowercase. We can do this in one line!
punctuation = list(string.punctuation)
austen_list_clean = [word.lower() for word in austen_list if word not in punctuation]
alcott_list_clean = [word.lower() for word in alcott_list if word not in punctuation]
print(austen_list_clean[:10])
print(alcott_list_clean[:10])
print("TTR for Pride and Prejudice")
print(len(set(austen_list_clean))/len(austen_list_clean))
print("TTR for A Garland for Girls")
print(len(set(alcott_list_clean))/len(alcott_list_clean))
austen_word_frequency = nltk.FreqDist(austen_list_clean)
alcott_word_frequency = nltk.FreqDist(alcott_list_clean)
print("Frequent words in Pride and Prejudice")
print(austen_word_frequency.most_common(10))
print("Frequent words in A Garland for Girls")
print(alcott_word_frequency.most_common(10))
austen_word_frequency.plot(50, cumulative=True)
austen_word_frequency.plot(50, cumulative=False)
austen_list_clean_sw = [word for word in austen_list_clean if word not in stopwords.words('english')]
alcott_list_clean_sw = [word for word in alcott_list_clean if word not in stopwords.words('english')]
austen_word_frequency_sw = nltk.FreqDist(austen_list_clean_sw)
alcott_word_frequency_sw = nltk.FreqDist(alcott_list_clean_sw)
print("Frequent words in Pride and Prejudice")
print(austen_word_frequency_sw.most_common(20))
print()
print("Frequent words in A Garland for Girls")
print(alcott_word_frequency_sw.most_common(20))
marx_string = open('../Data/Marx_CommunistManifesto.txt', encoding='utf-8').read()
prince_string = open('../Data/Machiavelli_ThePrince.txt', encoding='utf-8').read()
marx_list = word_tokenize(marx_string)
prince_list = word_tokenize(prince_string)
marx_nltk = nltk.Text(marx_list)
prince_nltk = nltk.Text(prince_list)
print(prince_nltk)
marx_nltk
marx_nltk.concordance('people')
prince_nltk.concordance('people')
print("Marx")
marx_nltk.similar('people')
print()
print("Machiavelli")
prince_nltk.similar('people')
| 0.126299 | 0.789315 |
# Filters in pycoco
---------------------
## Introduction
This notebook aims to serve as a short tutorial (along with the others in this directory). In this notebook, the tools for adding/testing/plotting filters in `pycoco`, as a companion to the `c` code `CoCo`
```
from __future__ import print_function ## Force python3-like printing
try:
reload # Python 2.7
except NameError:
try:
from importlib import reload # Python 3.4+
except ImportError:
from imp import reload # Python 3.0 - 3.3
%matplotlib inline
from matplotlib import pyplot as plt
import os
import numpy as np
from astropy.table import Table, Column
import astropy.units as u
import pycoco as pcc
reload(pcc) ## FOR DEV
```
## Using `FilterClass`
### `FilterClass` Methods and Variables
Filters in **`pycoco`** are handled using a **`classes.FilterClass()`**, which has the methods:
**`classes.FilterClass.__init__()`**
**`classes.FilterClass.read_filter_file()`**
**`classes.FilterClass.calculate_effective_wavelength()`**
**`classes.FilterClass.calculate_edges()`**
**`classes.FilterClass.plot()`**
**`classes.FilterClass.resample_response()`**
**`classes.FilterClass.calculate_plot_colour()`**
and variables:
**`classes.FilterClass._wavelength_units`**
**`classes.FilterClass._filter_file_path`**
**`classes.FilterClass._upper_edge`**
**`classes.FilterClass._lower_edge`**
**`classes.FilterClass.lambda_effective`**
**`classes.FilterClass.wavelength`**
**`classes.FilterClass.throughput`**
### Loading a Filter
We can use **`pcc.functions.load_filter()`** to intialise a FilterClass instance and load in a response function given a valid path to that filter.
**`pcc.functions.load_filter()`** is essentially a wrapper for the class methods: **read_filter_file()**, **calculate_effective_wavelength()** and **calculate_plot_colour()**.
```
verbose = False
filter_filename = "BessellB.dat"
path_to_filter = os.path.join(pcc.defaults._default_filter_dir_path, filter_filename)
if verbose: print("Path to the filter: ", path_to_filter)
B = pcc.classes.FilterClass()
B.read_filter_file(path_to_filter)
path_to_filter
B.calculate_AB_zp()
B.zp_AB
print(pcc.hex["B"])
print(pcc.hex["BessellB"])
```
Now we can check that everything has been loaded in automatically.
```
B.__dict__
```
Looks good! But we can always check by plotting.
```
B.plot()
```
If the effective wavelength of the filter has been calculated, then a colour can be picked from a colourmap. This will come in handy for datasets with more than a few filters. This can be done using **`FilterClass.calculate_plot_colour(...)`**
```
B.calculate_plot_colour()
B.plot()
```
You can also show the edges of the filter by passing `show_lims = True`. This uses the edges as defined by **`classes.FilterClass.calculate_edges()`** and stored in **`FilterClass._upper_edge`** and
**`classes.FilterClass._lower_edge`**
```
B.plot(show_lims = True)
B.plot(show_lims = True)
```
As well as dealing with the filters in wavelength-space, frequency conversions can also be done. The calculation for effective F_nu especially is useful for making flux unit conversions
```
B.calculate_frequency()
B.frequency_u
B.calculate_effective_frequency()
B.nu_effective
sdssg = pcc.functions.load_filter(path = os.path.join(pcc.defaults._default_filter_dir_path, 'SDSS_g.dat'))
sdssg.plot(show_lims=True)
sdssg._lower_edge
sdssz = pcc.functions.load_filter(path = os.path.join(pcc.defaults._default_filter_dir_path, 'SDSS_z.dat'))
sdssz.plot()
sdssz.resample_response(new_wavelength=sdssz.wavelength - 100*u.angstrom)
sdssz.plot(show_lims = True)
sdssz.plot(cumulative=True, show_lims = True)
BI = pcc.functions.load_filter(path = os.path.join(pcc.defaults._default_filter_dir_path, 'BessellI.dat'))
BI.plot()
```
## Adding Filters
----
We have shown above how to interact with existing filters, the following steps will take you though adding new filters.
The current best way to load in a new filter is using an `astropy` Table, with the wavelength and throughput as the columns, like so:
```
## Choose sensible values for wavelength
wavelength = Column(np.linspace(3500, 9000, 100), name = "wavelength", unit = u.angstrom)
## Choose some arbitrary values for the gaussian
throughput = pcc.utils.gaussian(wavelength, 0.8, 6000., 500.)
throughput.name = "throughput"
throughput.unit = None
input_table = Table([wavelength, throughput])
```
We can now load this in using **`classes.FilterClass.load_table(...)`** and take a look at what it looks like.
```
gauss_filter = pcc.classes.FilterClass()
gauss_filter.load_table(input_table,"gaussian_filter")
gauss_filter.plot()
```
### Saving Filters
---
When we decided everything is as it should be, we can save the throughput to the **`CoCo`** filters directory (or somewhere else, nobody put me in charge).
```
gauss_filter.save("gaussian_6000_500.dat", squash = True)
```
We can now load it in as usual:
```
load_gauss_filter = pcc.classes.FilterClass()
load_gauss_filter.read_filter_file(os.path.join(pcc.defaults._default_filter_dir_path, "gaussian_6000_500.dat"))
load_gauss_filter.plot()
```
### Registering a New Filter
---
Once we have saved a new filter, for **`CoCo`** to recognise it, it must be added to the registry found in `COCO_ROOT_DIR/data/filters/list.dat`.
To avoid doing anything unneccessarily, we can check the number of filters in the directory and in the list file.
```
## Check whether the list file is up to date
pcc.utils._check_filters()
```
This `False` means the directory and list are out of sync.
```
"gaussian_6000_500.dat" in pcc.utils._get_current_filter_registry()
```
To relist and add the new filter to the registry:
```
pcc.utils.relist()
pcc.utils._check_filters()
"gaussian_6000_500.dat" in pcc.utils._get_current_filter_registry()
```
|
github_jupyter
|
from __future__ import print_function ## Force python3-like printing
try:
reload # Python 2.7
except NameError:
try:
from importlib import reload # Python 3.4+
except ImportError:
from imp import reload # Python 3.0 - 3.3
%matplotlib inline
from matplotlib import pyplot as plt
import os
import numpy as np
from astropy.table import Table, Column
import astropy.units as u
import pycoco as pcc
reload(pcc) ## FOR DEV
verbose = False
filter_filename = "BessellB.dat"
path_to_filter = os.path.join(pcc.defaults._default_filter_dir_path, filter_filename)
if verbose: print("Path to the filter: ", path_to_filter)
B = pcc.classes.FilterClass()
B.read_filter_file(path_to_filter)
path_to_filter
B.calculate_AB_zp()
B.zp_AB
print(pcc.hex["B"])
print(pcc.hex["BessellB"])
B.__dict__
B.plot()
B.calculate_plot_colour()
B.plot()
B.plot(show_lims = True)
B.plot(show_lims = True)
B.calculate_frequency()
B.frequency_u
B.calculate_effective_frequency()
B.nu_effective
sdssg = pcc.functions.load_filter(path = os.path.join(pcc.defaults._default_filter_dir_path, 'SDSS_g.dat'))
sdssg.plot(show_lims=True)
sdssg._lower_edge
sdssz = pcc.functions.load_filter(path = os.path.join(pcc.defaults._default_filter_dir_path, 'SDSS_z.dat'))
sdssz.plot()
sdssz.resample_response(new_wavelength=sdssz.wavelength - 100*u.angstrom)
sdssz.plot(show_lims = True)
sdssz.plot(cumulative=True, show_lims = True)
BI = pcc.functions.load_filter(path = os.path.join(pcc.defaults._default_filter_dir_path, 'BessellI.dat'))
BI.plot()
## Choose sensible values for wavelength
wavelength = Column(np.linspace(3500, 9000, 100), name = "wavelength", unit = u.angstrom)
## Choose some arbitrary values for the gaussian
throughput = pcc.utils.gaussian(wavelength, 0.8, 6000., 500.)
throughput.name = "throughput"
throughput.unit = None
input_table = Table([wavelength, throughput])
gauss_filter = pcc.classes.FilterClass()
gauss_filter.load_table(input_table,"gaussian_filter")
gauss_filter.plot()
gauss_filter.save("gaussian_6000_500.dat", squash = True)
load_gauss_filter = pcc.classes.FilterClass()
load_gauss_filter.read_filter_file(os.path.join(pcc.defaults._default_filter_dir_path, "gaussian_6000_500.dat"))
load_gauss_filter.plot()
## Check whether the list file is up to date
pcc.utils._check_filters()
"gaussian_6000_500.dat" in pcc.utils._get_current_filter_registry()
pcc.utils.relist()
pcc.utils._check_filters()
"gaussian_6000_500.dat" in pcc.utils._get_current_filter_registry()
| 0.545044 | 0.970127 |
```
import os
import re
import itertools
import pandas as pd
from sklearn.metrics import cohen_kappa_score as cks
from tabulate import tabulate
```
### Building the dataframe with the results
```
datapath = 'E:\\IRELAND\\ChiA\\Chia\\data\\img_labeling_2nd_round\\'
label_files = sorted(os.listdir(datapath))
label_files = [f for f in label_files if 'A00' in f]
for f in label_files:
print(f)
list_dfs = []
for label_file in label_files:
task = int(re.findall(r'[1-3]{1}', label_file)[0])
user = re.findall(r'A001|A002|A003|A004|A005|A006', label_file)[0]
date = re.findall(r'202[0-1]{1}.[0-9]{2}.[0-9]{2}', label_file)[0]
#date = f'{date}-2020'
df = pd.read_csv(f'{datapath}{label_file}', names=['image name', 'class','w','h'])
df['task'] = task
df['user'] = user
df['date'] = date
df['date'] = pd.to_datetime(df['date'])
df.drop(['w','h'], axis=1, inplace=True)
df.drop_duplicates(inplace=True)
df = df[['task', 'user', 'date', 'image name', 'class']]
print(f'Task: {task}, User: {user}, Images Classified: {len(df)}')
list_dfs.append(df)
df_labeling = pd.concat(list_dfs)
df_labeling['id_image'] = pd.Categorical(df_labeling['image name']).codes
df_labeling["class"] = df_labeling["class"].apply(lambda x:x[1:-1])
df_labeling = df_labeling[['task', 'user', 'date', 'image name', 'id_image', 'class']]
df_labeling.head()
df_labeling['class'].unique()
df_labeling['image_appearances'] = df_labeling.groupby('id_image')['id_image'].transform('count')
df_labeling = df_labeling[df_labeling['image_appearances'] != 1]
df_labeling.info()
df_labeling.head()
```
#### Checking the numbers of images classified after fixing names:
```
for task in df_labeling.task.unique():
for user in df_labeling.user.unique():
size = len(df_labeling.loc[(df_labeling.user == user) & (df_labeling.task == task), 'id_image'].unique())
print(f'Task: {task}, User: {user}, Images Classified: {size}')
print()
```
#### Checking which images were not classified:
```
images = set(df_labeling.id_image.unique())
dfs = []
for task in df_labeling.task.unique():
for user in df_labeling.user.unique():
id_list = []
ids = images.difference(set(df_labeling.loc[(df_labeling.user == user) & (df_labeling.task == task), 'id_image']))
if len(ids) > 0:
#print(f'Missing files for task: {task}, by user: {user}')
for _id in ids:
try:
id_list.append(df_labeling.loc[(df_labeling.task == task) & (df_labeling.id_image == _id), 'image name'].values[0])
#print(df_labeling.loc[(df_labeling.task == task) & (df_labeling.id_image == _id), 'image name'].values[0])
except:
pass
#print('--->', df_labeling.loc[(df_labeling.task == task) & (df_labeling.id_image == _id), 'image name'].values)
#print()
dfm = pd.DataFrame({'images':id_list})
dfm['task'] = task
dfm['user'] = user
dfs.append(dfm)
df_missing = pd.concat(dfs)
df_missing.to_excel(f'{datapath}/missing.xlsx')
df_missing.head()
```
#### Checking duplicates
```
duplicates = df_labeling.loc[df_labeling.duplicated(['task', 'user', 'image name', 'id_image'], keep=False), ['task', 'user', 'image name', 'id_image', 'class']]
duplicates.sort_values(by=['user', 'image name', 'task'], inplace=True)
duplicates.to_excel(f'{datapath}/duplicates.xlsx')
duplicates.head(30)
```
### Analysing the [inter-annotator agreement](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.cohen_kappa_score.html) on the results
```
l1 = df_labeling.user.unique()
iter_users = list(itertools.product(l1,l1))
df_iaa = pd.DataFrame(index=l1, columns=l1)
for task in df_labeling.task.unique():
total_agreement = 0
for user1,user2 in iter_users:
classesA = df_labeling.loc[(df_labeling.user == user1) & (df_labeling.task == task),['id_image', 'class']]
classesA.sort_values(by=['id_image'], inplace=True)
classesB = df_labeling.loc[(df_labeling.user == user2) & (df_labeling.task == task),['id_image', 'class']]
classesB.sort_values(by=['id_image'], inplace=True)
classesAB = pd.merge(classesA, classesB, on=['id_image'])
classesAB.drop_duplicates(subset='id_image', keep = 'first', inplace=True)
classesAB.drop('id_image', axis=1, inplace=True)
classesAB.dropna(inplace=True)
agreement = cks(classesAB['class_x'], classesAB['class_y'])
total_agreement += agreement
df_iaa.loc[user1,user2] = f'{agreement:.3f}/({len(classesAB)})'
df_iaa.index.name = f'Task_{task}'
print(tabulate(df_iaa, headers='keys', tablefmt='psql'))
print(f'\nThe average agreement was {total_agreement/(len(l1)**2):.3f}\n\n')
df_labeling.info()
df_labeling['round'] = 2
df_labeling.drop('image_appearances', inplace=True, axis=1)
#df_labeling.to_hdf('../data/df_labeling.hdf', key='round2')
```
|
github_jupyter
|
import os
import re
import itertools
import pandas as pd
from sklearn.metrics import cohen_kappa_score as cks
from tabulate import tabulate
datapath = 'E:\\IRELAND\\ChiA\\Chia\\data\\img_labeling_2nd_round\\'
label_files = sorted(os.listdir(datapath))
label_files = [f for f in label_files if 'A00' in f]
for f in label_files:
print(f)
list_dfs = []
for label_file in label_files:
task = int(re.findall(r'[1-3]{1}', label_file)[0])
user = re.findall(r'A001|A002|A003|A004|A005|A006', label_file)[0]
date = re.findall(r'202[0-1]{1}.[0-9]{2}.[0-9]{2}', label_file)[0]
#date = f'{date}-2020'
df = pd.read_csv(f'{datapath}{label_file}', names=['image name', 'class','w','h'])
df['task'] = task
df['user'] = user
df['date'] = date
df['date'] = pd.to_datetime(df['date'])
df.drop(['w','h'], axis=1, inplace=True)
df.drop_duplicates(inplace=True)
df = df[['task', 'user', 'date', 'image name', 'class']]
print(f'Task: {task}, User: {user}, Images Classified: {len(df)}')
list_dfs.append(df)
df_labeling = pd.concat(list_dfs)
df_labeling['id_image'] = pd.Categorical(df_labeling['image name']).codes
df_labeling["class"] = df_labeling["class"].apply(lambda x:x[1:-1])
df_labeling = df_labeling[['task', 'user', 'date', 'image name', 'id_image', 'class']]
df_labeling.head()
df_labeling['class'].unique()
df_labeling['image_appearances'] = df_labeling.groupby('id_image')['id_image'].transform('count')
df_labeling = df_labeling[df_labeling['image_appearances'] != 1]
df_labeling.info()
df_labeling.head()
for task in df_labeling.task.unique():
for user in df_labeling.user.unique():
size = len(df_labeling.loc[(df_labeling.user == user) & (df_labeling.task == task), 'id_image'].unique())
print(f'Task: {task}, User: {user}, Images Classified: {size}')
print()
images = set(df_labeling.id_image.unique())
dfs = []
for task in df_labeling.task.unique():
for user in df_labeling.user.unique():
id_list = []
ids = images.difference(set(df_labeling.loc[(df_labeling.user == user) & (df_labeling.task == task), 'id_image']))
if len(ids) > 0:
#print(f'Missing files for task: {task}, by user: {user}')
for _id in ids:
try:
id_list.append(df_labeling.loc[(df_labeling.task == task) & (df_labeling.id_image == _id), 'image name'].values[0])
#print(df_labeling.loc[(df_labeling.task == task) & (df_labeling.id_image == _id), 'image name'].values[0])
except:
pass
#print('--->', df_labeling.loc[(df_labeling.task == task) & (df_labeling.id_image == _id), 'image name'].values)
#print()
dfm = pd.DataFrame({'images':id_list})
dfm['task'] = task
dfm['user'] = user
dfs.append(dfm)
df_missing = pd.concat(dfs)
df_missing.to_excel(f'{datapath}/missing.xlsx')
df_missing.head()
duplicates = df_labeling.loc[df_labeling.duplicated(['task', 'user', 'image name', 'id_image'], keep=False), ['task', 'user', 'image name', 'id_image', 'class']]
duplicates.sort_values(by=['user', 'image name', 'task'], inplace=True)
duplicates.to_excel(f'{datapath}/duplicates.xlsx')
duplicates.head(30)
l1 = df_labeling.user.unique()
iter_users = list(itertools.product(l1,l1))
df_iaa = pd.DataFrame(index=l1, columns=l1)
for task in df_labeling.task.unique():
total_agreement = 0
for user1,user2 in iter_users:
classesA = df_labeling.loc[(df_labeling.user == user1) & (df_labeling.task == task),['id_image', 'class']]
classesA.sort_values(by=['id_image'], inplace=True)
classesB = df_labeling.loc[(df_labeling.user == user2) & (df_labeling.task == task),['id_image', 'class']]
classesB.sort_values(by=['id_image'], inplace=True)
classesAB = pd.merge(classesA, classesB, on=['id_image'])
classesAB.drop_duplicates(subset='id_image', keep = 'first', inplace=True)
classesAB.drop('id_image', axis=1, inplace=True)
classesAB.dropna(inplace=True)
agreement = cks(classesAB['class_x'], classesAB['class_y'])
total_agreement += agreement
df_iaa.loc[user1,user2] = f'{agreement:.3f}/({len(classesAB)})'
df_iaa.index.name = f'Task_{task}'
print(tabulate(df_iaa, headers='keys', tablefmt='psql'))
print(f'\nThe average agreement was {total_agreement/(len(l1)**2):.3f}\n\n')
df_labeling.info()
df_labeling['round'] = 2
df_labeling.drop('image_appearances', inplace=True, axis=1)
#df_labeling.to_hdf('../data/df_labeling.hdf', key='round2')
| 0.128225 | 0.449211 |
# Single Neuron
## Setup Keras
```
!pip install keras
import numpy as np
from keras import backend as kbe
# Test Keras - backend interaction
data = kbe.variable(np.random.random((4,2))) # create 4 X 2 tensor of random numbers
print(kbe.eval(data)) # evaluate the data and print out the results
zero_data = kbe.zeros_like(data) # create 4 X 2 tensor of zeros
print(kbe.eval(zero_data)) # evaluate the zero_data and print out the results
```
## Helper functions for plotting the results
```
from sklearn.datasets import make_blobs
import numpy as np
import matplotlib.pyplot as plt
# plot the data on a figure
def plot_data(pl, X, y):
# plot class where y==0
pl.plot(X[y==0, 0], X[y==0,1], 'ob', alpha=0.5)
# plot class where y==1
pl.plot(X[y==1, 0], X[y==1,1], 'xr', alpha=0.5)
pl.legend(['0', '1'])
return pl
# Common function that draws the decision boundaries
def plot_decision_boundary(model, X, y):
amin, bmin = X.min(axis=0) - 0.1
amax, bmax = X.max(axis=0) + 0.1
hticks = np.linspace(amin, amax, 101)
vticks = np.linspace(bmin, bmax, 101)
aa, bb = np.meshgrid(hticks, vticks)
ab = np.c_[aa.ravel(), bb.ravel()]
# make prediction with the model and reshape the output so contourf can plot it
c = model.predict(ab)
Z = c.reshape(aa.shape)
plt.figure(figsize=(12, 8))
# plot the contour
plt.contourf(aa, bb, Z, cmap='bwr', alpha=0.2)
# plot the moons of data
plot_data(plt, X, y)
return plt
```
## Generate Demo Data
```
# Data will be either 0 or 1 when 2 is number of centers.
# X is a [number of samples, 2] sized array. X[sample] contains its x,y position of the sample in the space
# ex: X[1] = [1.342, -2.3], X[2] = [-4.342, 2.12]
# y is a [number of samples] sized array. y[sample] contains the class index (ie. 0 or 1 when there are 2 centers)
# ex: y[1] = 0 , y[1] = 1
X, y = make_blobs(n_samples=1000, centers=2, random_state=58)
pl = plot_data(plt, X, y)
pl.show()
# Split the data into Training and Test sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=58)
```
## Define Model
```
# Import Keras libraries
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
# Simple Sequential model
model = Sequential()
# Add a Dense Fully Connected Layer with 1 neuron. Using input_shape = (2,) says the input will
# be arrays of the form (*,2). The first dimension will be an unspecified
# number of batches (rows) of data. The second dimension is 2 which are the X, Y positions of each data element.
# The sigmoid activation function is used to return 0 or 1, signifying the data
# cluster the position is predicted to belong to.
model.add(Dense(1, input_shape=(2,), activation="sigmoid"))
model.summary()
```
## Train
```
# Compile the model. Minimize crossentopy for a binary. Maximize for accuracy
model.compile(Adam(lr=0.05), 'binary_crossentropy', metrics=['accuracy'])
# Fit the model with the data from make_blobs. Make 100 cycles through the data.
# Set verbose to 0 to supress progress messages
model.fit(X_train, y_train, epochs=100, verbose=1)
# Get loss and accuracy on test data
eval_result = model.evaluate(X_test, y_test)
# Print test accuracy
print("\n\nTest loss:", eval_result[0], "Test accuracy:", eval_result[1])
# Plot the decision boundary
plot_decision_boundary(model, X, y).show()
```
|
github_jupyter
|
!pip install keras
import numpy as np
from keras import backend as kbe
# Test Keras - backend interaction
data = kbe.variable(np.random.random((4,2))) # create 4 X 2 tensor of random numbers
print(kbe.eval(data)) # evaluate the data and print out the results
zero_data = kbe.zeros_like(data) # create 4 X 2 tensor of zeros
print(kbe.eval(zero_data)) # evaluate the zero_data and print out the results
from sklearn.datasets import make_blobs
import numpy as np
import matplotlib.pyplot as plt
# plot the data on a figure
def plot_data(pl, X, y):
# plot class where y==0
pl.plot(X[y==0, 0], X[y==0,1], 'ob', alpha=0.5)
# plot class where y==1
pl.plot(X[y==1, 0], X[y==1,1], 'xr', alpha=0.5)
pl.legend(['0', '1'])
return pl
# Common function that draws the decision boundaries
def plot_decision_boundary(model, X, y):
amin, bmin = X.min(axis=0) - 0.1
amax, bmax = X.max(axis=0) + 0.1
hticks = np.linspace(amin, amax, 101)
vticks = np.linspace(bmin, bmax, 101)
aa, bb = np.meshgrid(hticks, vticks)
ab = np.c_[aa.ravel(), bb.ravel()]
# make prediction with the model and reshape the output so contourf can plot it
c = model.predict(ab)
Z = c.reshape(aa.shape)
plt.figure(figsize=(12, 8))
# plot the contour
plt.contourf(aa, bb, Z, cmap='bwr', alpha=0.2)
# plot the moons of data
plot_data(plt, X, y)
return plt
# Data will be either 0 or 1 when 2 is number of centers.
# X is a [number of samples, 2] sized array. X[sample] contains its x,y position of the sample in the space
# ex: X[1] = [1.342, -2.3], X[2] = [-4.342, 2.12]
# y is a [number of samples] sized array. y[sample] contains the class index (ie. 0 or 1 when there are 2 centers)
# ex: y[1] = 0 , y[1] = 1
X, y = make_blobs(n_samples=1000, centers=2, random_state=58)
pl = plot_data(plt, X, y)
pl.show()
# Split the data into Training and Test sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=58)
# Import Keras libraries
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
# Simple Sequential model
model = Sequential()
# Add a Dense Fully Connected Layer with 1 neuron. Using input_shape = (2,) says the input will
# be arrays of the form (*,2). The first dimension will be an unspecified
# number of batches (rows) of data. The second dimension is 2 which are the X, Y positions of each data element.
# The sigmoid activation function is used to return 0 or 1, signifying the data
# cluster the position is predicted to belong to.
model.add(Dense(1, input_shape=(2,), activation="sigmoid"))
model.summary()
# Compile the model. Minimize crossentopy for a binary. Maximize for accuracy
model.compile(Adam(lr=0.05), 'binary_crossentropy', metrics=['accuracy'])
# Fit the model with the data from make_blobs. Make 100 cycles through the data.
# Set verbose to 0 to supress progress messages
model.fit(X_train, y_train, epochs=100, verbose=1)
# Get loss and accuracy on test data
eval_result = model.evaluate(X_test, y_test)
# Print test accuracy
print("\n\nTest loss:", eval_result[0], "Test accuracy:", eval_result[1])
# Plot the decision boundary
plot_decision_boundary(model, X, y).show()
| 0.884077 | 0.951863 |
[](https://www.pythonista.io)
# Introspección y ayuda.
## Introspección en Python.
Se entiende por instrospección a la capacidad de Python de obtener información y documentación útil a partir de un objeto.
## La función ```dir()``` .
Cada objeto contiene un espacio de nombres propio. La función ```dir()``` regresa una lista de los nombres que existen en el espacio de nombres de un objeto cuando éste es usado como parámetro.
**Ejemplo:**
* La siguiente celda regresará el listado del espacio de nombres del objeto ```object```.
```
dir(object)
```
Cabe recordar que cuando se ejectua ```dir()``` sin argumentos, la función regresa el listado de nombres del espacio de nombres principal.
**Ejemplo:**
```
dir()
```
## La función ```help()```.
Python puede ofrecer información al usuario mediante un proceso llamado "Introspección", el cual es capaz de analizar al objeto y a partir de su estructura y comentarios del código, generar documentación.
La función ```help(``` despliega la información sobre la estructura y documentación de un objeto en el entorno interactivo mediante la siguiente sintaxis:
```
help(<objeto>)
```
La función ```help()``` también despliega algunos otros datos a partir de ciertas palabras clave en formato de cadena de texto como ```"keywords"```, ```"modules"```, ```"topics"```, etc.
Si se usa ```help()``` con una cadena de caracteres que no coincida con alguna palabra clave como las mencionadas, se generará un error.
**Ejemplo:**
* La siguiente celda desplegará la documentación del objeto ```object```.
```
help(object)
```
### Navegación dentro de la ventana de ayuda desde el intérprete de Python.
Debido a que el contenido desplegado por ```help()``` generalmente se extiende más allá de la capacidad de una pantalla de texto, el entorno interactivo cambia a un modo de lectura en el cual uno se puede trasladar a lo largo del texto de ayuda con las teclas <kbd> ↑ </kbd>, <kbd> ↓ </kbd>, <kbd>AvPág</kbd>, <kbd>RePág</kbd>, <kbd>Inicio</kbd> y <kbd>Fin</kbd>.
Para salir del modo de lectura sólo es necesario ingresar la tecla <kbd>q</kbd>.
<p style="text-align: center"><a rel="license" href="http://creativecommons.org/licenses/by/4.0/"><img alt="Licencia Creative Commons" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/80x15.png" /></a><br />Esta obra está bajo una <a rel="license" href="http://creativecommons.org/licenses/by/4.0/">Licencia Creative Commons Atribución 4.0 Internacional</a>.</p>
<p style="text-align: center">© José Luis Chiquete Valdivieso. 2021.</p>
|
github_jupyter
|
dir(object)
dir()
help(<objeto>)
help(object)
| 0.22414 | 0.962988 |
```
# default_exp interactive_session
```
# Interactive session
## Challenge 1: Define the experiment.
First we define how the experiment works. Here, we will simulate a two-armed bandit experiment. In the two-armed bandit task participants repeatedly choose between two stimuli. Each stimulus has a certain <b>reward probability</b>. Participants complete several <b>trials</b> and their goal is to maximize <b>rewards</b>.
### Step 1: Define the number of trials and reward probabilities.
First, we have to decide on the number of trials and the reward probabilities for each stimulus. Store the number of trials in a variable `Tr` and store the reward probabilities (one for each of the two stimuli) in variable `mu`.
> Note: You can define these parameters however you want. In the Collins paper there were 100 trials and the reward probabilities were .2 for one stimulus and .8 for the other.
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
Tr = 100
mu = c(.2, .8)
```
### Step 2: Write the reward function.
The reward function allocates reward stochastically based on reward probabilities. This function uses an action and the reward probabilities as inputs and returns either a reward of 1 or no reward (0).
It achieves this by generating a random number from a uniform distribution ranging from 0 and 1 (in R you can do this using `runif(1, min=0, max=1)`).
Next, it compares the reward probability associated with the chosen action `mu[action]` to that number. If it is lower or equal `<=` to the reward probability it returns 1 (reward) otherwise it returns 0 (no reward).
> Note, in R you implement functions by writing:
```
allocate_reward = function(action, mu){ # choice and mu are your inputs
...
return(reward) # reward is your return value
}
```
> You implement if statements, by writing:
```
if(...){
...}
else{
...}
```
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
allocate_reward = function(action, mu){
rand = runif(1, min=0, max=1) # Chooses float from continuous uniform distribution between 0 and 1
if(rand <= mu[action]){ # If the random number is smaller than the chosen reward probability
return(1)} # reward allocated
else{
return(0)}
}
```
## Challenge 2: Set up your first behavioral model (Rescorla-Wagner).
The Rescorla-Wagner model consists of a softmax choice rule and a Q-learning update algorithm. Initially, the model does not know which action is the best choice, so both actions should have the same Q-value.
### Step 1: Initialize your Q-values
In this step you define the initial Q-values. Store them in a variable `Q`.
> Note: We will need to run some calculations with these Q-values. To allow for this you'll have to place your Q-values into a vector `c(...,...)`. The initial values should not matter much, but Collins et al. set them to .5.
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
Q = c(0.5, 0.5)
```
### Step 2: Implement the softmax function.
The softmax function determines <b>choice probabilities</b> based on Q-values using the following formula:
$p_a = \dfrac{exp(Q_{at}*beta)} {\Sigma{exp(Q_{at}*beta)}}$
As you can see, this function also introduces our first participant parameter the<b> inverse temperature (beta)</b>. The larger beta the more deterministic (less random) a person's choices are.
> Bonus Question: What else does this function do, next to introducing beta?
#### 2.2 Define beta
First define beta and store it in the variable `beta`. Here you can pick any positive value (we chose 4).
> Bonus Question: Why does beta need to be positive?
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
beta = 4
```
#### 2.3 Implement the softmax function.
> Note, remember in R you implement functions by writing:
```
softmax = function(Q, beta){ # Q and beta are your inputs
...
return(p) # p is your return value
}
```
> To exponentiate an array you use `exp()` and to calculate the sum of a vector, you use `sum()`.
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
softmax = function(Q, beta){
p = exp(Q*beta) / sum(exp(Q*beta))
return(p)
}
softmax(Q, beta)
```
### Step 3: Write a decision function.
This function uses choice probabilities as an input and returns a concrete choice as an output. It achieves this by first generating a random number from a uniform distribution ranging from 0 and 1 (in R you can do this using `runif(1, min=0, max=1)`).
Next, it compares the first choice probability to this number. If it is lower or equal to the choice probability the chosen action is 1 (1st slot machine), else the chosen action is 2 (2nd slot machine).
> Note: Call this function `choose = function()`. You will need an if statement. Remember, in R, you define this as:
```
if(...){
...}
else{
...}
```
<i>Enter your code here:</i>
```
choose = function(p){
rand = runif(1, min = 0, max = 1)
if(rand <= p[1]){
action = 1}
else{
action = 2}
return(action)
}
```
<i>Check the solution below:</i>
```
choose = function(p){
rand = runif(1, min=0, max=1) # Chooses float from continuous uniform distribution between 0 and 1
if(rand <= p[1]){ # If the random number is smaller than our first p
chosen_action = 1} # ... the first option was chosen
else{
chosen_action = 2}
return(chosen_action)
}
```
### Step 4: Write the update function
The update function updates Q-values based on the reward, according to this formula:
$Q_{a,t+1} = Q_{a,t} + \alpha (r - Q_{a,t})$
As you can see, this function introduces another participant parameter: the <b>learning rate (alpha)</b>.
#### 4.1 Define alpha
Pick a value between 0 and 1 (we chose .2) and store it as `alpha`.
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
alpha = .2
```
#### 4.2: Write the update function
Call this function `update_q_value()` with `Q`, `action`, `reward`, and `alpha` as inputs and `updated_q` and `delta` as outputs. This function first calculates the prediction error and then updates Q.
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
update_q = function(Q, action, reward, alpha){
delta = reward - Q[action] # prediction error
Q[action] = Q[action] + alpha * delta
return(list(Q, delta))
}
```
### Step 5: Putting it all together
Congratulations, you created all the components of your simulation function. Now let's put them all together and simulate some data. The simulation function (call it `simulate_M3RescorlaWagner_v1`) takes the experiment parameters, `mu` and `Tr`, as well as the participant parameters `alpha` and `beta` as inputs.
> Note: Don't forget to initialize the q-values as we did in step 2.1.
In each trial, we simulate an action chosen by the participant, allocate a reward, and update the participant's q-values accordingly.
> Note: In R you write loops like this:
```
for(t in c(1:Tr)){
...}
```
As outputs it returns the lists (i.e., vectors) `actions`, `rewards`, `Qs`, and `deltas` for each trial.
> Note: You create vectors like this `actions = []` and add data to a vector like this: `actions=(actions, action)`.
> Warning: For technical reasons, you have to initialize the vectors before appending, like: `actions = NULL`
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
starting_q_values = c(0.5, 0.5)
simulate_M3RescorlaWagner_v1 = function(Tr, mu, alpha, beta, starting_q_values){
Q = starting_q_values # Q are the Q-values the participant currently holds for each action
Qs = NULL
deltas = NULL
actions = NULL # the participants actions
rewards = NULL # the rewards received by the participant
# Looping through trials
for(t in c(1:Tr)){
Qs=c(Qs, Q)
p = softmax(Q, beta) # The probability with which a participant choses each action
action = choose(p) # The choice of the participant based on the choice probabilities
actions=c(actions,action)
reward = allocate_reward(action, mu) # The reward determined by the game for the action the participant chose
rewards=c(rewards,(as.integer(reward)))
list_update = update_q(Q, action, reward, alpha)
deltas=c(deltas,list_update[[2]])
Q = list_update[[1]]
}
return(list(actions, rewards, Qs, deltas))
}
```
## Challenge 3: Explore the parameters
We already wrote you a little function that simply uses your `simulate_M3RescorlaWagner_v1` function to simulate an experiment based on your parameters and plots its outputs in a figure. Below, we will go through some parameter combinations and explore their effects.
```
library(ggplot2)
plot_rescorla_game = function(Tr, mu, alpha, beta){
sim_list = simulate_M3RescorlaWagner_v1(Tr, mu, alpha, beta, starting_q_values)
actions = sim_list[[1]]
rewards = sim_list[[2]]
Qs = sim_list[[3]]
deltas = sim_list[[4]]
type = rep(c("Q1", "Q2"),length(Qs)/2)
df_Qs = data.frame(values=Qs, type, trial = rep(c(1:Tr),each = 2))
df_pe = data.frame(values=deltas, type="pe", trial = c(1:Tr))
df = rbind(df_Qs, df_pe)
plot = ggplot(df, aes(x = trial, y = values, group = type, color = type))+geom_line(size = 1.5)+
ylim(-1,1)+
theme_classic()+
theme(axis.title = element_text(size = 20, face = "bold")
, axis.title.y = element_text(vjust=2.0)
, axis.text.x = element_text(size = 20)
, axis.text.y = element_text(size = 20)
, strip.text.x = element_text(size=20, face = "bold")
, legend.title=element_blank()
, legend.text=element_text(size=20)
, axis.title.x=element_blank())
return(plot)
}
```
Here are some example parameter values:
```
Tr = 100 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .2 # learning rate
beta = -4 # inverse temperature
plot_rescorla_game(Tr, mu, alpha, beta)
options(repr.plot.width=20, repr.plot.height=5)
```
> Reducing the learning rate (participant does not manage to learn probabilities)
```
Tr = 100 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .01 # learning rate
beta = 4 # inverse temperature
plot_rescorla_game(Tr, mu, alpha, beta)
```
> Let's give them more trials
```
Tr = 1000 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .01 # learning rate
beta = 4 # inverse temperature
plot_rescorla_game(Tr, mu, alpha, beta)
```
> An extreme beta value makes participants stop exploring.
```
Tr = 1000 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .01 # learning rate
beta = 1000 # inverse temperature
plot_rescorla_game(Tr, mu, alpha, beta)
```
> If beta is very low, participants still learn, but they don't use that knowledge (something that we cannot see in this plot yet).
```
Tr = 1000 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .1 # learning rate
beta = 0.0000000001 # inverse temperature
plot_rescorla_game(Tr, mu, alpha, beta)
```
## Challenge 4: Choice Kernel
The only difference between choice kernel and rescorla-wagner is that the softmax function takes choice_kernel values instead of Q-values as inputs and the update function is indendent of rewards. Therefore, we only need to change the update function.
### Step 1: Write a new update function
The formula of the update function looks like this:
$CK_{a,t+1} = CK_{a,t} + \alpha * 1$
Before the choice kernel is updated, both choice kernels decay with the inverse of the learning rate:
$CK_{t+1} = CK_{t} * (1 - \alpha) $
Call this function `update_choice_kernels`, with the inputs `choice_kernel`, `action`, and `alpha`.
> Note: If you're confused by the multiplication with one: This is only for comparability with the Rescorla-Wagner.
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
update_choice_kernels = function(choice_kernel, action, alpha){
# choice_kernel = (1 - alpha) * choice_kernel
choice_kernel[action] = choice_kernel[action] + alpha * 1
return(choice_kernel)
}
choice_kernel = c(0.5,0.6)
update_choice_kernels(choice_kernel, 1, 0.2)
```
### Step 2: Putting it all together.
Now make a `simulate_M4ChoiceKernel_v1` function similar to the rescorla wagner function but with our new update function and choice kernels instead of Qs.
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
simulate_M4ChoiceKernel_v1 = function(Tr, mu, alpha_c, beta_c){
choice_kernel = c(0,0) # choice_kernel are the choice_kernel-values the participant currently holds for each action
choice_kernels = NULL
actions = NULL # the participants actions
rewards = NULL # the rewards received by the participant
# Looping through trials
for(t in c(1:Tr)){
choice_kernels=c(choice_kernels, choice_kernel)
p = softmax(choice_kernel, beta) # The probability with which a participant choses each action
action = choose(p) # The choice of the participant based on the choice probabilities
actions=c(actions,action)
reward = allocate_reward(action, mu) # The reward probability determined by the game for the action the participant chose
rewards=c(rewards,(as.integer(reward)))
choice_kernel = update_choice_kernels(choice_kernel, action, alpha)
}
return(list(actions, rewards, choice_kernels))
}
```
> Note that choice_kernel decays with the inverted alpha in each trial `choice_kernel = (1 - alpha_c) * choice_kernel`
## Challenge 5: Explore the parameters of your choice kernel simulations
```
plot_choice_kernel_game = function(Tr, mu, alpha, beta){
sim_list = simulate_M4ChoiceKernel_v1(Tr, mu, alpha, beta)
actions = sim_list[[1]]
rewards = sim_list[[2]]
CKs = sim_list[[3]]
type = rep(c("CK1", "CK2"),length(CKs)/2)
df_CKs = data.frame(values=CKs, type, trial = rep(c(1:Tr),each = 2))
df_action = data.frame(type = as.character(actions), values = -0.1, trial = c(1:Tr))
plot = ggplot(df_CKs, aes(x = trial, y = values, group = type, color = type))+geom_line(size = 2)+
#ylim(-0.2,1)+
theme_classic()
plot=plot+geom_point(data = df_action, size = 3)+
theme(axis.title = element_text(size = 20, face = "bold")
, axis.title.y = element_blank()
, axis.title.x=element_text(size = 20)
, axis.text.x = element_text(size = 20)
, axis.text.y = element_text(size = 20)
, legend.title=element_blank()
, legend.text=element_text(size=20)
)
plot = plot+scale_color_manual(breaks = c("CK1", "CK2", 1, 2),
values=c("orange", "blue", "orange", "blue"))
return(plot)
}
# why do choice kernel values go to different directions ???
Tr = 100 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .2 # learning rate
beta = 1 # inverse temperature
plot_choice_kernel_game(Tr, mu, alpha, beta)
Tr = 100 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .2 # learning rate
beta = .004 # inverse temperature
plot_choice_kernel_game(Tr, mu, alpha, beta)
Tr = 500 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .2 # learning rate
beta = 4 # inverse temperature
plot_choice_kernel_game(Tr, mu, alpha, beta)
```
> With a reasonably high beta one of the options should always move towards 1.
# Reproducing Collins' figures

## Challenge 6: Reproducing Panel A
Panel A shows the different in the probability of sticking to the same action (y-axis) depending on whether the last trial was a win or a loss (x-axis), split up by learning model (colors). Here, we will only focus on the Rescorla-Wagner and the Choice Kernel model.
### Step 1
Write a fuction that first defines last_action and last_reward. Then determines whether a trial was a stay or switch trial. Finally it calculates the proportion of stay trials depending on whether the last trial was rewarded or not rewarded and outputs the score for each case.
> You can use `data.table::shift(df$action)` to create variables that represent the value of the last row.
```
analysis_WSLS_v1 = function(df){
# Shifting data back by one
df$last_action = data.table::shift(df$action)
df$last_reward = data.table::shift(df$reward)
# Deciding whether trial is stay trial
df$stay = 0
df$stay[df$last_action == df$action] = 1
# Calculating mean stay by case and outputing as series
loseStay = mean(df$stay[df$last_reward == 0],na.rm=TRUE)
winStay = mean(df$stay[df$last_reward == 1],na.rm=TRUE)
s = c(loseStay, winStay)
return(s)
}
```
### Step 2
Simulate data for 110 participants using the Rescorla-Wagner model and store their proportion of stay trials depending on the last trial's reward in a dataframe. Finally, you calculate the mean proportion of stay trials (for wins and losses) over all participants (call the variable `rw`), which we will use in the plot.
For this, we will use the same experiment and participant parameters as Collins, below:
```
Tr = 100
mu = c(.2,.8)
alpha = .1
beta = 5
participants = 110
```
> Note: To turn the actions and rewards into a dataframe, you can use `df = data.frame(action = sim_list[[1]], reward = sim_list[[2]])`.
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
alpha = .1 # learning rate
beta = 5 # inverse temperature
participants = 110
data = data.frame()
for(i in c(1:participants)){
sim_list = simulate_M3RescorlaWagner_v1(Tr, mu, alpha, beta, starting_q_values)
df = data.frame(action = sim_list[[1]], reward = sim_list[[2]])
data= rbind(data,
data.frame(pstay = analysis_WSLS_v1(df),
type = c("loseStay", "winStay"),
model = "rw"))
}
rw = aggregate(pstay~type+model, data, FUN = mean)
rw
```
### Step 3
Now do the same for the choice kernel and call the variable `ck`. Note that for this, Collins changed beta to 3.
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
alpha = .1 # learning rate
beta = 3 # inverse temperature
participants = 110
data = data.frame()
for(i in c(1:participants)){
sim_list = simulate_M4ChoiceKernel_v1(Tr, mu, alpha, beta)
df = data.frame(action = sim_list[[1]], reward = sim_list[[2]])
data= rbind(data,
data.frame(pstay = analysis_WSLS_v1(df),
type = c("loseStay", "winStay"),
model = "ck"))
}
ck = aggregate(pstay~type+model, data, FUN = mean)
ck
```
### Step 4
We plot everything together.
```
df_a = rbind(rw, ck)
df_a
plot_a = ggplot(df_a, aes(x = type, y = pstay, group = model, color = model))+geom_line(size = 1.5)+geom_point(size = 5)+
theme_classic()+ylim(0,1)+ylab("p(stay)")+xlab("previous trial")+
theme(axis.title = element_text(size = 14, face = "bold")
, axis.text.x = element_text(size = 10)
, axis.text.y = element_text(size = 10)
, legend.title=element_blank()
, legend.text=element_text(size=14)
)
options(repr.plot.width=4, repr.plot.height=3)
plot_a
```
## Challenge 7: Reproducing Panel B
To create Panel B, we simulate the proportion of correct choices (y-axis) split by different values of alpha (x-axis) and beta (colors), split by early (first ten) and late (last ten) trials (subpanels). These are the alphas and betas that Collins uses for this plot:
```
alphas = seq(.02,1,by= .02)
betas = c(1,2,5,10,20)
length(alphas)*length(betas)*2
```
### Step 1
Write a nested loop that loops through 200 simulations, all alphas, and all betas. In each iteration it simulates data using the Rescorla-Wagner model and outputs the proportion of correct choices (a choice is correct when the stimulus that is more likely to return a reward is picked) in the first and last ten trials.
> Note: To store the output first make a `df` data frame and in each iteration make a `session_df` data frame which you append to the data.
> Note: To get the correct action (i.e. the action associated with the highest reward probability, us `which.max(mu)`.
> Note: Collins runs 1000 simulations, but because our code runs a bit slow, we recommend doing this 200 per alpha beta combination.
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
starting_q_values = c(0.5,0.5)
df = data.frame()
for(i in c(1:200)){
for(alpha in alphas){
{for(beta in betas){
sim_list = simulate_M3RescorlaWagner_v1(Tr, mu, alpha, beta, starting_q_values)
actions = sim_list[[1]]
imax = which.max(mu) # Mu max index
early = head(actions,10)
correct_early = length(early[early == (imax)])/length(early)
late = tail(actions,10)
correct_late = length(late[late == (imax)])/length(late)
session_df_early = data.frame(alpha=alpha, beta = beta, correct = correct_early, type = "early trials", index = i)
session_df_late = data.frame(alpha=alpha, beta = beta, correct = correct_late, type = "late trials", index = i)
session_df = rbind(session_df_early, session_df_late)
df = rbind(df, session_df)
}
}}}
df_variation = df
df_b = aggregate(correct~type+beta+alpha, df_variation, FUN = mean)
df_b$beta = as.character(df_b$beta)
```

### Step 2
Let's plot this all together.
> Note: You can use `facet_wrap(~...)` to split the figure into multiple plots based on a variable; you can use `geom_line()` to make nice lineplots; to choose a color palette, you can use some extra packages (we already chose `viridis` --> `scale_color_viridis(discrete = TRUE, option = "D")`).
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
library("viridis")
plot_b = ggplot(df_b, aes(x = alpha, y = correct, color = beta, group = beta)) +
geom_line(size = 0.9) + facet_wrap(~type, scales = "free")+
theme_classic()+ylab("correct (%)")+
theme(axis.title = element_text(size = 11)
, axis.text.x = element_text(size = 10)
, axis.text.y = element_text(size = 10)
, legend.text=element_text(size=11)
)+
scale_color_viridis(discrete = TRUE, option = "D")
options(repr.plot.width=7, repr.plot.height=3)
plot_b
```
# Well done! :)
## Bonus Challenge: Combine all plots to make them look exactly as Collins'.
<i>Enter your code here:</i>
<i>Check the solution below:</i>
```
# No solution, you're on your own :p
```
|
github_jupyter
|
# default_exp interactive_session
Tr = 100
mu = c(.2, .8)
allocate_reward = function(action, mu){ # choice and mu are your inputs
...
return(reward) # reward is your return value
}
if(...){
...}
else{
...}
allocate_reward = function(action, mu){
rand = runif(1, min=0, max=1) # Chooses float from continuous uniform distribution between 0 and 1
if(rand <= mu[action]){ # If the random number is smaller than the chosen reward probability
return(1)} # reward allocated
else{
return(0)}
}
Q = c(0.5, 0.5)
beta = 4
softmax = function(Q, beta){ # Q and beta are your inputs
...
return(p) # p is your return value
}
softmax = function(Q, beta){
p = exp(Q*beta) / sum(exp(Q*beta))
return(p)
}
softmax(Q, beta)
if(...){
...}
else{
...}
choose = function(p){
rand = runif(1, min = 0, max = 1)
if(rand <= p[1]){
action = 1}
else{
action = 2}
return(action)
}
choose = function(p){
rand = runif(1, min=0, max=1) # Chooses float from continuous uniform distribution between 0 and 1
if(rand <= p[1]){ # If the random number is smaller than our first p
chosen_action = 1} # ... the first option was chosen
else{
chosen_action = 2}
return(chosen_action)
}
alpha = .2
update_q = function(Q, action, reward, alpha){
delta = reward - Q[action] # prediction error
Q[action] = Q[action] + alpha * delta
return(list(Q, delta))
}
for(t in c(1:Tr)){
...}
starting_q_values = c(0.5, 0.5)
simulate_M3RescorlaWagner_v1 = function(Tr, mu, alpha, beta, starting_q_values){
Q = starting_q_values # Q are the Q-values the participant currently holds for each action
Qs = NULL
deltas = NULL
actions = NULL # the participants actions
rewards = NULL # the rewards received by the participant
# Looping through trials
for(t in c(1:Tr)){
Qs=c(Qs, Q)
p = softmax(Q, beta) # The probability with which a participant choses each action
action = choose(p) # The choice of the participant based on the choice probabilities
actions=c(actions,action)
reward = allocate_reward(action, mu) # The reward determined by the game for the action the participant chose
rewards=c(rewards,(as.integer(reward)))
list_update = update_q(Q, action, reward, alpha)
deltas=c(deltas,list_update[[2]])
Q = list_update[[1]]
}
return(list(actions, rewards, Qs, deltas))
}
library(ggplot2)
plot_rescorla_game = function(Tr, mu, alpha, beta){
sim_list = simulate_M3RescorlaWagner_v1(Tr, mu, alpha, beta, starting_q_values)
actions = sim_list[[1]]
rewards = sim_list[[2]]
Qs = sim_list[[3]]
deltas = sim_list[[4]]
type = rep(c("Q1", "Q2"),length(Qs)/2)
df_Qs = data.frame(values=Qs, type, trial = rep(c(1:Tr),each = 2))
df_pe = data.frame(values=deltas, type="pe", trial = c(1:Tr))
df = rbind(df_Qs, df_pe)
plot = ggplot(df, aes(x = trial, y = values, group = type, color = type))+geom_line(size = 1.5)+
ylim(-1,1)+
theme_classic()+
theme(axis.title = element_text(size = 20, face = "bold")
, axis.title.y = element_text(vjust=2.0)
, axis.text.x = element_text(size = 20)
, axis.text.y = element_text(size = 20)
, strip.text.x = element_text(size=20, face = "bold")
, legend.title=element_blank()
, legend.text=element_text(size=20)
, axis.title.x=element_blank())
return(plot)
}
Tr = 100 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .2 # learning rate
beta = -4 # inverse temperature
plot_rescorla_game(Tr, mu, alpha, beta)
options(repr.plot.width=20, repr.plot.height=5)
Tr = 100 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .01 # learning rate
beta = 4 # inverse temperature
plot_rescorla_game(Tr, mu, alpha, beta)
Tr = 1000 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .01 # learning rate
beta = 4 # inverse temperature
plot_rescorla_game(Tr, mu, alpha, beta)
Tr = 1000 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .01 # learning rate
beta = 1000 # inverse temperature
plot_rescorla_game(Tr, mu, alpha, beta)
Tr = 1000 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .1 # learning rate
beta = 0.0000000001 # inverse temperature
plot_rescorla_game(Tr, mu, alpha, beta)
update_choice_kernels = function(choice_kernel, action, alpha){
# choice_kernel = (1 - alpha) * choice_kernel
choice_kernel[action] = choice_kernel[action] + alpha * 1
return(choice_kernel)
}
choice_kernel = c(0.5,0.6)
update_choice_kernels(choice_kernel, 1, 0.2)
simulate_M4ChoiceKernel_v1 = function(Tr, mu, alpha_c, beta_c){
choice_kernel = c(0,0) # choice_kernel are the choice_kernel-values the participant currently holds for each action
choice_kernels = NULL
actions = NULL # the participants actions
rewards = NULL # the rewards received by the participant
# Looping through trials
for(t in c(1:Tr)){
choice_kernels=c(choice_kernels, choice_kernel)
p = softmax(choice_kernel, beta) # The probability with which a participant choses each action
action = choose(p) # The choice of the participant based on the choice probabilities
actions=c(actions,action)
reward = allocate_reward(action, mu) # The reward probability determined by the game for the action the participant chose
rewards=c(rewards,(as.integer(reward)))
choice_kernel = update_choice_kernels(choice_kernel, action, alpha)
}
return(list(actions, rewards, choice_kernels))
}
plot_choice_kernel_game = function(Tr, mu, alpha, beta){
sim_list = simulate_M4ChoiceKernel_v1(Tr, mu, alpha, beta)
actions = sim_list[[1]]
rewards = sim_list[[2]]
CKs = sim_list[[3]]
type = rep(c("CK1", "CK2"),length(CKs)/2)
df_CKs = data.frame(values=CKs, type, trial = rep(c(1:Tr),each = 2))
df_action = data.frame(type = as.character(actions), values = -0.1, trial = c(1:Tr))
plot = ggplot(df_CKs, aes(x = trial, y = values, group = type, color = type))+geom_line(size = 2)+
#ylim(-0.2,1)+
theme_classic()
plot=plot+geom_point(data = df_action, size = 3)+
theme(axis.title = element_text(size = 20, face = "bold")
, axis.title.y = element_blank()
, axis.title.x=element_text(size = 20)
, axis.text.x = element_text(size = 20)
, axis.text.y = element_text(size = 20)
, legend.title=element_blank()
, legend.text=element_text(size=20)
)
plot = plot+scale_color_manual(breaks = c("CK1", "CK2", 1, 2),
values=c("orange", "blue", "orange", "blue"))
return(plot)
}
# why do choice kernel values go to different directions ???
Tr = 100 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .2 # learning rate
beta = 1 # inverse temperature
plot_choice_kernel_game(Tr, mu, alpha, beta)
Tr = 100 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .2 # learning rate
beta = .004 # inverse temperature
plot_choice_kernel_game(Tr, mu, alpha, beta)
Tr = 500 # number of trials
mu = c(.2,.8) # reward probabilities
alpha = .2 # learning rate
beta = 4 # inverse temperature
plot_choice_kernel_game(Tr, mu, alpha, beta)
analysis_WSLS_v1 = function(df){
# Shifting data back by one
df$last_action = data.table::shift(df$action)
df$last_reward = data.table::shift(df$reward)
# Deciding whether trial is stay trial
df$stay = 0
df$stay[df$last_action == df$action] = 1
# Calculating mean stay by case and outputing as series
loseStay = mean(df$stay[df$last_reward == 0],na.rm=TRUE)
winStay = mean(df$stay[df$last_reward == 1],na.rm=TRUE)
s = c(loseStay, winStay)
return(s)
}
Tr = 100
mu = c(.2,.8)
alpha = .1
beta = 5
participants = 110
alpha = .1 # learning rate
beta = 5 # inverse temperature
participants = 110
data = data.frame()
for(i in c(1:participants)){
sim_list = simulate_M3RescorlaWagner_v1(Tr, mu, alpha, beta, starting_q_values)
df = data.frame(action = sim_list[[1]], reward = sim_list[[2]])
data= rbind(data,
data.frame(pstay = analysis_WSLS_v1(df),
type = c("loseStay", "winStay"),
model = "rw"))
}
rw = aggregate(pstay~type+model, data, FUN = mean)
rw
alpha = .1 # learning rate
beta = 3 # inverse temperature
participants = 110
data = data.frame()
for(i in c(1:participants)){
sim_list = simulate_M4ChoiceKernel_v1(Tr, mu, alpha, beta)
df = data.frame(action = sim_list[[1]], reward = sim_list[[2]])
data= rbind(data,
data.frame(pstay = analysis_WSLS_v1(df),
type = c("loseStay", "winStay"),
model = "ck"))
}
ck = aggregate(pstay~type+model, data, FUN = mean)
ck
df_a = rbind(rw, ck)
df_a
plot_a = ggplot(df_a, aes(x = type, y = pstay, group = model, color = model))+geom_line(size = 1.5)+geom_point(size = 5)+
theme_classic()+ylim(0,1)+ylab("p(stay)")+xlab("previous trial")+
theme(axis.title = element_text(size = 14, face = "bold")
, axis.text.x = element_text(size = 10)
, axis.text.y = element_text(size = 10)
, legend.title=element_blank()
, legend.text=element_text(size=14)
)
options(repr.plot.width=4, repr.plot.height=3)
plot_a
alphas = seq(.02,1,by= .02)
betas = c(1,2,5,10,20)
length(alphas)*length(betas)*2
starting_q_values = c(0.5,0.5)
df = data.frame()
for(i in c(1:200)){
for(alpha in alphas){
{for(beta in betas){
sim_list = simulate_M3RescorlaWagner_v1(Tr, mu, alpha, beta, starting_q_values)
actions = sim_list[[1]]
imax = which.max(mu) # Mu max index
early = head(actions,10)
correct_early = length(early[early == (imax)])/length(early)
late = tail(actions,10)
correct_late = length(late[late == (imax)])/length(late)
session_df_early = data.frame(alpha=alpha, beta = beta, correct = correct_early, type = "early trials", index = i)
session_df_late = data.frame(alpha=alpha, beta = beta, correct = correct_late, type = "late trials", index = i)
session_df = rbind(session_df_early, session_df_late)
df = rbind(df, session_df)
}
}}}
df_variation = df
df_b = aggregate(correct~type+beta+alpha, df_variation, FUN = mean)
df_b$beta = as.character(df_b$beta)
library("viridis")
plot_b = ggplot(df_b, aes(x = alpha, y = correct, color = beta, group = beta)) +
geom_line(size = 0.9) + facet_wrap(~type, scales = "free")+
theme_classic()+ylab("correct (%)")+
theme(axis.title = element_text(size = 11)
, axis.text.x = element_text(size = 10)
, axis.text.y = element_text(size = 10)
, legend.text=element_text(size=11)
)+
scale_color_viridis(discrete = TRUE, option = "D")
options(repr.plot.width=7, repr.plot.height=3)
plot_b
# No solution, you're on your own :p
| 0.426083 | 0.98847 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.