path
stringlengths 7
265
| concatenated_notebook
stringlengths 46
17M
|
---|---|
python/tutorials/finetune-CNN-catsvsdogs.ipynb | ###Markdown
Fine-tuning a CNN with MXNet: Cats vs Dogs (Kaggle Redux)In this tutorial we'll learn how to build a model to classifiy if an image is a cat or a dog. We'll use a pre-trained [imagenet](http://www.image-net.org/) model from the MXNet [model zoo](http://data.mxnet.io/models/). For practical problems we may not have a large dataset, hence its difficult to train these generalized models. However we can take advantage of models that are pre-trained on large dataset like imagenet where in the model has already learnt a lot of the image features. The model used is based on the Convolution Neural Network (CNN) architecture. CNN's consist of multiple layer of fields that are model on biological visual receptors. At each layer the neuron collection process portions of input images and the outputs get tiled so as to obtain a higher level representation of the image. For more details on the how CNN's work check out [CS231n course](http://cs231n.github.io/convolutional-networks/overview) and [MNIST example](https://github.com/dmlc/mxnet-notebooks/blob/master/python/tutorials/mnist.ipynb) with MXNet.To fine-tune a network we'll update all of the network’s weights and also replace the last fully-connected layer with the new number of output classes. In most cases to train we use a smaller learning rate given that we typically may have a small dataset. For more in depth reading on fine-tuning with MXNet check this [tutorial](http://mxnet.io/how_to/finetune.html) Setting up a deep learning environment with AWS Deep Learning AMI for MXNetIn this tutorial, we are going to use [Deep Learning AMI](https://aws.amazon.com/marketplace/pp/B06VSPXKDX). The Deep Learning AMI is a base Amazon Linux image provided by Amazon Web Services for use on Amazon Elastic Compute Cloud (Amazon EC2).It is designed to provide a stable, secure, and high performance execution environment for deep learning applications running on Amazon EC2. It includes popular deep learning frameworks, including MXNet.For setting up an Deep Learning environment on AWS using Deep Learning AMI, please read [this post on AWS AI Blog](https://aws.amazon.com/blogs/ai/the-aws-deep-learning-ami-now-with-ubuntu/) for detailed instruction. Or you can choose to [install MXNet](http://mxnet.io/get_started/install.html) to your own machine. Prerequisites - MXNet (0.9.3 or higher) - Python 2.7 or higher - im2rec.py (clone https://github.com/dmlc/mxnet) - [recommended] Amazon EC2 instance with GPU (p2.* family) with [Deep Learning AMI](https://bit.ly/deepami) Dataset: downoad and preprocessing1. Download data from https://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition/data2. Extract train.zip into a folder "data" and create two folders "train" and "valid"3. Create additonal directories to get a directory structure as shown below, We'll label dogs as class 0 and cats as 1 (hence the prefix)``` train/ ├── 1cats └── 0dogs valid/ ├── 1cats └── 0dogs```4. First move all the cat* images into train/1cats and dog* images into train/0dogs. 5. Now lets move a percentage of these images in to the validation directory to create the validation set. You could use the code below to execute in a python script``` import os import random import shutil cats_dir = 'train/1cats' dogs_dir = 'train/0dogs' all_cats = os.listdir(cats_dir) all_dogs = os.listdir(dogs_dir) p = 20.0 N = int(len(all_cats)/p) N = int(len(all_dogs)/p) for f in random.sample(all_cats, N): shutil.move( cats_dir + "/" + f, "valid/1cats/" + f) for f in random.sample(all_dogs, N): shutil.move( dogs_dir + "/" + f, "valid/0dogs/" + f)```6. Create a list for training and validation set``` python ~/mxnet/tools/im2rec.py --list True --recursive True cats_dogs_train.lst data/train python ~/mxnet/tools/im2rec.py --list True --recursive True cats_dogs_val.lst data/valid```7. Convert the images in to MXNet RecordIO format``` python ~/mxnet/tools/im2rec.py --resize 224 --quality 90 --num-thread 16 cats_dogs_train.lst data/train python ~/mxnet/tools/im2rec.py --resize 224 --quality 90 --num-thread 16 cats_dogs_val.lst data/valid``` You should see cats_dogs_train.rec and cats_dogs_val.rec files created. Next we define the function which returns the data iterators. CODE
###Code
# Data Iterators for cats vs dogs dataset
import mxnet as mx
def get_iterators(batch_size, data_shape=(3, 224, 224)):
train = mx.io.ImageRecordIter(
path_imgrec = './cats_dogs_train.rec',
data_name = 'data',
label_name = 'softmax_label',
batch_size = batch_size,
data_shape = data_shape,
shuffle = True,
rand_crop = True,
rand_mirror = True)
val = mx.io.ImageRecordIter(
path_imgrec = './cats_dogs_val.rec',
data_name = 'data',
label_name = 'softmax_label',
batch_size = batch_size,
data_shape = data_shape,
rand_crop = False,
rand_mirror = False)
return (train, val)
###Output
_____no_output_____
###Markdown
Dowload pre-trained model from the model zoo (Resnet-152)We then download a pretrained 152-layer ResNet model and load into memory. Note: If load_checkpoint reports error, we can remove the downloaded files and try get_model again.
###Code
# helper functions
import os, urllib
def download(url):
filename = url.split("/")[-1]
if not os.path.exists(filename):
urllib.urlretrieve(url, filename)
def get_model(prefix, epoch):
download(prefix+'-symbol.json')
download(prefix+'-%04d.params' % (epoch,))
get_model('http://data.mxnet.io/models/imagenet/resnet/152-layers/resnet-152', 0)
sym, arg_params, aux_params = mx.model.load_checkpoint('resnet-152', 0)
###Output
_____no_output_____
###Markdown
Fine tuning the modelTo fine-tune a network, we must first replace the last fully-connected layer with a new one that outputs the desired number of classes. We initialize its weights randomly. Then we continue training as normal. Sometimes it’s common use a smaller learning rate based on the intuition that we may already be close to a good result.We first define a function which replaces the the last fully-connected layer for a given network.
###Code
def get_fine_tune_model(symbol, arg_params, num_classes, layer_name='flatten0'):
"""
symbol: the pre-trained network symbol
arg_params: the argument parameters of the pre-trained model
num_classes: the number of classes for the fine-tune datasets
layer_name: the layer name before the last fully-connected layer
"""
all_layers = sym.get_internals()
net = all_layers[layer_name+'_output']
net = mx.symbol.FullyConnected(data=net, num_hidden=num_classes, name='fc1')
net = mx.symbol.SoftmaxOutput(data=net, name='softmax')
new_args = dict({k:arg_params[k] for k in arg_params if 'fc1' not in k})
return (net, new_args)
###Output
_____no_output_____
###Markdown
Training the modelWe now define a fit function that creates an MXNet module instance that we'll bind the data and symbols to. init_params is called to randomly initialize parametersset_params is called to replace all parameters except for the last fully-connected layer with pre-trained model. Note: change mx.gpu to mx.cpu to run training on CPU (much slower)
###Code
import logging
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
def fit(symbol, arg_params, aux_params, train, val, batch_size, num_gpus=1, num_epoch=1):
devs = [mx.gpu(i) for i in range(num_gpus)] # replace mx.gpu by mx.cpu for CPU training
mod = mx.mod.Module(symbol=new_sym, context=devs)
mod.bind(data_shapes=train.provide_data, label_shapes=train.provide_label)
mod.init_params(initializer=mx.init.Xavier(rnd_type='gaussian', factor_type="in", magnitude=2))
mod.set_params(new_args, aux_params, allow_missing=True)
mod.fit(train, val,
num_epoch=num_epoch,
batch_end_callback = mx.callback.Speedometer(batch_size, 10),
kvstore='device',
optimizer='sgd',
optimizer_params={'learning_rate':0.009},
eval_metric='acc')
return mod
###Output
_____no_output_____
###Markdown
Now that we have the helper functions setup, we can start training.Its recommended that you train on a GPU instance, preferably p2.* family. In this example we assume an AWS EC2 p2.xlarge, which has one NVIDIA K80 GPU.
###Code
num_classes = 2 # This is binary classification (dogs vs cat)
batch_per_gpu = 4
num_gpus = 1
(new_sym, new_args) = get_fine_tune_model(sym, arg_params, num_classes)
batch_size = batch_per_gpu * num_gpus
(train, val) = get_iterators(batch_size)
mod = fit(new_sym, new_args, aux_params, train, val, batch_size, num_gpus)
metric = mx.metric.Accuracy()
mod_score = mod.score(val, metric)
print mod_score
###Output
_____no_output_____
###Markdown
After 1 epoch we achive 97.22% training accuracy. Lets save the newly trained model
###Code
prefix = 'resnet-mxnet-catsvsdogs'
epoch = 1
mc = mod.save_checkpoint(prefix, epoch)
###Output
2017-06-01 01:33:56,263 Saved checkpoint to "resnet-mxnet-catsvsdogs-0001.params"
###Markdown
Loading saved model
###Code
# load the model, make sure you have executed previous cells to train
import cv2
dshape = [('data', (1,3,224,224))]
def load_model(s_fname, p_fname):
"""
Load model checkpoint from file.
:return: (arg_params, aux_params)
arg_params : dict of str to NDArray
Model parameter, dict of name to NDArray of net's weights.
aux_params : dict of str to NDArray
Model parameter, dict of name to NDArray of net's auxiliary states.
"""
symbol = mx.symbol.load(s_fname)
save_dict = mx.nd.load(p_fname)
arg_params = {}
aux_params = {}
for k, v in save_dict.items():
tp, name = k.split(':', 1)
if tp == 'arg':
arg_params[name] = v
if tp == 'aux':
aux_params[name] = v
return symbol, arg_params, aux_params
model_symbol = "resnet-mxnet-catsvsdogs-symbol.json"
model_params = "resnet-mxnet-catsvsdogs-0002.params"
sym, arg_params, aux_params = load_model(model_symbol, model_params)
mod = mx.mod.Module(symbol=sym)
# bind the model and set training == False; Define the data shape
mod.bind(for_training=False, data_shapes=dshape)
mod.set_params(arg_params, aux_params)
###Output
_____no_output_____
###Markdown
Generate Predictions for an arbitrary image
###Code
import urllib2
from collections import namedtuple
Batch = namedtuple('Batch', ['data'])
def preprocess_image(img, show_img=False):
'''
convert the image to a numpy array
'''
img = cv2.resize(img, (224, 224))
img = np.swapaxes(img, 0, 2)
img = np.swapaxes(img, 1, 2)
img = img[np.newaxis, :]
return img
url = 'https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg'
req = urllib2.urlopen(url)
image = np.asarray(bytearray(req.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
img = preprocess_image(image)
mod.forward(Batch([mx.nd.array(img)]))
# predict
prob = mod.get_outputs()[0].asnumpy()
print prob
###Output
[[ 9.99993086e-01 6.96629468e-06]]
###Markdown
Inspecting incorrect labels
###Code
# Generate predictions for entire validation dataset
import os
import cv2
path = 'data/valid/cats/' # change as needed
files = [path + f for f in os.listdir(path)]
incorrect_labels = []
# incorrect cat labels
for f in files:
img = cv2.imread(f)
img = preprocess_image(img)
mod.forward(Batch([mx.nd.array(img)]))
prob = mod.get_outputs()[0].asnumpy()
if prob.argmax() != 1: # not a cat
print f
incorrect_labels.append(f)
from matplotlib import pyplot as plt
%matplotlib inline
import numpy as np
# Plot helper
def plots(ims, figsize=(12,6), rows=1, interp=False, titles=None):
if type(ims[0]) is np.ndarray:
ims = np.array(ims).astype(np.uint8)
if (ims.shape[-1] != 3):
ims = ims.transpose((0,2,3,1))
f = plt.figure(figsize=figsize)
for i in range(len(ims)):
sp = f.add_subplot(rows, len(ims)//rows, i+1)
sp.axis('Off')
if titles is not None:
sp.set_title(titles[i], fontsize=16)
plt.imshow(ims[i], interpolation=None if interp else 'none')
#individual plot of incorrect label
img_path = incorrect_labels[0]
plots([cv2.imread(img_path)])
plt.show()
###Output
_____no_output_____
###Markdown
Fine-tuning a CNN with MXNet: Cats vs Dogs (Kaggle Redux)In this tutorial we'll learn how to build a model to classifiy if an image is a cat or a dog. We'll use a pre-trained [imagenet](http://www.image-net.org/) model from the MXNet [model zoo](http://data.mxnet.io/models/). For practical problems we may not have a large dataset, hence its difficult to train these generalized models. However we can take advantage of models that are pre-trained on large dataset like imagenet where in the model has already learnt a lot of the image features. The model used is based on the Convolution Neural Network (CNN) architecture. CNN's consist of multiple layer of fields that are model on biological visual receptors. At each layer the neuron collection process portions of input images and the outputs get tiled so as to obtain a higher level representation of the image. For more details on the how CNN's work check out [CS231n course](http://cs231n.github.io/convolutional-networks/overview) and [MNIST example](https://github.com/dmlc/mxnet-notebooks/blob/master/python/tutorials/mnist.ipynb) with MXNet.To fine-tune a network we'll update all of the network’s weights and also replace the last fully-connected layer with the new number of output classes. In most cases to train we use a smaller learning rate given that we typically may have a small dataset. For more in depth reading on fine-tuning with MXNet check this [tutorial](http://mxnet.io/how_to/finetune.html) Setting up a deep learning environment with AWS Deep Learning AMI for MXNetIn this tutorial, we are going to use [Deep Learning AMI](https://aws.amazon.com/marketplace/pp/B06VSPXKDX). The Deep Learning AMI is a base Amazon Linux image provided by Amazon Web Services for use on Amazon Elastic Compute Cloud (Amazon EC2).It is designed to provide a stable, secure, and high performance execution environment for deep learning applications running on Amazon EC2. It includes popular deep learning frameworks, including MXNet.For setting up an Deep Learning environment on AWS using Deep Learning AMI, please read [this post on AWS AI Blog](https://aws.amazon.com/blogs/ai/the-aws-deep-learning-ami-now-with-ubuntu/) for detailed instruction. Or you can choose to [install MXNet](http://mxnet.io/get_started/install.html) to your own machine. Prerequisites - MXNet (0.9.3 or higher) - Python 2.7 or higher - im2rec.py (clone https://github.com/dmlc/mxnet) - [recommended] Amazon EC2 instance with GPU (p2.* family) with [Deep Learning AMI](https://bit.ly/deepami) Dataset: downoad and preprocessing1. Download data from https://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition/data2. Extract train.zip into a folder "data" and create two folders "train" and "valid"3. Create additonal directories to get a directory structure as shown below, We'll label dogs as class 0 and cats as 1 (hence the prefix)``` train/ ├── 1cats └── 0dogs valid/ ├── 1cats └── 0dogs```4. First move all the cat* images into train/1cats and dog* images into train/0dogs. 5. Now lets move a percentage of these images in to the validation directory to create the validation set. You could use the code below to execute in a python script``` import os import random import shutil cats_dir = 'train/1cats' dogs_dir = 'train/0dogs' all_cats = os.listdir(cats_dir) all_dogs = os.listdir(dogs_dir) p = 20.0 N = int(len(all_cats)/p) N = int(len(all_dogs)/p) for f in random.sample(all_cats, N): shutil.move( cats_dir + "/" + f, "valid/1cats/" + f) for f in random.sample(all_dogs, N): shutil.move( dogs_dir + "/" + f, "valid/0dogs/" + f)```6. Create a list for training and validation set``` python ~/mxnet/tools/im2rec.py --list True --recursive True cats_dogs_train.lst data/train python ~/mxnet/tools/im2rec.py --list True --recursive True cats_dogs_val.lst data/valid```7. Convert the images in to MXNet RecordIO format``` python ~/mxnet/tools/im2rec.py --resize 224 --quality 90 --num-thread 16 cats_dogs_train.lst data/train python ~/mxnet/tools/im2rec.py --resize 224 --quality 90 --num-thread 16 cats_dogs_val.lst data/valid``` You should see cats_dogs_train.rec and cats_dogs_val.rec files created. Next we define the function which returns the data iterators. CODE
###Code
# Data Iterators for cats vs dogs dataset
import mxnet as mx
def get_iterators(batch_size, data_shape=(3, 224, 224)):
train = mx.io.ImageRecordIter(
path_imgrec = './cats_dogs_train.rec',
data_name = 'data',
label_name = 'softmax_label',
batch_size = batch_size,
data_shape = data_shape,
shuffle = True,
rand_crop = True,
rand_mirror = True)
val = mx.io.ImageRecordIter(
path_imgrec = './cats_dogs_val.rec',
data_name = 'data',
label_name = 'softmax_label',
batch_size = batch_size,
data_shape = data_shape,
rand_crop = False,
rand_mirror = False)
return (train, val)
###Output
_____no_output_____
###Markdown
Dowload pre-trained model from the model zoo (Resnet-152)We then download a pretrained 152-layer ResNet model and load into memory. Note: If load_checkpoint reports error, we can remove the downloaded files and try get_model again.
###Code
# helper functions
import os, urllib
def download(url):
filename = url.split("/")[-1]
if not os.path.exists(filename):
urllib.urlretrieve(url, filename)
def get_model(prefix, epoch):
download(prefix+'-symbol.json')
download(prefix+'-%04d.params' % (epoch,))
get_model('http://data.mxnet.io/models/imagenet/resnet/152-layers/resnet-152', 0)
sym, arg_params, aux_params = mx.model.load_checkpoint('resnet-152', 0)
###Output
_____no_output_____
###Markdown
Fine tuning the modelTo fine-tune a network, we must first replace the last fully-connected layer with a new one that outputs the desired number of classes. We initialize its weights randomly. Then we continue training as normal. Sometimes it’s common use a smaller learning rate based on the intuition that we may already be close to a good result.We first define a function which replaces the the last fully-connected layer for a given network.
###Code
def get_fine_tune_model(symbol, arg_params, num_classes, layer_name='flatten0'):
"""
symbol: the pre-trained network symbol
arg_params: the argument parameters of the pre-trained model
num_classes: the number of classes for the fine-tune datasets
layer_name: the layer name before the last fully-connected layer
"""
all_layers = sym.get_internals()
net = all_layers[layer_name+'_output']
net = mx.symbol.FullyConnected(data=net, num_hidden=num_classes, name='fc1')
net = mx.symbol.SoftmaxOutput(data=net, name='softmax')
new_args = dict({k:arg_params[k] for k in arg_params if 'fc1' not in k})
return (net, new_args)
###Output
_____no_output_____
###Markdown
Training the modelWe now define a fit function that creates an MXNet module instance that we'll bind the data and symbols to. init_params is called to randomly initialize parametersset_params is called to replace all parameters except for the last fully-connected layer with pre-trained model. Note: change mx.gpu to mx.cpu to run training on CPU (much slower)
###Code
import logging
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
def fit(symbol, arg_params, aux_params, train, val, batch_size, num_gpus=1, num_epoch=1):
devs = [mx.gpu(i) for i in range(num_gpus)] # replace mx.gpu by mx.cpu for CPU training
mod = mx.mod.Module(symbol=new_sym, context=devs)
mod.bind(data_shapes=train.provide_data, label_shapes=train.provide_label)
mod.init_params(initializer=mx.init.Xavier(rnd_type='gaussian', factor_type="in", magnitude=2))
mod.set_params(new_args, aux_params, allow_missing=True)
mod.fit(train, val,
num_epoch=num_epoch,
batch_end_callback = mx.callback.Speedometer(batch_size, 10),
kvstore='device',
optimizer='sgd',
optimizer_params={'learning_rate':0.009},
eval_metric='acc')
return mod
###Output
_____no_output_____
###Markdown
Now that we have the helper functions setup, we can start training.Its recommended that you train on a GPU instance, preferably p2.* family. In this example we assume an AWS EC2 p2.xlarge, which has one NVIDIA K80 GPU.
###Code
num_classes = 2 # This is binary classification (dogs vs cat)
batch_per_gpu = 4
num_gpus = 1
(new_sym, new_args) = get_fine_tune_model(sym, arg_params, num_classes)
batch_size = batch_per_gpu * num_gpus
(train, val) = get_iterators(batch_size)
mod = fit(new_sym, new_args, aux_params, train, val, batch_size, num_gpus)
metric = mx.metric.Accuracy()
mod_score = mod.score(val, metric)
print mod_score
###Output
_____no_output_____
###Markdown
After 1 epoch we achive 97.22% training accuracy. Lets save the newly trained model
###Code
prefix = 'resnet-mxnet-catsvsdogs'
epoch = 1
mc = mod.save_checkpoint(prefix, epoch)
###Output
2017-06-01 01:33:56,263 Saved checkpoint to "resnet-mxnet-catsvsdogs-0001.params"
###Markdown
Loading saved model
###Code
# load the model, make sure you have executed previous cells to train
import cv2
dshape = [('data', (1,3,224,224))]
def load_model(s_fname, p_fname):
"""
Load model checkpoint from file.
:return: (arg_params, aux_params)
arg_params : dict of str to NDArray
Model parameter, dict of name to NDArray of net's weights.
aux_params : dict of str to NDArray
Model parameter, dict of name to NDArray of net's auxiliary states.
"""
symbol = mx.symbol.load(s_fname)
save_dict = mx.nd.load(p_fname)
arg_params = {}
aux_params = {}
for k, v in save_dict.items():
tp, name = k.split(':', 1)
if tp == 'arg':
arg_params[name] = v
if tp == 'aux':
aux_params[name] = v
return symbol, arg_params, aux_params
model_symbol = "resnet-mxnet-catsvsdogs-symbol.json"
model_params = "resnet-mxnet-catsvsdogs-0002.params"
sym, arg_params, aux_params = load_model(model_symbol, model_params)
mod = mx.mod.Module(symbol=sym)
# bind the model and set training == False; Define the data shape
mod.bind(for_training=False, data_shapes=dshape)
mod.set_params(arg_params, aux_params)
###Output
_____no_output_____
###Markdown
Generate Predictions for an arbitrary image
###Code
import urllib2
from collections import namedtuple
Batch = namedtuple('Batch', ['data'])
def preprocess_image(img, show_img=False):
'''
convert the image to a numpy array
'''
img = cv2.resize(img, (224, 224))
img = np.swapaxes(img, 0, 2)
img = np.swapaxes(img, 1, 2)
img = img[np.newaxis, :]
return img
url = 'https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg'
req = urllib2.urlopen(url)
image = np.asarray(bytearray(req.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
img = preprocess_image(image)
mod.forward(Batch([mx.nd.array(img)]))
# predict
prob = mod.get_outputs()[0].asnumpy()
print prob
###Output
[[ 9.99993086e-01 6.96629468e-06]]
###Markdown
Inspecting incorrect labels
###Code
# Generate predictions for entire validation dataset
import os
import cv2
path = 'data/valid/cats/' # change as needed
files = [path + f for f in os.listdir(path)]
incorrect_labels = []
# incorrect cat labels
for f in files:
img = cv2.imread(f)
img = preprocess_image(img)
mod.forward(Batch([mx.nd.array(img)]))
prob = mod.get_outputs()[0].asnumpy()
if prob.argmax() != 1: # not a cat
print f
incorrect_labels.append(f)
from matplotlib import pyplot as plt
%matplotlib inline
import numpy as np
# Plot helper
def plots(ims, figsize=(12,6), rows=1, interp=False, titles=None):
if type(ims[0]) is np.ndarray:
ims = np.array(ims).astype(np.uint8)
if (ims.shape[-1] != 3):
ims = ims.transpose((0,2,3,1))
f = plt.figure(figsize=figsize)
for i in range(len(ims)):
sp = f.add_subplot(rows, len(ims)//rows, i+1)
sp.axis('Off')
if titles is not None:
sp.set_title(titles[i], fontsize=16)
plt.imshow(ims[i], interpolation=None if interp else 'none')
#individual plot of incorrect label
img_path = incorrect_labels[0]
plots([cv2.imread(img_path)])
plt.show()
###Output
_____no_output_____ |
climbing-competition-analyses/Epic-Data-Analysis.ipynb | ###Markdown
Basic Analyses
###Code
# Import data
epic_male_scores = pd.read_csv('datasets/epic-male.csv')
epic_female_scores = pd.read_csv('datasets/epic-female.csv')
print(epic_male_scores.describe())
print(epic_female_scores.describe())
# Basic plots
x1 = epic_male_scores.Score.values
x2 = epic_female_scores.Score.values
# Find the maximum score for the graph limits, then add 100 for visibility.
x_max = np.max(np.concatenate((x1,x2))) + 100
# Plot the figures
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)
ax1.plot(x1, np.zeros_like(x1),'|b', markersize=15)
ax1.set_xlim(0,x_max)
ax1.set_yticks([])
ax2.plot(x2, np.zeros_like(x2)+1,'|r', markersize=15)
ax2.set_xlim(0,x_max)
ax2.set_yticks([])
###Output
_____no_output_____
###Markdown
Kernel Density Estimation
###Code
# Kernel Density Estimation using Sklearn
X_plot = np.linspace(0,x_max,500)[:, np.newaxis]
kde1 = KernelDensity(kernel='gaussian', bandwidth=250).fit(x1.reshape(-1,1))
log_dens1 = kde1.score_samples(X_plot)
kde2 = KernelDensity(kernel='gaussian', bandwidth=400).fit(x2.reshape(-1,1))
log_dens2 = kde2.score_samples(X_plot)
fig, ax = plt.subplots(nrows = 2, ncols = 2)
ax1, ax2, ax3, ax4 = ax.flatten()
ax1.plot(X_plot, np.exp(log_dens1))
ax1.plot(x1, np.zeros_like(x1),'|')
ax2.plot(X_plot, log_dens1)
ax2.plot(x1, np.zeros_like(x1),'|')
ax2.set_ylim(1,-20)
ax3.plot(X_plot, np.exp(log_dens2))
ax3.plot(x2, np.zeros_like(x2),'|')
ax4.plot(X_plot, log_dens2)
ax4.plot(x2, np.zeros_like(x2),'|')
ax4.set_ylim(1,-20)
# Finding Extrema
# mi, ma = argrelextrema(e, np.less)[0], argrelextrema(e, np.greater)[0]
# print("Minima:", s[mi])
# print("Maxima:", s[ma])
# print("Max: ", np.max(x), " Min: ", np.min(x))
###Output
_____no_output_____
###Markdown
CategorizationUsing K-Means and Gaussian Mixture Models
###Code
n_clusters = 3
# K-Means
kmeans1 = KMeans(n_clusters=n_clusters, random_state=0).fit(x1.reshape(-1, 1))
kcat1 = kmeans1.labels_
kmeans2 = KMeans(n_clusters=n_clusters, random_state=0).fit(x2.reshape(-1, 1))
kcat2 = kmeans2.labels_
# Gaussian Mixture Models
X1 = np.append(x1.reshape(-1,1),np.zeros([x1.size,1]),axis=1)
gmm1 = GaussianMixture(n_components=n_clusters,covariance_type='spherical',random_state=0).fit(X1)
gcat1 = gmm1.predict(X1)
X2 = np.append(x2.reshape(-1,1),np.zeros([x2.size,1]),axis=1)
gmm2 = GaussianMixture(n_components=n_clusters,covariance_type='spherical',random_state=0).fit(X2)
gcat2 = gmm2.predict(X2)
# Plot Everything
fig, (ax1, ax2) = plt.subplots(nrows = 2, ncols = 1)
ax1.plot(x1, np.zeros_like(x1),'|')
ax1.plot(x1, kcat1+1,'|')
ax1.plot(x1, gcat1+4,'|')
ax2.plot(x2, np.zeros_like(x2),'|')
ax2.plot(x2, kcat2+1,'|')
ax2.plot(x2, gcat2+4,'|')
###Output
_____no_output_____ |
python/PB-day4.ipynb | ###Markdown
Class & Inheritance
###Code
class Student:
def __init__(self, Name, Roll):
self.name = Name
self.roll = Roll
def printName(self):
print(self.name)
Student1 = Student("Ishan", 9)
Student1.printName()
class Student:
def __init__(self, Name, Roll):
self.name = Name
self.roll = Roll
S1 = Student("Ishan", 9)
del S1.name
# print(S1.name)
del S1
# print(S1.roll)
class A:
pass # avoids error
class College:
def __init__(self, NameOfDepartment):
self.nameOfDepartment = NameOfDepartment
# inheritance
class Department(College):
def __init__(self, NameOfDepartment, Strength):
# College.__init__(self, NameOfDepartment) # 1st method
super().__init__(NameOfDepartment) # 2nd method
self.strength = Strength
dept = Department("CSE", 104)
print(dept.nameOfDepartment)
print(dept.strength)
class Student:
def __init__(self, Name, Roll):
self.__name = Name
self.roll = Roll
def printName(self):
print(self.__name)
# __ makes the name encapsulated
# we cannot access the data from outside
# so we have to use printName()
Student1 = Student('Ishan', 9)
Student1.printName()
from abc import ABC, abstractmethod
class Animals:
@abstractmethod
def sound(self):
pass
class Birds(Animals):
def sound(self):
print("Birds Chirp!")
Bird1 = Birds()
Bird1.sound()
###Output
_____no_output_____ |
Jupyter-Notebook/Python Basic/Functions.ipynb | ###Markdown
Function Example of defning function :
###Code
def cylinder_volume(height, radius):
pi = 3.14159
return height * pi * radius ** 2
print(cylinder_volume(4,10))
###Output
1256.636
###Markdown
Function with default argument, if radius is not specified then default value of radius will be 5.If radius value is specified then the dafult value of radius will overwrite.
###Code
def cylinder_volume(height, radius=5):
pi = 3.14159
return height * pi * radius ** 2
print(cylinder_volume(4))
print(cylinder_volume(4,7))
###Output
314.159
615.75164
###Markdown
Variable Scope :Variable scope refers to which parts of a program a variable can be referenced, or used, from.
###Code
egg_count = 0
def test():
egg_count += 12
test() # will throw an error
###Output
_____no_output_____
###Markdown
**Global can not modified inside local scope**If you want to modify that variable's value inside this function, it should be passed in as an argument.
###Code
egg_count = 0
def test():
print(egg_count)
test() # will throw an error
###Output
0
###Markdown
Lambda Expressionslamda expression is used to anonymous function. it is usefull to create small function. syntax of lamda expression: ```lambda argument1, argument2 : expression```
###Code
square = lambda x: x * 2
print(square(4))
multiple = lambda x,y : x * y
print(multiple(16, 7))
###Output
8
112
###Markdown
Iterator and Generator **Iterator** is an object that represent a **stream** of data.`list` is an iterable not not iterator since it does not represent stream of data. **Generator** is a function that creates an iterator.
###Code
def my_range(x):
i = 0
while i<x:
yield i
i += 1
for x in my_range(5):
print(x)
print(type(my_range(5)))
###Output
0
1
2
3
4
<class 'generator'>
|
homework_3.ipynb | ###Markdown
[Zoomcamp Homework 3](https://github.com/alexeygrigorev/mlbookcamp-code/blob/master/course-zoomcamp/03-classification/homework.md)
###Code
!wget https://raw.githubusercontent.com/alexeygrigorev/datasets/master/AB_NYC_2019.csv
import numpy as np
import pandas as pd
from sklearn.feature_extraction import DictVectorizer
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.metrics import mutual_info_score, mean_squared_error
from sklearn.model_selection import train_test_split
df = pd.read_csv('./AB_NYC_2019.csv')
print(df.columns)
df.head()
df = df[['neighbourhood_group', 'room_type', 'latitude', 'longitude', 'price', 'minimum_nights', 'number_of_reviews', 'reviews_per_month', 'calculated_host_listings_count', 'availability_365']]
df = df.fillna(0)
###Output
_____no_output_____
###Markdown
Answer 1: Mode
###Code
df.neighbourhood_group.mode()
###Output
_____no_output_____
###Markdown
Answer 2: Correlation Matrix
###Code
df_train_full, df_test = train_test_split(df, test_size=0.2, random_state=42)
df_train, df_val = train_test_split(df_train_full, test_size=0.25, random_state=42)
print(len(df), len(df_train), len(df_val), len(df_test))
y_train = df_train.price.values
y_val = df_val.price.values
del df_train['price']
del df_val['price']
df_train.corr()
c = df_train.corr().abs()
s = c.unstack()
so = s.sort_values(kind="quicksort", ascending=False)
rows_to_skip = len(df_train.corr())
print(so[rows_to_skip:rows_to_skip+3])
###Output
number_of_reviews reviews_per_month 0.590374
reviews_per_month number_of_reviews 0.590374
calculated_host_listings_count availability_365 0.225913
dtype: float64
###Markdown
Answer 3: Mutual Information Score
###Code
above_average = (y_train >= 152).astype(int)
above_average
from sklearn.metrics import mutual_info_score
round(mutual_info_score(above_average, df_train.neighbourhood_group), 2)
round(mutual_info_score(above_average, df_train.room_type), 2)
###Output
_____no_output_____
###Markdown
Answer 4: Logistic Regression
###Code
dv = DictVectorizer(sparse=False)
train_dict = df_train.to_dict(orient='records')
df_train_transformed = dv.fit_transform(train_dict)
model = LogisticRegression(solver='lbfgs', C=1.0, random_state=42, max_iter=2000)
model.fit(df_train_transformed, above_average)
val_dict = df_val.to_dict(orient='records')
df_val_transformed = dv.transform(val_dict)
y_val_binary = (y_val >= 152).astype(int)
round(model.score(df_val_transformed, y_val_binary), 2)
###Output
_____no_output_____
###Markdown
Answer 5: Feature Elimination
###Code
dv = DictVectorizer(sparse=False)
train_dict = df_train.to_dict(orient='records')
df_train_transformed = dv.fit_transform(train_dict)
val_dict = df_val.to_dict(orient='records')
df_val_transformed_full = dv.transform(val_dict)
df_val_binary = (y_val >= 152).astype(int)
full_model = LogisticRegression(solver='lbfgs', C=1.0, random_state=42, max_iter=2000)
full_model.fit(df_train_transformed, above_average)
features = ['neighbourhood_group', 'room_type', 'latitude', 'longitude', 'minimum_nights', 'number_of_reviews', 'reviews_per_month', 'calculated_host_listings_count', 'availability_365']
diffs = {}
for feature in features:
dv = DictVectorizer(sparse=False)
train_dict = df_train.drop([feature], axis=1).to_dict(orient='records')
df_train_transformed = dv.fit_transform(train_dict)
val_dict = df_val.drop([feature], axis=1).to_dict(orient='records')
df_val_transformed = dv.transform(val_dict)
model = LogisticRegression(solver='lbfgs', C=1.0, random_state=42, max_iter=2000)
model.fit(df_train_transformed, above_average)
diffs[feature] = full_model.score(df_val_transformed_full, y_val_binary) - model.score(df_val_transformed, y_val_binary)
min(diffs.items(), key=lambda x: x[1])
###Output
_____no_output_____
###Markdown
Answer 6: Ridge Regression
###Code
y_train = np.log1p(y_train)
y_train
dv = DictVectorizer(sparse=False)
train_dict = df_train.to_dict(orient='records')
df_train_transformed = dv.fit_transform(train_dict)
val_dict = df_val.to_dict(orient='records')
df_val_transformed = dv.transform(val_dict)
scores = {}
for alpha in [0, 0.01, 0.1, 1, 10]:
model = Ridge(alpha)
model.fit(df_train_transformed, y_train)
scores[alpha] = (round(mean_squared_error(model.predict(df_val_transformed), y_val, squared=False), 3))
min(scores.items(), key=lambda x: x[1])
###Output
_____no_output_____
###Markdown
№3. Списки (list), цикл for 1) Распечатать на экране все цвета из списка colors с помощью цикла for
###Code
colors = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'violet']
###Output
_____no_output_____
###Markdown
2) Посчитать сумму всех чисел от 1 до введенного целого числа n (включая) с помощью цикла for
###Code
n = input()
summ
for i in range(1, n+1):
summ
print(summ)
###Output
_____no_output_____
###Markdown
3) Перебрать все числа от 0 до n (с помощью цикла for) и возвести в куб, вывести на экран
###Code
n = input()
for i in range(n)
###Output
_____no_output_____
###Markdown
4) Отсортировать список A по возрастанию, перебрать с помощью цикла for все элементы списка и если число нечетное, то возвести его в квадрат и добавить в пустой список B
###Code
A = [1, 100, 54, 67, 3, 9, 72, 26, 29, 68, 64, 99, 88, 83, 34, 36, 40, 5, 2, 6, 77, 44, 31, 13, 8, 4, 53]
B = []
# посмотреть методы (функции списка) через точку A.
for i in A:
print(B)
###Output
_____no_output_____
###Markdown
5) Перебрать список из слов, и вывести на экран каждое слово и его длину
###Code
# На экране должно быть наподобие такой строчки для каждого слова: "Слово - cat; длина слова 3 буквы"
# поэтому помни вот это)) print(f'Привет {name}')
slovar = ['cat', 'dog', 'window', 'school', 'game', 'sun', 'athletic', 'home', 'work']
###Output
_____no_output_____
###Markdown
6) Перебрать все элементы списка A и если элемент положительный, то вывести OK и этот элемент
###Code
A = [-1, 100, -54, 67, -3, 9, -72, -26, -29, 68, -64, 99, -88, -83, 34, 36, -40, 5, -2, -6, 77, 44, -31, -13, 8, -4, 53]
for elem in a:
###Output
_____no_output_____
###Markdown
7) Найти все индексы числа 7 в списке A и выписать в список B, и вывести количество этого числа (длина списка В)
###Code
A = [7, 0, 6, 7, 3, 6, 88, 35, 33, 32, 76, 7, 8, 10, 16, 7, 19, 21, 7, 54, 99, 100, 43, 7]
B = []
# напомню есть метод у списка (называется .count()), он ищет количество элементов ^_^,
# поэтому можно в одну строчку это сделать, но я хочу чтобы понимали как этот метод работает )))
###Output
_____no_output_____
###Markdown
8) Перебрать список имен, если имя начинается на букву А, то не выписывать его в отдельный список new_ name. Подсчитать количество имен в новом списке
###Code
names = ["Timon", "Eric", "Aleksandr", "John", "Michael", "Alex", "Adrian", "Doshik", "Pumba", "Alesha"]
new_name = []
###Output
_____no_output_____
###Markdown
9) Перебрать все e-mail в списке EMAILS, если email оканчивается на .ru, то вывести на экран
###Code
# Подсказка:
a = '[email protected]'
a[-3:] # последние три символа
a[-3:-1] # последние символы от третьего с конца до последнего, не включая его
'.ru' == '.ru'
EMAILS = ['[email protected]', '[email protected]', 'hunnn@yahoo.сom', '[email protected]', '[email protected]', '[email protected]']
###Output
_____no_output_____
###Markdown
10) Есть список name, вывести новый список new_name, в котором записаны имена, длина которых больше 5 символов
###Code
names = ["Timon", "Eric", "Aleksandr", "John", "Michael", "Alex", "Adrian", "Doshik", "Pumba", "Alesha"]
new_names = []
###Output
_____no_output_____
###Markdown
11) Представим, что есть текст (Властелин колец), добавить в список все слова длина которых меньше больше 3 и меньше 6 символов. И вывести этот список на экран через цикл for
###Code
# Напомню метод AA.split(' ') -> означает разделить строку AA по пробелам и вывести в список
TEXT = 'Рассказ у нас пойдет в особенности о хоббитах, и любознательный читатель многое узнает об их нравах и кое-что из их истории. Самых любознательных отсылаем к повести под названием «Хоббит», где пересказаны начальные главы Алой Книги Западных Пределов, которые написал Бильбо Торбинс, впервые прославивший свой народец в большом мире. Главы эти носят общий подзаголовок «Туда и обратно», потому что повествуют о странствии Бильбо на восток ивозвращении домой. Как раз по милости Бильбо хоббиты и угодили в самую лавину грозных событий, о которых нам предстоит поведать'
words = []
###Output
_____no_output_____
###Markdown
12) Представим, что ты охранник-секьюрети. Тебе говорят "имя и фамилию" через пробел на входе, если фамилия есть в списке запрещенных alarm_names, то вывести Вход запрещен, иначе Входите
###Code
name = input() # 'Иван Иванов'
alarm_names = ['Мавроди', 'Трамп', 'Пупкин', 'Грифин', 'Колобородыч']
###Output
_____no_output_____
###Markdown
list, find the length, find elements between the second element and the 3rd from the end, use append, use remove
###Code
list_1 = ["dcbj","dcberhj","dcbjgsr","dcgrbj","dcynhbj","dcbimyj","dwrfcbj","dnnujcbj","dergcbj"]
print(len(list_1))
print(list_1[1:-3])
list_1.append(554)
list_1.remove(554)
###Output
_____no_output_____
###Markdown
1. 请利用Criteria API读取DJL ModelZoo里的预训练模型
###Code
Criteria<Image, Classifications> criteria = Criteria.builder()
//选择需要读取的预训练模型
.build();
Model model = ModelZoo.loadModel(criteria);
###Output
_____no_output_____
###Markdown
2. 去掉预训练模型的最后一个全连接层, 加上一个102个分类的全连接层(Linear Block)
###Code
SymbolBlock block = (SymbolBlock) model.getBlock();
block.removeLastBlock();
SequentialBlock newBlock = new SequentialBlock();
newBlock.add(block);
//添加一个batch flatten层用来把前面的二维输出转化为一维,给全连接层
//添加一个新的102分类全连接层
newBlock.add(Blocks.batchFlattenBlock());
newBlock.add(Linear.builder().setUnits(10).build());
model.setBlock(newBlock);
###Output
_____no_output_____
###Markdown
3. 准备数据集: [102分类花朵数据集](https://www.robots.ox.ac.uk/~vgg/data/flowers/102/index.html)下载地址:https://d2l-java-resources.s3.amazonaws.com/flower_dataset.zip
###Code
import ai.djl.training.util.DownloadUtils;
import ai.djl.util.ZipUtils;
URL url = new URL("https://d2l-java-resources.s3.amazonaws.com/flower_dataset.zip");
ZipUtils.unzip(url.openStream(), Paths.get("./"))
import ai.djl.basicdataset.ImageFolder;
import ai.djl.repository.Repository;
int batchSize = 32;
float[] mean = {0.485f, 0.456f, 0.406f};
float[] std = {0.229f, 0.224f, 0.225f};
int resize_w = 224;
int resize_h = 224;
ImageFolder trainDataset =
ImageFolder.builder()
.setRepository(Repository.newInstance("flower_train", "flower_dataset/train"))
.optPipeline(
// create preprocess pipeline you want
new Pipeline()
// 设置预处理Pipeline, 裁剪,缩放,张量化,归一化
.setSampling(batchSize, true)
.build();
ImageFolder testDataset =
ImageFolder.builder()
.setRepository(Repository.newInstance("flower_test", "flower_dataset/test"))
.optPipeline(
new Pipeline()
// 设置预处理Pipeline
.setSampling(batchSize, true)
.build();
trainDataset.prepare(new ProgressBar());
testDataset.prepare(new ProgressBar());
//打印出数据标注,花的所有类别
trainDataset.getSynset()
###Output
_____no_output_____
###Markdown
4. 配置TrainingConfig, 选择softmaxCrossEntropy作为损失函数,Accuracy作为Evaluator,在一个GPU上进行训练
###Code
DefaultTrainingConfig config =
//选择Loss, Optimizer, Device, Listener
Trainer trainer = model.newTrainer(config);
import ai.djl.metric.Metrics;
int epoch = 10;
Shape inputShape = new Shape(1, 3, resize_w, resize_h);
trainer.initialize(inputShape);
trainer.setMetrics(new Metrics());
###Output
_____no_output_____
###Markdown
5. 用EasyTrain的fit方法进行训练
###Code
//EasyTrain.fit()
###Output
_____no_output_____
###Markdown
6. 保存模型到本地 7. 读取刚刚保存的模型,对一张花朵图片做预测
###Code
Path imageFile = Paths.get("flower_dataset/test/rose/image_01213.jpg");
Image img = ImageFactory.getInstance().fromFile(imageFile);
###Output
_____no_output_____ |
Data Preprocessing and Bias Variance/Data Preprocessing.ipynb | ###Markdown
Missing Values
###Code
imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis=0)
# use mean median or mode according to the need.
#axis = 0 means that we take the mean of the column.
#axis = 1 means that we are going to take the mean of the row.
#get data
import pandas as pd
dataset = pd.read_csv('Data.csv')
dataset
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:,3].values
X
X[:, 1:3]
imputer = imputer.fit(X[:, 1:3])
#index in python start at 0, so we are going to take the second column and the third column.
#We have to give +1 for the end column so that it takes it till 2.
X[:, 1:3] = imputer.transform(X[:, 1:3])
#transform is used to apply the changes.
X[:, 1:3]
###Output
_____no_output_____
###Markdown
Categorical DataWe would only want numbers in our dataset. Let's see how we can do that with categorical data.
###Code
from sklearn.preprocessing import LabelEncoder
# this is used for data transformation of categorical data
labelEncoder_X = LabelEncoder()
X
###Output
_____no_output_____
###Markdown
Let's encode the Countries column which is Spain, France and Germany and assign a number to each value.
###Code
X[:, 0] = labelEncoder_X.fit_transform(X[:, 0])
X
###Output
_____no_output_____
###Markdown
However, there is a problem with this. Since 1 is greater than 0 and 2 is greater than 1 and 2, the algorithm might tthink that Spain nis greater than France and Germany. So this is not exactly the right way. Id it would had been small, large and medium, it still could had made sense since large is greater than small and medium and so on. But here it does not make any sense. Dummy Encoding / One Hot EncodingInstead of having one column here, we are going to have 3(number of categories) columns representing the value.
###Code
from sklearn.preprocessing import OneHotEncoder
# this is used for data transformation of categorical data
#help(OneHotEncoder())
onehotencoder = OneHotEncoder(categorical_features = [0])
#help(OneHotEncoder())
X = onehotencoder.fit_transform(X).toarray()
pd.DataFrame(X)
###Output
_____no_output_____
###Markdown
Let's take care of the Purchased column now. So we will be working with y.However, we do not need to use one hot encoder here, we can simplyt do this with labelEncoder as there are just two categories.
###Code
labelEncoder_y = LabelEncoder()
y = labelEncoder_y.fit_transform(y)
y
###Output
_____no_output_____
###Markdown
Since the above code has depreciated, you can use the below code as well.Here, you do not need to use the labelEncoder and can directly work with the one hot encoder.
###Code
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
coltransf_X = ColumnTransformer([("one_hot_encoder", OneHotEncoder(), [0])], remainder='passthrough')
X = coltransf_X.fit_transform(X)
pd.DataFrame(X)
?ColumnTransformer
###Output
_____no_output_____
###Markdown
Data SplittingSplit data into test and training set
###Code
#Splitting the data into training and test set
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 = 0)
###Output
_____no_output_____
###Markdown
Feature ScalingConvert the data into the same scale
###Code
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
# we have already fit the data with the train set so we do not need to fit it again
#so only transform is run on the test set
pd.DataFrame(X_train)
pd.DataFrame(X_test)
#we do not need to transform the
###Output
_____no_output_____ |
community-labs/regularization/Community Lab - Regularization.ipynb | ###Markdown
Run in Google ColabFor best performance using Colab, once the notebook is launched, from dropdown menu select **Runtime -> Change Runtime Type**, and select **GPU** for **Hardware Accelerator**. Composable "Design Pattern" for AutoML friendly models Community Lab 2: Using Regularization to Tackle Overfitting ObjectivePrior success for training models for high accuracy was to use large models. Today, we believe the success of large models is due to the fact that they are a collection of sub-models, and one of the sub-models is the winning model (lottery ticket hypothesis).Today, we try to train compact size models. One of the challenges in such a model is the training data may "fit" itself to the model's weights, and not generalize to the validation/test data.In this lab, we will explore methods of regularization and learning rates to prevent the training data from "fitting" to the weights in a compact model -- without use of historical methods such as dropout or data augmentation.*Question*: Can we generalize a compact model without image augmentation?*Question*: How is training time effected?*Question*: How small can a compact model be made and maintain accuracy on the validation/test data? ApproachWe will use the composable design pattern, and prebuilt units from the Google Cloud AI Developer Relations repo: [Model Zoo](https://github.com/GoogleCloudPlatform/keras-idiomatic-programmer/tree/master/zoo)If you are not familiar with the Composable design pattern, we recommemd you review the [ResNet](https://github.com/GoogleCloudPlatform/keras-idiomatic-programmer/tree/master/zoo/resnet) model in our zoo.We recommend a constant set for hyperparameters, where batch_size is 32 and initial learning rate is 0.001 -- but you may use any value for hyperparameters you prefer.We will use the metaparameters feature in the composable design pattern for the macro architecture search -- sort of a 'human assisted AutoML'. Reporting FindingsYou can contact us on your findings via the twitter account: @andrewferlitsch DatasetIn this notebook, we use the CIFAR-10 datasets which consist of images 32x32x3 for 10 classes -- but you may use any dataset you prefer. Steps1. Build a baseline (reference) model for CIFAR-10 with no regularization.2. Add regularization to the classifier (softmax) layer by adding Guassian noise.3. Add a large and small amounts of L2 regularization to convolutional and dense layers' weights.4. Compare the results of different magnitudes of layer regularization.5. Train with a two-tier learning rate schedule.**Note** The suggested training accuracies i Lab Imports
###Code
import tensorflow as tf
from tensorflow.keras import Input, Model
from tensorflow.keras.layers import Conv2D, ReLU, Add, Dense, GaussianNoise, ZeroPadding2D
from tensorflow.keras.layers import BatchNormalization, GlobalAveragePooling2D, Activation
from tensorflow.keras.layers import MaxPooling2D, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.regularizers import l2
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.datasets import cifar10
import numpy as np
###Output
_____no_output_____
###Markdown
Import Composable classComposable is a super (base) class that is inherited by our models which are coded using the Composable design pattern. It provides many abstracted functions in the construction and training of the models. Don't concern yourself about the details; it's not necessary to know how the underlying base works for the purpose of this lab.
###Code
# from models_c.py
class Composable(object):
''' Composable base (super) class for Models '''
init_weights = 'he_normal' # weight initialization
reg = None # kernel regularizer
relu = None # ReLU max value
bias = True # whether to use bias in dense/conv layers
def __init__(self, init_weights=None, reg=None, relu=None, bias=True):
""" Constructor
init_weights : kernel initializer
reg : kernel regularizer
relu : clip value for ReLU
bias : whether to use bias
"""
if init_weights is not None:
self.init_weights = init_weights
if reg is not None:
self.reg = reg
if relu is not None:
self.relu = relu
if bias is not None:
self.bias = bias
# Feature maps encoding at the bottleneck layer in classifier (high dimensionality)
self._encoding = None
# Pooled and flattened encodings at the bottleneck layer (low dimensionality)
self._embedding = None
# Pre-activation conditional probabilities for classifier
self._probabilities = None
# Post-activation conditional probabilities for classifier
self._softmax = None
self._model = None
@property
def model(self):
return self._model
@model.setter
def model(self, _model):
self._model = _model
@property
def encoding(self):
return self._encoding
@encoding.setter
def encoding(self, layer):
self._encoding = layer
@property
def embedding(self):
return self._embedding
@embedding.setter
def embedding(self, layer):
self._embedding = layer
@property
def probabilities(self):
return self._probabilities
@probabilities.setter
def probabilities(self, layer):
self._probabilities = layer
def classifier(self, x, n_classes, **metaparameters):
""" Construct the Classifier Group
x : input to the classifier
n_classes : number of output classes
pooling : type of feature map pooling
"""
if 'pooling' in metaparameters:
pooling = metaparameters['pooling']
else:
pooling = GlobalAveragePooling2D
if 'dropout' in metaparameters:
dropout = metaparameters['dropout']
else:
dropout = None
if pooling is not None:
# Save the encoding layer (high dimensionality)
self.encoding = x
# Pooling at the end of all the convolutional groups
x = pooling()(x)
# Save the embedding layer (low dimensionality)
self.embedding = x
if dropout is not None:
x = Dropout(dropout)(x)
# Final Dense Outputting Layer for the outputs
x = self.Dense(x, n_classes, use_bias=True, **metaparameters)
# Save the pre-activation probabilities layer
self.probabilities = x
outputs = Activation('softmax')(x)
# Save the post-activation probabilities layer
self.softmax = outputs
return outputs
def top(self, layer):
""" Add layer to top of the model
layer: layer to add
"""
outputs = layer(self._model.output)
self._model = Model(self._model.inputs, outputs)
def summary(self):
""" Call underlying summary method
"""
self._model.summary()
def Dense(self, x, units, activation=None, use_bias=True, **hyperparameters):
""" Construct Dense Layer
x : input to layer
activation : activation function
use_bias : whether to use bias
init_weights: kernel initializer
reg : kernel regularizer
"""
if 'reg' in hyperparameters:
reg = hyperparameters['reg']
else:
reg = self.reg
if 'init_weights' in hyperparameters:
init_weights = hyperparameters['init_weights']
else:
init_weights = self.init_weights
x = Dense(units, activation, use_bias=use_bias,
kernel_initializer=init_weights, kernel_regularizer=reg)(x)
return x
def Conv2D(self, x, n_filters, kernel_size, strides=(1, 1), padding='valid', activation=None, **hyperparameters):
""" Construct a Conv2D layer
x : input to layer
n_filters : number of filters
kernel_size : kernel (filter) size
strides : strides
padding : how to pad when filter overlaps the edge
activation : activation function
use_bias : whether to include the bias
init_weights: kernel initializer
reg : kernel regularizer
"""
if 'reg' in hyperparameters:
reg = hyperparameters['reg']
else:
reg = self.reg
if 'init_weights' in hyperparameters:
init_weights = hyperparameters['init_weights']
else:
init_weights = self.init_weights
if 'bias' in hyperparameters:
bias = hyperparameters['bias']
else:
bias = self.bias
x = Conv2D(n_filters, kernel_size, strides=strides, padding=padding, activation=activation,
use_bias=bias, kernel_initializer=init_weights, kernel_regularizer=reg)(x)
return x
def Conv2DTranspose(self, x, n_filters, kernel_size, strides=(1, 1), padding='valid', activation=None, **hyperparameters):
""" Construct a Conv2DTranspose layer
x : input to layer
n_filters : number of filters
kernel_size : kernel (filter) size
strides : strides
padding : how to pad when filter overlaps the edge
activation : activation function
use_bias : whether to include the bias
init_weights: kernel initializer
reg : kernel regularizer
"""
if 'reg' in hyperparameters:
reg = hyperparameters['reg']
else:
reg = self.reg
if 'init_weights' in hyperparameters:
init_weights = hyperparameters['init_weights']
else:
init_weights = self.init_weights
if 'bias' in hyperparameters:
bias = hyperparameters['bias']
else:
bias = self.bias
x = Conv2DTranspose(n_filters, kernel_size, strides=strides, padding=padding, activation=activation,
use_bias=bias, kernel_initializer=init_weights, kernel_regularizer=reg)(x)
return x
def ReLU(self, x):
""" Construct ReLU activation function
x : input to activation function
"""
x = ReLU(self.relu)(x)
return x
def BatchNormalization(self, x, **params):
""" Construct a Batch Normalization function
x : input to function
"""
x = BatchNormalization(epsilon=1.001e-5, **params)(x)
return x
###
# Preprocessing
###
def normalization(self, x_train, x_test=None, centered=False):
""" Normalize the input
x_train : training images
y_train : test images
"""
if x_train.dtype == np.uint8:
if centered:
x_train = ((x_train - 1) / 127.5).astype(np.float32)
if x_test:
x_test = ((x_test - 1) / 127.5).astype(np.float32)
else:
x_train = (x_train / 255.0).astype(np.float32)
if x_test:
x_test = (x_test / 255.0).astype(np.float32)
return x_train, x_test
def standardization(self, x_train, x_test):
""" Standardize the input
x_train : training images
x_test : test images
"""
self.mean = np.mean(x_train)
self.std = np.std(x_train)
x_train = ((x_train - self.mean) / self.std).astype(np.float32)
x_test = ((x_test - self.mean) / self.std).astype(np.float32)
return x_train, x_test
def label_smoothing(self, y_train, n_classes, factor=0.1):
""" Convert a matrix of one-hot row-vector labels into smoothed versions.
y_train : training labels
n_classes: number of classes
factor : smoothing factor (between 0 and 1)
"""
if 0 <= factor <= 1:
# label smoothing ref: https://www.robots.ox.ac.uk/~vgg/rg/papers/reinception.pdf
y_train *= 1 - factor
y_train += factor / n_classes
else:
raise Exception('Invalid label smoothing factor: ' + str(factor))
return y_train
###
# Training
###
def compile(self, loss='categorical_crossentropy', optimizer=Adam(lr=0.001, decay=1e-5), metrics=['acc']):
""" Compile the model for training
loss : the loss function
optimizer: the optimizer
metrics : metrics to report
"""
self.model.compile(loss=loss, optimizer=optimizer, metrics=metrics)
def warmup_scheduler(self, epoch, lr):
""" learning rate schedular for warmup training
epoch : current epoch iteration
lr : current learning rate
"""
if epoch == 0:
return lr
return epoch * self.w_lr / self.w_epochs
def warmup(self, x_train, y_train, epochs=5, s_lr=1e-6, e_lr=0.001):
""" Warmup for numerical stability
x_train : training images
y_train : training labels
epochs : number of epochs for warmup
s_lr : start warmup learning rate
e_lr : end warmup learning rate
"""
print("*** Warmup")
# Setup learning rate scheduler
self.compile(optimizer=Adam(s_lr))
lrate = LearningRateScheduler(self.warmup_scheduler, verbose=1)
self.w_epochs = epochs
self.w_lr = e_lr - s_lr
# Train the model
self.model.fit(x_train, y_train, epochs=epochs, batch_size=32, verbose=1,
callbacks=[lrate])
def cosine_decay(self, epoch, lr, alpha=0.0):
""" Cosine Decay
"""
cosine_decay = 0.5 * (1 + np.cos(np.pi * (self.e_steps * epoch) / self.t_steps))
decayed = (1 - alpha) * cosine_decay + alpha
return lr * decayed
def training_scheduler(self, epoch, lr):
""" Learning Rate scheduler for full-training
epoch : epoch number
lr : current learning rate
"""
# First epoch (not started) - do nothing
if epoch == 0:
return lr
# Decay the learning rate
if self.t_decay > 0:
lr -= self.t_decay
self.t_decay *= 0.9 # decrease the decay
else:
lr = self.cosine_decay(epoch, lr)
return lr
def training(self, x_train, y_train, epochs=10, batch_size=32, lr=0.001, decay=0):
""" Full Training of the Model
x_train : training images
y_train : training labels
epochs : number of epochs
batch_size : size of batch
lr : learning rate
decay : step-wise learning rate decay
"""
# Check for hidden dropout layer in classifier
for layer in self.model.layers:
if isinstance(layer, Dropout):
self.hidden_dropout = layer
break
self.t_decay = decay
self.e_steps = x_train.shape[0] // batch_size
self.t_steps = self.e_steps * epochs
self.compile(optimizer=Adam(lr=lr, decay=decay))
lrate = LearningRateScheduler(self.training_scheduler, verbose=1)
self.model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.1, verbose=1,
callbacks=[lrate])
def evaluate(self, x_test, y_test):
""" Call underlying evaluate() method
"""
return self._model.evaluate(x_test, y_test)
###Output
_____no_output_____
###Markdown
Get the DatasetLoad the dataset into memory as numpy arrays, and then normalize the image data (preprocessing).
###Code
from tensorflow.keras.datasets import cifar10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = (x_train / 255.0).astype(np.float32)
x_test = (x_test / 255.0).astype(np.float32)
print(x_train.shape)
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
###Output
_____no_output_____
###Markdown
Build Baseline Model for CIFAR-10
###Code
class ResNetV2(Composable):
""" Construct a Residual Convolution Network Network V2 """
# Meta-parameter: list of groups: number of filters and number of blocks
groups = { 50 : [ { 'n_filters' : 64, 'n_blocks': 3 },
{ 'n_filters': 128, 'n_blocks': 4 },
{ 'n_filters': 256, 'n_blocks': 6 },
{ 'n_filters': 512, 'n_blocks': 3 } ], # ResNet50
101: [ { 'n_filters' : 64, 'n_blocks': 3 },
{ 'n_filters': 128, 'n_blocks': 4 },
{ 'n_filters': 256, 'n_blocks': 23 },
{ 'n_filters': 512, 'n_blocks': 3 } ], # ResNet101
152: [ { 'n_filters' : 64, 'n_blocks': 3 },
{ 'n_filters': 128, 'n_blocks': 8 },
{ 'n_filters': 256, 'n_blocks': 36 },
{ 'n_filters': 512, 'n_blocks': 3 } ] # ResNet152
}
def __init__(self, n_layers, input_shape=(224, 224, 3), n_classes=1000, include_top=True,
reg=l2(0.001), relu=None, init_weights='he_normal', bias=False):
""" Construct a Residual Convolutional Neural Network V2
n_layers : number of layers
input_shape : input shape
n_classes : number of output classes
reg : kernel regularizer
init_weights: kernel initializer
relu : max value for ReLU
bias : whether to include a bias in the dense/conv layers
"""
# Configure base (super) class
super().__init__(reg=reg, init_weights=init_weights, relu=relu, bias=bias)
# predefined
if isinstance(n_layers, int):
if n_layers not in [50, 101, 152]:
raise Exception("ResNet: Invalid value for n_layers")
groups = self.groups[n_layers]
# user defined
else:
groups = n_layers
# The input tensor
inputs = Input(input_shape)
# The stem convolutional group
x = self.stem(inputs)
# The learner
outputs = self.learner(x, groups=groups)
# The classifier
if include_top:
# Add hidden dropout for training-time regularization
outputs = self.classifier(outputs, n_classes, dropout=0.0)
# Instantiate the Model
self._model = Model(inputs, outputs)
def stem(self, inputs):
""" Construct the Stem Convolutional Group
inputs : the input vector
"""
# The 224x224 images are zero padded (black - no signal) to be 230x230 images prior to the first convolution
x = ZeroPadding2D(padding=(3, 3))(inputs)
# First Convolutional layer uses large (coarse) filter
x = self.Conv2D(x, 64, (7, 7), strides=(2, 2), padding='valid')
x = self.BatchNormalization(x)
x = self.ReLU(x)
# Pooled feature maps will be reduced by 75%
x = ZeroPadding2D(padding=(1, 1))(x)
x = MaxPooling2D((3, 3), strides=(2, 2))(x)
return x
def learner(self, x, **metaparameters):
""" Construct the Learner
x : input to the learner
groups: list of groups: number of filters and blocks
"""
groups = metaparameters['groups']
# First Residual Block Group (not strided)
x = self.group(x, strides=(1, 1), **groups.pop(0))
# Remaining Residual Block Groups (strided)
for group in groups:
x = self.group(x, **group)
return x
def group(self, x, strides=(2, 2), **metaparameters):
""" Construct a Residual Group
x : input into the group
strides : whether the projection block is a strided convolution
n_blocks : number of residual blocks with identity link
"""
n_blocks = metaparameters['n_blocks']
# Double the size of filters to fit the first Residual Block
x = self.projection_block(x, strides=strides, **metaparameters)
# Identity residual blocks
for _ in range(n_blocks):
x = self.identity_block(x, **metaparameters)
return x
def identity_block(self, x, **metaparameters):
""" Construct a Bottleneck Residual Block with Identity Link
x : input into the block
n_filters: number of filters
"""
n_filters = metaparameters['n_filters']
del metaparameters['n_filters']
# Save input vector (feature maps) for the identity link
shortcut = x
## Construct the 1x1, 3x3, 1x1 convolution block
# Dimensionality reduction
x = self.BatchNormalization(x)
x = self.ReLU(x)
x = self.Conv2D(x, n_filters, (1, 1), strides=(1, 1), **metaparameters)
# Bottleneck layer
x = self.BatchNormalization(x)
x = self.ReLU(x)
x = self.Conv2D(x, n_filters, (3, 3), strides=(1, 1), padding="same", **metaparameters)
# Dimensionality restoration - increase the number of output filters by 4X
x = self.BatchNormalization(x)
x = self.ReLU(x)
x = self.Conv2D(x, n_filters * 4, (1, 1), strides=(1, 1), **metaparameters)
# Add the identity link (input) to the output of the residual block
x = Add()([shortcut, x])
return x
def projection_block(self, x, strides=(2,2), **metaparameters):
""" Construct a Bottleneck Residual Block of Convolutions with Projection Shortcut
Increase the number of filters by 4X
x : input into the block
strides : whether the first convolution is strided
n_filters: number of filters
reg : kernel regularizer
"""
n_filters = metaparameters['n_filters']
del metaparameters['n_filters']
# Construct the projection shortcut
# Increase filters by 4X to match shape when added to output of block
shortcut = self.BatchNormalization(x)
shortcut = self.Conv2D(shortcut, 4 * n_filters, (1, 1), strides=strides, **metaparameters)
## Construct the 1x1, 3x3, 1x1 convolution block
# Dimensionality reduction
x = self.BatchNormalization(x)
x = self.ReLU(x)
x = self.Conv2D(x, n_filters, (1, 1), strides=(1,1), **metaparameters)
# Bottleneck layer
# Feature pooling when strides=(2, 2)
x = self.BatchNormalization(x)
x = self.ReLU(x)
x = self.Conv2D(x, n_filters, (3, 3), strides=strides, padding='same', **metaparameters)
# Dimensionality restoration - increase the number of filters by 4X
x = self.BatchNormalization(x)
x = self.ReLU(x)
x = self.Conv2D(x, 4 * n_filters, (1, 1), strides=(1, 1), **metaparameters)
# Add the projection shortcut to the output of the residual block
x = Add()([x, shortcut])
return x
def makeModel(reg=None, n_blocks=4, lr=0.001, noise=None):
groups = [ { 'n_filters' : 16, 'n_blocks': n_blocks },
{ 'n_filters' : 64, 'n_blocks': n_blocks },
{ 'n_filters': 128, 'n_blocks': n_blocks }]
resnet = ResNetV2(groups, input_shape=(32, 32, 3), n_classes=10, include_top=False, reg=reg)
# Classifier
resnet.top(GlobalAveragePooling2D())
if noise:
resnet.top(GaussianNoise(noise))
resnet.top(ReLU())
resnet.top(Dense(10, activation='softmax'))
resnet.compile(loss='categorical_crossentropy', optimizer=Adam(lr=lr), metrics=['acc'])
return resnet
###Output
_____no_output_____
###Markdown
Train Model and Tackle OverfittingThis small models still has too many parameters, that the training data can't fit to the parameters. As is (after 10 epochs), the validation/test data will plateau out at ~73% accuracy, while the training accuracy has climbed to 91%. But if we reduce the size of the model, we eliminate too many parameters to increase accuracy. Base ModelLet's first train as-is to demonstrate.
###Code
resnet = makeModel()
resnet.summary()
resnet.training(x_train, y_train, epochs=10, batch_size=32, lr=0.001, decay=1e-5)
resnet.evaluate(x_test, y_test)
###Output
_____no_output_____
###Markdown
Gaussian NoiseLet's try adding some noise to the input to the output classification layer. This will act as a regularizer. Note how we added a ReLU() afterwards. If we did not, some of the weights might have a negative value from the noise (as if it was a leaky ReLU).As is (after 10 epochs), the training accuracy remains unchanged, but the validation/test data has crept up a small amount to ~75%.
###Code
resnet = makeModel(noise=0.1)
resnet.summary()
resnet.training(x_train, y_train, epochs=10, batch_size=32, lr=0.001, decay=1e-5)
resnet.evaluate(x_test, y_test)
###Output
_____no_output_____
###Markdown
Layer RegularizationLet's use an aggresive form of kernel regularization -- this will penalize any large weight changes to prevent data snapping into the node (L2 regularation), but may greatly reduce the rate of learning - or learning at all (rate = 0.1). As is (after 10 epochs), the training accuracy will be plateaued around ~60%. It just won't learn at this level of aggressive layer regularization.
###Code
resnet = makeModel(noise=0.1, reg=l2(0.1))
resnet.training(x_train, y_train, epochs=10, batch_size=32, lr=0.001, decay=1e-5)
resnet.evaluate(x_test, y_test)
###Output
_____no_output_____
###Markdown
Let's now try less aggressive amount of regularization (reduce by a magnitude of 100). The rate of increase in training accuracy will slow down and be more stable with the validation accuracy. We can now increase the number of epochs to 30.As is (after 30 epochs), the validation/test data has crept up a modest amount to ~80%, while the training accuracy has plauteaued also around 80%.
###Code
resnet = makeModel(noise=0.1, reg=l2(0.001))
resnet.training(x_train, y_train, epochs=30, batch_size=32, lr=0.001, decay=1e-5)
resnet.evaluate(x_test, y_test)
###Output
_____no_output_____
###Markdown
Learning RateYou can see that we are plateauing out around 80% on the validation/test data after 30 epochs and the training accuracy seems to be equally plateaud. This suggests that the weight updates are bouncing back/forth trying to fit the training data; whereby, lines of linear separation are slightly shifting causing swings in the validation loss.Let's address this by dropping the learning rate a magnitude after the 30 epochs, and run another 10. We can see now that the validation/test data climb and plateaus at ~84%.
###Code
resnet.training(x_train, y_train, epochs=10, batch_size=32, lr=0.0001)
resnet.evaluate(x_test, y_test)
###Output
_____no_output_____ |
10.10-reactor_physics/migration-fission-matrix-method.ipynb | ###Markdown
Energy groupsTo capture the variation of neutron energies in the reactor, we can **discretize the flux into energy groups.**\begin{align}\phi &= \sum_{g=1}^{g=G}\phi_g\\\phi_g &= \int_{E_g}^{E_{g-1}}\phi(E)dE\rvert_{g = 1,G}\end{align}The various parameters (such as cross sections) also need to be individually evaluated for each energy group such that we have a $\Sigma_{ag}$ for each group g. The various cross sections and coefficients also need to be individually evaluated for each energy group such that we have a $\Sigma_{a,g}$ for each group $g\in[1,G] \rightarrow E_g\in[E_1,E_G]$. Also, it is important to consider possible paths of demise for potential fission neutrons. \begin{align}\chi_g &= \int_{E_g}^{E_{g-1}}\chi(E)dE\\ \sum_{g=1}^{g=G}\chi_g &= \int_0^\infty\chi(E) dE\\ \end{align}And the source of fission neutrons is:\begin{align}S &= \sum_{g'=1}^{g'=G}(\nu\Sigma_f)_{g'}\phi_{g'}\end{align} Group-wise Scattering Cross SectionsThis energy group notation is used to indicate scattering from one group into another as well.Most of the scattering is from other groups into our energy group of interest, $g$, but some of the scattering is from this group into itself. Scattering from group $g$ to group $g'$ is denoted as $\Sigma_{s,g\rightarrow g'}$. Group orderingLet's define just two groups, $E_1$ and $E_{2}$. One of these groups will represent the fast neutrons and the other will represent the thermal neutrons. Think-pair share:Which group should be **$g=1$** and which should be **$g=2$**?For simple problems, one can typically also assume that prompt neutrons are born fast.Since they are born fast, energy group 1 is always the fastest group. Upscattering and DownscatteringDownscattering (with cross section $\Sigma_{s,g\rightarrow g'}$) is when energy decreases because of the scatter ( so $g < g'$ ). Upscattering (with cross section $\Sigma_{s,g\rightarrow g'}$) is when energy increases because of the scatter ( so $g > g'$ ). Think Pair ShareGiven what you know about reactors and elastic scattering, which is likely more common in a reactor, upscattering or downscattering? $\infty$ Medium, Two-Group Neutron BalanceBalance equation for group g:\begin{align*} \mbox{Loss} &= \mbox{Gain}\\ \mbox{Absorption} + \mbox{Outscattering} &= \mbox{Fission} + \mbox{Inscattering}\\\Sigma_{ag} \phi_g + \Sigma_{g\rightarrow g'}\phi_g &= \frac{\chi_g}{k}\left(\nu \Sigma_{fg} \phi_g + \nu\Sigma_{fg'}\phi_{g'}\right) + \Sigma_{g'\rightarrow g}\phi_{g'}\end{align*}Group 1 (fast):\begin{align*}\Sigma_{a1} \phi_1 + \Sigma_{1\rightarrow 2}\phi_1 &= \frac{\chi_1}{k}\left(\nu \Sigma_{f1} \phi_1 + \nu\Sigma_{f2}\phi_2\right) + \Sigma_{2\rightarrow 1}\phi_2\end{align*}Group 2 (thermal):\begin{align*}\Sigma_{a2} \phi_2 + \Sigma_{2\rightarrow 1}\phi_2 &= \frac{\chi_2}{k}\left(\nu \Sigma_{f2} \phi_2 + \nu\Sigma_{f1}\phi_1\right) + \Sigma_{1\rightarrow 2}\phi_1\end{align*}We can rewrite these equations in matrix form:\begin{align*} \left[ {\begin{array}{cc} \Sigma_{a1} & 0 \\ 0 & \Sigma_{a2} \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]+ \left[ {\begin{array}{cc} \Sigma_{1\rightarrow 2} & 0 \\ 0 & \Sigma_{2\rightarrow 1} \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]&=\frac{1}{k} \left[ {\begin{array}{c} \chi_1 \\ \chi_2 \\ \end{array} } \right] \left[ {\begin{array}{cc} \nu \Sigma_{f1} & \nu \Sigma_{f2} \end{array}}\right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right] + \left[ {\begin{array}{cc} 0 & \Sigma_{2\rightarrow 1} \\ \Sigma_{1\rightarrow 2} & 0 \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]\end{align*}Moving the inscattering to the left side of the equation, the equation becomes:\begin{align*} \left[ {\begin{array}{cc} \Sigma_{a1} & 0 \\ 0 & \Sigma_{a2} \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]+ \left[ {\begin{array}{cc} \Sigma_{1\rightarrow 2} & 0 \\ 0 & \Sigma_{2\rightarrow 1} \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]- \left[ {\begin{array}{cc} 0 & \Sigma_{2\rightarrow 1} \\ \Sigma_{1\rightarrow 2} & 0 \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]&=\frac{1}{k} \left[ {\begin{array}{cc} \chi_1\nu \Sigma_{f1} & \chi_1\nu \Sigma_{f2}\\ \chi_2\nu \Sigma_{f1} & \chi_2\nu \Sigma_{f2}\\ \end{array}}\right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]\end{align*}Here, we can define the macroscopic absorption, inscattering, outscattering,and fission cross-section matrices:\begin{align*}\mbox{Absorption Matrix } (\mathbf{A}): &= \left[ {\begin{array}{cc} \Sigma_{a1} & 0\\ 0 & \Sigma_{a2}\\ \end{array}}\right]\\\mbox{Inscattering Matrix } (\mathbf{S_{in}}): &= \left[ {\begin{array}{cc} 0 & \Sigma_{2\rightarrow 1}\\ \Sigma_{1\rightarrow 2} & 0\\ \end{array}}\right]\\\mbox{Outscattering Matrix } (\mathbf{S_{out}}): &= \left[ {\begin{array}{cc} \Sigma_{1\rightarrow 2} & 0\\ 0 & \Sigma_{2\rightarrow 1}\\ \end{array}}\right]\\\mbox{Fission Matrix } (\mathbf{F}): &= \left[ {\begin{array}{cc} \chi_1\nu \Sigma_{f1} & \chi_1\nu \Sigma_{f2}\\ \chi_2\nu \Sigma_{f1} & \chi_2\nu \Sigma_{f2}\\ \end{array}}\right]\\\end{align*}And now our equation is reduced to:\begin{align*}\left[A + S_{out} - S_{in}\right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\\end{array} } \right]&=\frac{1}{k} \left[F\right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]\end{align*}So, the final version is:\begin{align*}k \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right] &= \left[A + S_{out} - S_{in}\right]^{-1}\left[F\right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\\end{array} } \right]\end{align*}This gives us the final definition to note, the migration matrix:\begin{align*} \mbox{Migration Matrix:} &= \left[A + S_{out} - S_{in}\right]\\\end{align*}For the two group problem, let the eigenvector be$\left(\begin{array}{c}\phi_1\\\phi_2\end{array}\right)$,let the eigenvalue be $k$, andcalculate the eigenvalue and eigenvector of$\left[A + S_{out} - S_{in}\right]^{-1}[F]$. Power Iteration<a title="By Konrad Jacobs, Erlangen (https://opc.mfo.de/detail?photo_id=2896) [CC BY-SA 2.0 de (https://creativecommons.org/licenses/by-sa/2.0/de/deed.en)], via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File:Richard_von_Mises.jpeg">[1] Richard von Mises and H. Pollaczek-Geiringer, Praktische Verfahren der Gleichungsauflösung, ZAMM - Zeitschrift für Angewandte Mathematik und Mechanik 9, 152-164 (1929)> Given a diagonalizable matrix $A$, the algorithm will produce a number $\lambda$, which is the greatest (in absolute value) eigenvalue of $A$, and a nonzero vector $v$, the corresponding eigenvector of $\lambda$, such that $Av=\lambda v$. The algorithm is also known as the Von Mises iteration.[1]Facts about Power Iteration: - It is simple to implement- It can sometimes be quite slow to converge (reach the answer)- It doesn't compute a matrix decomposition, so it can be used on very large sparse matricesWe'd like to solve for $\phi$. If we assume:- B has an eigenvalue strictly greater in magnitude than its others - the starting vector ($\phi_0$) has a nonzero component in the direction of an eigenvector associated with the dominant eigenvalue, the a sequence $\phi_k$ converges to an eigenvector associated with the dominant eigenvalue.Iterate with the following definitions:\begin{align*} \phi_{i+1} &= \frac{B\phi_i}{\lVert B\phi_i \rVert_2}\\\end{align*}Note the definition of the euclidean norm (a.k.a the $L^2$ norm) for a vector$\vec{x} = (x_1, x_2, \cdots, x_n)$ is :\begin{align*} \lVert \vec{x}\rVert_2 \equiv \sqrt{x_1^2 + x_2^2 + \cdots + x_n^2}.\end{align*}
###Code
import numpy as np
def power_iteration(B, num_simulations):
"""
Returns the normalized
"""
# By chosing a random solution vector we decrease the chance
# that it is orthogonal to the eigenvector
phi_k = np.random.rand(B.shape[1])
for _ in range(num_simulations):
# calculate the matrix-by-vector product Bphi
phi_k1 = np.dot(B, phi_k)
# calculate the norm
phi_k1_norm = np.linalg.norm(phi_k1)
# re normalize the vector
phi_k = phi_k1 / phi_k1_norm
return phi_k
B = np.array([[0.5, 0.5], [0.2, 0.8]])
power_iteration(B, 100)
###Output
_____no_output_____
###Markdown
Energy groupsTo capture the variation of neutron energies in the reactor, we can **discretize the flux into energy groups.**\begin{align}\phi &= \sum_{g=1}^{g=G}\phi_g\\\phi_g &= \int_{E_g}^{E_{g-1}}\phi(E)dE\rvert_{g = 1,G}\end{align}The various parameters (such as cross sections) also need to be individually evaluated for each energy group such that we have a $\Sigma_{ag}$ for each group g. The various cross sections and coefficients also need to be individually evaluated for each energy group such that we have a $\Sigma_{a,g}$ for each group $g\in[1,G] \rightarrow E_g\in[E_1,E_G]$. Also, it is important to consider possible paths of demise for potential fission neutrons. \begin{align}\chi_g &= \int_{E_g}^{E_{g-1}}\chi(E)dE\\ \sum_{g=1}^{g=G}\chi_g &= \int_0^\infty\chi(E) dE\\ \end{align}And the source of fission neutrons is:\begin{align}S &= \sum_{g'=1}^{g'=G}(\nu\Sigma_f)_{g'}\phi_{g'}\end{align} Group-wise Scattering Cross SectionsThis energy group notation is used to indicate scattering from one group into another as well.Most of the scattering is from other groups into our energy group of interest, $g$, but some of the scattering is from this group into itself. Scattering from group $g$ to group $g'$ is denoted as $\Sigma_{s,g\rightarrow g'}$. Group orderingLet's define just two groups, $E_1$ and $E_{2}$. One of these groups will represent the fast neutrons and the other will represent the thermal neutrons. Think-pair share:Which group should be **$g=1$** and which should be **$g=2$**?For simple problems, one can typically also assume that prompt neutrons are born fast.Since they are born fast, energy group 1 is always the fastest group. Upscattering and DownscatteringDownscattering (with cross section $\Sigma_{s,g\rightarrow g'}$) is when energy decreases because of the scatter ( so $g < g'$ ). Upscattering (with cross section $\Sigma_{s,g\rightarrow g'}$) is when energy increases because of the scatter ( so $g > g'$ ). Think Pair ShareGiven what you know about reactors and elastic scattering, which is likely more common in a reactor, upscattering or downscattering? $\infty$ Medium, Two-Group Neutron BalanceBalance equation for group g:\begin{align*} \mbox{Loss} &= \mbox{Gain}\\ \mbox{Absorption} + \mbox{Outscattering} &= \mbox{Fission} + \mbox{Inscattering}\\\Sigma_{ag} \phi_g + \Sigma_{g\rightarrow g'}\phi_g &= \frac{\chi_g}{k}\left(\nu \Sigma_{fg} \phi_g + \nu\Sigma_{fg'}\phi_{g'}\right) + \Sigma_{g'\rightarrow g}\phi_{g'}\end{align*}Group 1 (fast):\begin{align*}\Sigma_{a1} \phi_1 + \Sigma_{1\rightarrow 2}\phi_1 &= \frac{\chi_1}{k}\left(\nu \Sigma_{f1} \phi_1 + \nu\Sigma_{f2}\phi_2\right) + \Sigma_{2\rightarrow 1}\phi_2\end{align*}Group 2 (thermal):\begin{align*}\Sigma_{a2} \phi_2 + \Sigma_{2\rightarrow 1}\phi_2 &= \frac{\chi_2}{k}\left(\nu \Sigma_{f2} \phi_2 + \nu\Sigma_{f1}\phi_1\right) + \Sigma_{1\rightarrow 2}\phi_1\end{align*}We can rewrite these equations in matrix form:\begin{align*} \left[ {\begin{array}{cc} \Sigma_{a1} & 0 \\ 0 & \Sigma_{a2} \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]+ \left[ {\begin{array}{cc} \Sigma_{1\rightarrow 2} & 0 \\ 0 & \Sigma_{2\rightarrow 1} \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]&=\frac{1}{k} \left[ {\begin{array}{c} \chi_1 \\ \chi_2 \\ \end{array} } \right] \left[ {\begin{array}{cc} \nu \Sigma_{f1} & \nu \Sigma_{f2} \end{array}}\right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right] + \left[ {\begin{array}{cc} 0 & \Sigma_{2\rightarrow 1} \\ \Sigma_{1\rightarrow 2} & 0 \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]\end{align*}Moving the inscattering to the left side of the equation, the equation becomes:\begin{align*} \left[ {\begin{array}{cc} \Sigma_{a1} & 0 \\ 0 & \Sigma_{a2} \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]+ \left[ {\begin{array}{cc} \Sigma_{1\rightarrow 2} & 0 \\ 0 & \Sigma_{2\rightarrow 1} \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]- \left[ {\begin{array}{cc} 0 & \Sigma_{2\rightarrow 1} \\ \Sigma_{1\rightarrow 2} & 0 \\ \end{array} } \right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]&=\frac{1}{k} \left[ {\begin{array}{cc} \chi_1\nu \Sigma_{f1} & \chi_1\nu \Sigma_{f2}\\ \chi_2\nu \Sigma_{f1} & \chi_2\nu \Sigma_{f2}\\ \end{array}}\right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]\end{align*}Here, we can define the macroscopic absorption, inscattering, outscattering,and fission cross-section matrices:\begin{align*}\mbox{Absorption Matrix } (\mathbf{A}): &= \left[ {\begin{array}{cc} \Sigma_{a1} & 0\\ 0 & \Sigma_{a2}\\ \end{array}}\right]\\\mbox{Inscattering Matrix } (\mathbf{S_{in}}): &= \left[ {\begin{array}{cc} 0 & \Sigma_{2\rightarrow 1}\\ \Sigma_{1\rightarrow 2} & 0\\ \end{array}}\right]\\\mbox{Outscattering Matrix } (\mathbf{S_{out}}): &= \left[ {\begin{array}{cc} \Sigma_{1\rightarrow 2} & 0\\ 0 & \Sigma_{2\rightarrow 1}\\ \end{array}}\right]\\\mbox{Fission Matrix } (\mathbf{F}): &= \left[ {\begin{array}{cc} \chi_1\nu \Sigma_{f1} & \chi_1\nu \Sigma_{f2}\\ \chi_2\nu \Sigma_{f1} & \chi_2\nu \Sigma_{f2}\\ \end{array}}\right]\\\end{align*}And now our equation is reduced to:\begin{align*}\left[A + S_{out} - S_{in}\right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\\end{array} } \right]&=\frac{1}{k} \left[F\right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right]\end{align*}So, the final version is:\begin{align*}k \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\ \end{array} } \right] &= \left[A + S_{out} - S_{in}\right]^{-1}\left[F\right] \left[ {\begin{array}{c} \phi_1 \\ \phi_2 \\\end{array} } \right]\end{align*}This gives us the final definition to note, the migration matrix:\begin{align*} \mbox{Migration Matrix:} &= \left[A + S_{out} - S_{in}\right]\\\end{align*}For the two group problem, let the eigenvector be$\left(\begin{array}{c}\phi_1\\\phi_2\end{array}\right)$,let the eigenvalue be $k$, andcalculate the eigenvalue and eigenvector of$\left[A + S_{out} - S_{in}\right]^{-1}[F]$. Power Iteration<a title="By Konrad Jacobs, Erlangen (https://opc.mfo.de/detail?photo_id=2896) [CC BY-SA 2.0 de (https://creativecommons.org/licenses/by-sa/2.0/de/deed.en)], via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File:Richard_von_Mises.jpeg">[1] Richard von Mises and H. Pollaczek-Geiringer, Praktische Verfahren der Gleichungsauflösung, ZAMM - Zeitschrift für Angewandte Mathematik und Mechanik 9, 152-164 (1929)> Given a diagonalizable matrix $A$, the algorithm will produce a number $\lambda$, which is the greatest (in absolute value) eigenvalue of $A$, and a nonzero vector $v$, the corresponding eigenvector of $\lambda$, such that $Av=\lambda v$. The algorithm is also known as the Von Mises iteration.[1]Facts about Power Iteration: - It is simple to implement- It can sometimes be quite slow to converge (reach the answer)- It doesn't compute a matrix decomposition, so it can be used on very large sparse matricesWe'd like to solve for $\phi$. If we assume:- B has an eigenvalue strictly greater in magnitude than its others - the starting vector ($\phi_0$) has a nonzero component in the direction of an eigenvector associated with the dominant eigenvalue, the a sequence $\phi_k$ converges to an eigenvector associated with the dominant eigenvalue.Iterate with the following definitions:\begin{align*} \phi_{i+1} &= \frac{B\phi_i}{\lVert B\phi_i \rVert_2}\\\end{align*}Note the definition of the euclidean norm (a.k.a the $L^2$ norm) for a vector$\vec{x} = (x_1, x_2, \cdots, x_n)$ is :\begin{align*} \lVert \vec{x}\rVert_2 \equiv \sqrt{x_1^2 + x_2^2 + \cdots + x_n^2}.\end{align*}
###Code
import numpy as np
def power_iteration(B, num_simulations):
"""
Returns the normalized
"""
# By chosing a random solution vector we decrease the chance
# that it is orthogonal to the eigenvector
phi_k = np.random.rand(B.shape[1])
for _ in range(num_simulations):
# calculate the matrix-by-vector product Bphi
phi_k1 = np.dot(B, phi_k)
# calculate the norm
phi_k1_norm = np.linalg.norm(phi_k1)
# re normalize the vector
phi_k = phi_k1 / phi_k1_norm
return phi_k
B = np.array([[0.5, 0.5], [0.2, 0.8]])
power_iteration(B, 100)
###Output
_____no_output_____ |
0.13/_downloads/plot_label_activation_from_stc.ipynb | ###Markdown
Extracting time course from source_estimate objectLoad a SourceEstimate object from stc files andextract the time course of activation inindividual labels, as well as in a complex labelformed through merging two labels.
###Code
# Author: Christian Brodbeck <[email protected]>
#
# License: BSD (3-clause)
import os
import mne
from mne.datasets import sample
import matplotlib.pyplot as plt
print(__doc__)
data_path = sample.data_path()
os.environ['SUBJECTS_DIR'] = data_path + '/subjects'
meg_path = data_path + '/MEG/sample'
# load the stc
stc = mne.read_source_estimate(meg_path + '/sample_audvis-meg')
# load the labels
aud_lh = mne.read_label(meg_path + '/labels/Aud-lh.label')
aud_rh = mne.read_label(meg_path + '/labels/Aud-rh.label')
# extract the time course for different labels from the stc
stc_lh = stc.in_label(aud_lh)
stc_rh = stc.in_label(aud_rh)
stc_bh = stc.in_label(aud_lh + aud_rh)
# calculate center of mass and transform to mni coordinates
vtx, _, t_lh = stc_lh.center_of_mass('sample')
mni_lh = mne.vertex_to_mni(vtx, 0, 'sample')[0]
vtx, _, t_rh = stc_rh.center_of_mass('sample')
mni_rh = mne.vertex_to_mni(vtx, 1, 'sample')[0]
# plot the activation
plt.figure()
plt.axes([.1, .275, .85, .625])
hl = plt.plot(stc.times, stc_lh.data.mean(0), 'b')[0]
hr = plt.plot(stc.times, stc_rh.data.mean(0), 'g')[0]
hb = plt.plot(stc.times, stc_bh.data.mean(0), 'r')[0]
plt.xlabel('Time (s)')
plt.ylabel('Source amplitude (dSPM)')
plt.xlim(stc.times[0], stc.times[-1])
# add a legend including center-of-mass mni coordinates to the plot
labels = ['LH: center of mass = %s' % mni_lh.round(2),
'RH: center of mass = %s' % mni_rh.round(2),
'Combined LH & RH']
plt.figlegend([hl, hr, hb], labels, 'lower center')
plt.suptitle('Average activation in auditory cortex labels', fontsize=20)
plt.show()
###Output
_____no_output_____ |
study-notes-dictionaries.ipynb | ###Markdown
Notes - Python Dictionaries Python Collections (Arrays)There are four collection data types in the Python programming language:* **List** is a collection which is ordered and changeable. Allows duplicate members.* **Tuple** is a collection which is ordered and **unchangeable**. Allows duplicate members.* **Set** is a collection which is unordered and **unindexed**. **No duplicate** members.* **Dictionary** is a collection which is unordered and changeable. **No duplicate** members. Python Dictionaries* a collection which is unordered, changeable and does not allow duplicates* stores data values in key:value pairs* Dictionaries are written with curly brackets, and have keys and values* Refer to items by keys, rather than by index Creating Dictionaries
###Code
Zoey = {"animal": "dog", "breed": "Yorkie", "gender": "female", "birth_year": 2008, "weight_pounds": 5.1, "nicknames":["Zo-zo", "Zamboey","Isabella"]}
Harley = {"animal": "dog", "breed": "Labrador", "gender": "male", "birth_year": 2020, "weight_pounds": 62.5, "nicknames":["Harley-Barley", "Barley-Boo","Har-Har"]}
Mochi = {"animal": "cat", "gender": "male", "birth_year": 2019, "weight_pounds": 7, "nicknames":["Mo-mo", "T",]}
Cade = {"animal": "gecko", "breed": "spotted leopard", "gender": "male", "birth_year": 2018}
print(Zoey)
print(Harley)
print(Mochi)
print(Cade)
#Note data types:
print(type(Zoey)) #dictionary
print(type(Zoey["breed"])) # string
print(type(Zoey["birth_year"])) # integer
print(type(Zoey["weight_pounds"])) # float
print(type(Zoey["nicknames"]))# list
###Output
{'animal': 'dog', 'breed': 'Yorkie', 'gender': 'female', 'birth_year': 2008, 'weight_pounds': 5.1, 'nicknames': ['Zo-zo', 'Zamboey', 'Isabella']}
{'animal': 'dog', 'breed': 'Labrador', 'gender': 'male', 'birth_year': 2020, 'weight_pounds': 62.5, 'nicknames': ['Harley-Barley', 'Barley-Boo', 'Har-Har']}
{'animal': 'cat', 'gender': 'male', 'birth_year': 2019, 'weight_pounds': 7, 'nicknames': ['Mo-mo', 'T']}
{'animal': 'gecko', 'breed': 'spotted leopard', 'gender': 'male', 'birth_year': 2018}
<class 'dict'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'list'>
###Markdown
Items* Items are unordered, changeable, and do not allow duplicates.* Items are presented in key:value pairs, and can be referred to by using the key name.
###Code
# Examples of referring to a key:value pair
print(Cade["breed"])
print(Zoey["breed"])
print(Harley["gender"])
print(Mochi["birth_year"])
###Output
spotted leopard
Yorkie
male
2019
###Markdown
* A duplicate item will overwrite itself.
###Code
# Example of overwriting an item
my_favorites = {"color":"blue", "number":14,"sport":"volleyball","color":"green"}
print(my_favorites)
###Output
{'color': 'green', 'number': 14, 'sport': 'volleyball'}
###Markdown
* To determine how many items a dictionary has, use the ```len()``` function:
###Code
len(Zoey)
len(Cade)
###Output
_____no_output_____
###Markdown
Accessing Individual Dictionary Items* You can access items of a dictionary by referring to its key name, inside square brackets:* You can use ```get``` to access items
###Code
# access using []
x = Cade["breed"]
print(x)
# access using get()
x = Cade.get("breed")
print(x)
###Output
spotted leopard
###Markdown
Accessing Dictionary Keys * The ```keys()``` method will **return a list of all the keys** in the dictionary. * This is a good way to check if there have been changes to the dictionary.
###Code
#Example of how to list the keys in a dictionary
Zoey.keys()
###Output
_____no_output_____
###Markdown
Accessing Dictionary Values * The ```values()``` method will **return a list of all the values** in the dictionary.
###Code
#Example of how to list the keys in a dictionary
Zoey.values()
###Output
_____no_output_____
###Markdown
Accessing ALL Dictionary Items -- key:value * The ```items()``` method will **return a list of all the items** in the dictionary as a **tuples list**. * This is a good way to check if there have been changes to the dictionary.
###Code
#Example of how to list the keys in a dictionary
Zoey.items()
###Output
_____no_output_____
###Markdown
To Check if a Key Exists * To determine if a specified key is present in a dictionary use the ```in``` keyword
###Code
if "nicknames" in Zoey:
print("Yes, 'nicknames' is one of the keys in the thisdict dictionary")
###Output
Yes, 'nicknames' is one of the keys in the thisdict dictionary
###Markdown
To Change Values * You can change the value of a specific item by referring to its key name:
###Code
Cade["birth_year"] = 2017
print(Cade)
###Output
{'animal': 'gecko', 'breed': 'spotted leopard', 'gender': 'male', 'birth_year': 2017}
###Markdown
Updating Dictionaries * The ```update()``` method will update the dictionary with the items from the given argument.* The argument must be a dictionary, or an iterable object with key:value pairs.
###Code
Cade.update({"gender": "female"})
print(Cade)
###Output
{'animal': 'gecko', 'breed': 'spotted leopard', 'gender': 'female', 'birth_year': 2017}
###Markdown
Adding Items to Dictionaries * Adding an item to the dictionary is done by using a new index key and assigning a value to it* The ```update()``` method will update the dictionary with the items from a given argument. **If the item does not exist, the item will be added.** The argument must be a dictionary, or an iterable object with key:value pairs.
###Code
# Example of adding an item:
Cade["weight_pounds"] = 0.05
print(Cade)
# Example of adding an item with update():
Mochi.update({"breed": "mixed"})
print(Mochi)
###Output
{'animal': 'cat', 'gender': 'male', 'birth_year': 2019, 'weight_pounds': 7, 'nicknames': ['Mo-mo', 'T'], 'breed': 'mixed'}
###Markdown
Removing Items from Dictionaries There are several methods to remove items from a dictionary:* The ```pop()``` method removes the item with the specified key name:
###Code
# using .pop to remove and item
Mochi.pop("breed")
print(Mochi)
###Output
{'animal': 'cat', 'gender': 'male', 'birth_year': 2019, 'weight_pounds': 7, 'nicknames': ['Mo-mo', 'T']}
###Markdown
* The ```popitem()``` method removes the last inserted item (in versions before 3.7, a random item is removed instead):
###Code
Cade.popitem()
print(Cade)
###Output
{'animal': 'gecko', 'breed': 'spotted leopard', 'gender': 'female', 'birth_year': 2017}
###Markdown
* The ```del``` keyword removes the item with the specified key name. BE CAREFUL not to delete the entire dictionary.
###Code
Mochi = {"animal": "cat", "gender": "male", "birth_year": 2019, "weight_pounds": 7, "nicknames":["Mo-mo", "T",]}
del Mochi["gender"]
print(Mochi)
###Output
{'animal': 'cat', 'birth_year': 2019, 'weight_pounds': 7, 'nicknames': ['Mo-mo', 'T']}
###Markdown
---------------------------------------------------------------------- ! ! ! W A R N I N G ! ! !* The ```del``` keyword can also be used to delete the dictionary completely* The ```clear()``` method empties the dictionary---------------------------------------------------------------------- Loop Through a DictionaryYou can loop through a dictionary by using a for loop.When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well. * Print all **key names** in the dictionary, one by one:
###Code
# Example to print key names:
for x in Zoey:
print(x)
###Output
animal
breed
gender
birth_year
weight_pounds
nicknames
###Markdown
* Print all **values** in the dictionary, one by one:
###Code
for x in Zoey:
print(Zoey[x])
###Output
dog
Yorkie
female
2008
5.1
['Zo-zo', 'Zamboey', 'Isabella']
###Markdown
* You can also use the ```values()``` method to return values of a dictionary:
###Code
for x in Zoey.values():
print(x)
###Output
dog
Yorkie
female
2008
5.1
['Zo-zo', 'Zamboey', 'Isabella']
###Markdown
* You can use the ```keys()``` method to return the keys of a dictionary:
###Code
for x in Zoey.keys():
print(x)
###Output
animal
breed
gender
birth_year
weight_pounds
nicknames
###Markdown
* Loop through **both keys and values**, by using the ```items()``` method:
###Code
for x, y in Zoey.items():
print(x, y)
# For readability try: print(x,':', y)
###Output
animal dog
breed Yorkie
gender female
birth_year 2008
weight_pounds 5.1
nicknames ['Zo-zo', 'Zamboey', 'Isabella']
###Markdown
Copy a Dictionary You **cannot copy a dictionary simply by typing dict2 = dict1**, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.* There are ways to make a copy, one way is to use the built-in Dictionary method ```copy()```.
###Code
# Example of copying a dictionary using copy()
new_zoey = Zoey.copy()
print(new_zoey)
###Output
{'animal': 'dog', 'breed': 'Yorkie', 'gender': 'female', 'birth_year': 2008, 'weight_pounds': 5.1, 'nicknames': ['Zo-zo', 'Zamboey', 'Isabella']}
###Markdown
* Another way to make a copy is to use the built-in function ```dict()```.
###Code
# Example of copying a dictionary using dict()
new_Mochi = dict(Mochi)
print(new_Mochi)
###Output
{'animal': 'cat', 'birth_year': 2019, 'weight_pounds': 7, 'nicknames': ['Mo-mo', 'T']}
###Markdown
Nested Dictionaries A dictionary can contain dictionaries, this is called **nested dictionaries**.
###Code
# Example
# Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Rachel",
"year" : 2000
},
"child2" : {
"name" : "Sarah",
"year" : 2004
},
"child3" : {
"name" : "Darrell",
"year" : 1955
}
}
###Output
_____no_output_____
###Markdown
* Or, if you want to add three dictionaries into a new dictionary:
###Code
# Example
# Create three dictionaries, then create one dictionary that will contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
###Output
_____no_output_____ |
examples/CommunityFBA2.ipynb | ###Markdown
2 member community model
###Code
modelInfo_2 = ["CMM_iAH991V2_iML1515.kb",40576]
mediaInfo_2 = ["Btheta_Ecoli_minimal_media",40576]
communityFBA(modelInfo_2,mediaInfo_2,2100,{"1":0.5,"2":0.5})
# Increasing the kinetic coefficient
communityFBA(modelInfo_2,mediaInfo_2,3000,{"1":0.5,"2":0.5})
# Decreasing the kinetic coefficient
communityFBA(modelInfo_2,mediaInfo_2,2000,{"1":0.5,"2":0.5})
# Decreasing the kinetic coefficient so there is no biomass produced
communityFBA(modelInfo_2,mediaInfo_2,1000,{"1":0.5,"2":0.5})
# SPECIES ABUNDANCE BUG?
# Changing the species abundances
communityFBA(modelInfo_2,mediaInfo_2,2100,{"1":0.1,"2":0.9})
# No change in interaction flux
###Output
WARNING:cobrakbase.core.kbasefba.fbamodel_builder:unable to add sink for [cpd02701_c0]: not found
WARNING:cobrakbase.core.kbasefba.fbamodel_builder:unable to add sink for [cpd15302_c0]: not found
###Markdown
3 member community model
###Code
modelInfo_3 = ["electrosynth_comnty.mdl.gf.2021",93204]
mediaInfo_3 = ["CO2_minimal",93204]
communityFBA(modelInfo_3,mediaInfo_3,2100,{"1":0.3,"2":0.3,"3":0.4})
# Increasing the kinetic coefficient
communityFBA(modelInfo_3,mediaInfo_3,2500,{"1":0.1,"2":0.1,"3":0.8})
# Decreasing the kinetic coefficient
communityFBA(modelInfo_3,mediaInfo_3,2700)
# SPECIES ABUNDANCE BUG?
# Changing the species abundances
communityFBA(modelInfo_3,mediaInfo_3,2100,{"1":0.1,"2":0.1,"3":0.8})
# No change?
###Output
WARNING:cobrakbase.core.kbasefba.fbamodel_builder:unable to add sink for [cpd02701_c0]: not found
WARNING:cobrakbase.core.kbasefba.fbamodel_builder:unable to add sink for [cpd15302_c0]: not found
|
Source Codes/Feature Engineering.ipynb | ###Markdown
Colab for Feature Engineering. --- To Do: 1. Separate the Duplicates and Non-Duplicates2. Copy the DataFrames into new variables3. Process the data into the feature to be extracted4. Plot the Histogram to see to observe the distribution---Features1. Number of unique words which occur in q1 and q2 2. Ratio of common words / total words (q1+q2)2. Common Word Ratio min ( words common/ min(len(q1), len(q2)))2. Common Word Ratio mmax ( words common/ max(len(q1), len(q2)))2. Common Stop Words min ( common stopwords/ min(len(q1), len(q2)))2. Common Stop Words max ( common stopwords/ max(len(q1), len(q2)))2. Common Tokens min ( common Tokens / min(len(q1), len(q2)))2. Common Tokens max ( common Tokens / max(len(q1), len(q2)))2. Common Adjectives min ( common adjectives /min(len(q1), len(q2)))2. Common Adjectives max ( common adjectives /max(len(q1), len(q2)))2. Common Noun min ( common nouns / min(len(q1), len(q2)))2. Common Noun max ( common nouns / max(len(q1), len(q2)))2. Fuzz ratio2. Fuzz partial ratio 2. Fuzz Token Sort Ratio 2. Fuzz Token Set Ratio2. Mean Length of 2 questions2. Ratio of Length of Questions ( len(q1) / len(q2) )2. Absolute Length Difference (| len(q1) - len(q2) |2. Longest Matching Substring min ( longest substring/min(len(q1), len(q2)))2. Longest Matching Substring max ( longest substring/max(len(q1), len(q2))) Download your required libraries here
###Code
!pip install bs4
!pip install fuzzywuzzy
!pip install TextBlob
!python -m spacy download en_core_web_lg
###Output
Requirement already satisfied: bs4 in c:\python38\lib\site-packages (0.0.1)
Requirement already satisfied: beautifulsoup4 in c:\python38\lib\site-packages (from bs4) (4.9.3)
Requirement already satisfied: soupsieve>1.2 in c:\python38\lib\site-packages (from beautifulsoup4->bs4) (2.2.1)
###Markdown
Import your required libraries here
###Code
import pandas as pd
import numpy as np
import re
from bs4 import BeautifulSoup
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import nltk
from fuzzywuzzy import fuzz
from difflib import SequenceMatcher #For finding longest substring
from textblob import TextBlob
from sklearn.feature_extraction.text import TfidfVectorizer
import spacy
import en_core_web_lg
nlp = spacy.load('en_core_web_lg')
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('averaged_perceptron_tagger') # for pos tagging
###Output
[nltk_data] Downloading package punkt to
[nltk_data] C:\Users\luciu\AppData\Roaming\nltk_data...
[nltk_data] Package punkt is already up-to-date!
[nltk_data] Downloading package stopwords to
[nltk_data] C:\Users\luciu\AppData\Roaming\nltk_data...
[nltk_data] Package stopwords is already up-to-date!
[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data] C:\Users\luciu\AppData\Roaming\nltk_data...
[nltk_data] Package averaged_perceptron_tagger is already up-to-
[nltk_data] date!
###Markdown
Mounting the dataset onto this google colab
###Code
from google.colab import drive
drive.mount('/content/drive')
%cd "/content/drive/MyDrive/CS3244 45 Project/quora-question-pairs/"
train_set = pd.read_csv('./train.csv')
test_set = pd.read_csv('./test.csv')
%cd './Desktop/CS3244/Project/quora-question-pairs'
# train_set = pd.read_csv('train.csv')
train_set = pd.read_csv('./Desktop/NUS Lecture Notes/Y3S1/CS3244/Project/train.csv')
###Output
_____no_output_____
###Markdown
**Dropping NA Rows**
###Code
train_set.dropna(inplace=True)
train_set.info()
###Output
<class 'pandas.core.frame.DataFrame'>
Int64Index: 404287 entries, 0 to 404289
Data columns (total 6 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id 404287 non-null int64
1 qid1 404287 non-null int64
2 qid2 404287 non-null int64
3 question1 404287 non-null object
4 question2 404287 non-null object
5 is_duplicate 404287 non-null int64
dtypes: int64(4), object(2)
memory usage: 21.6+ MB
###Markdown
**Preprocess the questions**
###Code
# This function accepts a question and preprocesses it. Returns cleaned question.
def preprocess(q):
# Firstly, we convert to lowercase and remove trailing and leading spaces
q = str(q).lower().strip()
# Replace certain special characters with their string equivalents
q = q.replace('%', ' percent')
q = q.replace('$', ' dollar ')
q = q.replace('₹', ' rupee ')
q = q.replace('€', ' euro ')
q = q.replace('@', ' at ')
# The pattern '[math]' appears around 900 times in the whole dataset.
q = q.replace('[math]', '')
# Replacing some numbers with string equivalents (not perfect, can be done better to account for more cases)
q = q.replace(',000,000,000 ', 'b ')
q = q.replace(',000,000 ', 'm ')
q = q.replace(',000 ', 'k ')
q = re.sub(r'([0-9]+)000000000', r'\1b', q)
q = re.sub(r'([0-9]+)000000', r'\1m', q)
q = re.sub(r'([0-9]+)000', r'\1k', q)
# Decontracting words
# https://en.wikipedia.org/wiki/Wikipedia%3aList_of_English_contractions
# https://stackoverflow.com/a/19794953
contractions = {
"ain't": "am not",
"aren't": "are not",
"can't": "can not",
"can't've": "can not have",
"'cause": "because",
"could've": "could have",
"couldn't": "could not",
"couldn't've": "could not have",
"didn't": "did not",
"doesn't": "does not",
"don't": "do not",
"hadn't": "had not",
"hadn't've": "had not have",
"hasn't": "has not",
"haven't": "have not",
"he'd": "he would",
"he'd've": "he would have",
"he'll": "he will",
"he'll've": "he will have",
"he's": "he is",
"how'd": "how did",
"how'd'y": "how do you",
"how'll": "how will",
"how's": "how is",
"i'd": "i would",
"i'd've": "i would have",
"i'll": "i will",
"i'll've": "i will have",
"i'm": "i am",
"i've": "i have",
"isn't": "is not",
"it'd": "it would",
"it'd've": "it would have",
"it'll": "it will",
"it'll've": "it will have",
"it's": "it is",
"let's": "let us",
"ma'am": "madam",
"mayn't": "may not",
"might've": "might have",
"mightn't": "might not",
"mightn't've": "might not have",
"must've": "must have",
"mustn't": "must not",
"mustn't've": "must not have",
"needn't": "need not",
"needn't've": "need not have",
"o'clock": "of the clock",
"oughtn't": "ought not",
"oughtn't've": "ought not have",
"shan't": "shall not",
"sha'n't": "shall not",
"shan't've": "shall not have",
"she'd": "she would",
"she'd've": "she would have",
"she'll": "she will",
"she'll've": "she will have",
"she's": "she is",
"should've": "should have",
"shouldn't": "should not",
"shouldn't've": "should not have",
"so've": "so have",
"so's": "so as",
"that'd": "that would",
"that'd've": "that would have",
"that's": "that is",
"there'd": "there would",
"there'd've": "there would have",
"there's": "there is",
"they'd": "they would",
"they'd've": "they would have",
"they'll": "they will",
"they'll've": "they will have",
"they're": "they are",
"they've": "they have",
"to've": "to have",
"wasn't": "was not",
"we'd": "we would",
"we'd've": "we would have",
"we'll": "we will",
"we'll've": "we will have",
"we're": "we are",
"we've": "we have",
"weren't": "were not",
"what'll": "what will",
"what'll've": "what will have",
"what're": "what are",
"what's": "what is",
"what've": "what have",
"when's": "when is",
"when've": "when have",
"where'd": "where did",
"where's": "where is",
"where've": "where have",
"who'll": "who will",
"who'll've": "who will have",
"who's": "who is",
"who've": "who have",
"why's": "why is",
"why've": "why have",
"will've": "will have",
"won't": "will not",
"won't've": "will not have",
"would've": "would have",
"wouldn't": "would not",
"wouldn't've": "would not have",
"y'all": "you all",
"y'all'd": "you all would",
"y'all'd've": "you all would have",
"y'all're": "you all are",
"y'all've": "you all have",
"you'd": "you would",
"you'd've": "you would have",
"you'll": "you will",
"you'll've": "you will have",
"you're": "you are",
"you've": "you have"
}
q_decontracted = []
for word in q.split():
if word in contractions:
word = contractions[word]
q_decontracted.append(word)
q = ' '.join(q_decontracted)
q = q.replace("'ve", " have")
q = q.replace("n't", " not")
q = q.replace("'re", " are")
q = q.replace("'ll", " will")
# Removing HTML tags
q = BeautifulSoup(q)
q = q.get_text()
# Remove punctuations
pattern = re.compile('\W')
q = re.sub(pattern, ' ', q).strip()
return q
train_set['question1'] = train_set['question1'].apply(preprocess)
train_set['question2'] = train_set['question2'].apply(preprocess)
###Output
c:\python38\lib\site-packages\bs4\__init__.py:332: MarkupResemblesLocatorWarning: "." looks like a filename, not markup. You should probably open this file and pass the filehandle into Beautiful Soup.
warnings.warn(
###Markdown
**Removing empty questions**
###Code
train_set = train_set.drop(train_set[train_set['question1'] == ''].index)
train_set = train_set.drop(train_set[train_set['question2'] == ''].index)
###Output
_____no_output_____
###Markdown
**Jun An**1. Ratio of Common Words (Common words / total words) (Done)2. Ratio of Common Tokens (Common tokens/ max(q1, q2)) (Done)3. Fuzz partial ratio (Done)4. Longest Matching Substring Min (Done)
###Code
def num_common_words_ratio(row):
set1 = set(row['question1'].lower().split())
set2 = set(row['question2'].lower().split())
total = len(set1) + len(set2)
return len(set1.intersection(set2))/total
train_set['common_words_ratio'] = train_set.apply(num_common_words_ratio, axis=1)
def common_tokens_ratio_max(row):
q1 = set(word_tokenize(row['question1'].lower()))
q2 = set(word_tokenize(row['question2'].lower()))
stop_words = set(stopwords.words('english'))
token1 = [word for word in q1 if word not in stop_words]
token2 = [word for word in q2 if word not in stop_words]
ratio = len(set(token1).intersection(set(token2))) / max(len(row['question1']), len(row['question2']))
return ratio
train_set['common_tokens_ratio'] = train_set.apply(common_tokens_ratio_max, axis=1)
def fuzz_partial_ratio(row):
q1 = row['question1']
q2 = row['question2']
fuzz_partial = fuzz.partial_ratio(q1,q2)
return fuzz_partial
train_set['fuzz_partial_ratio'] = train_set.apply(fuzz_partial_ratio, axis=1)
def min_longest_substring(row):
q1 = row['question1']
q2 = row['question2']
match = SequenceMatcher(None, q1, q2).find_longest_match(0, len(q1), 0, len(q2))
return match.size/min(len(q1), len(q2))
train_set['min_longest_substring'] = train_set.apply(min_longest_substring, axis=1)
train_set.head()
###Output
_____no_output_____
###Markdown
**Penn Han**1. Number of unique words that occur in q1 and q22. Ratio of Common Tokens to min(len(q1), len(q2))3. Fuzz Ratio4. Absolute Length Difference between q1 and q25. Mean TF-IDF value6. Mean IDF-weighted vector
###Code
def unique_words_count(row):
set1 = set(row['question1'].lower().split())
set2 = set(row['question2'].lower().split())
return len(set1.intersection(set2))
train_set["unique_words_count"] = train_set.apply(unique_words_count, axis=1)
def common_token_ratio_min(row):
q1 = set(word_tokenize(row['question1'].lower()))
q2 = set(word_tokenize(row['question2'].lower()))
stop_words = set(stopwords.words('english'))
token1 = [word for word in q1 if word not in stop_words]
token2 = [word for word in q2 if word not in stop_words]
ratio = len(set(token1).intersection(set(token2))) / min(len(row['question1']), len(row['question2']))
return ratio
train_set["common_token_ratio_min"] = train_set.apply(common_token_ratio_min, axis=1)
def fuzz_ratio(row):
q1 = row['question1']
q2 = row['question2']
fuzz_ratio = fuzz.ratio(q1,q2)
return fuzz_ratio
train_set["fuzz_ratio"] = train_set.apply(fuzz_ratio, axis=1)
def abs_len_difference(row):
q1 = row['question1']
q2 = row['question2']
abs_len_diff = abs(len(q1) - len(q2))
return abs_len_diff
train_set["abs_len_difference"] = train_set.apply(abs_len_difference, axis=1)
#Stop words not removed PLEASE ONLY USE EITHER THIS OR THE BELOW, NOT BOTH
tf_idf_vectoriser = TfidfVectorizer(lowercase=True)
q1_train_list = list(train_set['question1'])
q2_train_list = list(train_set['question2'])
question_corpus = list(q1_train_list + q2_train_list)
tf_idf_vectoriser.fit(question_corpus)
idf = dict(zip(tf_idf_vectoriser.get_feature_names(), tf_idf_vectoriser.idf_)) #For Weighted W2V
nlp = en_core_web_lg.load()
#Stop words removed PLEASE ONLY USE THIS OR THE ABOVE, NOT BOTH
tf_idf_vectoriser = TfidfVectorizer(lowercase=True)
stop_words = set(stopwords.words('english'))
question_corpus = []
for question1, question2 in zip(list(train_set['question1']), list(train_set['question2'])):
q1 = word_tokenize(question1.lower())
token1 = " ".join([word for word in q1 if word not in stop_words])
q2 = word_tokenize(question2.lower())
token2 = " ".join([word for word in q2 if word not in stop_words])
question_corpus.append((token1 + token2))
tf_idf_vectoriser.fit(question_corpus)
idf = dict(zip(tf_idf_vectoriser.get_feature_names(), tf_idf_vectoriser.idf_)) #For Weighted W2V
nlp = en_core_web_lg.load()
def mean_tfidf_value_q1(row):
q1 = word_tokenize(row['question1'].lower())
stop_words = set(stopwords.words('english'))
token1 = [word for word in q1 if word not in stop_words]
if len(token1) > 0:
q1_vector_matrix = tf_idf_vectoriser.transform(token1) #Transform must take in a iterable so [str]
return q1_vector_matrix #Returns a sparse matrix
else:
return 0
def mean_tfidf_value_q2(row):
q2 = set(word_tokenize(row['question2'].lower()))
stop_words = set(stopwords.words('english'))
token2 = [word for word in q1 if word not in stop_words]
if len(token1) > 0:
q2_vector_matrix = tf_idf_vectoriser.transform(token2) #Transform must take in a iterable so [str]
return q2_vector_matrix #Returns a sparse matrix
else:
return 0
def calculate_weighted_vector(question):
weighted_vectors = []
doc = nlp(question)
mean_vec = np.zeros((len(doc[0].vector)))
for word in doc:
vector = word.vector
if str(word) in idf:
idf_weight = idf[str(word)]
else:
idf_weight = 0
mean_vec += vector * idf_weight
mean_vec /= len(doc)
return mean_vec
def mean_idfweighted_vector_q1(row):
idfweighted_vector_q1 = calculate_weighted_vector(row['question1'])
return idfweighted_vector_q1
def mean_idfweighted_vector_q2(row):
idfweighted_vector_q2 = calculate_weighted_vector(row['question2'])
return idfweighted_vector_q2
train_set["tfidf_matrix_q1"] = train_set.apply(mean_tfidf_value_q1, axis=1)
train_set["tfidf_matrix_q2"] = train_set.apply(mean_tfidf_value_q2, axis=1)
train_set["mean_idfweighted_vector_q1"] = train_set.apply(mean_idfweighted_vector_q1, axis=1)
train_set["mean_idfweighted_vector_q2"] = train_set.apply(mean_idfweighted_vector_q2, axis=1)
train_set.head()
###Output
_____no_output_____
###Markdown
Jeremy1. common stop words min2. common noun min3. mean length of 2 questions
###Code
stop_words = set(stopwords.words('english'))
def get_min_len_qn(row):
return min(len(row['question1'].split()), len(row['question2'].split()))
def calc_common_stop_words_min(row):
q1 = word_tokenize(row['question1'])
q2 = word_tokenize(row['question2'])
stop_words_q1 = set([x for x in q1 if x in stop_words])
stop_words_q2 = set([x for x in q2 if x in stop_words])
num_intersect = len(stop_words_q1.intersection(stop_words_q2))
return num_intersect / get_min_len_qn(row)
train_set['common_stop_words_min'] = train_set.apply(calc_common_stop_words_min, axis=1)
def calc_common_nouns_min(row):
q1_tokens = word_tokenize(row["question1"].lower())
q2_tokens = word_tokenize(row["question2"].lower())
pos_tagged_q1 = nltk.pos_tag(q1_tokens)
pos_tagged_q2 = nltk.pos_tag(q2_tokens)
# x[0] is the word, x[1] is the tag
q1_nouns = set([x[0] for x in pos_tagged_q1 if x[1] == "NN"])
q2_nouns = set([x[0] for x in pos_tagged_q2 if x[1] == "NN"])
return len(q1_nouns.intersection(q2_nouns)) / get_min_len_qn(row)
train_set['common_nouns_min'] = train_set.apply(calc_common_nouns_min, axis=1)
def mean_len_qns(row):
return (len(word_tokenize(row["question1"].lower())) + len(word_tokenize(row["question2"].lower()))) / 2
train_set['mean_len'] = train_set.apply(mean_len_qns, axis=1)
train_set.head(5)
###Output
_____no_output_____
###Markdown
Kay Chi1. Common stop words max2. Common noun max3. Ratio of length of questions
###Code
def get_max_len_qn(row):
return max(len(row['question1'].split()), len(row['question2'].split()))
def calc_common_stop_words_max(row):
q1 = word_tokenize(row['question1'])
q2 = word_tokenize(row['question2'])
stop_words_q1 = set([x for x in q1 if x in stop_words])
stop_words_q2 = set([x for x in q2 if x in stop_words])
num_intersect = len(stop_words_q1.intersection(stop_words_q2))
return num_intersect / get_max_len_qn(row)
train_set['common_stop_words_max'] = train_set.apply(calc_common_stop_words_max, axis=1)
def calc_common_nouns_max(row):
q1_tokens = word_tokenize(row["question1"].lower())
q2_tokens = word_tokenize(row["question2"].lower())
pos_tagged_q1 = nltk.pos_tag(q1_tokens)
pos_tagged_q2 = nltk.pos_tag(q2_tokens)
# x[0] is the word, x[1] is the tag
q1_nouns = set([x[0] for x in pos_tagged_q1 if x[1] == "NN"])
q2_nouns = set([x[0] for x in pos_tagged_q2 if x[1] == "NN"])
return len(q1_nouns.intersection(q2_nouns)) / get_max_len_qn(row)
train_set['common_nouns_max'] = train_set.apply(calc_common_nouns_max, axis=1)
def ratio_len_qn(row):
q1 = row['question1']
q2 = row['question2']
return len(q1) / len(q2)
train_set['ratio_len_qn'] = train_set.apply(ratio_len_qn, axis=1)
train_set.head()
###Output
_____no_output_____
###Markdown
YS1. Common Word Ratio max ( words common/ max(len(q1), len(q2))) 2. Common Adjectives max ( common adjectives /max(len(q1), len(q2)))3. Fuzz Token Set Ratio
###Code
def common_word_ratio_max(row):
q1 = row['question1']
q2 = row['question2']
return len(set(q1).intersection(set(q2))) / max(len(q1), len(q2))
train_set['common_word_ratio_max'] = train_set.apply(common_word_ratio_max, axis=1)
# This has been tested to be correct, but result seems off.
def get_adjectives(text):
blob = TextBlob(text)
return set(word for (word,tag) in blob.tags if tag.startswith("JJ"))
def common_adjectives_max(row):
q1 = row['question1']
q2 = row['question2']
return len(get_adjectives(q1).intersection(get_adjectives(q2))) / max(len(q1), len(q2))
train_set['common_adjectives_max'] = train_set.apply(common_adjectives_max, axis=1)
def calc_fuzz_token_set_ratio(row):
q1 = row['question1']
q2 = row['question2']
return fuzz.token_set_ratio(q1, q2)
train_set['fuzz_token_set_ratio'] = train_set.apply(calc_fuzz_token_set_ratio, axis=1)
train_set.head()
###Output
_____no_output_____
###Markdown
**Neaton**
###Code
def common_words_ratio_min(row):
set1 = set(row['question1'].lower().split())
set2 = set(row['question2'].lower().split())
common_words = len(set1.intersection(set2))
return common_words/min(len(set1), len(set2))
train_set['common_words_ratio_min'] = train_set.apply(common_words_ratio_min, axis=1)
# This has been tested to be correct, but result seems off.
def get_adjectives(text):
blob = TextBlob(text)
return set(word for (word,tag) in blob.tags if tag.startswith("JJ"))
def common_adjectives_min(row):
q1 = row['question1']
q2 = row['question2']
return len(get_adjectives(q1).intersection(get_adjectives(q2))) / min(len(q1), len(q2))
train_set['common_adjectives_min'] = train_set.apply(common_adjectives_min, axis=1)
def fuzz_token_sort_ratio(row):
q1 = row['question1']
q2 = row['question2']
fuzz_token = fuzz.token_sort_ratio(q1,q2)
return fuzz_token
train_set['fuzz_token_sort_ratio'] = train_set.apply(fuzz_token_sort_ratio, axis=1)
def max_longest_substring(row):
q1 = row['question1']
q2 = row['question2']
match = SequenceMatcher(None, q1, q2).find_longest_match(0, len(q1), 0, len(q2))
return match.size/max(len(q1), len(q2))
train_set['max_longest_substring'] = train_set.apply(max_longest_substring, axis=1)
train_set.head()
train_set.to_csv('train_set_with_features.csv')
train_set["tfidf_matrix_q1"]
train_set["mean_idfweighted_vector_q1"]
train_set2 = train_set.drop(columns=["tfidf_matrix_q1", "tfidf_matrix_q2", "mean_idfweighted_vector_q1", "mean_idfweighted_vector_q2"])
train_set2.to_csv("train_set_2.csv")
###Output
_____no_output_____ |
tutorials/ComplexArithmetic/ComplexArithmetic.ipynb | ###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
a, b = x
c, d = y
return (a*c - b*d, a*d + b*c)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], -x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a, b = x
c, d = y
de = c**2 + d**2
r0, r1 = complex_mult(x, conjugate(y))
return (r0/de, r1/de)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
import math
return math.sqrt(x[0]**2+x[1]**2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
import math
r = math.e**x[0]
return (r*math.cos(x[1]), r*math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if r==0:
return (0, 0)
r0 = r**x[0]
return (r0*math.cos(x[1]*math.log(r)), r0*math.sin(x[1]*math.log(r)))
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
import math
r = modulus(x)
if r==0:
return (0, 0)
if x[1]>=0:
theta = math.acos(x[0]/r)
else:
theta = -math.acos(x[0]/r)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
import math
return (x[0]*math.cos(x[1]), x[0]*math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
import math
r = x[0]*y[0]
if r==0:
return (0, 0)
t = x[1]+y[1]
if t > math.pi:
t -= 2*math.pi
if t <= -math.pi:
t += 2*math.pi
return (r, t)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
import math
r, t = polar_convert(x)
c, d = y
if r==0:
return (0, 0)
rr = r**c*math.e**(-t*d)
tt = math.log(r)*d + t*c
return cartesian_convert((rr, tt))
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
first = (a * c) - (b*d)
second = (a*d) + (c * b)
ans = (first, second)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
a = x[0]
b = x[1] * -1
ans = (a, b)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
bottom = (c ** 2) + (d ** 2)
first = ((a * c) + (b * d)) / bottom
second = ((a * (-d) ) + (c * b)) / bottom
ans = (first, second)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
(a, b) = x
first = (a **2) + (b **2)
ans = math.sqrt(first)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
(a,b) = x
euler = math.e ** a
first = euler * math.cos(b)
second = euler * math.sin(b)
return (first, second)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if(r == 0):
return (0,0)
(a,b) = x
lg = math.log(r)
check = r ** a
first = check * math.cos(b * lg)
second = check * math.sin(b * lg)
return (first, second)
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
(a, b) = x
r = math.sqrt(a**2 + b **2)
O = math.atan2(b, a)
return (r, O)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
(r, O) = x
first = r * math.cos(O)
second = r * math.sin(O)
ans = (first, second)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
(r1, O1) = x
(r2, O2) = y
radius = r1 * r2
angle = O1 + O2
if (angle > math.pi):
angle = angle - 2.0 * math.pi
elif (angle <= -math.pi):
angle = angle + 2.0 * math.pi
return (radius, angle)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
(a, b) = x
(c, d) = y
r = math.sqrt(a ** 2 + b ** 2)
O = math.atan2(b, a)
if (r == 0):
return (0, 0)
lnr = math.log(r)
exponent = math.exp(lnr * c - d * O)
first = exponent * (math.cos(lnr * d + O * c ))
second = exponent * (math.sin(lnr * d + O * c))
ans = (first, second)
return ans
###Output
Success!
###Markdown
Belum beres Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b+d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
#complex mult (a+ib)(c+id)
a = x[0]
b = x[1]
c = y[0]
d = y[1]
g = a*c - b*d
h = a*d + b*c
z = (g,h)
return z
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$**This means that a complex number multiplied by its conjugate always produces a non-negative real number.**Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
a = x[0]
b = x[1]
g = a
h = -b
z = (g,h)
return z
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
denom = (c**2 + d**2)
g = (a*c + b*d)/denom
h = (c*b - a*d )/denom
z = (g,h)
return z
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
import math
@exercise
def modulus(x : Complex) -> float:
return math.sqrt((x[0])**2 + (x[1])**2) #!!! inget, kl modulus, i-nya gak ikut! b dikuadratin gak jadi negatif!
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
# code change
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
# copying from above
a = x[0]
b = x[1]
c = y[0]
d = y[1]
real = a*c - b*d
imaginary = a*d + b*c
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
a = x[0]
b = x[1]
return (a, b * -1)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
denominator = (c*c + d*d)
real = (a*c + b*d) / denominator
imaginary = -1 * (a*d - b*c) / denominator
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
return math.sqrt(a**2 + b**2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
a = x[0]
b = x[1]
e_to_the_a = math.e**a
return (e_to_the_a * math.cos(b), e_to_the_a * math.sin(b))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if r == 0:
return (0, 0)
a = x[0]
b = x[1]
return (r**a * math.cos(b * math.log(r)), r**a * math.sin(b * math.log(r)))
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
a = x[0]
b = x[1]
r = math.sqrt(a**2 + b**2)
theta = math.atan2(b, a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
r = x[0]
theta = x[1]
return (r * math.cos(theta), r * math.sin(theta))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
r1 = x[0]
theta1 = x[1]
r2 = y[0]
theta2 = y[1]
r3 = r1 * r2
theta3 = theta1 + theta2
if (theta3 > math.pi):
theta3 = theta3 - 2 * math.pi
elif (theta3 <= -math.pi):
theta3 = theta3 + 2 * math.pi
return (r3, theta3)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
if a == 0:
return (0,0)
r = math.sqrt(a**2 + b**2)
theta = math.atan2(b,a)
coeff_result = math.e**(math.log(r)*c - d * theta)
angle_result = math.log(r) * d + c * theta
return (coeff_result * math.cos(angle_result), coeff_result * math.sin(angle_result))
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b+d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
real = (a * c) - (b * d)
img = (a * d) + (b * c)
ans = (real, img)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
a = x[0]
b = x[1]
conj = (a, -b)
return conj
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
r = (c*c) + (d*d)
real = ((a *c) + (b*d))/r
img = ((a * -d) + (b * c))/r
return (real, img)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
mod = math.sqrt((a**2) + (b**2))
return mod
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
a = x[0]
b = x[1]
eA = math.e ** a
real = eA * math.cos(b)
img = eA * math.sin(b)
return (real, img)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if (r == 0):
return (0,0)
a = x[0]
b = x[1]
rA = r ** a
real = rA * math.cos(b * math.log(r))
img = rA * math.sin(b * math.log(r))
return (real, img)
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
a = x[0]
b = x[1]
r = math.sqrt((a**2) + (b **2))
theta = math.atan2(b, a) #got from b/a = sin(theta)/cos(theta)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
r = x[0]
theta = x[1]
a = r * math.cos(theta)
b = r * math.sin(theta)
return (a,b)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar: #x*y = (r1 * e^theta1i) * (r2 * e^theta12) = (r1 * r2) * e^ (theta1 + theta2)i
r1 = x[0]
theta1 =x[1]
r2 = y[0]
theta2 = y[1]
r3 = r1 * r2
theta3 = theta1 + theta2
if (theta3 > math.pi):
theta3 = theta3 - (2.0 * math.pi) #subtract 2pi from the new theta to give it an equal value within the parameters
if (theta3 < -math.pi):
theta3 = theta3 + (2.0 * math.pi) #add 2pi to the new theta to give it an equal value within the parameters
return (r3,theta3)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# first part needs to be in polar form for this to work
r = math.sqrt((a**2) + (b**2))
theta = math.atan2(b, a)
if (r == 0):
return (0, 0)
exp = math.exp((math.log(r) * c) - (d * theta))
real = exp * (math.cos((math.log(r) * d) + (theta * c)))
img = exp * (math.sin(((math.log(r)) * d) + (theta * c)))
return (real,img)
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
a = x[0]
b = x[1]
c = y[0]
d = y[1]
real = (a*c) - (b*d)
imaginary = (a*d) + (b*c)
return (real,imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
real = x[0]
imaginary = x[1]
return (real,-imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
numeratorReal = (a*c) + (b*d)
numeratorImaginary = -(a*d) + (b*c)
denominator = (c*c) + (d*d)
real = numeratorReal/denominator
imaginary = numeratorImaginary/denominator
return (real,imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
ans = (a*a) + (b*b)
return math.sqrt(ans)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
real = x[0]
imaginary = x[1]
ansReal = (math.e ** real) * math.cos(imaginary)
ansImaginary = (math.e ** real) * math.sin(imaginary)
return (ansReal,ansImaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
(a,b) = x
r = math.sqrt(a**2 + b**2)
theta = math.atan2(b,a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
r = x[0]
theta = x[1]
real = r * math.cos(theta)
imaginary = r * math.sin(theta)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
(r1,theta1) = x
(r2,theta2) = y
r = r1*r2
angle = theta1+theta2
# If the calculated angle is larger then pi, we will subtract 2pi
if (angle > math.pi):
# Reassign the value for angle
angle = angle - 2.0 * math.pi
# If the calculated angle is smaller then -pi, we will add 2 pi
elif (angle <= -math.pi):
angle = angle + 2.0 * math.pi
return (r,angle)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**. Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return ...
else:
return ...
###Output
_____no_output_____
###Markdown
Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html).> Need a hint? Click here In particular, you might be interested in Python's square root function
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** arount $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$ - return the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should not be negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should not be negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$?
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
partA = a * c + b * d * -1
partB = a * d + b * c
return (partA, partB)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0],x[1]*-1)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
num1 = (a*c + b*d) / (c*c + d*d)
num2 = -1*(a*d - b*c) / (c*c + d*d)
return (num1, num2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
ans = (a**2 + b**2)**(1/2)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
a = x[0]
b = x[1]
num1 = math.e**a
num2 = num1*(math.cos(b))
num3 = num1*(math.sin(b))
return (num2,num3)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
a = x[0]
b = x[1]
num1 = r**a
num2 = num1*(math.cos(b))
num3 = num1*(math.sin(b))
return (num2,num3)
###Output
Result of exponentiation doesn't seem to match expected value: expected 9.431^(1.352 + 7.500i) = -9.026 - 18.735i, got 7.209 + 19.506i
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
(a,b) = x
r = (a**2 + b**2)**(1/2)
theta = math.atan2(b,a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
(a,b) = x
num1 = a * math.cos(b)
num2 = a * math.sin(b)
return (num1,num2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
num1 = a * c
tmpNum = b + d
if (tmpNum > math.pi):
tmpNum = tmpNum - 2 * math.pi
elif (tmpNum <= -math.pi):
tmpNum = tmpNum + 2 * math.pi
return (num1, tmpNum)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
g = (x[0] * y[0]) - (x[1] * y[1])
h = (x[0] * y[1]) + (x[1] * y[0])
return (g, h)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], -x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
num = (x[0], x[1])
den = (y[0], y[1])
num = complex_mult(num, conjugate(den))
den = complex_mult(den, conjugate(den))
real = num[0] / den[0]
imaginary = num[1] / den[0]
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
import math
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
return math.sqrt(a ** 2 + b ** 2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
a = x[0]
b = x[1]
part1 = math.e ** a
part2 = (math.cos(b), math.sin(b))
real = part1 * part2[0]
imaginary = part1 * part2[1]
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
a = x[0]
b = x[1]
if r == 0:
return (0, 0)
else:
exp_real = math.log(r) * a
exp_imaginary = math.log(r) * b
solution = complex_exp((exp_real, exp_imaginary))
return solution
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = modulus(x)
theta = math.atan2(x[1], x[0])
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
r = x[0]
theta = x[1]
real = r * math.cos(theta)
imaginary = r * math.sin(theta)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
r = x[0] * y[0]
theta = x[1] + y[1]
if theta <= -math.pi:
theta += 2 * math.pi
elif theta > math.pi:
theta -= 2 * math.pi
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
(a, b) = x
(c, d) = y
# Convert x to polar form
r = math.sqrt(a ** 2 + b ** 2)
theta = math.atan2(b, a)
if (r == 0):
return (0, 0)
lnr = math.log(r)
exponent = math.exp(lnr * c - d * theta)
real = exponent * (math.cos(lnr * d + theta * c ))
imaginary = exponent * (math.sin(lnr * d + theta * c))
return (real, imaginary)
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**. Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return ...
else:
return ...
###Output
_____no_output_____
###Markdown
Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html).> Need a hint? Click here In particular, you might be interested in Python's square root function
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** arount $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$ - return the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should not be negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should not be negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$?
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
ans = (- b * d + a * c, a * d + c * b)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], - x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b= x[1]
c = y[0]
d = y[1]
div = c*c + d*d
return ((a*c + b*d)/div, (b*c-a*d)/div)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return math.sqrt(x[0]**2 + x[1]**2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
r = math.e ** x[0]
return (r * math.cos(x[1]), r * math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if r == 0:
return (0, 0)
a = x[0]
b = x[1]
r2a = r ** a
r2bi = complex_exp( (0, math.log(r) * b))
return complex_mult((r2a, 0), r2bi)
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
a = x[0]
b = x[1]
if a == 0 and b == 0:
return (0, 0)
r = math.sqrt(a ** 2 + b **2)
theta = math.acos(a/r)
if b < 0:
theta = - theta
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return complex_mult((x[0], 0), complex_exp((0, x[1])))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
theta = x[1] + y[1]
if theta > math.pi:
theta -= 2 * math.pi
elif theta < -math.pi:
theta += 2*math.pi
return (x[0]*y[0], theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
if x[0] == 0 and x[1] == 0:
return (0, 0)
xp = polar_convert(x)
r1 = xp[0]
theta1 = xp[1]
c = y[0]
d = y[1]
r = math.e ** (-theta1 * d) * r1 ** c
theta = math.log(r1) * d + c * theta1
return cartesian_convert((r, theta))
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return (x[0]*y[0]-x[1]*y[1], x[1]*y[0]+x[0]*y[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], -1*x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ((x[0]*y[0] + x[1]*y[1])/(y[0]*y[0]+y[1]*y[1]),(x[1]*y[0] - x[0]*y[1])/(y[0]*y[0]+y[1]*y[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return math.sqrt(x[0]**2 + x[1]**2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return (math.e**x[0]*math.cos(x[1]), math.e**x[0]*math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if r == 0 :
return (0,0)
else :
blnr = x[1] * math.log(r)
return ((r**x[0])*math.cos(blnr),(r**x[0])*math.sin(blnr))
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = modulus(x)
theta = math.atan2(x[1],x[0])
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return (x[0]*math.cos(x[1]), x[0]*math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
(r1, theta1) = x
(r2, theta2) = y
r1r2 = r1*r2
angle = theta1 + theta2
if (angle > math.pi):
angle = angle - 2.0 * math.pi
elif (angle <= -math.pi):
angle = angle + 2.0 * math.pi
return (r1r2, angle)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
(a,b) = x
(c,d) = y
(r, theta) = polar_convert(x)
if r == 0:
return (0,0)
else:
lnr = math.log(r)
term = math.exp(lnr * c - d * theta)
real = term*math.cos(lnr * d + theta * c)
imaginary = term*math.sin(lnr * d + theta * c)
return (real, imaginary)
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
(a, b) = x
(c, d) = y
real = (a * c) - (b * d)
imaginary = (a * d) + (c * b)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
real = x[0]
imaginary = -x[1]
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
(a, b) = x
(c, d) = y
denominator = (c ** 2) + (d ** 2)
real = ((a * c) + (b * d)) / denominator
imaginary = ((a * (-d) ) + (c * b)) / denominator
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return math.sqrt(x[0] ** 2 + x[1] ** 2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
(a, b) = x
expa = math.e ** a
real = expa * math.cos(b)
imaginary = expa * math.sin(b)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if (r == 0):
return (0,0)
(a, b) = x
ra = r ** a
lnr = math.log(r)
real = ra * math.cos(b * lnr)
imaginary = ra * math.sin(b * lnr)
return (real, imaginary)
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
(a, b) = x
r = math.sqrt(a**2 + b **2)
theta = math.atan2(b, a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
(r, theta) = x
real = r * math.cos(theta)
imaginary = r * math.sin(theta)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
(r1, theta1) = x
(r2, theta2) = y
radius = r1 * r2
angle = theta1 + theta2
if (angle > math.pi):
angle = angle - 2.0 * math.pi
elif (angle <= -math.pi):
angle = angle + 2.0 * math.pi
return (radius, angle)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
(a, b) = x
(c, d) = y
r = math.sqrt(a ** 2 + b ** 2)
theta = math.atan2(b, a)
if (r == 0):
return (0, 0)
lnr = math.log(r)
exponent = math.exp(lnr * c - d * theta)
real = exponent * (math.cos(lnr * d + theta * c ))
imaginary = exponent * (math.sin(lnr * d + theta * c))
return (real, imaginary)
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
a = x[0]
b = x[1]
c = y[0]
d = y[1]
real = (a * c) - (b * d)
imaginary = (a * d) + (c * b)
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
real = x[0]
imaginary = -x[1]
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
(a,b) = x
(c,d) = y
denominator = (c ** 2) + (d ** 2)
real = ((a * c) + (b * d)) / denominator
imaginary = ((a * (-d) ) + (c * b)) / denominator
ans = (real,imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
ans = math.sqrt((a ** 2) + (b ** 2))
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
a = x[0]
b = x[1]
expa = math.e ** a
real = expa * math.cos(b)
imaginary = expa * math.sin(b)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if (r == 0):
return (0,0)
(a, b) = x
# Raise r to the power of a
ra = r ** a
# Natural logarithm of r
lnr = math.log(r)
real = ra * math.cos(b * lnr)
imaginary = ra * math.sin(b * lnr)
return (real, imaginary)
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
(a, b) = x
r = math.sqrt(a**2 + b **2)
theta = math.atan2(b, a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
r = x[0]
theta = x[1]
real = r * math.cos(theta)
imaginary = r * math.sin(theta)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
(r1, theta1) = x
(r2, theta2) = y
radius = r1 * r2
angle = theta1 + theta2
if (angle > math.pi):
angle = angle - 2.0 * math.pi
elif (angle <= -math.pi):
angle = angle + 2.0 * math.pi
return (radius, angle)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
x_polar = polar_convert(x)
(c,d) = y
r = x_polar[0]
theta = x_polar[1]
if (r == 0):
return (0, 0)
lnr = math.log(r)
exponent = math.exp(lnr * c - d * theta)
real = exponent * (math.cos(lnr * d + theta * c ))
imaginary = exponent * (math.sin(lnr * d + theta * c))
return (real, imaginary)
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$-th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
real = a * c - b*d
imaginary = a*d + b*c
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], -x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
r = (c**2 + d**2)
real = a * c + b * d
imaginary = - a * d + b * c
return (real/r, imaginary/r)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return (x[0]**2 + x[1]**2) ** 0.5
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
# (a, b) = x
# expa = math.e ** a
# real = expa * math.cos(b)
# imaginary = expa * math.sin(b)
real = math.e ** x[0] * math.cos(x[1])
imag = math.e ** x[0] * math.sin(x[1])
return (real, imag)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previouslyYou can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
# r^(a+bi) = r^a * r^bi
# r^bi = e^bi*ln(r)
# e^bi = cos(bi*ln(r) + i * sin(b*ln(r))
if (r == 0):
return (0,0)
a = x[0]
b = x[1]
lnr = math.log(r)
real = r**a * math.cos(b*lnr)
imag = r**a * math.sin(b*lnr)
return real, imag
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = (x[0]**2 + x[1]**2)**0.5
if (r == 0):
return (0,0)
theta = math.atan2(x[1], x[0])
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return x[0] * math.cos(x[1]), x[0] * math.sin(x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
x = cartesian_convert(x)
y = cartesian_convert(y)
return polar_convert(complex_mult(x, y))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
(r, theta) = polar_convert(x)
if (r == 0):
return (0,0)
(c, d) = y
exp = math.exp(math.log(r)*c - theta*d)
real = exp * math.cos(math.log(r)*d + theta*c)
imag = exp * math.sin(math.log(r)*d + theta*c)
return (real, imag)
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b+d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
xr, xc = x[0], x[1]
yr, yc = y[0], y[1]
res = (xr*yr - xc*yc, xr*yc + xc*yr)
return res
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], -x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return math.sqrt(x[0]**2 + x[1]**2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
e = math.exp(1)
a, b = x[0], x[1]
return (e**a * math.cos(b), e**a * math.sin(b))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
# this is nice, did not occur to me
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if r == 0:
return (0,0)
else:
a, b = math.log(r)*x[0], math.log(r)*x[1]
return complex_exp((a,b))
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
a, b = x[0], x[1]
# find the modulus
r = math.sqrt(a**2 + b**2)
# find tan-1
theta = math.atan2(b,a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return (x[0]*math.cos(x[1]), x[0]*math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
theta = x[1] + y[1]
if theta > math.pi:
theta -= 2*math.pi
elif theta <= -math.pi:
theta += 2*math.pi
return (x[0]*y[0], theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo) Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return ...
else:
return ...
###Output
_____no_output_____
###Markdown
Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video expanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** arount $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$ - return the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should not be negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should not be negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$?
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ((x[0] * y[0] - x[1] * y[1]), (x[0] * y[1] + x[1] * y[0]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], -x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ((x[0] * y[0] + x[1] * y[1]) / (y[0]**2 + y[1]**2), (-x[0] * y[1] + x[1] * y[0]) / (y[0]**2 + y[1]**2))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return math.sqrt(x[0]**2 + x[1]**2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return (math.e**x[0] * math.cos(x[1]), math.e**x[0] * math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if r == 0:
return (0.0, 0.0)
else:
return complex_exp((math.log(r) * x[0], math.log(r) * x[1]))
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
# r = math.sqrt(x[0]**2 + x[1]**2)
#
# if r == 0:
# return (0.0, 0.0)
# else:
# theta = math.atan(x[1] / x[0])
# if x[0] >= 0:
# return (r, theta)
# elif x[1] >= 0:
# return (r, theta + math.pi)
# else:
# return (r, theta - math.pi)
return (math.sqrt(x[0]**2 + x[1]**2), math.atan2(x[1], x[0]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return (x[0] * math.cos(x[1]), x[0] * math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
if x[1] + y[1] >= math.pi:
return (x[0] * y[0], (x[1] + y[1]) - 2 * math.pi)
elif x[1] + y[1] <= -math.pi:
return (x[0] * y[0], (x[1] + y[1]) + 2 * math.pi)
else:
return (x[0] * y[0], x[1] + y[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
x_polar = polar_convert(x)
if x_polar[0] == 0:
return (0, 0)
else:
x_polar_exponent = (math.log(x_polar[0]), x_polar[1])
multiplication = complex_mult(x_polar_exponent, (y[0], y[1]))
return cartesian_convert((math.exp(multiplication[0]), multiplication[1]))
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
a = x[0]
b = x[1]
c = y[0]
d = y[1]
real = (a * c) - (b * d)
imaginary = (a * d) + (c * b)
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], x[1]*-1)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
bottom = (c ** 2) + (d ** 2)
real = ((a * c) + (b * d)) / bottom
imaginary = ((a * (-d)) + (c * b)) / bottom
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
ans = math.sqrt(a**2 + b**2)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
a = x[0]
b = x[1]
expa = math.e ** a
real = expa * math.cos(b)
imaginary = expa * math.sin(b)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
(a, b) = x
r = math.sqrt(a**2 + b **2)
theta = math.atan2(b, a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
(r, theta) = x
real = r * math.cos(theta)
imaginary = r * math.sin(theta)
return (real, imaginary)
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
(r1, theta1) = x
(r2, theta2) = y
radius = r1 * r2
angle = theta1 + theta2
# If the calculated angle is larger then pi, we will subtract 2pi
if (angle > math.pi):
# Reassign the value for angle
angle = angle - 2.0 * math.pi
# If the calculated angle is smaller then -pi, we will add 2 pi
elif (angle <= -math.pi):
angle = angle + 2.0 * math.pi
return (radius, angle)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/master/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo) Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return ...
else:
return ...
###Output
_____no_output_____
###Markdown
Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video expanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** arount $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$ - return the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should not be negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should not be negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$?
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/master/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return ...
else:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**. Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return ...
else:
return ...
###Output
_____no_output_____
###Markdown
Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html).> Need a hint? Click here In particular, you might be interested in Python's square root function
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** arount $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$ - return the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should not be negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should not be negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$?
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/master/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
assert n % 2 == 0
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
a = x[0]
b = x[1]
c = y[0]
d = y[1]
return (a*c - b*d, a*d + b*c)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], -x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
c = y[0]
d = y[1]
prod = complex_mult(x, conjugate(y))
return complex_mult(prod, (1/(c**2 + d**2),0))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return math.sqrt(x[0]**2 + x[1]**2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return (math.exp(x[0])*math.cos(x[1]),math.exp(x[0])*math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if r == 0:
if x == (0,0):
return (1,0)
else:
return (0,0)
else:
return complex_exp((math.log(r)*x[0], math.log(r)*x[1]))
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = modulus(x)
if r==0:
return (0,0)
else:
theta = math.atan2(x[1],x[0])
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
r = x[0]
theta = x[1]
return (r*math.cos(theta), r*math.sin(theta))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
r1 = x[0]
theta1 = x[1]
r2 = y[0]
theta2 = y[1]
r3 = r1*r2
theta3 = theta1 + theta2
if theta3 <= -math.pi:
theta3 += 2*math.pi
elif theta3 > math.pi:
theta3 -=2*math.pi
return (r3, theta3)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
(r, theta) = polar_convert(x)
z1 = complex_exp_real(r, y)
z2 = complex_exp((-theta*y[1], theta*y[0]))
return complex_mult(z1, z2)
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
real = a * c + (b * d * -1)
imaginary = (a * d) + (b * c)
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
real = x[0]
imaginary = -1 * x[1]
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
real = (a * c) + (b * d)
imaginary = (a * d * -1) + (b * c)
denominator = (c * c) + (d * d)
real = real / denominator
imaginary = imaginary / denominator
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
ans = math.sqrt(a ** 2 + b ** 2)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
a = x[0]
b = x[1]
e_to_a = math.e ** a
real = e_to_a * math.cos(b)
imaginary = e_to_a * math.sin(b)
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
a = x[0]
b = x[1]
if r == 0:
return (0, 0)
e_to_lnr = math.e ** (a * math.log(r))
real = e_to_lnr * math.cos(b * math.log(r))
imaginary = e_to_lnr * math.sin(b * math.log(r))
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
a = x[0]
b = x[1]
r = math.sqrt(a ** 2 + b ** 2)
theta = math.atan2(b, a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
r = x[0]
phase = x[1]
a = r * math.cos(phase)
b = r * math.sin(phase)
ans = (a, b)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
r1 = x[0]
phase1 = x[1]
r2 = y[0]
phase2 = y[1]
r3 = r1 * r2
phase3 = phase1 + phase2
if phase3 > math.pi:
diff = phase3 - math.pi
phase3 = -1.0 * (math.pi - diff)
if phase3 < math.pi * - 1:
diff = phase3 + math.pi
phase3 = math.pi - (diff * -1.0)
ans = (r3, phase3)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
r = math.sqrt(a ** 2 + b ** 2)
theta = math.atan2(b, a)
# Special case for r = 0
# got this part from answers
if (r == 0):
return (0, 0)
coefficient = math.e ** (c * math.log(r) - d * theta)
phi = c * theta + math.log(r) * d
real = coefficient * math.cos(phi)
imaginary = coefficient * math.sin(phi)
ans = (real,imaginary)
return ans
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/master/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return (x[0] * y[0] - x[1] * y[1], x[0] * y[1] + x[1] * y[0])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], -x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ((x[0] * y[0] + x[1] * y[1]) / (y[0] * y[0] + y[1] * y[1]),
(x[1] * y[0] - x[0] * y[1]) / (y[0] * y[0] + y[1] * y[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return math.sqrt(x[0] * x[0] + x[1] * x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return (math.exp(x[0]) * math.cos(x[1]), math.exp(x[0]) * math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if r == 0:
return (0, 0)
return (r ** x[0] * math.cos(x[1] * math.log(r)), r ** x[0] * math.sin(x[1] * math.log(r)))
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = math.sqrt(x[0] * x[0] + x[1] * x[1])
theta = math.atan2(x[1], x[0])
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return (x[0] * math.cos(x[1]), x[0] * math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return (x[0] * y[0], (x[1] + y[1] + math.pi) % (2 * math.pi) - math.pi)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
r, theta = polar_convert(x)
if r == 0:
return (0, 0)
a, b = complex_mult((math.log(r), theta), y)
return (math.exp(a) * math.cos(b), math.exp(a) * math.sin(b))
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b+d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
a = x[0]
b = x[1]
c = y[0]
d = y[1]
real= a*c-(b*d)
imaginary= (a*d)+(c*b)
ans= (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
a=x[0]
b=x[1]
real=a
imaginary=b*-1
ans=(real,imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a=x[0]
b=x[1]
c=y[0]
d=y[1]
numReal= a*c+(b*d)
numImg= (a*(-1*d))+(c*b)
denom = (c*c)+(d*d)
real=numReal/denom
Img= numImg/denom
ans=(real,Img)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a=x[0]
b=x[1]
toRoot=a**2+b**2
root=toRoot**.5
if(root<0):
root=root*-1
return root
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
a=x[0]
b=x[1]
realExp= math.e ** a
real= realExp * math.cos(b)
img= realExp * math.sin(b)
return (real, img)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
(a,b)=x
r = modulus(x)
theta = math.atan2(b,a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
(r1,theta1)= x
(r2,theta2)= y
radius= r1*r2
theta3= theta1+theta2
if(theta3> math.pi):
theta3=theta3-2.0*math.pi
elif(theta3<-math.pi):
theta3=theta3+2.0*math.pi
return (radius,theta3)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
a = x[0]
b = x[1]
c = y[0]
d = y[1]
real = (a*c-b*d)
imaginary = (a*d+b*c)
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
a = x[0]
b = x[1]
real = a
imaginary = -b
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
c = y[0]
d = y[1]
r = c**2 + d**2
num = complex_mult(x,conjugate(y))
real = num[0]/r
imaginary = num[1]/r
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
ans = (a**2 + b**2)**0.5
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
real = math.e**x[0] * math.cos(x[1])
imaginary = math.e**x[0] * math.sin(x[1])
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if (r==0):
return (0,0)
real = r**x[0] * math.cos(x[1]*math.log(r))
imaginary = r**x[0] * math.sin(x[1]*math.log(r))
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
a = x[0]
b = x[1]
r = (a**2 + b**2)**0.5
theta = math.atan2(b,a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
r = x[0]
theta = x[1]
a = r*math.cos(theta)
b = r*math.sin(theta)
ans = (a,b)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
(r1,theta1) = x
(r2, theta2) = y
r3 = r1*r2
theta3 = theta1 + theta2
if (theta3 > math.pi):
theta3 = theta3 - 2*math.pi
elif (theta3 <= -math.pi):
theta3 = theta3 + 2*math.pi
ans = (r3, theta3)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
(a, b) = x
(c, d) = y
# Convert x to polar form
r = math.sqrt(a ** 2 + b ** 2)
theta = math.atan2(b, a)
# Special case for r = 0
if (r == 0):
return (0, 0)
lnr = math.log(r)
exponent = math.exp(lnr * c - d * theta)
real = exponent * (math.cos(lnr * d + theta * c ))
imaginary = exponent * (math.sin(lnr * d + theta * c))
return (real, imaginary)
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**. Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return ...
else:
return ...
###Output
_____no_output_____
###Markdown
Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html).> Need a hint? Click here In particular, you might be interested in Python's square root function
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** arount $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$ - return the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should not be negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should not be negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$?
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/master/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return ...
else:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video expanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** arount $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return ...
else:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return (x[0] * y[0] - x[1] * y[1], x[1] * y[0] + x[0] * y[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], -1 * x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
numerator = complex_mult(x, conjugate(y))
denominator = y[0] ** 2 + y[1] ** 2
return (numerator[0] / denominator, numerator[1] / denominator)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return math.sqrt(x[0] ** 2 + x[1] ** 2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
rePower = math.e ** x[0]
return (rePower * math.cos(x[1]), rePower * math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if r == 0:
return (0, 0)
lnr = math.log(r)
return complex_exp((lnr * x[0], lnr * x[1]))
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = modulus(x)
theta = math.atan2(x[1], x[0])
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return (x[0] * math.cos(x[1]), x[0] * math.sin(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
theta = x[1] + y[1]
if theta < -1 * math.pi:
theta = theta + (2 * math.pi)
if theta > math.pi:
theta = theta - (2 * math.pi)
return (x[0] * y[0], theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
polarx = polar_convert(x)
r_exp = complex_exp_real(polarx[0], y)
e_exp = complex_exp((-1 * polarx[1] * y[1], polarx[1] * y[0]))
return complex_mult(r_exp, e_exp)
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/master/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return ...
else:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video expanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** arount $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$?
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = (a * c)- (b*d)
# Replace the ... with code to calculate the imaginary component
imaginary = (b*c)+(d*a)
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
real = x[0]
imaginary = -x[1]
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
(a,b) = x
(c,d) = y
den = (c*c)+(d*d)
real = ((a*c)+(b*d))/den
imaginary = ((a*(-d))+(c*b))/den
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return math.sqrt(x[0] ** 2 + x[1] ** 2)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
(a, b) = x
ex = math.e ** a
real = ex * math.cos(b)
imaginary = ex * math.sin(b)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if (r == 0):
return (0,0)
(a, b) = x
ra = r ** a
l = math.log(r)
real = ra * math.cos(b * l)
imaginary = ra * math.sin(b * l)
return (real, imaginary)
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
(a, b) = x
r = math.sqrt(a**2 + b **2)
theta = math.atan2(b, a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
(r, theta) = x
real = r * math.cos(theta)
imaginary = r * math.sin(theta)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
(r1, theta1) = x
(r2, theta2) = y
r = r1 * r2
a = theta1 + theta2
if (a > math.pi):
a = a - 2.0 * math.pi
elif (a <= -math.pi):
a = a + 2.0 * math.pi
return (r, a)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
(a, b) = x
(c, d) = y
r = math.sqrt(a ** 2 + b ** 2)
theta = math.atan2(b, a)
if (r == 0):
return (0, 0)
l = math.log(r)
exponent = math.exp(l * c - d * theta)
real = exponent * (math.cos(l * d + theta * c ))
imaginary = exponent * (math.sin(l * d + theta * c))
return (real, imaginary)
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**. Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
i = sqrt(-1)
if n % 4 == 0:
return i**n
else:
return i**n
###Output
_____no_output_____
###Markdown
Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html).> Need a hint? Click here In particular, you might be interested in Python's square root function
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** arount $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$ - return the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should not be negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should not be negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$?
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
i^4 = 1
i^5 = i^4 * i = i
i^6 = i^5 * i = -1
i^7 = i^6 * i = -i
i^8 = i^7 * i = 1
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
# (ac - bd) + (ad + bc)i
a = x[0]
b = x[1]
c = y[0]
d = y[1]
real = a*c - b*d
imag = a*d + b*c
return (real, imag)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], -x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a, b, c, d = x[0], x[1], y[0], y[1]
denom = c*c + d*d
num = complex_mult((a, b), (c, -d))
real = num[0] / denom
imag = num[1] / denom
return (real, imag)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
import math
def squared(n):
return n ** 2
@exercise
def modulus(x : Complex) -> float:
return math.sqrt(squared(x[0]) + squared(x[1]))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
real = math.e ** x[0]
imag = (math.cos(x[1]), math.sin(x[1]))
return (real * imag[0], real * imag[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if (r == 0):
return (0, 0)
# r = e^ln(r)
# r^x = (e^ln(r))^x = e^(xln(r)) = e^(aln(r) + bln(r))
return complex_exp((x[0]*math.log(r), x[1]*math.log(r)))
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
if (x[0] == 0):
return (0, 0)
r = math.sqrt(squared(x[0]) + squared(x[1]))
theta = math.atan2(x[1], x[0])
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
r, theta = x[0], x[1]
return (r*math.cos(theta), r*math.sin(theta))
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
r = x[0] * y[0]
theta = x[1] + y[1]
angle = theta
### Taken from solution ###
# If the calculated angle is larger then pi, we will subtract 2pi
if (angle > math.pi):
# Reassign the value for angle
angle = angle - 2.0 * math.pi
# If the calculated angle is smaller then -pi, we will add 2 pi
elif (angle <= -math.pi):
angle = angle + 2.0 * math.pi
##########################
return (r, angle)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
# x = a+bi
# x_polar = re^(itheta) = (r, theta)
(r, theta) = polar_convert(x)
real = complex_exp_real(r, y)
### Copied ###
(a, b) = x
(c, d) = y
# Special case for r = 0
if (r == 0):
return (0, 0)
lnr = math.log(r)
exponent = math.exp(lnr * c - d * theta)
real = exponent * (math.cos(lnr * d + theta * c ))
imaginary = exponent * (math.sin(lnr * d + theta * c))
return (real, imaginary)
##################
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a * c - (b * d)
# Replace the ... with code to calculate the imaginary component
imaginary = a * d + b * c
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return (x[0], -x[1])
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
denominator = (c * c) + (d * d)
real = (a * c + (b * d))/denominator
imaginary = (a * -d + b * c)/denominator
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
modulus = ((a**2) + (b**2))**0.5
return modulus
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
a = x[0]
b = x[1]
ea = math.e ** a
real = ea * math.cos(b)
imaginary = ea * math.sin(b)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
if(r == 0):
return (0,0)
a = x[0]
b = x[1]
ra = r ** a
lnr = math.log(r)
real = ra * math.cos(b * lnr)
imaginary = ra * math.sin(b * lnr)
return (real, imaginary)
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
a = x[0]
b = x[1]
r = math.sqrt(a**2 + b **2)
theta = math.atan2(b, a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
r = x[0]
theta = x[1]
real = r * math.cos(theta)
imaginary = r * math.sin(theta)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
r1 = x[0]
theta1 = x[1]
r2 = y[0]
theta2 = y[1]
radius = r1 * r2
angle = theta1 + theta2
if (angle > math.pi):
# Reassign the value for angle
angle = angle - 2.0 * math.pi
elif (angle <= -math.pi):
angle = angle + 2.0 * math.pi
return (radius, angle)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
r = math.sqrt(a ** 2 + b ** 2)
theta = math.atan2(b, a)
if (r == 0):
return (0, 0)
lnr = math.log(r)
exponent = math.exp(lnr * c - d * theta)
real = exponent * (math.cos(lnr * d + theta * c ))
imaginary = exponent * (math.sin(lnr * d + theta * c))
return (real, imaginary)
###Output
Success!
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/master/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
_____no_output_____
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return ...
else:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = ...
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
r = ...
theta = ...
return (r, theta)
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
return ...
###Output
_____no_output_____
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1;
else:
return -1;
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b+d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = (a*c)-(b*d)
# Replace the ... with code to calculate the imaginary component
imaginary = (a*d)+(b*c)
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
# Fill in your own code
a = x[0]
b = x[1]
real = a
imaginary = -1*b
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
# Fill in your own code
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = ((a*c)+(b*d))/((c*c)+(d*d))
# Replace the ... with code to calculate the imaginary component
imaginary = ((b*c)-(a*d))/((c*c)+(d*d))
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
# You can create a tuple like this
ans = ((a*a)+(b*b))**0.5
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
e = math.e
a = x[0]
b = x[1]
real = (e**a) * math.cos(b)
imaginary = (e**a) * math.sin(b)
return (real, imaginary)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
e = math.e
a = x[0]
b = x[1]
real = (e**a) * math.cos(b)
imaginary = (e**a) * math.sin(b)
r = (a**2 + b **2)**0.5
theta = math.atan2(b, a)
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
e = math.e
r = x[0]
theta = x[1]
a = r * math.cos(theta)
b = r * math.sin(theta)
return (a, b)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-10:-Polar-to-Cartesian-conversion.).* Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
pi = math.pi
(r1, theta1) = x
(r2, theta2) = y
r = r1*r2
theta = theta1+theta2
if (theta > pi):
theta = theta - 2.0 * pi
if (theta <= -pi):
theta = theta + 2.0 * pi
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Complex ArithmeticThis is a tutorial designed to introduce you to complex arithmetic.This topic isn't particularly expansive, but it's important to understand it to be able to work with quantum computing.This tutorial covers the following topics:* Imaginary and complex numbers* Basic complex arithmetic* Complex plane* Modulus operator* Imaginary exponents* Polar representationIf you need to look up some formulas quickly, you can find them in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).If you are curious to learn more, you can find more information at [Wikipedia](https://en.wikipedia.org/wiki/Complex_number). This notebook has several tasks that require you to write Python code to test your understanding of the concepts. If you are not familiar with Python, [here](https://docs.python.org/3/tutorial/index.html) is a good introductory tutorial for it. Let's start by importing some useful mathematical functions and constants, and setting up a few things necessary for testing the exercises. **Do not skip this step**.Click the cell with code below this block of text and press `Ctrl+Enter` (`⌘+Enter` on Mac).
###Code
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise
from typing import Tuple
import math
Complex = Tuple[float, float]
Polar = Tuple[float, float]
###Output
Success!
###Markdown
Algebraic Perspective Imaginary numbersFor some purposes, real numbers aren't enough. Probably the most famous example is this equation:$$x^{2} = -1$$which has no solution for $x$ among real numbers. If, however, we abandon that constraint, we can do something interesting - we can define our own number. Let's say there exists some number that solves that equation. Let's call that number $i$.$$i^{2} = -1$$As we said before, $i$ can't be a real number. In that case, we'll call it an **imaginary unit**. However, there is no reason for us to define it as acting any different from any other number, other than the fact that $i^2 = -1$:$$i + i = 2i \\i - i = 0 \\-1 \cdot i = -i \\(-i)^{2} = -1$$We'll call the number $i$ and its real multiples **imaginary numbers**.> A good video introduction on imaginary numbers can be found [here](https://youtu.be/SP-YJe7Vldo). Exercise 1: Powers of $i$.**Input:** An even integer $n$.**Goal:** Return the $n$th power of $i$, or $i^n$.> Fill in the missing code (denoted by `...`) and run the cell below to test your work.
###Code
@exercise
def imaginary_power(n : int) -> int:
# If n is divisible by 4
if n % 4 == 0:
return 1
else:
return -1
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-1:-Powers-of-$i$.).* Complex NumbersAdding imaginary numbers to each other is quite simple, but what happens when we add a real number to an imaginary number? The result of that addition will be partly real and partly imaginary, otherwise known as a **complex number**. A complex number is simply the real part and the imaginary part being treated as a single number. Complex numbers are generally written as the sum of their two parts: $a + bi$, where both $a$ and $b$ are real numbers. For example, $3 + 4i$, or $-5 - 7i$ are valid complex numbers. Note that purely real or purely imaginary numbers can also be written as complex numbers: $2$ is $2 + 0i$, and $-3i$ is $0 - 3i$.When performing operations on complex numbers, it is often helpful to treat them as polynomials in terms of $i$. Exercise 2: Complex addition.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the sum of these two numbers $x + y = z = g + hi$, represented as a tuple `(g, h)`.> A tuple is a pair of numbers.> You can make a tuple by putting two numbers in parentheses like this: `(3, 4)`.> * You can access the $n$th element of tuple `x` like so: `x[n]`> * For this tutorial, complex numbers are represented as tuples where the first element is the real part, and the second element is the real coefficient of the imaginary part> * For example, $1 + 2i$ would be represented by a tuple `(1, 2)`, and $7 - 5i$ would be represented by `(7, -5)`.>> You can find more details about Python's tuple data type in the [official documentation](https://docs.python.org/3/library/stdtypes.htmltuples). Need a hint? Click here Remember, adding complex numbers is just like adding polynomials. Add components of the same type - add the real part to the real part, add the complex part to the complex part. A video explanation can be found here.
###Code
@exercise
def complex_add(x : Complex, y : Complex) -> Complex:
# You can extract elements from a tuple like this
a = x[0]
b = x[1]
c = y[0]
d = y[1]
# This creates a new variable and stores the real component into it
real = a + c
# Replace the ... with code to calculate the imaginary component
imaginary = b + d
# You can create a tuple like this
ans = (real, imaginary)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-2:-Complex-addition.).* Exercise 3: Complex multiplication.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the product of these two numbers $x \cdot y = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Remember, multiplying complex numbers is just like multiplying polynomials. Distribute one of the complex numbers: $$(a + bi)(c + di) = a(c + di) + bi(c + di)$$Then multiply through, and group the real and imaginary terms together. A video explanation can be found here.
###Code
@exercise
def complex_mult(x : Complex, y : Complex) -> Complex:
# Fill in your own code
a = x[0]
b = x[1]
c = y[0]
d = y[1]
first = a * c
second = a * d
third = b * c
fourth = -(b * d)
ans = ((first+fourth), (second+third))
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-3:-Complex-multiplication.).* Complex ConjugateBefore we discuss any other complex operations, we have to cover the **complex conjugate**. The conjugate is a simple operation: given a complex number $x = a + bi$, its complex conjugate is $\overline{x} = a - bi$.The conjugate allows us to do some interesting things. The first and probably most important is multiplying a complex number by its conjugate:$$x \cdot \overline{x} = (a + bi)(a - bi)$$Notice that the second expression is a difference of squares:$$(a + bi)(a - bi) = a^2 - (bi)^2 = a^2 - b^2i^2 = a^2 + b^2$$This means that a complex number multiplied by its conjugate always produces a non-negative real number.Another property of the conjugate is that it distributes over both complex addition and complex multiplication:$$\overline{x + y} = \overline{x} + \overline{y} \\\overline{x \cdot y} = \overline{x} \cdot \overline{y}$$ Exercise 4: Complex conjugate.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return $\overline{x} = g + hi$, the complex conjugate of $x$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def conjugate(x : Complex) -> Complex:
a = x[0]
b = x[1]
ans = (a,-b)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-4:-Complex-conjugate.).* Complex DivisionThe next use for the conjugate is complex division. Let's take two complex numbers: $x = a + bi$ and $y = c + di \neq 0$ (not even complex numbers let you divide by $0$). What does $\frac{x}{y}$ mean?Let's expand $x$ and $y$ into their component forms:$$\frac{x}{y} = \frac{a + bi}{c + di}$$Unfortunately, it isn't very clear what it means to divide by a complex number. We need some way to move either all real parts or all imaginary parts into the numerator. And thanks to the conjugate, we can do just that. Using the fact that any number (except $0$) divided by itself equals $1$, and any number multiplied by $1$ equals itself, we get:$$\frac{x}{y} = \frac{x}{y} \cdot 1 = \frac{x}{y} \cdot \frac{\overline{y}}{\overline{y}} = \frac{x\overline{y}}{y\overline{y}} = \frac{(a + bi)(c - di)}{(c + di)(c - di)} = \frac{(a + bi)(c - di)}{c^2 + d^2}$$By doing this, we re-wrote our division problem to have a complex multiplication expression in the numerator, and a real number in the denominator. We already know how to multiply complex numbers, and dividing a complex number by a real number is as simple as dividing both parts of the complex number separately:$$\frac{a + bi}{r} = \frac{a}{r} + \frac{b}{r}i$$ Exercise 5: Complex division.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di \neq 0$, represented as a tuple `(c, d)`.**Goal:** Return the result of the division $\frac{x}{y} = \frac{a + bi}{c + di} = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here A video explanation can be found here.
###Code
@exercise
def complex_div(x : Complex, y : Complex) -> Complex:
a = x[0]
b = x[1]
c = y[0]
d = y[1]
first = a*c
second = a*-d
third = b*c
fourth = -(b*-d)
denom = (c*c) + (d*d)
ans = ((first+fourth)/denom,(second+third)/denom)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-5:-Complex-division.).* Geometric Perspective The Complex PlaneYou may recall that real numbers can be represented geometrically using the [number line](https://en.wikipedia.org/wiki/Number_line) - a line on which each point represents a real number. We can extend this representation to include imaginary and complex numbers, which gives rise to an entirely different number line: the imaginary number line, which only intersects with the real number line at $0$.A complex number has two components - a real component and an imaginary component. As you no doubt noticed from the exercises, these can be represented by two real numbers - the real component, and the real coefficient of the imaginary component. This allows us to map complex numbers onto a two-dimensional plane - the **complex plane**. The most common mapping is the obvious one: $a + bi$ can be represented by the point $(a, b)$ in the **Cartesian coordinate system**.This mapping allows us to apply complex arithmetic to geometry, and, more importantly, apply geometric concepts to complex numbers. Many properties of complex numbers become easier to understand when viewed through a geometric lens. ModulusOne such property is the **modulus** operator. This operator generalizes the **absolute value** operator on real numbers to the complex plane. Just like the absolute value of a number is its distance from $0$, the modulus of a complex number is its distance from $0 + 0i$. Using the distance formula, if $x = a + bi$, then:$$|x| = \sqrt{a^2 + b^2}$$There is also a slightly different, but algebraically equivalent definition:$$|x| = \sqrt{x \cdot \overline{x}}$$Like the conjugate, the modulus distributes over multiplication.$$|x \cdot y| = |x| \cdot |y|$$Unlike the conjugate, however, the modulus doesn't distribute over addition. Instead, the interaction of the two comes from the triangle inequality:$$|x + y| \leq |x| + |y|$$ Exercise 6: Modulus.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the modulus of this number, $|x|$.> Python's exponentiation operator is `**`, so $2^3$ is `2 ** 3` in Python.>> You will probably need some mathematical functions to solve the next few tasks. They are available in Python's math library. You can find the full list and detailed information in the [official documentation](https://docs.python.org/3/library/math.html). Need a hint? Click here In particular, you might be interested in Python's square root function. A video explanation can be found here.
###Code
@exercise
def modulus(x : Complex) -> float:
a = x[0]
b = x[1]
ans = math.sqrt((a*a)+(b*b))
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-6:-Modulus.).* Imaginary ExponentsThe next complex operation we're going to need is exponentiation. Raising an imaginary number to an integer power is a fairly simple task, but raising a number to an imaginary power, or raising an imaginary (or complex) number to a real power isn't quite as simple.Let's start with raising real numbers to imaginary powers. Specifically, let's start with a rather special real number - Euler's constant, $e$:$$e^{i\theta} = \cos \theta + i\sin \theta$$(Here and later in this tutorial $\theta$ is measured in radians.)Explaining why that happens is somewhat beyond the scope of this tutorial, as it requires some calculus, so we won't do that here. If you are curious, you can see [this video](https://youtu.be/v0YEaeIClKY) for a beautiful intuitive explanation, or [the Wikipedia article](https://en.wikipedia.org/wiki/Euler%27s_formulaProofs) for a more mathematically rigorous proof.Here are some examples of this formula in action:$$e^{i\pi/4} = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\e^{i\pi/2} = i \\e^{i\pi} = -1 \\e^{2i\pi} = 1$$> One interesting consequence of this is Euler's Identity:>> $$e^{i\pi} + 1 = 0$$>> While this doesn't have any notable uses, it is still an interesting identity to consider, as it combines 5 fundamental constants of algebra into one expression.We can also calculate complex powers of $e$ as follows:$$e^{a + bi} = e^a \cdot e^{bi}$$Finally, using logarithms to express the base of the exponent as $r = e^{\ln r}$, we can use this to find complex powers of any positive real number. Exercise 7: Complex exponents.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $e^x = e^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Euler's constant $e$ is available in the [math library](https://docs.python.org/3/library/math.htmlmath.e),> as are [Python's trigonometric functions](https://docs.python.org/3/library/math.htmltrigonometric-functions).
###Code
@exercise
def complex_exp(x : Complex) -> Complex:
a = x[0]
b = x[1]
real = math.exp(a) * math.cos(b)
imag = math.exp(a) * math.sin(b)
ans = (real, imag)
return ans
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-7:-Complex-exponents.).* Exercise 8*: Complex powers of real numbers.**Inputs:**1. A non-negative real number $r$.2. A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the complex number $r^x = r^{a + bi} = g + hi$, represented as a tuple `(g, h)`.> Remember, you can use functions you have defined previously Need a hint? Click here You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately!
###Code
@exercise
def complex_exp_real(r : float, x : Complex) -> Complex:
return ...
###Output
_____no_output_____
###Markdown
Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-8*:-Complex-powers-of-real-numbers.). Polar coordinatesConsider the expression $e^{i\theta} = \cos\theta + i\sin\theta$. Notice that if we map this number onto the complex plane, it will land on a **unit circle** around $0 + 0i$. This means that its modulus is always $1$. You can also verify this algebraically: $\cos^2\theta + \sin^2\theta = 1$.Using this fact we can represent complex numbers using **polar coordinates**. In a polar coordinate system, a point is represented by two numbers: its direction from origin, represented by an angle from the $x$ axis, and how far away it is in that direction.Another way to think about this is that we're taking a point that is $1$ unit away (which is on the unit circle) in the specified direction, and multiplying it by the desired distance. And to get the point on the unit circle, we can use $e^{i\theta}$.A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$.Sometimes $\theta$ will be referred to as the number's **phase**. Exercise 9: Cartesian to polar conversion.**Input:** A complex number $x = a + bi$, represented as a tuple `(a, b)`.**Goal:** Return the polar representation of $x = re^{i\theta}$, i.e., the distance from origin $r$ and phase $\theta$ as a tuple `(r, θ)`.* $r$ should be non-negative: $r \geq 0$* $\theta$ should be between $-\pi$ and $\pi$: $-\pi < \theta \leq \pi$ Need a hint? Click here Python has a separate function for calculating $\theta$ for this purpose. A video explanation can be found here.
###Code
@exercise
def polar_convert(x : Complex) -> Polar:
a = x[0]
b = x[1]
r = math.sqrt((a*a)+(b*b))
theta = (math.atan2(b,a))
return (r, theta)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-9:-Cartesian-to-polar-conversion.).* Exercise 10: Polar to Cartesian conversion.**Input:** A complex number $x = re^{i\theta}$, represented in polar form as a tuple `(r, θ)`.**Goal:** Return the Cartesian representation of $x = a + bi$, represented as a tuple `(a, b)`.
###Code
@exercise
def cartesian_convert(x : Polar) -> Complex:
r = x[0]
theta = x[1]
a = r * math.cos(theta)
b = r * math.sin(theta)
return (a,b)
###Output
Success!
###Markdown
Can't come up with a solution? See the explained solution in the Complex Arithmetic Workbook. Exercise 11: Polar multiplication.**Inputs:**1. A complex number $x = r_{1}e^{i\theta_1}$ represented in polar form as a tuple `(r1, θ1)`.2. A complex number $y = r_{2}e^{i\theta_2}$ represented in polar form as a tuple `(r2, θ2)`.**Goal:** Return the result of the multiplication $x \cdot y = z = r_3e^{i\theta_3}$, represented in polar form as a tuple `(r3, θ3)`.* $r_3$ should be non-negative: $r_3 \geq 0$* $\theta_3$ should be between $-\pi$ and $\pi$: $-\pi < \theta_3 \leq \pi$* Try to avoid converting the numbers into Cartesian form. Need a hint? Click here Remember, a number written in polar form already involves multiplication. What is $r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}$? Need another hint? Click here Is your θ not coming out correctly? Remember you might have to check your boundaries and adjust it to be in the range requested.
###Code
@exercise
def polar_mult(x : Polar, y : Polar) -> Polar:
r1 = x[0]
theta1 = x[1]
r2 = y[0]
theta2 = y[1]
r3 = r1*r2
theta3 = theta1+theta2
if (theta3 > math.pi):
theta3 -= math.pi*2
elif (theta3 < -math.pi):
theta3 += math.pi*2
return (r3, theta3)
###Output
Success!
###Markdown
*Can't come up with a solution? See the explained solution in the [Complex Arithmetic Workbook](./Workbook_ComplexArithmetic.ipynbExercise-11:-Polar-multiplication.).* Exercise 12**: Arbitrary complex exponents.You now know enough about complex numbers to figure out how to raise a complex number to a complex power.**Inputs:**1. A complex number $x = a + bi$, represented as a tuple `(a, b)`.2. A complex number $y = c + di$, represented as a tuple `(c, d)`.**Goal:** Return the result of raising $x$ to the power of $y$: $x^y = (a + bi)^{c + di} = z = g + hi$, represented as a tuple `(g, h)`. Need a hint? Click here Convert $x$ to polar form, and raise the result to the power of $y$.
###Code
@exercise
def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex:
return ...
###Output
_____no_output_____ |
20200907/.ipynb_checkpoints/Morning-checkpoint.ipynb | ###Markdown
Course on webscraping, morning part*By Olav ten Bosch and Dick Windmeijer*
###Code
# Imports:
import requests # for issueing HTTP requests
from bs4 import BeautifulSoup # for parsing and navigating HTML results
import time # for sleeping between multiple requests
import re # for regular expressions
###Output
_____no_output_____
###Markdown
Documentation:- [Requests.py](http://docs.python-requests.org)- [Beautifulsoup.py](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)- [regular expressions](https://developers.google.com/edu/python/regular-expressions) Request, headers, user-agent, parameters, sleeping, regex:
###Code
# Retrieving home page of Statistics Netherlands:
r1 = requests.get('https://www.cbs.nl/en-gb')
#r1.headers['content-type']
print(r1.status_code, r1.headers['content-type'], r1.encoding)
#print(r1.headers)
#print(r1.text)
# Retrieving home page of Statistics Netherlands with user-agent string:
headers = {'user-agent': 'scrapingCourseBot'}
r2 = requests.get('https://www.cbs.nl/en-gb', headers=headers)
# Headers of the request:
print(r2.request.headers)
# Headers of the response:
print(r2.headers)
# Issue a request with parameters:
pars = {'products': 2, 'years': 2}
r3 = requests.get('http://testing-ground.scraping.pro/table?', params=pars, headers=headers)
#print(r3.url)
#print(r3.text)
# In a loop, always add some idle time (time.sleep) to not overload server:
for products in range(1, 6):
for years in range(1, 6):
pars = {'products': products, 'years': years}
r4 = requests.get('http://testing-ground.scraping.pro/table?', params=pars, headers=headers)
print(r4.url, r4.status_code)
time.sleep(1)
# Use a regexp to retrieve title of main article:
# The main article is in an h2:
# <h2 style="background-color:#0058b8;" class="bottom">TITLE</h2>
match = re.search(r'<h2 style="background-color:#0058b8;" class="bottom">.*</h2>', r1.text)
if match:
print(match.group())
else:
print('not found')
###Output
_____no_output_____
###Markdown
Soup with native syntax (find, find_all):
###Code
# Using soup find and find_all to access parts of page:
r4 = requests.get('https://www.cbs.nl/en-gb')
soup = BeautifulSoup(r4.text, 'lxml') # use lxml, is faster and more relaxed in parsing
# find returns the first element:
print(soup.find("h2"))
print(soup.find("h2").text)
print(soup.find("h3"))
print(soup.find("h3").text)
# find the first element which belongs to a class:
part = soup.find("div", class_="thumbnail")
print(part)
# find the first element with an id:
#aside = soup.find("section", id="aside-main")
#print(aside)
# You can use find on a find result:
print(part.find("h3").text)
# Or change find commands:
print(soup.find("div", class_="thumbnail").find("h3").text)
print(soup.find("div", class_="multi-rows").find("div", class_="thumbnail").find("h3").text)
# how to get a URL from an a tag:
print(part.find("a")['href'])
#find_all returns a list:
print(soup.find_all("h2"))
print("")
print(soup.find_all("h3"))
# Get the URLS to all news articles of CBS using find_all and find:
articles = soup.find_all("div", class_='thumbnail')
for article in articles:
link = article.find("a")['href'] # we retrieve the attribute href of the a tag
print(link)
# Follow the links and get all texts of the news articles:
articles = soup.find_all("div", class_='thumbnail')
links3 = []
for article in articles:
links3.append(article.find("a")['href'])
for link in links3:
r = requests.get('https://www.cbs.nl'+link)
#print(r.url)
soup2 = BeautifulSoup(r.text, 'lxml')
leadtext = soup2.find('section', class_='leadtext')
if leadtext is None: continue
print(leadtext.text)
time.sleep(1) # in robots.txt CBS advises a delay of 1 second
###Output
_____no_output_____
###Markdown
Soup with CSS selectors: (select):
###Code
# CSS selectors: by class
r5 = requests.get('https://www.cbs.nl/en-gb')
soup = BeautifulSoup(r5.text, 'lxml')
# Get all headlines via CSS selector:
headlines = soup.select("div.thumbnail h3")
for headline in headlines:
print(headline.text)
# CSS selectors: by id
aside_H2s = soup.select("section#aside-main h2")
print(aside_H2s)
aside_H3s = soup.select("section#aside-main h3")
print(aside_H3s)
for a in aside_H3s:
print(a.text)
###Output
_____no_output_____ |
Examples/.ipynb_checkpoints/Untitled-checkpoint.ipynb | ###Markdown
Generate and Save Random Networks
###Code
max_num_layers = 10
num_nets = 100
num_hidden_units_per_layer = 50
dim_in = 2
dim_out = 1
import os
nets = {}
generate = True
save = True
for num_layers in range(1,max_num_layers+1):
path = 'comparison/networks/'+str(num_layers)+'L/'
#path = str(num_layers)+'L/'
if not os.path.isdir(path):
os.makedirs(path)
for i in range(0,num_nets):
dims = [dim_in] + [num_hidden_units_per_layer]*num_layers + [dim_out]
if generate:
net = generate_random_net(dims)
if save:
export2matlab(path + 'random-net-'+str(num_layers)+'L-'+str(i+1),net,True)
#net = generate_random_net([2,50,50,50,50,50,1])
#export2matlab('networks_hist/5L/random-net-5L-36',net,True)
x = np.ones((1,dim_in))
epsilon = 0.5
c = np.array([1])
import scipy
lb = np.zeros((max_num_layers,num_nets),dtype=np.float64)
ub = np.zeros((max_num_layers,num_nets),dtype=np.float64)
lb_time = np.zeros((max_num_layers,num_nets),dtype=np.float64)
ub_time = np.zeros((max_num_layers,num_nets),dtype=np.float64)
for num_layers in range(1,max_num_layers+1):
L = num_layers-1
for i in range(0,num_nets):
net = torch.load('11-06-2019/networks_small/'+str(num_layers)+'L/random-net-'+str(num_layers)+'L-'+ str(i+1) + '.pt')
lb_,ub_,time = LP_optimizer(net,x,epsilon,c)
lb[L][i] = lb_
ub[L][i] = ub_
lb_time[L][i] = time/2.0
ub_time[L][i] = time/2.0
data = {}
#print(lb[L][:])
#data['LP_'+'num_layers'+'L'] = {'lb_lp': lb[L][:], 'ub_lp': ub[L][:]}
data['LP_'+str(num_layers)+'L'] = ub[L][:]
scipy.io.savemat('11-06-2019/networks_small/'+str(num_layers)+'L/' 'LP_'+str(num_layers)+'L' + '.mat', data)
#print('LP_'+str(num_layers)+'L')
# for num_layers in range(1,max_num_layers+1):
# L = num_layers - 1
# print('num_layers=' + str(num_layers) + ': lb=' + ('%.4f' % np.mean(lb[L][:])) + ' std:' + ('%.4f' % np.std(lb[L][:])))
for num_layers in range(1,max_num_layers+1):
L = num_layers - 1
print('num_layers=' + str(num_layers) + ': ub=' + ('%.4f' % np.mean(ub[L][:])) + ' std:' + ('%.4f' % np.std(ub[L][:])))
#print('mean(ub)='+ ('%.4f' % np.mean(ub[L][:])) + ' std(ub)=' + ('%.2f' % np.std(ub[L][:])))
for num_layers in range(1,max_num_layers+1):
L = num_layers - 1
print('num_layers=' + str(num_layers) + ': time=' + ('%.4f' % np.mean(2*lb_time[L][:])) + ' std:' + ('%.4f' % np.std(2*lb_time[L][:])))
#print('mean(ub)='+ ('%.4f' % np.mean(ub[L][:])) + ' std(ub)=' + ('%.2f' % np.std(ub[L][:])))
# worked
#x = torch.Tensor(np.ones((1,100)))
#c = torch.tensor([[[1]]]).type_as(x)
#lb,ub = LP_optimizer(nets[0],x,epsilon,c)
# worked-final
# x = np.ones((1,100))
# c = np.array([1])
# lb,ub = LP_optimizer(nets[0],x,epsilon,c)
# lb,ub
# nets = {}
# num_nets = 10
# num_layers = 9
# lower_bounds = []
# upper_bounds = []
# lower_bounds_time = []
# upper_bounds_time = []
# for i in range(0,num_nets):
# nets[i] = torch.load('networks/'+str(num_layers)+'L/random-net-'+str(num_layers)+'L-'+ str(i+1) + '.pt')
# lb,ub,time = LP_optimizer(nets[i],x,epsilon,c)
# lower_bounds.append(lb)
# upper_bounds.append(ub)
# lower_bounds_time.append(time/2.0)
# upper_bounds_time.append(time/2.0)
# sum(lower_bounds)/len(lower_bounds),sum(lower_bounds_time)/len(lower_bounds_time)
# sum(upper_bounds)/len(upper_bounds),sum(upper_bounds_time)/len(upper_bounds_time)
# np.std(np.asarray(lower_bounds)),np.std(np.asarray(lower_bounds_time)),np.std(np.asarray(upper_bounds)),np.std(np.asarray(upper_bounds_time))
net
###Output
_____no_output_____
###Markdown
Create an artificial org structure for testingcreate a random organisation structure for app testing purposesmaxWidth=max siblings, maxDepth=max children depth, maxDept=nr of departments to generate.place the data.js file in \static\data.js
###Code
maxWidth=10
maxDepth=10
maxDept=1000
from random import randrange
print(2+randrange(maxWidth-2))
rStr="Morning isn't all seed had male seasons isn't one seasons void is fourth may bring hath which likeness so you the isn't years upon days, form let sea, after, lights. Above day, appear creeping which creature from, given, may saying were good above Evening lesser she'd spirit which. Fill together under sixth bring behold of, gathering dominion night in appear moved fly whales called. Evening saying seed light, their void bring. Spirit darkness years isn't him earth after doesn't itself spirit herb multiply yielding face Lesser appear very fifth whose stars. Greater be gathered Thing, doesn't fifth great that. In earth saying. Behold his it all is. Days them life lights to he given seed dominion isn't doesn't. One, unto god I all man face after a one our living deep you'll, saying light saw won't every green creepeth green a. Sixth beast. Meat land whales seasons lights and grass appear life. Beast first. There fourth kind heaven one gathered i god it together. Meat his stars land their heaven a Moving together have after life creeping light of you're she'd form under bearing heaven fruitful days. Replenish that. Day. Their thing tree female unto. There hath creature. Female won't night fill isn't light, together said. Creature living earth Behold land. Sea you're form won't let thing for thing doesn't to behold second i, heaven green replenish given given them signs void yielding made given above void cattle gathering was thing every green. Gathered grass place darkness were so seas together said him. Replenish, deep whales air gathered appear and stars herb moveth. They're so had also fourth void form multiply saw face may thing greater every, open without have fruitful third seed firmament. Yielding brought. Also place seasons green gathered, you shall likeness fifth deep abundantly forth. Midst gathered make creepeth deep face moved fruit moving place they're. Fifth waters seas bring seed bearing. Under above was. Two lesser great fruit after us there and multiply saying heaven air let blessed hath thing whales hath behold night above creeping seasons likeness. Thing i great sea which heaven divided beast and multiply to them replenish multiply seas stars saw over two from a for make. Doesn't own likeness darkness cattle for which let light over. Lights. Tree firmament moved and also great hath, i kind seasons unto, have there creature called thing. Given saw forth grass spirit form cattle you creature their darkness. That In. Whose divide fill. Great won't beast, greater days, moving which, was. Stars Great i open make. Signs for you which fourth. Image fly gathered. Seasons may herb day hath whales set, seasons great cattle image for moving. Stars won't it evening bearing their created. Moveth give green. He appear called. Gathered place great god second meat. Two you're living seas them earth behold bring creepeth us was, doesn't dominion stars subdue of be life. Brought unto life own bring one. Multiply land. Meat let years fowl his dominion she'd waters days face land years, deep."
rWrd=rStr.split()
def calcLevel(n, parent):
global gId, maxDept, maxWdidth, maxDepth, depts
if n < 2+ randrange(maxDepth-2):
for x in range(2+ randrange(maxWidth-2)):
dName=rWrd[randrange(len(rWrd))] + ' ' + rWrd[randrange(len(rWrd))]
dId=str(gId)
gId=gId+1
dept={
'id':dId,
'name':dName,
'description': '',
'parent_id':parent,
'staff_department': 'N',
'manager_id': '',
'DATA_Location': ''
}
if gId < maxDept:
depts.append(dept)
if gId<maxDept:
calcLevel(n+1, dId)
gId=0
depts=[]
calcLevel(0, '')
print(depts)
import json
y=json.dumps(depts)
outStr='var INPUT_DATA = { "chart" :' + y + ', "assignments": [], "people": []}; var UPDATED_ON = "19-02-2019"'
print (outStr)
file1 = open("data.js","w")#write mode
file1.write(outStr)
file1.close()
###Output
_____no_output_____ |
03 - NumPy arrays.ipynb | ###Markdown
NumPy arrays Nikolay [email protected] ================ - a powerful N-dimensional array object- sophisticated (broadcasting) functions- tools for integrating C/C++ and Fortran code- useful linear algebra, Fourier transform, and random number capabilities
###Code
import numpy as np
%matplotlib inline
np.set_printoptions(precision=3 , suppress= True) # this is just to make the output look better
###Output
_____no_output_____
###Markdown
Load data Load data in to a variable:
###Code
temp = np.loadtxt('Ham_3column.txt')
temp
temp.shape
###Output
_____no_output_____
###Markdown
###Code
temp.size
###Output
_____no_output_____
###Markdown
So it's a *row-major* order. Matlab and Fortran use *column-major* order for arrays.
###Code
type(temp)
###Output
_____no_output_____
###Markdown
Numpy arrays are statically typed, which allow faster operations
###Code
temp.dtype
###Output
_____no_output_____
###Markdown
You can't assign value of different type to element of the numpy array:
###Code
temp[0,0] = 'Year'
###Output
_____no_output_____
###Markdown
Slicing works similarly to Matlab:
###Code
temp[0:5,:]
temp[-5:-1,:]
###Output
_____no_output_____
###Markdown
One can look at the data. This is done by matplotlib module:
###Code
import matplotlib.pylab as plt
plt.plot(temp[:,3])
###Output
_____no_output_____
###Markdown
Index slicing In general it is similar to Matlab First 12 elements of **second** column (months). Remember that indexing starts with 0:
###Code
temp[0:12,2]
###Output
_____no_output_____
###Markdown
First raw:
###Code
temp[0,:]
###Output
_____no_output_____
###Markdown
Exercise - Plot only first 1000 values - Plot last 1000 values
###Code
plt.plot(temp[-1000:,3])
###Output
_____no_output_____
###Markdown
We can create mask, selecting all raws where values in third raw (days) equals 10:
###Code
mask = (temp[:,2]==10)
###Output
_____no_output_____
###Markdown
Here we apply this mask and show only first 5 raws of the array:
###Code
temp[mask][:20,:]
###Output
_____no_output_____
###Markdown
You don't have to create separate variable for mask, but apply it directly. Here instead of first five rows I show five last rows:
###Code
temp[temp[:,2]==10][-5:,:]
###Output
_____no_output_____
###Markdown
You can combine conditions. In this case we select days from 10 to 12 (only first 10 elements are shown):
###Code
temp[(temp[:,2]>=10)&(temp[:,2]<=12)][0:10,:]
###Output
_____no_output_____
###Markdown
Exercise Select only summer months Select only first half of the year Basic operations Create example array from first 12 values of second column and perform some basic operations:
###Code
days = temp[0:12,2]
days
days+10
days*20
days*days
###Output
_____no_output_____
###Markdown
What's wrong with this figure?
###Code
plt.plot(temp[:100,3])
###Output
_____no_output_____
###Markdown
Exercise- Create new array that will contain only temperatures- Convert temperature to deg C- Convert all temperatures to deg F Basic statistics Create *temp_values* that will contain only data values:
###Code
temp_values = temp[:,3]/10.
temp_values
###Output
_____no_output_____
###Markdown
Simple statistics:
###Code
temp_values.min()
temp_values.max()
temp_values.mean()
temp_values.std()
temp_values.sum()
###Output
_____no_output_____
###Markdown
You can also use *sum* function:
###Code
np.sum(temp_values)
###Output
_____no_output_____
###Markdown
One can make operations on the subsets: Exercise Calculate mean for first 1000 values of temperature Saving data You can save your data as a text file
###Code
np.savetxt('temp_only_values.csv',temp[:, 3]/10., fmt='%.4f')
###Output
_____no_output_____
###Markdown
Head of resulting file:
###Code
!head temp_only_values.csv
###Output
-7.2000
-4.3000
-3.2000
1.2000
-2.9000
-4.3000
-3.7000
-9.7000
-9.9000
-8.9000
###Markdown
You can also save it as binary:
###Code
f=open('temp_only_values.bin', 'w')
temp[:,3].tofile(f)
f.close()
###Output
_____no_output_____
###Markdown
NumPy arrays Nikolay [email protected] This is part of [**Python for Geosciences**](https://github.com/koldunovn/python_for_geosciences) notes. ================ - a powerful N-dimensional array object- sophisticated (broadcasting) functions- tools for integrating C/C++ and Fortran code- useful linear algebra, Fourier transform, and random number capabilities
###Code
#allow graphics inline
%matplotlib inline
import matplotlib.pylab as plt #import plotting library
import numpy as np #import numpy library
np.set_printoptions(precision=3) # this is just to make the output look better
###Output
_____no_output_____
###Markdown
Load data I am going to use some real data as an example of array manipulations. This will be the AO index downloaded by wget through a system call (you have to be on Linux of course):
###Code
!wget www.cpc.ncep.noaa.gov/products/precip/CWlink/daily_ao_index/monthly.ao.index.b50.current.ascii
###Output
_____no_output_____
###Markdown
This is how data in the file look like (we again use system call for *head* command):
###Code
!head monthly.ao.index.b50.current.ascii
###Output
1950 1 -0.60310E-01
1950 2 0.62681E+00
1950 3 -0.81275E-02
1950 4 0.55510E+00
1950 5 0.71577E-01
1950 6 0.53857E+00
1950 7 -0.80248E+00
1950 8 -0.85101E+00
1950 9 0.35797E+00
1950 10 -0.37890E+00
###Markdown
Load data in to a variable:
###Code
ao = np.loadtxt('monthly.ao.index.b50.current.ascii')
ao
ao.shape
###Output
_____no_output_____
###Markdown
So it's a *row-major* order. Matlab and Fortran use *column-major* order for arrays.
###Code
type(ao)
###Output
_____no_output_____
###Markdown
Numpy arrays are statically typed, which allow faster operations
###Code
ao.dtype
###Output
_____no_output_____
###Markdown
You can't assign value of different type to element of the numpy array:
###Code
ao[0,0] = 'Year'
###Output
_____no_output_____
###Markdown
Slicing works similarly to Matlab:
###Code
ao[0:5,:]
###Output
_____no_output_____
###Markdown
One can look at the data. This is done by matplotlib.pylab module that we have imported in the beggining as `plt`. We will plot only first 780 poins:
###Code
plt.plot(ao[:780,2])
###Output
_____no_output_____
###Markdown
Index slicing In general it is similar to Matlab First 12 elements of **second** column (months). Remember that indexing starts with 0:
###Code
ao[0:12,1]
###Output
_____no_output_____
###Markdown
First raw:
###Code
ao[0,:]
###Output
_____no_output_____
###Markdown
We can create mask, selecting all raws where values in second raw (months) equals 10 (October):
###Code
mask = (ao[:,1]==10)
###Output
_____no_output_____
###Markdown
Here we apply this mask and show only first 5 rowd of the array:
###Code
ao[mask][:5,:]
###Output
_____no_output_____
###Markdown
You don't have to create separate variable for mask, but apply it directly. Here instead of first five rows I show five last rows:
###Code
ao[ao[:,1]==10][-5:,:]
###Output
_____no_output_____
###Markdown
You can combine conditions. In this case we select October-December data (only first 10 elements are shown):
###Code
ao[(ao[:,1]>=10)&(ao[:,1]<=12)][0:10,:]
###Output
_____no_output_____
###Markdown
You can assighn values to subset of values (*thi expression fixes the problem with very small value at 2015-04*)
###Code
ao[ao<-10]=0
###Output
_____no_output_____
###Markdown
Basic operations Create example array from first 12 values of second column and perform some basic operations:
###Code
months = ao[0:12,1]
months
months+10
months*20
months*months
###Output
_____no_output_____
###Markdown
Basic statistics Create *ao_values* that will contain onlu data values:
###Code
ao_values = ao[:,2]
###Output
_____no_output_____
###Markdown
Simple statistics:
###Code
ao_values.min()
ao_values.max()
ao_values.mean()
ao_values.std()
ao_values.sum()
###Output
_____no_output_____
###Markdown
You can also use *np.sum* function:
###Code
np.sum(ao_values)
###Output
_____no_output_____
###Markdown
One can make operations on the subsets:
###Code
np.mean(ao[ao[:,1]==1,2]) # January monthly mean
###Output
_____no_output_____
###Markdown
Result will be the same if we use method on our selected data:
###Code
ao[ao[:,1]==1,2].mean()
###Output
_____no_output_____
###Markdown
Saving data You can save your data as a text file
###Code
np.savetxt('ao_only_values.csv',ao[:, 2], fmt='%.4f')
###Output
_____no_output_____
###Markdown
Head of resulting file:
###Code
!head ao_only_values.csv
###Output
-0.0603
0.6268
-0.0081
0.5551
0.0716
0.5386
-0.8025
-0.8510
0.3580
-0.3789
###Markdown
You can also save it as binary:
###Code
f=open('ao_only_values.bin', 'w')
ao[:,2].tofile(f)
f.close()
###Output
_____no_output_____
###Markdown
NumPy arrays Nikolay [email protected] ================ - a powerful N-dimensional array object- sophisticated (broadcasting) functions- tools for integrating C/C++ and Fortran code- useful linear algebra, Fourier transform, and random number capabilities
###Code
import numpy as np
%matplotlib inline
np.set_printoptions(precision=3 , suppress= True) # this is just to make the output look better
###Output
_____no_output_____
###Markdown
Load data Load data in to a variable:
###Code
temp = np.loadtxt('Ham_3column.txt')
temp
temp.shape
###Output
_____no_output_____
###Markdown
###Code
temp.size
###Output
_____no_output_____
###Markdown
So it's a *row-major* order. Matlab and Fortran use *column-major* order for arrays.
###Code
type(temp)
###Output
_____no_output_____
###Markdown
Numpy arrays are statically typed, which allow faster operations
###Code
temp.dtype
###Output
_____no_output_____
###Markdown
You can't assign value of different type to element of the numpy array:
###Code
temp[0,0] = 'Year'
###Output
_____no_output_____
###Markdown
Slicing works similarly to Matlab:
###Code
temp[0:5,:]
temp[-5:-1,:]
###Output
_____no_output_____
###Markdown
One can look at the data. This is done by matplotlib module:
###Code
import matplotlib.pylab as plt
plt.plot(temp[:,3])
###Output
_____no_output_____
###Markdown
Index slicing In general it is similar to Matlab First 12 elements of **second** column (months). Remember that indexing starts with 0:
###Code
temp[0:12,2]
###Output
_____no_output_____
###Markdown
First raw:
###Code
temp[0,:]
###Output
_____no_output_____
###Markdown
Exercise - Plot only first 1000 values - Plot last 1000 values We can create mask, selecting all raws where values in third raw (days) equals 10:
###Code
mask = (temp[:,2]==10)
###Output
_____no_output_____
###Markdown
Here we apply this mask and show only first 5 raws of the array:
###Code
temp[mask][:20,:]
###Output
_____no_output_____
###Markdown
You don't have to create separate variable for mask, but apply it directly. Here instead of first five rows I show five last rows:
###Code
temp[temp[:,2]==10][-5:,:]
###Output
_____no_output_____
###Markdown
You can combine conditions. In this case we select days from 10 to 12 (only first 10 elements are shown):
###Code
temp[(temp[:,2]>=10)&(temp[:,2]<=12)][0:10,:]
###Output
_____no_output_____
###Markdown
Exercise Select only summer months Select only first half of the year Basic operations Create example array from first 12 values of second column and perform some basic operations:
###Code
days = temp[0:12,2]
days
days+10
days*20
days*days
###Output
_____no_output_____
###Markdown
What's wrong with this figure?
###Code
plt.plot(temp[:100,3])
###Output
_____no_output_____
###Markdown
Exercise- Create new array that will contain only temperatures- Convert temperature to deg C- Convert all temperatures to deg F Basic statistics Create *temp_values* that will contain only data values:
###Code
temp_values = temp[:,3]/10.
temp_values
###Output
_____no_output_____
###Markdown
Simple statistics:
###Code
temp_values.min()
temp_values.max()
temp_values.mean()
temp_values.std()
temp_values.sum()
###Output
_____no_output_____
###Markdown
You can also use *sum* function:
###Code
np.sum(temp_values)
###Output
_____no_output_____
###Markdown
One can make operations on the subsets: Exercise Calculate mean for first 1000 values of temperature Saving data You can save your data as a text file
###Code
np.savetxt('temp_only_values.csv',temp[:, 3]/10., fmt='%.4f')
###Output
_____no_output_____
###Markdown
[Python formatting options](https://pyformat.info/) Head of resulting file:
###Code
!head temp_only_values.csv
###Output
-7.2000
-4.3000
-3.2000
1.2000
-2.9000
-4.3000
-3.7000
-9.7000
-9.9000
-8.9000
###Markdown
You can also save it as binary:
###Code
f=open('temp_only_values.bin', 'w')
temp[:,3].tofile(f)
f.close()
###Output
_____no_output_____ |
Protein_conditional_generation.ipynb | ###Markdown
Generating proteins with a conditional character-level RNN
###Code
import string
import glob
import torch
import torch.nn as nn
from torch.autograd import Variable
import random
import time
import math
use_cuda = torch.cuda.is_available()
print("Running GPU.") if use_cuda else print("No GPU available.")
if use_cuda:
dvc = torch.cuda.current_device()
print(torch.cuda.get_device_name(dvc))
print(torch.cuda.get_device_capability(dvc))
print(torch.cuda.get_device_properties(dvc))
###Output
Running GPU.
Tesla P4
(6, 1)
_CudaDeviceProperties(name='Tesla P4', major=6, minor=1, total_memory=7611MB, multi_processor_count=20)
###Markdown
Prep data
###Code
## TODO: optimization of all_letters: instead of having the whole alphabet of small and captial letters, then get the set of letters that is present in the files
all_letters = string.ascii_uppercase
n_letters = len(all_letters) + 1 # Plus EOS marker
EOS = n_letters - 1 # get index of EOS symbol
all_letters
EOS
# read a file and split into lines
def read_lines(filename):
lines = open(filename).read().strip().split('\n')
lines = [line.replace(' ','') for line in lines] # remove space between the characters
return lines
###Output
_____no_output_____
###Markdown
Remember to upload the files.
###Code
# test read of file
test = read_lines('./protein-datasets/arc_full/train.txt')
print(len(test))
# find the categories, i.e. protein groups
all_categories = list()
path = './protein-datasets/'
for foldername in glob.glob(path + '*'):
categ = foldername.replace(path,'').replace('_full','')
#print(categ)
all_categories.append(categ)
print('found protein categories: {}'.format(all_categories))
n_categories = len(all_categories)
print('Nr. of protein groups (categories) =>', n_categories)
# build the category_lines dict, a list of lines per category
category_lines = dict()
for categ in all_categories:
for file in glob.glob(path + categ + '_full/train.txt'):
lines = read_lines(file)
category_lines[categ] = lines
len(category_lines['arc'])
for categ in all_categories:
print(glob.glob(path + categ + '_full/train.txt'))
print(glob.glob(path + categ + '_full/valid.txt'))
print(glob.glob(path + categ + '_full/test.txt'))
# average, max and min length of protein sequence overall
total_seq_len = 0
max_seq_len = 0
min_seq_len = 99999
total_seq = 0
for categ in all_categories:
for file in glob.glob(path + categ + '_full/train.txt'):
lines = read_lines(file)
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
for file in glob.glob(path + categ + '_full/valid.txt'):
lines = read_lines(file)
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
for file in glob.glob(path + categ + '_full/test.txt'):
lines = read_lines(file)
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
print("total seq length:", total_seq_len)
print("total number of sequences:", total_seq)
print("avg sequence lenght:", total_seq_len / total_seq)
print("max sequence length:", max_seq_len)
print("min sequence length:", min_seq_len)
# average, min and max length of protein sequence in each domain - bacteria
total_seq_len = 0
max_seq_len = 0
min_seq_len = 99999
total_seq = 0
# bac
lines = read_lines(glob.glob(path + 'bac' + '_full/train.txt')[0])
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
lines = read_lines(glob.glob(path + 'bac' + '_full/valid.txt')[0])
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
lines = read_lines(glob.glob(path + 'bac' + '_full/test.txt')[0])
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
print('-- bacteria --')
print("total seq length:", total_seq_len)
print("total number of sequences:", total_seq)
print("avg sequence lenght:", total_seq_len / total_seq)
print("max sequence length:", max_seq_len)
print("min sequence length:", min_seq_len)
# average, min and max length of protein sequence in each domain - vira
total_seq_len = 0
max_seq_len = 0
min_seq_len = 99999
total_seq = 0
# vir
lines = read_lines(glob.glob(path + 'vir' + '_full/train.txt')[0])
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
lines = read_lines(glob.glob(path + 'vir' + '_full/valid.txt')[0])
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
lines = read_lines(glob.glob(path + 'vir' + '_full/test.txt')[0])
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
print('-- vira --')
print("total seq length:", total_seq_len)
print("total number of sequences:", total_seq)
print("avg sequence lenght:", total_seq_len / total_seq)
print("max sequence length:", max_seq_len)
print("min sequence length:", min_seq_len)
# average, min and max length of protein sequence in each domain - archaeas
total_seq_len = 0
max_seq_len = 0
min_seq_len = 99999
total_seq = 0
# vir
lines = read_lines(glob.glob(path + 'arc' + '_full/train.txt')[0])
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
lines = read_lines(glob.glob(path + 'arc' + '_full/valid.txt')[0])
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
lines = read_lines(glob.glob(path + 'arc' + '_full/test.txt')[0])
total_seq = total_seq + len(lines)
for line in lines:
total_seq_len = total_seq_len + len(line)
if len(line) > max_seq_len:
max_seq_len = len(line)
elif len(line) < min_seq_len:
min_seq_len = len(line)
print('-- archaeas --')
print("total seq length:", total_seq_len)
print("total number of sequences:", total_seq)
print("avg sequence lenght:", total_seq_len / total_seq)
print("max sequence length:", max_seq_len)
print("min sequence length:", min_seq_len)
###Output
-- archaeas --
total seq length: 1083806
total number of sequences: 3314
avg sequence lenght: 327.038624019312
max sequence length: 2951
min sequence length: 29
###Markdown
Create net
###Code
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.i2h = nn.Linear(n_categories + input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(n_categories + input_size + hidden_size, output_size)
self.o2o = nn.Linear(hidden_size + output_size, output_size)
self.softmax = nn.LogSoftmax()
def forward(self, category, input, hidden):
input_combined = torch.cat((category, input, hidden), 1)
hidden = self.i2h(input_combined)
output = self.i2o(input_combined)
output_combined = torch.cat((hidden, output), 1)
output = self.o2o(output_combined)
return output, hidden
def init_hidden(self):
return Variable(torch.zeros(1, self.hidden_size))
# helper function to get random pars of (category, line)
# Get a random category and random line from that category
def random_training_pair():
category = random.choice(all_categories)
line = random.choice(category_lines[category])
return category, line
random_training_pair()
# One-hot vector for category
def make_category_input(category):
li = all_categories.index(category)
tensor = torch.zeros(1, n_categories)
tensor[0][li] = 1
return Variable(tensor)
# One-hot matrix of first to last letters (not including EOS) for input
def make_chars_input(chars):
tensor = torch.zeros(len(chars), n_letters)
for ci in range(len(chars)):
char = chars[ci]
tensor[ci][all_letters.find(char)] = 1
tensor = tensor.view(-1, 1, n_letters)
return Variable(tensor)
# LongTensor of second letter to end (EOS) for target
def make_target(line):
letter_indexes = [all_letters.find(line[li]) for li in range(1, len(line))]
letter_indexes.append(n_letters - 1) # EOS
tensor = torch.LongTensor(letter_indexes)
return Variable(tensor)
# make onehot encoding of category
make_category_input(all_categories[0])
make_chars_input(category_lines['arc'][0]).shape
# Make category, input, and target tensors from a random category, line pair
def random_training_set():
category, line = random_training_pair()
category_input = make_category_input(category)
line_input = make_chars_input(line)
line_target = make_target(line)
return category_input, line_input, line_target
category_input, line_input, line_target = random_training_set()
print(line_target)
#for i in range(line_target.size()[0]):
#print(line_target[i])
###Output
tensor([17, 17, 0, 21, 21, 18, 18, 18, 15, 15, 15, 18, 24, 4, 18, 21, 12, 0,
16, 0, 19, 11, 4, 21, 15, 5, 21, 15, 15, 17, 24, 12, 0, 15, 19, 4,
6, 17, 13, 18, 8, 17, 24, 18, 4, 11, 0, 15, 16, 24, 3, 19, 19, 17,
21, 24, 11, 21, 3, 13, 10, 18, 0, 3, 8, 0, 18, 11, 13, 24, 16, 13,
3, 7, 18, 13, 5, 11, 19, 19, 21, 21, 16, 13, 13, 3, 5, 19, 15, 0,
4, 0, 18, 19, 16, 19, 8, 13, 5, 3, 4, 17, 18, 17, 22, 6, 6, 3,
11, 10, 19, 8, 11, 7, 19, 13, 12, 15, 13, 21, 13, 4, 24, 12, 5, 19,
18, 10, 5, 10, 0, 17, 21, 12, 21, 0, 17, 10, 7, 15, 10, 3, 21, 3,
0, 18, 3, 11, 18, 10, 3, 8, 11, 4, 24, 3, 22, 5, 4, 5, 19, 11,
15, 4, 6, 13, 5, 18, 4, 19, 12, 19, 8, 3, 11, 12, 13, 13, 0, 8,
11, 4, 13, 24, 11, 16, 21, 6, 17, 16, 13, 6, 21, 11, 4, 18, 3, 8,
6, 21, 10, 5, 3, 18, 17, 13, 5, 10, 11, 6, 22, 3, 15, 21, 19, 10,
11, 21, 12, 15, 6, 21, 24, 19, 24, 4, 0, 5, 7, 15, 3, 21, 21, 11,
11, 15, 6, 2, 6, 21, 3, 5, 19, 4, 18, 17, 11, 18, 13, 11, 11, 6,
8, 17, 10, 10, 16, 15, 5, 16, 4, 6, 5, 17, 8, 12, 24, 4, 3, 11,
21, 6, 6, 13, 8, 15, 0, 11, 11, 13, 21, 10, 4, 24, 11, 10, 3, 10,
4, 4, 0, 6, 19, 0, 3, 0, 13, 19, 8, 10, 0, 16, 13, 3, 0, 21,
15, 17, 6, 3, 13, 24, 0, 18, 0, 0, 4, 0, 10, 0, 0, 6, 10, 4,
8, 4, 11, 10, 0, 8, 11, 10, 3, 3, 18, 13, 17, 18, 24, 13, 21, 8,
4, 6, 19, 19, 3, 19, 11, 24, 17, 18, 22, 24, 11, 18, 24, 19, 24, 6,
3, 15, 4, 10, 6, 21, 16, 18, 22, 19, 11, 11, 19, 19, 15, 3, 21, 19,
2, 6, 0, 4, 16, 21, 24, 22, 18, 11, 15, 3, 11, 12, 16, 3, 15, 21,
19, 5, 17, 18, 19, 16, 16, 21, 18, 13, 24, 15, 21, 21, 6, 0, 4, 11,
12, 15, 5, 17, 0, 10, 18, 5, 24, 13, 3, 11, 0, 21, 24, 18, 16, 11,
8, 17, 18, 24, 19, 18, 11, 19, 7, 21, 5, 13, 17, 5, 15, 3, 13, 16,
8, 11, 2, 17, 15, 15, 0, 15, 19, 8, 19, 19, 21, 18, 4, 13, 21, 15,
0, 11, 19, 3, 7, 6, 19, 11, 15, 11, 17, 18, 18, 8, 17, 6, 21, 16,
17, 21, 19, 21, 19, 3, 0, 17, 17, 17, 19, 2, 15, 24, 21, 24, 10, 0,
11, 6, 8, 21, 0, 15, 17, 21, 11, 18, 18, 17, 19, 5, 26])
###Markdown
Training the net
###Code
def train(category_tensor, input_line_tensor, target_line_tensor):
hidden = rnn.init_hidden()
optimizer.zero_grad()
loss = 0
for i in range(input_line_tensor.size()[0]):
if use_cuda:
output, hidden = rnn(category_tensor.cuda(), input_line_tensor[i].cuda(), hidden.cuda())
#loss += criterion(output, target_line_tensor[i])
loss += criterion(output, torch.LongTensor([target_line_tensor[i]]).cuda())
else:
output, hidden = rnn(category_tensor, input_line_tensor[i], hidden)
loss += criterion(output, torch.LongTensor([target_line_tensor[i]]))
loss.backward()
optimizer.step()
#return output, loss.data[0] / input_line_tensor.size()[0]
return output, loss.data.item() / input_line_tensor.size()[0]
# to keep track of how long training takes
def time_since(t):
now = time.time()
s = now - t
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
n_epochs = 1000
print_every = 50
plot_every = 50
all_losses = list()
all_epochs = list()
loss_avg = 0 # Zero every plot_every epochs to keep a running average
learning_rate = 0.0005
#rnn = RNN(n_letters, 128, n_letters)
rnn = RNN(n_letters, 512, n_letters)
if use_cuda:
rnn.cuda()
print('Using GPU %s with compute capability %s' % (torch.cuda.get_device_name(dvc),torch.cuda.get_device_capability(dvc)))
optimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)
criterion = nn.CrossEntropyLoss()
start = time.time()
for epoch in range(1, n_epochs + 1):
output, loss = train(*random_training_set())
loss_avg += loss
if epoch % print_every == 0:
print('%s (%d %d%%) %.4f' % (time_since(start), epoch, epoch / n_epochs * 100, loss))
if epoch % plot_every == 0:
all_losses.append(loss_avg / plot_every)
all_epochs.append(epoch)
loss_avg = 0
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
%matplotlib inline
plt.figure()
plt.plot(all_epochs,all_losses)
plt.show()
###Output
_____no_output_____
###Markdown
Samling the network
###Code
max_length = 6000
# Generate given a category and starting letter
def generate_one(category, start_char='A', temperature=0.5):
category_input = make_category_input(category)
chars_input = make_chars_input(start_char)
rnn.cpu() # move back to cpu
hidden = rnn.init_hidden()
output_str = start_char
for i in range(max_length):
if False: #use_cuda:
output, hidden = rnn(category_input.cuda(), chars_input[0].cuda(), hidden.cuda())
else:
output, hidden = rnn(category_input, chars_input[0], hidden)
# Sample as a multinomial distribution
output_dist = output.data.view(-1).div(temperature).exp()
top_i = torch.multinomial(output_dist, 1)[0]
# Stop at EOS, or add to output_str
if top_i == EOS:
break
else:
char = all_letters[top_i]
output_str += char
chars_input = make_chars_input(char)
return output_str
# Get multiple samples from one category and multiple starting letters
def generate(category, start_chars='ABC'):
for start_char in start_chars:
print(generate_one(category, start_char))
#res = generate('arc', 'A')
#print(len(res))
#print(res)
res = generate_one('arc', 'M')
print(len(res))
print(res)
res in category_lines['arc']
###Output
_____no_output_____
###Markdown
###Code
res = generate_one('arc', 'MAADIFAKFKKS')
print(len(res))
print(res)
res = generate_one('arc', 'gshmkmgvke'.upper())
print(len(res))
print(res)
res = generate_one('arc', 'M'.upper())
print(len(res))
print(res)
res = generate_one('vir', 'M'.upper())
print(len(res))
print(res)
res in category_lines['arc']
###Output
_____no_output_____ |
Chapter10/01_example.ipynb | ###Markdown
Statistical machine translation with NLTK
###Code
from nltk.translate.ibm1 import IBMModel1
from nltk.translate.api import AlignedSent
import dill as pickle
import gzip
import random
def read_sents(filename):
sents = []
c=0
with open(filename,'r') as fi:
for li in fi:
sents.append(li.split())
return sents
max_count=5000
eng_sents_all = read_sents('data/train_en_lines.txt')
fr_sents_all = read_sents('data/train_fr_lines.txt')
eng_sents = eng_sents_all[:max_count]
fr_sents = fr_sents_all[:max_count]
print("Size of english sentences: ", len(eng_sents))
print("Size of french sentences: ", len(fr_sents))
aligned_text = []
for i in range(len(eng_sents)):
al_sent = AlignedSent(fr_sents[i],eng_sents[i])
aligned_text.append(al_sent)
print("Training smt model")
ibm_model = IBMModel1(aligned_text,5)
print("Training complete")
fi = open('/tmp/ibm_smt.pkl','wb')
pickle.dump(ibm_model,fi)
fi.close()
#n_random = random.randint(max_count,len(fr_sents_all))
n_random = random.randint(0,max_count)
fr_sent = fr_sents_all[n_random]
eng_sent_actual_tr = eng_sents_all[n_random]
tr_sent = []
for w in fr_sent:
probs = ibm_model.translation_table[w]
if(len(probs)==0):
continue
sorted_words = sorted([(k,v) for k, v in probs.items()],key=lambda x: x[1], reverse=True)
top_word = sorted_words[1][0]
if top_word is not None:
tr_sent.append(top_word)
print("French sentence: ", " ".join(fr_sent))
print("Translated Eng sentence: ", " ".join(tr_sent))
print("Original translation: ", " ".join(eng_sent_actual_tr))
###Output
French sentence: On appelle ça l'accessibilité financière.
Translated Eng sentence: suggests affordability. works. called called
Original translation: And it's called affordability.
|
SIRModelVsISTAT.ipynb | ###Markdown
Estimating the prevalence of CoViD19 in Italy During the pandemic I wrote with my friends Fabio Verachi and Luciano Lanzi a paper that proposed a quantitative modeling approach to estimate the direct costs of CoViD19 in Italy. It was based on a standard epidemic model (a variant of SIR) and a multi state model (to calculate hospital and ICU occupation rates).You can find the preprint on medRxiv, [here](https://www.medrxiv.org/content/10.1101/2020.05.28.20115790v1); the paper has been accepted by the Risk Management Magazine, you can find the published version [here](https://www.aifirm.it/wp-content/uploads/2020/08/RMM_2020_2.pdf). The model was fitted on data available on May 4th 2020. Recently ISTAT published the [results](https://www.istat.it/it/files//2020/08/ReportPrimiRisultatiIndagineSiero.pdf) of a serological test campaign in Italy that estimated prevalence in the time span from May 25 to July 15 at 2.5% of population (confidence interval from 2.3% to 2.6%), 1.482.377 people. This results are quite a surprise. During the pandemic statistic institutions in Italy (like ISPI) estimated a much larger prevalence (4.4%, 2.642.326) and their results had great diffusion (see fo example the Financial Times,https://www.ft.com/content/7c312d8a-fcfe-4ce7-94d5-f681221e6042). I will show here that the numbers implied in our model are in line with ISTAT observations Let's start defining our model (just had fun trying to not to use numpy):
###Code
class SIR_Model:
def __init__(self,beta,D1,D2,PCatch,LockDnT,LockDnBeta):
self.beta=beta
self.D1=D1
self.D2=D2
self.PCatch=PCatch
self.LockDnT=LockDnT
self.LockDnBeta=LockDnBeta
def Diff_SIR(self,Status,isBefore=False):
CurrentBeta=self.LockDnBeta
if (isBefore):
CurrentBeta=self.beta
PFree=1-self.PCatch
Gamma1=1/self.D1
Gamma2=1/self.D2
# Status=[S,I,R1,R2]
# Output=[dS,dI,dR1,dR2]
return [-Status[0]*Status[1]*CurrentBeta,
Status[0]*Status[1]*CurrentBeta-(self.PCatch*Gamma1+PFree*Gamma2)*Status[1],
self.PCatch*Gamma1*Status[1],
PFree*Gamma2*Status[1]]
def NextStep(self,Status,isBefore=False):
# Runge-Kutta integration
D1=self.Diff_SIR(Status,isBefore)
S1=[0.5*x+y for x,y in zip(D1,Status)]
D2=self.Diff_SIR(S1,isBefore)
S2=[0.5*x+y for x,y in zip(D2,Status)]
D3=self.Diff_SIR(S2,isBefore)
S3=[x+y for x,y in zip(D2,Status)]
D4=self.Diff_SIR(S3,isBefore)
increment=[w/6+x/3+y/3+z/6 for w,x,y,z in zip(D1,D2,D3,D4)]
NewStatus=[x+y for x,y in zip(Status,increment)]
return NewStatus
def SIR_Simulation(self,Status,StartDays=0,NumOfDays=180):
Simulation=[[0,Status]]
for i in range(NumOfDays):
if i<=self.LockDnT:
NewStatus=self.NextStep(Status,True)
else:
NewStatus=self.NextStep(Status)
Simulation.append([i,NewStatus])
Status=NewStatus
return(Simulation)
###Output
_____no_output_____
###Markdown
For details on the model see the paper: basically we simulate the population among with the pandemic spreads S (that is less than the total population, since we had a lockdown), the infected I, and the Removed of type one (infection detected) or type 2 (infection silent): the idea is that the type 2 infected are able to spread infection. In order to simulate death toll we need to implement also the multi state model. Again, see the paper: type one removed can either heal or die after some time, during with they evolve trhough different states (alive at home, alive at hospital, alive in ICU, dead, alive and healed). In this notebook we are interested only in the ones that die. Notice that in our model no type 2 infected die: the idea is that you don't die of CoViD in hours, so anybody that is going to dye is detected.
###Code
class MultiStateModel:
def __init__(self,DeathProbs,HealProbs,Time1,Time2):
# Destiny of a covid infected simulated human
# that is catched by Health Guard system is
# divided in three periods:
# Catch -> Catch + Time1
# Dies with prob DeathProbs[0]
# Catch + Time1 -> Catch + Time2
# Dies with prob DeathProbs[1]
# Heals with prob HealProbs[0]
# Catch + Time2 -> infinity
# Dies with prob DeathProbs[2]
# Heals with prob HealProbs[1]
# All probabilities are "per day"
self.DP1=DeathProbs[0]
self.DP2=DeathProbs[1]
self.DP3=DeathProbs[2]
self.HP2=HealProbs[0]
self.HP3=HealProbs[1]
self.Time1=Time1
self.Time2=Time2
def DeathSimulation(self,CatchedFlow,StartLoad,Memory=200):
# Set Initial status
Status=[]
CumDeaths=[0]
for i in range(Memory):
if i<len(StartLoad):
Status.append(StartLoad[i])
else:
Status.append(0)
# Evolution rules
# Calculate outflows
for t in range(len(CatchedFlow)):
# Calculate outflows
Pop1=0
Pop2=0
Pop3=0
for i in range(Memory):
if i<self.Time1:
Pop1+=Status[i]
if i<self.Time2:
Pop2+=Status[i]
Pop3+=Status[i]
Pop3=Pop3-Pop2-Pop1
Pop2=Pop2-Pop1
Outflow1=np.int(self.DP1*Pop1)
Outflow2=np.int(self.DP2*Pop2+self.HP2*Pop2)
Outflow3=np.int(self.DP3*Pop3+self.HP3*Pop3)
Deaths=np.int(self.DP1*Pop1+self.DP2*Pop2+self.DP3*Pop3)
CumDeaths.append(CumDeaths[-1]+Deaths)
# GrowOneDay and inflow
for i in range(Memory):
j=Memory-i-1
if j>0:
Status[j]=Status[j-1]
Status[0]=CatchedFlow[t]
# Outflow group 3
for i in range(Memory):
j=Memory-i-1
if Status[j]>0 and Outflow3>0:
if Status[j]<Outflow3:
Outflow3=Outflow3-Status[j]
Status[j]=0
else:
Status[j]=Status[j]-Outflow3
Outflow3=0
# Outflow group 2
for i in range(Memory):
j=Memory-i-1
if Status[j]>0 and Outflow2>0 and j<self.Time2:
if Status[j]<Outflow2:
Outflow2=Outflow2-Status[j]
Status[j]=0
else:
Status[j]=Status[j]-Outflow2
Outflow2=0
# Outflow group 1
for i in range(Memory):
j=Memory-i-1
if Status[j]>0 and Outflow1>0 and j<self.Time1:
if Status[j]<Outflow1:
Outflow1=Outflow1-Status[j]
Status[j]=0
else:
Status[j]=Status[j]-Outflow1
Outflow1=0
return CumDeaths
###Output
_____no_output_____
###Markdown
Now we have all definitions, so let's start playing. Using the parameters of the paper, we instatiate models:
###Code
SIRModel=SIR_Model(0.27704,5.2,15,0.05375,13+38,0.16632)
StateModel=MultiStateModel([0.03557,0.001298,0.001566],[0.032750,0.015831],4,9)
###Output
_____no_output_____
###Markdown
Let's start the epidemiological simulation:
###Code
Initial_Status=[1-5e-6,5e-6,0,0]
SIRDynamics=SIRModel.SIR_Simulation(Initial_Status)
###Output
_____no_output_____
###Markdown
Since in the paper we estimated a Dimension of the pandemic (the total people that are around the infected) of 1.995.898, and that May 25 and July 15 are the 129th and 180th simulated days, the total removed and infected people at start and end of the ISTAT campaing are:
###Code
import numpy as np
Dimension=1995898
TotalCount=[0,0]
TotalCount[1]=np.int((SIRDynamics[180][1][1]+SIRDynamics[180][1][2]+SIRDynamics[180][1][3])*Dimension)
TotalCount[0]=np.int((SIRDynamics[129][1][1]+SIRDynamics[129][1][2]+SIRDynamics[129][1][3])*Dimension)
TotalCount[0]
TotalCount[1]
###Output
_____no_output_____
###Markdown
Since we want alive infected, we need to estimate deaths. The state model needs the infected detection inflow. It is annoying since the SIR simulation starts before the infection was found in italy, so there's an offset. Let's start putting in the time series of inflows observed from 2020-02-25 (vs 24) to 2020-05-04 (vs 03) (data coming from Protezione Civile GitHub [repository](https://github.com/pcm-dpc/COVID-19)):
###Code
TrueInflows=[93,78,250,238,240,566,342,466,587,769,778,1247,1492,1797,977,
2313,2651,2547,3497,3590,3233,3526,4207,5322,5986,6557,5560,4789,
5249,5210,6153,5959,5974,5217,4050,4053,4782,4668,4585,4805,4316,
3599,3039,3836,4204,3951,4694,4092,3153,2972,2667,3786,3493,3491,
3047,2256,2729,3370,2646,3021,2357,2324,1739,2091,2086,1872,1965,
1900,1389,1221]
###Output
_____no_output_____
###Markdown
We need to combine this with the simulated data for inflows after May 4th:
###Code
SimulatedInFlow=[]
for i in range(len(SIRDynamics)):
if i>0:
CatchedIncrement=np.int(Dimension*(SIRDynamics[i][1][2]-SIRDynamics[i-1][1][2]))
SimulatedInFlow.append(CatchedIncrement)
JoinedInFlow=TrueInflows
for i in range(51):
JoinedInFlow.append(SimulatedInFlow[108+i])
###Output
_____no_output_____
###Markdown
Now we can feed the joined inflow estimation into the state model and find the expected deaths:
###Code
StateModel=MultiStateModel([0.03557,0.001298,0.001566],[0.032750,0.015831],4,9)
DeceaseSeries=StateModel.DeathSimulation(JoinedInFlow,[46,46,46,46,45])
DeadCount=[0,0]
DeadCount[1]=DeceaseSeries[121]
DeadCount[0]=DeceaseSeries[70]
###Output
_____no_output_____
###Markdown
The expected alive infected at the starting of ISTAT campaign are:
###Code
TotalCount[0]-DeadCount[0]
###Output
_____no_output_____
###Markdown
While at the end are:
###Code
TotalCount[1]-DeadCount[1]
###Output
_____no_output_____
###Markdown
In terms of prevalence, our central value is:
###Code
(TotalCount[0]+TotalCount[1]-DeadCount[0]-DeadCount[1])/2/60030201
###Output
_____no_output_____ |
_doc/notebooks/td1a_algo/td1a_cenonce_session4_5_jaccard.ipynb | ###Markdown
1A.algo - distance de Jaccard (dictionnaires)Le notebook part du problème qui consiste à construire une distance entre deux chaînes de caractères en partant d'une idée naïve pour aller jusque la distance d'édition. distance de [Jaccard](https://fr.wikipedia.org/wiki/Indice_et_distance_de_Jaccard).
###Code
from jyquickhelper import add_notebook_menu
add_notebook_menu()
###Output
_____no_output_____ |
sandbox/digits_dataset.ipynb | ###Markdown
Digits datasetThe purpose of this notebook is to display how to apply different machine learning models to the toy data set **Digits Dataset**.http://scikit-learn.org/stable/auto_examples/datasets/plot_digits_last_image.html
###Code
%matplotlib inline
from functools import reduce
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.datasets import load_digits
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split, GridSearchCV, KFold
from sklearn.linear_model import LogisticRegression
from xgboost import XGBClassifier
###Output
_____no_output_____
###Markdown
Load data set
###Code
digits = load_digits()
###Output
_____no_output_____
###Markdown
There are 1797 images (8 by 8 pixels each) ranging from 0 to 9.
###Code
print('x: {}'.format(digits.data.shape))
print('y: {}'.format(digits.target.shape))
###Output
x: (1797, 64)
y: (1797,)
###Markdown
Display data set
###Code
n_images = 5
fig, ax = plt.subplots(1, n_images, figsize=(14, 4))
for idx, (x, y) in enumerate(zip(digits.data[:n_images], digits.target[:n_images])):
x_image = np.reshape(x, (8, 8))
ax[idx].imshow(x_image, cmap=plt.cm.gray)
ax[idx].set_title('label = {}'.format(y))
ax[idx].grid(False)
###Output
_____no_output_____
###Markdown
Distributionx ranges from 0 to 16. Most pixels are zero.
###Code
x_concat = pd.DataFrame(reduce(lambda x, y: np.concatenate((x, y)), digits.data),
columns=['x']).astype(int)
x_concat.describe()
x_concat.reset_index().groupby('x').count().plot(kind='bar');
###Output
_____no_output_____
###Markdown
Train test split
###Code
x_train, x_test, y_train, y_test = train_test_split(digits.data, digits.target,
test_size=0.25, random_state=0)
print(x_train.shape)
print(y_train.shape)
print(x_test.shape)
print(y_test.shape)
###Output
(1347, 64)
(1347,)
(450, 64)
(450,)
###Markdown
Logistic regression fitFor multi-class logistic regression, the one-vs-rest (`multi_class='ovr'`) algorithm is used, which will end up creating k different binary models.$$p \left( y=k \mid X, \beta \right) = \hat{y}^{\left( k \right)} \left( X \right) = \frac{1}{1 + e^{-X \beta^{\left( k \right)}}} \\\hat{y}\left( X \right) = \max_{k} \hat{y}^{\left( k \right)} \left( X \right)$$
###Code
lr = LogisticRegression()
lr.fit(x_train, y_train)
lr.coef_.shape
plt.plot(lr.coef_);
###Output
_____no_output_____
###Markdown
predict
###Code
print(lr.predict(x_train[[0]])[0])
print(y_train[0])
###Output
2
2
###Markdown
scoreThe `score` method is based on accuracy.
###Code
lr.score(x_train, y_train)
lr.score(x_test, y_test)
###Output
_____no_output_____
###Markdown
confusion matrixThe confusion matrix shows how each label is classified. A good model should have higher numbers on diagonal elements while off-diagonals contain smaller numbers.
###Code
lr_cm = confusion_matrix(y_test, lr.predict(x_test))
fig, ax = plt.subplots()
sns.heatmap(lr_cm, annot=True, cmap='RdBu', center=0, ax=ax)
ax.set_title('Logistic regression')
ax.set_ylabel('Actual label')
ax.set_xlabel('Predicted label');
###Output
_____no_output_____
###Markdown
Random forest classifierThe default number of trees is 10 (`n_estimators` = 10) cross-validation
###Code
def plot_grid_search_cv_result(grid_result):
params = grid_result.cv_results_['params']
means = pd.DataFrame(grid_result.cv_results_['mean_test_score'],
index=params, columns=['score'])
stds = pd.Series(grid_result.cv_results_['std_test_score'], index=params)
means.plot(kind='barh', xerr=stds)
rf_param_grid = {
'n_estimators': [10, 100, 1000]
}
rf_base_model = RandomForestClassifier()
rf_cv = KFold(n_splits=10)
rf_grid_search = GridSearchCV(
estimator=rf_base_model,
param_grid=rf_param_grid,
cv=rf_cv,
return_train_score=False
)
rf_grid_result = rf_grid_search.fit(x_train, y_train)
plot_grid_search_cv_result(rf_grid_result)
###Output
_____no_output_____
###Markdown
fit
###Code
rf = RandomForestClassifier(n_estimators=100, random_state=0)
rf.fit(x_train, y_train)
###Output
_____no_output_____
###Markdown
score
###Code
rf.score(x_train, y_train)
rf.score(x_test, y_test)
###Output
_____no_output_____
###Markdown
confusion matrix
###Code
rf_cm = confusion_matrix(y_test, rf.predict(x_test))
fig, ax = plt.subplots()
sns.heatmap(rf_cm, annot=True, cmap='RdBu', center=0, ax=ax)
ax.set_title('Random forest classifier')
ax.set_ylabel('Actual label')
ax.set_xlabel('Predicted label');
###Output
_____no_output_____
###Markdown
XGBoost classifierscikit-learn wrapper: http://xgboost.readthedocs.io/en/latest/python/python_api.htmlmodule-xgboost.sklearn cross-validation
###Code
xgb_param_grid = {
'max_depth': [1, 3],
'learning_rate': [1, 0.1, 0.01],
'n_estimators': [10, 100, 1000]
}
xgb_base_model = XGBClassifier()
xgb_cv = KFold(n_splits=10)
xgb_grid_search = GridSearchCV(
estimator=xgb_base_model,
param_grid=xgb_param_grid,
cv=xgb_cv,
return_train_score=False
)
xgb_grid_result = xgb_grid_search.fit(x_train, y_train)
###Output
_____no_output_____
###Markdown
The off-the-shelve set of parameters look good enough.
###Code
plot_grid_search_cv_result(xgb_grid_result)
###Output
_____no_output_____
###Markdown
fit
###Code
xgb = XGBClassifier()
xgb.fit(x_train, y_train)
###Output
_____no_output_____
###Markdown
score
###Code
rf.score(x_train, y_train)
rf.score(x_test, y_test)
###Output
_____no_output_____
###Markdown
confusion matrix
###Code
xgb_cm = confusion_matrix(y_test, xgb.predict(x_test))
fig, ax = plt.subplots()
sns.heatmap(xgb_cm, annot=True, cmap='RdBu', center=0, ax=ax)
ax.set_title('XGBoost classifier')
ax.set_ylabel('Actual label')
ax.set_xlabel('Predicted label');
###Output
_____no_output_____ |
demo/jupyter/numbas.ipynb | ###Markdown
$\int_a^b f(x) = F(b) - F(a)$
###Code
sigma=0.01
I = 10000
M = 50
dt = T / M
S = np.zeros((M + 1, I))
S[0] = S0
for t in range(1, M + 1):
S[t] = S[t - 1] * np.exp((r - 0.5 * sigma ** 2) * dt + sigma * math.sqrt(dt) * npr.standard_normal(I))
plt.figure(figsize=(10,6))
plt.plot(S[:,:10], lw=1.5)
plt.xlabel('time')
plt.ylabel('index level')
x0 = 1.35
kappa = 1.35
theta = 1.35
sigma = 0.6
I = 10000
M = 2000
dt = T / M
def srd_exact():
x = np.zeros((M + 1, I))
x[0] = x0
for t in range(1, M + 1):
df = 4 * theta * kappa / sigma ** 2
c = (sigma ** 2 * (1 - np.exp(-kappa * dt))) / (4 * kappa)
nc = np.exp(-kappa * dt) / c * x[t - 1]
x[t] = c * npr.noncentral_chisquare(df, nc, size=I)
return x
x2 = srd_exact()
plt.figure(figsize=(10,6))
plt.plot(x2[:,:5], lw=1.5)
plt.xlabel('time')
plt.ylabel('index level')
###Output
_____no_output_____ |
Applied Text Mining in Python/Assignment+1.ipynb | ###Markdown
---_You are currently looking at **version 1.1** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._--- Assignment 1In this assignment, you'll be working with messy medical data and using regex to extract relevant infromation from the data. Each line of the `dates.txt` file corresponds to a medical note. Each note has a date that needs to be extracted, but each date is encoded in one of many formats.The goal of this assignment is to correctly identify all of the different date variants encoded in this dataset and to properly normalize and sort the dates. Here is a list of some of the variants you might encounter in this dataset:* 04/20/2009; 04/20/09; 4/20/09; 4/3/09* Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009;* 20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009* Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009* Feb 2009; Sep 2009; Oct 2010* 6/2008; 12/2009* 2009; 2010Once you have extracted these date patterns from the text, the next step is to sort them in ascending chronological order accoring to the following rules:* Assume all dates in xx/xx/xx format are mm/dd/yy* Assume all dates where year is encoded in only two digits are years from the 1900's (e.g. 1/5/89 is January 5th, 1989)* If the day is missing (e.g. 9/2009), assume it is the first day of the month (e.g. September 1, 2009).* If the month is missing (e.g. 2010), assume it is the first of January of that year (e.g. January 1, 2010).* Watch out for potential typos as this is a raw, real-life derived dataset.With these rules in mind, find the correct date in each note and return a pandas Series in chronological order of the original Series' indices.For example if the original series was this: 0 1999 1 2010 2 1978 3 2015 4 1985Your function should return this: 0 2 1 4 2 0 3 1 4 3Your score will be calculated using [Kendall's tau](https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient), a correlation measure for ordinal data.*This function should return a Series of length 500 and dtype int.*
###Code
import pandas as pd
doc = []
with open('dates.txt') as file:
for line in file:
doc.append(line)
df = pd.Series(doc)
df.head(10)
def date_sorter():
regex1 = '(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})'
regex2 = '((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\S]*[+\s]\d{1,2}[,]{0,1}[+\s]\d{4})'
regex3 = '(\d{1,2}[+\s](?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\S]*[+\s]\d{4})'
regex4 = '((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\S]*[+\s]\d{4})'
regex5 = '(\d{1,2}[/-][1|2]\d{3})'
regex6 = '([1|2]\d{3})'
full_regex = '(%s|%s|%s|%s|%s|%s)' %(regex1, regex2, regex3, regex4, regex5, regex6)
parsed_date = df.str.extract(full_regex)
parsed_date = parsed_date.iloc[:,0].str.replace('Janaury', 'January').str.replace('Decemeber', 'December')
parsed_date = pd.Series(pd.to_datetime(parsed_date))
parsed_date = parsed_date.sort_values(ascending=True).index
return pd.Series(parsed_date.values)
date_sorter()
###Output
/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:10: FutureWarning: currently extract(expand=None) means expand=False (return Index/Series/DataFrame) but in a future version of pandas this will be changed to expand=True (return DataFrame)
# Remove the CWD from sys.path while we load stuff.
###Markdown
---_You are currently looking at **version 1.1** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._--- Assignment 1In this assignment, you'll be working with messy medical data and using regex to extract relevant infromation from the data. Each line of the `dates.txt` file corresponds to a medical note. Each note has a date that needs to be extracted, but each date is encoded in one of many formats.The goal of this assignment is to correctly identify all of the different date variants encoded in this dataset and to properly normalize and sort the dates. Here is a list of some of the variants you might encounter in this dataset:* 04/20/2009; 04/20/09; 4/20/09; 4/3/09* Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009;* 20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009* Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009* Feb 2009; Sep 2009; Oct 2010* 6/2008; 12/2009* 2009; 2010Once you have extracted these date patterns from the text, the next step is to sort them in ascending chronological order accoring to the following rules:* Assume all dates in xx/xx/xx format are mm/dd/yy* Assume all dates where year is encoded in only two digits are years from the 1900's (e.g. 1/5/89 is January 5th, 1989)* If the day is missing (e.g. 9/2009), assume it is the first day of the month (e.g. September 1, 2009).* If the month is missing (e.g. 2010), assume it is the first of January of that year (e.g. January 1, 2010).* Watch out for potential typos as this is a raw, real-life derived dataset.With these rules in mind, find the correct date in each note and return a pandas Series in chronological order of the original Series' indices.For example if the original series was this: 0 1999 1 2010 2 1978 3 2015 4 1985Your function should return this: 0 2 1 4 2 0 3 1 4 3Your score will be calculated using [Kendall's tau](https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient), a correlation measure for ordinal data.*This function should return a Series of length 500 and dtype int.*
###Code
import pandas as pd
doc = []
with open('dates.txt') as file:
for line in file:
doc.append(line)
df = pd.Series(doc)
df.head(10)
def date_sorter():
# Your code here
#04/20/2009; 04/20/09; 4/20/09; 4/3/09
type1 = df.str.extractall(r'(?P<Month>\d?\d)[/-](?P<Day>\d?\d)[/-](?P<Year>\d\d?\d?\d)')
type1.reset_index(level=1, drop=True, inplace=True)
#Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009;
type2 = df.str.extractall(r'((?P<Month>(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))[a-z]*[-,\s\.]\s?(?P<Day>\d\d)[-,\s]\s?(?P<Year>\d\d\d\d))')
type2.reset_index(level=1, drop=True, inplace=True)
# 20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009
type3 = df.str.extractall(r'((?P<Day>\d\d)\s(?P<Month>(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))[a-z]*[\s\.,]\s?(?P<Year>\d\d\d\d))')
type3.reset_index(level=1, drop=True, inplace=True)
# Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009
type4 = df.str.extractall(r'((?P<Month>(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\s(?P<Day>\d\d)[a-z]{2},\s(?P<Year>\d\d\d\d))')
if len(type4.index)>=2:
type4.reset_index(level=1, drop=True, inplace=True)
#Feb 2009; Sep 2009; Oct 2010
type5 = df.str.extractall(r'((?P<Month>(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))[a-z]*[\s\.,]\s?(?P<Year>\d\d\d\d))')
type5.reset_index(level=1, drop=True, inplace=True)
# 6/2008; 12/2009
type6 = df.str.extractall(r'(?P<Month>\d?\d)/(?P<Year>\d\d\d\d)')
type6.reset_index(level=1, drop=True, inplace=True)
# 2009; 2010
type7 = df.str.extractall(r'(?P<Year>19\d\d|20\d\d)')
type7.reset_index(level=1, drop=True, inplace=True)
type1['Year'] = type1['Year'].astype(int).apply(lambda x: x+1900 if x < 100 else x)
type1 = type1[type1['Year'] >= 1900]
doc_says = df.to_frame().rename(columns={0:'Text'})
types = [type2, type3, type4, type5, type6, type7]
doc_says = doc_says.merge(type1,how='left',left_index=True,right_index=True)
for col in ['Year','Month','Day']:
for tt in types:
if col not in tt.columns.values:
continue
to_update = set(doc_says[doc_says[col].isnull()].index.tolist())
this_update = list(to_update.intersection(set(tt.index.values)))
doc_says.loc[this_update,col] = tt.loc[this_update,col]
#print(col, len(doc_says))
doc_says = doc_says.fillna(1)
doc_says['Month'] = doc_says['Month'].replace({'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,'Jul':7,'Aug':8,
'Sep':9,'Oct':10,'Nov':11,'Dec':12})
for col in ['Year','Month','Day']:
doc_says[col] = doc_says[col].astype(int)
sort_doc = doc_says.sort_values(by=['Year','Month','Day'])
sort_doc = sort_doc.reset_index()
return sort_doc['index']# Your answer here
date_sorter()
###Output
_____no_output_____
###Markdown
---_You are currently looking at **version 1.1** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._--- Assignment 1In this assignment, you'll be working with messy medical data and using regex to extract relevant infromation from the data. Each line of the `dates.txt` file corresponds to a medical note. Each note has a date that needs to be extracted, but each date is encoded in one of many formats.The goal of this assignment is to correctly identify all of the different date variants encoded in this dataset and to properly normalize and sort the dates. Here is a list of some of the variants you might encounter in this dataset:* 04/20/2009; 04/20/09; 4/20/09; 4/3/09* Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009;* 20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009* Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009* Feb 2009; Sep 2009; Oct 2010* 6/2008; 12/2009* 2009; 2010Once you have extracted these date patterns from the text, the next step is to sort them in ascending chronological order accoring to the following rules:* Assume all dates in xx/xx/xx format are mm/dd/yy* Assume all dates where year is encoded in only two digits are years from the 1900's (e.g. 1/5/89 is January 5th, 1989)* If the day is missing (e.g. 9/2009), assume it is the first day of the month (e.g. September 1, 2009).* If the month is missing (e.g. 2010), assume it is the first of January of that year (e.g. January 1, 2010).* Watch out for potential typos as this is a raw, real-life derived dataset.With these rules in mind, find the correct date in each note and return a pandas Series in chronological order of the original Series' indices.For example if the original series was this: 0 1999 1 2010 2 1978 3 2015 4 1985Your function should return this: 0 2 1 4 2 0 3 1 4 3Your score will be calculated using [Kendall's tau](https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient), a correlation measure for ordinal data.*This function should return a Series of length 500 and dtype int.*
###Code
import pandas as pd
import numpy as np
import re
doc = []
with open('dates.txt') as file:
for line in file:
doc.append(line)
df = pd.Series(doc)
df.head(10)
def date_sorter():
a1_1 =df.str.extractall(r'(\d{1,2})[/-](\d{1,2})[/-](\d{2})\b')
a1_2 =df.str.extractall(r'(\d{1,2})[/-](\d{1,2})[/-](\d{4})\b')
a1 = pd.concat([a1_1,a1_2])
a1.reset_index(inplace=True)
a1_index = a1['level_0']
a2 = df.str.extractall(r'((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*[-.]* )((?:\d{1,2}[?:, -]*)\d{4})')
a2.reset_index(inplace=True)
a2_index = a2['level_0']
a3 = df.str.extractall(r'((?:\d{1,2} ))?((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*[?:, -]* )(\d{4})')
a3.reset_index(inplace=True)
a3_index = a3['level_0']
a6 = df.str.extractall(r'(\d{1,2})[/](\d{4})')
a6.reset_index(inplace=True)
a6_index = a6['level_0']
save=[]
for i in a6_index:
if not(i in a1_index.values):
save.append(i)
save = np.asarray(save)
a6 = a6[a6['level_0'].isin(save)]
a7_1= df.str.extractall(r'[a-z]?[^0-9](\d{4})[^0-9]')
a7_2 = df.str.extractall(r'^(\d{4})[^0-9]')
a7 = pd.concat([a7_1,a7_2])
a7.reset_index(inplace=True)
a7_index = a7['level_0']
save=[]
for i in a7_index:
if not((i in a2_index.values) | (i in a3_index.values) | (i in a6_index.values)):
save.append(i)
save = np.asarray(save)
a7 = a7[a7['level_0'].isin(save)]
s = a1.level_0.values.tolist()+a2.level_0.values.tolist()+a3.level_0.values.tolist()+a6.level_0.values.tolist()+a7.level_0.values.tolist()
s = np.asarray(s)
a1.columns=['level_0','match','month','day','year']
a1['year']=a1['year'].apply(str)
a1['year']=a1['year'].apply(lambda x: '19'+x if len(x)<=2 else x)
a2[1] = a2[1].apply(lambda x: x.replace(',',''))
a2['day'] = a2[1].apply(lambda x:x.split(' ')[0])
a2['year'] = a2[1].apply(lambda x:x.split(' ')[1])
a2.columns=['level_0','match','month','day-year','day','year']
a2.drop('day-year',axis=1,inplace=True)
a3.columns=['level_0','match','day','month','year']
a3['day'] = a3['day'].replace(np.nan,-99)
a3['day'] = a3['day'].apply(lambda x: 1 if int(x)==-99 else x)
a3['month'] = a3.month.apply(lambda x: x[:3])
a3['month'] = pd.to_datetime(a3.month, format='%b').dt.month
a6.columns=['level_0','match','month','year']
a6['day']=1
a7.columns=['level_0','match','year']
a7['day']=1
a7['month']=1
final = pd.concat([a1,a2,a3,a6,a7])
final['date'] =pd.to_datetime(final['month'].apply(str)+'/'+final['day'].apply(str)+'/'+final['year'].apply(str))
final = final.sort_values(by='level_0').set_index('level_0')
myList = final['date']
answer = pd.Series([i[0] for i in sorted(enumerate(myList), key=lambda x:x[1])],np.arange(500))
return answer
date_sorter()
###Output
_____no_output_____ |
std_lib/random.ipynb | ###Markdown
Generating Random Numbers- random()> The random() funciton returns the next random floating point value from the range [0,1)- uniform()> generate numbers in a specific numberical range> Actually,this equals to **(min + (max-min) * random())**
###Code
import random
for i in range(5):
print('%04.3f' % random.random(), end=' ')
print("\n", "-"*20)
for i in range(5):
print('{:04.3f}'.format(random.uniform(1,100)), end=' ')
###Output
0.758 0.892 0.462 0.372 0.681
--------------------
96.538 49.208 40.640 80.843 92.202
###Markdown
Seeding> Random includes the seed() function for initializing the pseudorandom generator so that it produces an expected set of values.
###Code
import random
random.seed(1)
for i in range(5):
print('{:04.3f}'.format(random.random()), end=' ')
###Output
0.134 0.847 0.764 0.255 0.495
###Markdown
Saving State> The internal state of the pseudorandom algorithm used by random() can be saved and used to control the numbers produced in subsequent runs. Restoring the previous state before continuing reduces the likelihood of repeating values or sequences of values from the earlier input. > > The **getstate()** function returns data that can be used to re-initialize the random number generator later with **setstate()**.> > 保存随机算法内部状态,用来控制后续各轮的随机数,继续生成随机数前恢复到前一个状态,这减少由之前输入得到重复的值或值序列的可能性。>> **getstate()**会返回一些值,以后可以用**setstate()**恢复这些数据重新初始化随机数生成器。
###Code
import random
import os
import pickle
if os.path.exists('state.dat'):
# Restore the previously saved state
print('Found state.dat, initializing random module')
with open('state.dat', 'rb') as f:
state = pickle.load(f)
random.setstate(state)
else:
# Use a well-known start state
print('No state.dat, seeding')
random.seed(1)
# Produce random values
for i in range(3):
print('{:04.3f}'.format(random.random()), end=' ')
print()
# Save state for next time
with open('state.dat', 'wb') as f:
pickle.dump(random.getstate(), f)
# Produce more random values
print('\nAfter saving state:')
for i in range(3):
print('{:04.3f}'.format(random.random()), end=' ')
print()
###Output
No state.dat, seeding
0.134 0.847 0.764
After saving state:
0.255 0.495 0.449
###Markdown
Random Integers> random() generates floating point numbers. It is possible to convert the results to integers, but using randint() to generate integers directly is more convenient.- randint()> randint()参数的值是随机数区间两端,第一个值要小于第二个值- randrange()> 从区间选择值的更一般形式,更高效,并不真正构造区间 > randrange(start,stop,step)等价从range(start,stop,step)中随机选择一个值
###Code
import random
print('[1,100]:', end=' ')
for i in range(3):
print(random.randint(1, 100), end=' ')
print('\n[-5, 5]', end=' ')
for i in range(3):
print(random.randint(-5,5), end=' ')
for i in range(3):
print(random.randrange(0, 100, 5), end=' ')
###Output
60 65 95
###Markdown
Picking Random Items> One common use for random number generators is to select a random item from a sequence of enumerated values, even if those values are not numbers. random includes the choice() function for making a random selection from a sequence. This example simulates flipping a coin 10,000 times to count how many times it comes up heads and how many times tails.- choice()> 在一个序列中随机选择一个元素
###Code
import random
import itertools
outcomes = {'heads':0,
'tails':0,
}
sides = list(outcomes.keys())
for i in range(100):
outcomes[random.choice(sides)] += 1
print('Heads:', outcomes['heads'])
print('Tails:', outcomes['tails'])
###Output
Heads: 51
Tails: 49
###Markdown
Permutations> A simulation of a card game needs to mix up the deck of cards and then deal them to the players, without using the same card more than once. Using choice() could result in the same card being dealt twice, so instead, the deck can be mixed up with shuffle() and then individual cards removed as they are dealt.- **shuffle()**> shuffle()洗牌,避免将一张牌发出去两次
###Code
import random
import itertools
FACE_CARDS = ('J', 'Q', 'K', 'A')
SUITS = ('H', 'D', 'C', 'S')
def new_deck():
return [
# Always use 2 places for the value, so the strings
# are a consistent width.
'{:>2}{}'.format(*c)
for c in itertools.product(
itertools.chain(range(2, 11), FACE_CARDS),
SUITS,
)
]
def show_deck(deck):
p_deck = deck[:]
while p_deck:
row = p_deck[:13]
p_deck = p_deck[13:]
for j in row:
print(j, end=' ')
print()
# Make a new deck, with the cards in order
deck = new_deck()
print('Initial deck:')
show_deck(deck)
# Shuffle the deck to randomize the order
random.shuffle(deck)
print('\nShuffled deck:')
show_deck(deck)
# Deal 4 hands of 5 cards each
hands = [[], [], [], []]
for i in range(5):
for h in hands:
h.append(deck.pop())
# Show the hands
print('\nHands:')
for n, h in enumerate(hands):
print('{}:'.format(n + 1), end=' ')
for c in h:
print(c, end=' ')
print()
# Show the remaining deck
print('\nRemaining deck:')
show_deck(deck)
###Output
Initial deck:
2H 2D 2C 2S 3H 3D 3C 3S 4H 4D 4C 4S 5H
5D 5C 5S 6H 6D 6C 6S 7H 7D 7C 7S 8H 8D
8C 8S 9H 9D 9C 9S 10H 10D 10C 10S JH JD JC
JS QH QD QC QS KH KD KC KS AH AD AC AS
Shuffled deck:
AH 2C 10H 2H JC AD 3S 10C 9C 7D 9H 10S 6S
4C JD AC 5C 8D 6H QD QH 3H KD 7S 8C 6D
10D 2S 3D 3C 2D KC 7C QC JH 9S KH 9D 4D
5S 8S 4S JS 6C AS 5H QS 4H 5D 8H 7H KS
Hands:
1: KS 4H 6C 5S 9S
2: 7H QS JS 4D JH
3: 8H 5H 4S 9D QC
4: 5D AS 8S KH 7C
Remaining deck:
AH 2C 10H 2H JC AD 3S 10C 9C 7D 9H 10S 6S
4C JD AC 5C 8D 6H QD QH 3H KD 7S 8C 6D
10D 2S 3D 3C 2D KC
###Markdown
Sampling> Many simulations need random samples from a population of input values. The sample() function generates samples without repeating values and without modifying the input sequence. This example prints a random sample of words from the system dictionary.- **sample()**> 采样,可以从大量样本中获得随机样本,sample函数可以生成无重复值的样本,且不会修改输入序列。
###Code
import random
with open('/usr/share/dict/words', 'rt') as f:
words = f.readlines()
words = [w.rstrip() for w in words]
for w in random.sample(words, 5):
print(w)
###Output
Westerns
refreshed
embeds
asterisking
pillow
###Markdown
Multiple Simultaneous Generators> In addition to module-level functions, random includes a Random class to manage the internal state for several random number generators. All of the functions described earlier are available as methods of the Random instances, and each instance can be initialized and used separately, without interfering with the values returned by other instances.> > On a system with good native random value seeding, the instances start out in unique states. However, if there is no good platform random value generator, the instances are likely to have been seeded with the current time, and therefore produce the same values.> random还包括一个Random类,可以生成Random实例,各个实例单独初始化和使用,不会和其他实例返回的值相互干扰> > 具体实现依赖系统,需要测试。
###Code
import random
import time
print('Default initializiation:\n')
r1 = random.Random()
r2 = random.Random()
for i in range(3):
print('{:04.3f} {:04.3f}'.format(r1.random(), r2.random()))
print('\nSame seed:\n')
seed = time.time()
r1 = random.Random(seed)
r2 = random.Random(seed)
for i in range(3):
print('{:04.3f} {:04.3f}'.format(r1.random(), r2.random()))
###Output
Default initializiation:
0.105 0.897
0.986 0.647
0.437 0.813
Same seed:
0.407 0.407
0.155 0.155
0.922 0.922
|
kostra-koder-nor.ipynb | ###Markdown
Hente KOSTRA koder for arter og funksjoner via Klass API Importerer nødvendige biblioteker
###Code
import pandas as pd
import requests
###Output
_____no_output_____
###Markdown
Hente data fra json url og se innholdet
###Code
url = 'http://data.ssb.no/api/klass/v1/versions/795.json' # regnskapsarter versjon 2016-
# 'http://data.ssb.no/api/klass/v1/versions/1204.json' - regnskapsfunksjoner 2019-
# 'http://data.ssb.no/api/klass/v1/versions/795.json' # regnskapsarter versjon 2016-
r = requests.get(url = url)
type(r)
###Output
_____no_output_____
###Markdown
Det enkleste her er å bruke request for json() for å konvertere det til en dictionary
###Code
# request av json og se på innholdet
dataset = r.json()
dataset
# sjekke at uttrekket er endret fra json til en dictionary (dict)
type(dataset)
###Output
_____no_output_____
###Markdown
Begrenser uttrekket til dimensjonen med classificationItems og henter noen få felt til dataframe df
###Code
classItems = (dataset['classificationItems'])
classItems[0]
df = pd.DataFrame(classItems, columns =['code', 'name', 'notes'])
# se på de første 5 radene av dataframe ved å bruke .head()
df.head()
# se på de 15 siste radene av dataframe ved å bruke .tail()
df.tail(15)
###Output
_____no_output_____ |
examples/Neural Network-Dropout.ipynb | ###Markdown
Load the dataset
###Code
X, y = make_circles(n_samples=1_000, noise=0.2, factor=0.1)
assert len(X) == len(y)
###Output
_____no_output_____
###Markdown
Quick EDA
###Code
plt.scatter(X[y==0, 0], X[y==0, 1], c="r")
plt.scatter(X[y==1, 0], X[y==1, 1], c="b")
plt.grid()
plt.show();
###Output
_____no_output_____
###Markdown
Build the Neural Network
###Code
M, N_INPUTS = X.shape
model = NeuralNetwork(optimizer=Adam(alpha=0.03), n_epochs=3_000, batch_size=256)
model.add(Dense(8, n_inputs=N_INPUTS, activation="relu"))
model.add(Dense(6, activation="relu"))
model.add(Dropout(0.8))
model.add(Dense(2, activation="softmax"))
###Output
_____no_output_____
###Markdown
Training
###Code
model.fit(X, y)
model.summary()
###Output
+---------------+
| Model Summary |
+---------------+
Input Shape: (2, 1)
+------------+----------------------+--------------+
| Layer Type | Number of Parameters | Output Shape |
+------------+----------------------+--------------+
| Dense | 24 | (8, 1) |
| Dense | 54 | (6, 1) |
| Dropout | 0 | (6, 1) |
| Dense | 14 | (2, 1) |
+------------+----------------------+--------------+
Total Number of Parameters: 92
###Markdown
Learning Curve
###Code
plt.plot(model._loss_values[::10]);
###Output
_____no_output_____
###Markdown
Evaluate
###Code
model.evaluate(X, y)
plot_decision_boundary(model, X, y)
###Output
_____no_output_____ |
yolo-assignment1.ipynb | ###Markdown
The very first step we need to take for implementing YOLO algorithm is to install required liberaries.We need to instll following liberaries:1. OpenCV: Used for Computer vision problems, like facial recognition and detection.2. PIL: Used for providing support for opening, manipulating and saving images of different formats.3. Glob: The Glob module lists the files matching pattrens.4. DarkFlow: DarkFlow and Darknet are tools to detect common object in images or videos. it is trained on alreaady trained weights.**NOTE: Glob is part of standard liberary in python so we don't need to install it and here is link for Standard liberary in python "https://docs.python.org/3/library/index.html"**
###Code
# Installing required Liberaries
#!pip3 install opencv-python
#!pip3 install Pillow==2.2.2
#!git clone https://github.com/thtrieu/darkflow.git
#%cd darkflow
#!python3 setup.py build_ext --inplace+9-
#!pip3 install
#!pip3 install
###Output
_____no_output_____
###Markdown
Importing Liberaries
###Code
#Importing liberaries
import cv2
import numpy as np
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Designing Network
###Code
YOLO_algorithum_model= cv2.dnn.readNet("../input/yolo-coco-data/yolov3.weights", "../input/yolo-coco-data/yolov3.cfg")
###Output
_____no_output_____
###Markdown
Now since we are done with designing a network, We will do two things.1. We will form a list that will hold names of our classes.2. We will check lenght of classes and names.
###Code
#Creating a list where we will save classes
Classes=[]
with open("../input/yolo-coco-data/coco.names", 'r') as F:
Classes= F.read().splitlines()
#Lenght and names of classes
len(Classes)
#Classes
###Output
_____no_output_____
###Markdown
What we have done so for?1. We called our model with pre-trained weights2. We have uploaded our classes. It's time to test our model. Let's read any image.
###Code
Image= cv2.imread("../input/another-r-t-image/IMG_20210102_134430.jpg")
#Image.shape
#width, height= Image.size
#print(width, height)
plt.imshow(Image)
###Output
_____no_output_____
###Markdown
With above code we have read the file but we have to things to consider.1. The image is of integers and we have to regulaize it to get float.2. This code takes image as "B_G_R" so we need to convert it into "R_G_B"
###Code
Test_image= cv2.dnn.blobFromImage(Image, 1/225, (512, 768), (0,0,0), swapRB= True, crop= False)
# Print image (Optional)
Test_image.shape
I= Test_image[0].reshape(768, 512, 3)
plt.imshow(I)
###Output
_____no_output_____
###Markdown
Now since we are done with all required preprocessing of our image that we read, We are goig to input it in our model.
###Code
YOLO_algorithum_model.setInput(Test_image)
###Output
_____no_output_____
###Markdown
Time to set output layer
###Code
#Setting output layers
Outlay_name= YOLO_algorithum_model.getUnconnectedOutLayersNames()
OutputL= YOLO_algorithum_model.forward(Outlay_name)
###Output
_____no_output_____
###Markdown
**Most Important Part**for bounding boxes, confidence score and classes wee will make lists.We will run for loop to get boxes and confidence score for each bounding box and class, then we will save them in lists.
###Code
#Creating lists for saving no: of bounding boxes, their confidence score and classes.
Boxes=[]
Confidence_score=[]
Classes_ID=[]
width=4300;
height=3200;
#Run through Image to find bounding boxes, their confidence and classes
for Output in OutputL:
for detection in Output:
score = detection[5:]
Classes_id= np.argmax(score)
Confidence= score[Classes_id]
#Preventing Multiple bunding boxes
if Confidence > 0.7:
center_x= int(detection[0]*width)
center_y= int(detection[0]*height)
w=int(detection[0]*width)
h=int(detection[0]*height)
x= int(center_x-w/2)
y= int(center_y-h/2)
Boxes.append([x,y,w,h])
Confidence_score.append(float(Confidence))
Classes_ID.append(Classes_id)
###Output
_____no_output_____
###Markdown
How many bounding boxes our algorithum has found in Input image.
###Code
#Finding the boxes in our image by our algorithum
len(Boxes)
# Creating boxes
indexes= cv2.dnn.NMSBoxes(Boxes, Confidence_score, 0.5, 0.4)
###Output
_____no_output_____
###Markdown
Setting fonts and colors of boxes
###Code
font= cv2.FONT_HERSHEY_PLAIN
clr= np.random.uniform(0, 225, size = (len(Boxes), 3))
for i in indexes.flatten():
x,y,w,h=Boxes[i]
label= str(Classes[Classes_ID[i]])
confidence=str(round(Confidence_score[i], 2))
color= clr[i]
cv2.rectangle(Image, (x,y), (x+w,y+h), color, 3)
cv2.putText(Image, label+" "+confidence, (x,y+20), font, 2, (255,255,255), 3)
plt.imshow(Image)
cv2.imwrite("./another-r-t-image.jpg", Image)
###Output
_____no_output_____ |
lectures/Improved_abstract_factory.ipynb | ###Markdown
Паттерн "Абстрактная фабрика" 1. Объявим абстрактную фабрикуОбявим методы, которые позволят создать персонажа. Используем механизм `classmethod`
###Code
class HeroFactory:
@classmethod
def create_hero(Class, name):
return Class.Hero(name)
@classmethod
def create_weapon(Class):
return Class.Weapon()
@classmethod
def create_spell(Class):
return Class.Spell()
###Output
_____no_output_____
###Markdown
2. Определим конкретные фабрикиВ каждой конкретной фабрике объявим собственные классы героя, оружия и заклинаний, которые будут специфичны для класса персонажа
###Code
class WariorFactory(HeroFactory):
class Hero:
def __init__(self, name):
self.name = name
self.weapon = None
self.armor = None
self.spell = None
def add_weapon(self, weapon):
self.weapon = weapon
def add_spell(self, spell):
self.spell = spell
def hit(self):
print(f"Warior hits with {self.weapon.hit()}")
self.weapon.hit()
def cast(self):
print(f"Warior casts {self.spell.cast()}")
self.spell.cast()
class Weapon:
def hit(self):
return "Claymore"
class Spell:
def cast(self):
return "Power"
class MageFactory(HeroFactory):
class Hero:
def __init__(self, name):
self.name = name
self.weapon = None
self.armor = None
self.spell = None
def add_weapon(self, weapon):
self.weapon = weapon
def add_spell(self, spell):
self.spell = spell
def hit(self):
print(f"Mage hits with {self.weapon.hit()}")
self.weapon.hit()
def cast(self):
print(f"Mage casts {self.spell.cast()}")
self.spell.cast()
class Weapon:
def hit(self):
return "Staff"
class Spell:
def cast(self):
return "Fireball"
class AssassinFactory(HeroFactory):
class Hero:
def __init__(self, name):
self.name = name
self.weapon = None
self.armor = None
self.spell = None
def add_weapon(self, weapon):
self.weapon = weapon
def add_spell(self, spell):
self.spell = spell
def hit(self):
print(f"Assassin hits with {self.weapon.hit()}")
self.weapon.hit()
def cast(self):
print(f"Assassin casts {self.spell.cast()}")
class Weapon:
def hit(self):
return "Dagger"
class Spell:
def cast(self):
return "Invisibility"
###Output
_____no_output_____
###Markdown
3. Определим функцию, создающую персонажейОна не отличается от базовой реализации
###Code
def create_hero(factory):
hero = factory.create_hero("Nagibator")
weapon = factory.create_weapon()
spell = factory.create_spell()
hero.add_weapon(weapon)
hero.add_spell(spell)
return hero
###Output
_____no_output_____
###Markdown
4. Попробуем создать персонажей различных классовПопробуем создать персонажей различных классов, передавая функции назличные фабрики.
###Code
player = create_hero(AssassinFactory)
player.cast()
player.hit()
player = create_hero(MageFactory)
player.cast()
player.hit()
###Output
Mage casts Fireball
Mage hits with Staff
|
tools/[CTP]_Long_Formulas_and_Cats_(CTP).ipynb | ###Markdown
CTP Publish Shift: Long-long-but-easy Formulas How to use:Running a specific cell: click the ▶️ (play) button text to the cell, or `ctrl+Enter` the cellRunning the entire notebook: "Runtime" menu -> "Run all", or `ctrl-F9`
###Code
# DE positives
import pandas as pd
from datetime import datetime
print("Last Run", datetime.now())
df = pd.read_csv('https://myhealthycommunity.dhss.delaware.gov/locations/state/download_covid_19_data')
df = df[df['Unit'] == 'tests'].set_index(['Year', 'Month', 'Day']).sort_index()
df.loc[df.index.unique()[-3]][['Statistic', 'Value']]
# HI PCR Test Encounters
import pandas as pd
from datetime import datetime
print("Last run at: ", datetime.now())
hi = pd.read_csv("https://public.tableau.com/views/EpiCurveApr4/CSVDownload.csv?:showVizHome=no")
hi.select_dtypes(exclude=['object']).sum()
# ID test
# MA
from io import StringIO, BytesIO
from bs4 import BeautifulSoup
import pandas as pd
import re
import requests
import zipfile
url = 'https://www.mass.gov/info-details/covid-19-response-reporting'
req = requests.get(url)
soup = BeautifulSoup(req.text, 'html.parser')
a = soup.find('a', string=re.compile("COVID-19 Raw Data"))
link = "https://www.mass.gov{}".format(a['href'])
print("Download link = ", link)
res = requests.get(link)
zipdata = BytesIO(res.content)
zip = zipfile.ZipFile(zipdata, 'r')
df = pd.read_csv(zip.open('Testing2.csv'))[['Molecular Total']].iloc[-1]
print("Molecular Total People", df.sum())
df = pd.read_excel(BytesIO(zip.open('TestingByDate.xlsx', 'r').read())).filter(like="All Positive")
print(df.sum())
# weekly report
url = 'https://www.mass.gov/info-details/covid-19-response-reporting'
req = requests.get(url)
soup = BeautifulSoup(req.text, 'html.parser')
a = soup.find('a', string=re.compile("Weekly Public Health Report - Raw"))
link = "https://www.mass.gov{}".format(a['href'])
print("\nWeekly link = ", link)
res = requests.get(link)
df = pd.read_excel(BytesIO(res.content), sheet_name='Antibody', parse_dates=['Test Date'], index_col='Test Date')
print(df.sum())
# ever hospitalized
print('\nEver Hospitalized')
foo = pd.read_excel(BytesIO(res.content), sheet_name='RaceEthnicity')
maxdate = foo['Date'].max()
foo[foo['Date'] == maxdate].sum()
# MI Testing
import pandas as pd
import requests
from bs4 import BeautifulSoup
url = 'https://www.michigan.gov/coronavirus/0,9753,7-406-98163_98173---,00.html'
req = requests.get(url)
soup = BeautifulSoup(req.text, 'html.parser')
a = soup.find('a', string="Diagnostic Tests by Result and County")
mi_link = "https://www.michigan.gov/{}".format(a['href'])
print("Link = ", mi_link)
mi = pd.read_excel(mi_link).drop(columns=['COUNTY'])
mi.sum()
# NC Antigen tests
import pandas as pd
nc = pd.read_csv("https://public.tableau.com/views/NCDHHS_COVID-19_DataDownload/DailyTestingMetrics.csv", parse_dates=['Date'], index_col='Date', thousands=',')
nc.pivot(columns='Measure Names').sum().astype('int64')
# ND Negatives
import pandas as pd
import requests
from io import StringIO
url = "https://static.dwcdn.net/data/NVwou.csv"
headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:79.0) Gecko/20100101 Firefox/79.0"}
req = requests.get(url, headers=headers)
data = StringIO(req.text)
nd = pd.read_csv(data)
nd.sum()
# ND other stuff:
import pandas as pd
nd = pd.read_csv("https://www.health.nd.gov/sites/www/files/documents/Files/MSS/coronavirus/charts-data/CovidTracking.csv")
nd.sum()['Total PCR tests (susceptible test encounters)']
# TX
import pandas as pd
url = 'https://www.dshs.texas.gov/coronavirus/TexasCOVID-19HospitalizationsOverTimebyTSA.xlsx'
df = pd.read_excel(url, sheet_name='COVID-19 ICU', skiprows=2)
print("ICU")
df.loc[df[df.columns[0]] == 'Total'][df.columns[-1]]
# UT
from io import StringIO, BytesIO
import pandas as pd
import requests
import zipfile
url = 'https://coronavirus-dashboard.utah.gov/Utah_COVID19_data.zip'
res = requests.get(url)
zipdata = BytesIO(res.content)
zip = zipfile.ZipFile(zipdata, 'r')
for zf in zip.filelist:
if zf.filename.startswith('Overview_Total Tests by Date'):
# yay, the testing file
title = 'Tests'
elif zf.filename.startswith('Overview_Number of People Tested by Date'):
title = 'People'
else:
title = None
if title:
title = "Metrics for {} (from {})".format(title, zf.filename)
print(title, "\n"+"="*len(title))
df = pd.read_csv(zip.open(zf.filename)).drop(columns=[' Total Daily Tests', 'Total Positive Tests', 'Daily People Tested', 'Daily Positive Tests'], errors="ignore")
print(df.groupby(['Test Type', 'Result']).sum())
# WI PCR Testing Encounters
import pandas as pd
from datetime import datetime
print("Last run at: ", datetime.now().isoformat())
wi = pd.read_csv("https://bi.wisconsin.gov/t/DHS/views/PercentPositivebyTestPersonandaComparisonandTestCapacity/TestCapacityDashboard.csv", thousands=",")
wi[wi['Measure Names'] == 'Total people tested daily']['Totals'].sum()
###Output
_____no_output_____
###Markdown
CTP Publish Shift: Long-long-but-easy Formulas How to use:Running a specific cell: click the ▶️ (play) button text to the cell, or `ctrl+Enter` the cellRunning the entire notebook: "Runtime" menu -> "Run all", or `ctrl-F9`
###Code
# DE positives
import pandas as pd
from datetime import datetime
print("Last Run", datetime.now())
df = pd.read_csv('https://myhealthycommunity.dhss.delaware.gov/locations/state/download_covid_19_data')
df = df[df['Unit'] == 'tests'].set_index(['Year', 'Month', 'Day']).sort_index()
df.loc[df.index.unique()[-3]][['Statistic', 'Value']]
# HI PCR Test Encounters
import pandas as pd
import requests
from datetime import datetime, timezone
from pytz import timezone as tz # replace with ZoneInfo once G upgrades to 3.9
hi = pd.read_csv("https://public.tableau.com/views/EpiCurveApr4/CSVDownload.csv?:showVizHome=no")
print(hi.select_dtypes(exclude=['object']).sum())
# HI updated time
res = requests.get("https://services9.arcgis.com/aKxrz4vDVjfUwBWJ/arcgis/rest/services/HIEMA_TEST_DATA_PUBLIC_LATEST/FeatureServer/0/query?where=name%3D'State'&returnGeometry=false&outFields=*&orderByFields=reportdt desc&resultOffset=0&resultRecordCount=1&f=json")
updated = datetime.fromtimestamp(res.json()['features'][0]['attributes']['reportdt']/1000) # because ms
# format we want: 12/27/2020 8:30:00
print("\nUpdate time: ", updated.replace(tzinfo=timezone.utc).astimezone(tz=tz("Pacific/Honolulu")).strftime("%m/%d/%Y %H:%M:%S"))
# MA
from io import StringIO, BytesIO
from bs4 import BeautifulSoup
import pandas as pd
import re
import requests
import zipfile
url = 'https://www.mass.gov/info-details/covid-19-response-reporting'
req = requests.get(url)
soup = BeautifulSoup(req.text, 'html.parser')
a = soup.find('a', string=re.compile("COVID-19 Raw Data"))
link = "https://www.mass.gov{}".format(a['href'])
print("Download link = ", link)
res = requests.get(link)
tabs = pd.read_excel(res.content, sheet_name=None)
print("PCR Total People")
print(tabs['Testing2 (Report Date)']['Molecular Total'].iloc[-1], "\n")
df = tabs['TestingByDate (Test Date)'].filter(like="All Positive")
print(df.sum())
# weekly report
url = 'https://www.mass.gov/info-details/covid-19-response-reporting'
req = requests.get(url)
soup = BeautifulSoup(req.text, 'html.parser')
a = soup.find('a', string=re.compile("Weekly Public Health Report - Raw"))
link = "https://www.mass.gov{}".format(a['href'])
print("\nWeekly link = ", link)
res = requests.get(link)
df = pd.read_excel(BytesIO(res.content), sheet_name='Antibody', parse_dates=['Test Date'], index_col='Test Date')
print(df.sum())
# ever hospitalized
print('\nEver Hospitalized')
max_date = tabs['RaceEthnicityLast2Weeks']['Date'].max()
tabs['RaceEthnicityLast2Weeks'][tabs['RaceEthnicityLast2Weeks']['Date'] == max_date].sum()
# ME
import pandas as pd
import requests
from io import StringIO
url = "https://gateway.maine.gov/dhhs-apps/mecdc_covid/hospital_capacity.csv"
pd.read_csv(url, nrows=1).filter(like='COVID')
###Output
_____no_output_____
###Markdown
###Code
# MI Testing
import pandas as pd
import requests
from bs4 import BeautifulSoup
url = 'https://www.michigan.gov/coronavirus/0,9753,7-406-98163_98173---,00.html'
req = requests.get(url)
soup = BeautifulSoup(req.text, 'html.parser')
a = soup.find('a', string="Diagnostic Tests by Result and County")
mi_link = "https://www.michigan.gov/{}".format(a['href'])
print("Link = ", mi_link)
mi = pd.read_excel(mi_link).drop(columns=['COUNTY'])
mi.sum()
# NC Antigen tests
import pandas as pd
nc = pd.read_csv("https://public.tableau.com/views/NCDHHS_COVID-19_DataDownload/DailyTestingMetrics.csv", parse_dates=['Date'], index_col='Date', thousands=',')
nc.pivot(columns='Measure Names').sum().astype('int64')
# ND Negatives + Testing
import pandas as pd
import requests
from io import StringIO
url = "https://static.dwcdn.net/data/NVwou.csv"
headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:79.0) Gecko/20100101 Firefox/79.0"}
req = requests.get(url, headers=headers)
print(pd.read_csv(StringIO(req.text)).filter(like='Negative').sum())
print("\n")
print("Testing Data")
df = pd.read_csv('https://www.health.nd.gov/sites/www/files/documents/Files/MSS/coronavirus/charts-data/PublicUseData.csv')
df.filter(like='tests').sum()
# OH testing
import requests
import pandas as pd
key_url = "https://data.ohio.gov/apigateway-secure/data-portal/download-file/cba54974-06ab-4ec8-92bc-62a83b40614e?key=2b4420ffc0c5885f7cd42a963cfda0b489a9a6dff49461e1a921b355ee0424c029cf4ff2ee80c8c82ef901d818d71f9def8cba3651f6595bd6a07e1477438b97bbc5d7ccf7b5b66c154779ce7a4f5b83"
testing_url = "https://data.ohio.gov/apigateway-secure/data-portal/download-file/2ad05e55-2b1a-486c-bc07-ecb3be682d29?key=e42285cfa9a0b157b3f1bdaadcac509c44db4cfa0f90735e12b770acb1307b918cee14d5d8e4d4187eb2cab71fc9233bda8ee3eed924b8a3fad33aaa6c8915fe6f3de6f82ad4b995c2359b168ed88fa9"
url = testing_url
pd.read_csv(requests.get(url).json()['url']).filter(like='Daily').sum()
_# TX
import pandas as pd
import requests
from datetime import datetime, timedelta
url = 'https://www.dshs.texas.gov/coronavirus/TexasCOVID-19HospitalizationsOverTimebyTSA.xlsx'
df = pd.read_excel(url, sheet_name='COVID-19 ICU', skiprows=2)
print("ICU")
print(df.loc[df[df.columns[0]] == 'Total'][df.columns[-1]])
# PCR Positives
res = requests.get('https://services5.arcgis.com/ACaLB9ifngzawspq/arcgis/rest/services/TX_DSHS_COVID19_TestData_Service/FeatureServer/6/query?where=1%3D1&outStatistics=%5B%7B%27statisticType%27%3A+%27sum%27%2C+%27onStatisticField%27%3A+%27NewPositive%27%7D%2C+%7B%27statisticType%27%3A+%27sum%27%2C+%27onStatisticField%27%3A+%27OldPositive%27%7D%5D&f=json')
print("\nPCR Positives")
print(sum(res.json()['features'][0]['attributes'].values()))
res = requests.get('https://services5.arcgis.com/ACaLB9ifngzawspq/ArcGIS/rest/services/TX_DSHS_COVID19_Cases_Service/FeatureServer/2/query?where=1%3D1&outFields=%2A&orderByFields=Date+desc&resultRecordCount=1&f=json')
print("\nCases Timestamp (as-of)")
cases_date = datetime.fromtimestamp(res.json()['features'][0]['attributes']['Date']/1000)
# convent to TX time through trickery (from UTC)
print(cases_date - timedelta(hours=6))
# Antigen Positives
res = requests.get('https://services5.arcgis.com/ACaLB9ifngzawspq/ArcGIS/rest/services/TX_DSHS_COVID19_TestData_Service/FeatureServer/3/query?where=1%3D1&objectIds=&time=&resultType=none&outFields=*&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=false&cacheHint=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=json')
print("\nAntigen Positives")
print(res.json()['features'][5]['attributes']['Count_'])
# Antibody Positives
print("\nAntibody Positives")
print(res.json()['features'][2]['attributes']['Count_'])
# UT
from io import StringIO, BytesIO
import pandas as pd
import requests
import zipfile
url = 'https://coronavirus-dashboard.utah.gov/Utah_COVID19_data.zip'
res = requests.get(url)
zipdata = BytesIO(res.content)
zip = zipfile.ZipFile(zipdata, 'r')
for zf in zip.filelist:
if zf.filename.startswith('Overview_Total Tests by Date'):
# yay, the testing file
title = 'Tests'
elif zf.filename.startswith('Overview_Number of People Tested by Date'):
title = 'People'
else:
title = None
if title:
title = "Metrics for {} (from {})".format(title, zf.filename)
print(title, "\n"+"="*len(title))
df = pd.read_csv(zip.open(zf.filename)).drop(columns=[' Total Daily Tests', 'Total Positive Tests', 'Daily People Tested', 'Daily Positive Tests'], errors="ignore")
print(df.groupby(['Test Type', 'Result']).sum())
# WI PCR Testing Encounters
import pandas as pd
from datetime import datetime
print("Last run at: ", datetime.now().isoformat())
wi = pd.read_csv("https://bi.wisconsin.gov/t/DHS/views/PercentPositivebyTestPersonandaComparisonandTestCapacity/TestCapacityDashboard.csv", thousands=",")
wi[wi['Measure Names'] == 'Total people tested daily']['Totals'].sum()
###Output
Last run at: 2020-11-18T19:01:53.066877
|
notebooks/array ordering of numpy.ipynb | ###Markdown
mapping Cartesian x and y to numpy dimensionsin a 2d numpy array arr[:,:], the first dimension moves along rows and the 2nd dimension moves along columns. rows correspond to y while columns correspond to y1. order = 'C': C-contiguous...last index varies the fastest2. order = 'F': fortran...first index varies the fastest (matlab uses this)
###Code
## in matlab Xn would be transposed
Nx = 10;
Ny = 10;
xn = np.arange(Nx)
yn = np.arange(Ny)
N = [Nx,Ny]
dL = [1,1]
Xn, Yn = np.meshgrid(xn, yn)
print(Xn.T)
print(np.reshape(np.arange(100),(10,10), order = 'F')); ## matlab
fd = grid.FiniteDifferenceGrid(dL,N)
plt.figure(figsize= (5,5))
plt.spy(fd.Dxb, markersize = 0.5)
plt.show();
plt.figure(figsize= (5,5))
plt.spy(fd.Dyb, markersize = 0.5)
plt.show();
dxf = fd.createDws_bloch('y', 'b', k = 1, L = 1)
plt.figure(figsize = (5,5))
plt.spy(dxf, markersize = 1)
dxf2 = fd.createDws_bloch2('y', 'b', k = 1, L = 1)
dxf3 = fd.createDws('y','b')
plt.figure(figsize = (5,5))
plt.spy(dxf-dxf2, markersize = 1)
print(dxf)
print(dxf2)
#dxf3.diagonal()
###Output
_____no_output_____ |
classifiers/CNN-BiLSTM-attention-ensemble-model.ipynb | ###Markdown
Domain Specific Fasttext Embeddings
###Code
start = process_time()
embedding_path1 = "/home/eastwind/word-embeddings/fasttext/TechDofication.mr.raw.complete.ft.skipgram.new.d300.vec"
embedding_matrix1 = get_embedding_matrix(embedding_path1, vocab, embedding_dim=300)
end = process_time()
print("Total time taken: ", end-start)
embedding_matrix1.shape
input_dim1 = embedding_matrix1.shape[0]
embedding_dim1 = 300
input_len = pad_len
print("Input dimension 1: ", input_dim1)
print("Embedding dimensions 1: ", embedding_dim1)
print("Input sentence dimensions 1: ", input_len)
###Output
Input dimension 1: 55030
Embedding dimensions 1: 300
Input sentence dimensions 1: 100
###Markdown
Hybrid BiLSTM-CNN Architecture with Attention
###Code
class AttentionLayer(Layer):
def __init__(self, **kwargs):
super(AttentionLayer, self).__init__(**kwargs)
def build(self, attention_input):
super(AttentionLayer, self).build(attention_input)
lstm_shape, cnn_shape = attention_input
# Attention Weights for LSTM
self.W_in = self.add_weight(shape=(lstm_shape[-1], 1),
initializer='glorot_normal',
trainable=True,
name='input_attention_weights')
# Attention Weights for CNN
self.W_context = self.add_weight(shape=(cnn_shape[-1], 1),
initializer='glorot_normal',
trainable=True,
name='context_attention_weights')
# Attention Bias
self.b = self.add_weight(shape=(lstm_shape[1], 1),
initializer='glorot_normal',
trainable=True,
name='attention_bias')
def call(self, attention_input):
lstm_output, cnn_output = attention_input
et = K.squeeze(K.tanh(K.dot(lstm_output, self.W_in) +
K.dot(cnn_output, self.W_context) +
self.b), axis=-1)
at = K.expand_dims(K.softmax(et), axis=-1)
attention_output = at * lstm_output
attention_output = K.sum(attention_output, axis=1)
return attention_output
def get_config(self):
return super(AttentionLayer, self).get_config()
Input1 = Input(shape=(input_len,))
Embedding_layer1 = Embedding(input_dim=input_dim1,
output_dim=embedding_dim1,
weights=[embedding_matrix1],
trainable=False)(Input1)
# Input 1(BiLSTM):
Lstm = Bidirectional(LSTM(128, dropout=0.3, return_sequences=True))(Embedding_layer1)
# Input 2 (CNN):
Conv1 = Conv1D(filters=256, kernel_size=3, activation='relu', padding='same')(Embedding_layer1)
Dropout1 = Dropout(0.3)(Conv1)
Conv2 = Conv1D(filters=256, kernel_size=4, activation='relu', padding='same')(Embedding_layer1)
Dropout2 = Dropout(0.3)(Conv2)
Conv3 = Conv1D(filters=256, kernel_size=5, activation='relu', padding='same')(Embedding_layer1)
Dropout3 = Dropout(0.3)(Conv3)
merged = concatenate([Dropout1, Dropout2, Dropout3], axis=1)
max_pool = MaxPooling1D(pool_size=3)(merged)
attention = AttentionLayer()([Lstm, max_pool])
Dense1 = Dense(64, activation='relu')(attention)
Dropout_dense = Dropout(0.25)(Dense1)
outputs = Dense(4, activation='softmax')(Dropout_dense)
classifier = Model(inputs=Input1, outputs=outputs)
classifier.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc'])
classifier.summary()
plot_model(classifier, show_shapes=False)
# ModelCheckPoint Callback:
checkpoint_filepath = "../models/multi-channel-LSTM-CNN/multi-channel-LSTM-CNN-epoch-{epoch:02d}-val-acc-{val_acc:02f}.h5"
model_checkpoint_callback = ModelCheckpoint(filepath=checkpoint_filepath,
save_weights_only=True,
monitor='val_acc',
mode='max',
save_freq = 'epoch',
save_best_only=True)
# Reduce Learning Rate on Plateau Callback:
reduce_lr_callback = ReduceLROnPlateau( monitor='val_acc',
factor=0.1,
patience=2,
min_lr=0.0005,
verbose=2)
#myCB = myCallbacks(metrics='acc', threshold=0.97)
history = classifier.fit(x_train_padded,
y_train,
epochs=16,
batch_size=128,
verbose=1,
validation_data=(x_val_padded, y_val),
callbacks=[model_checkpoint_callback, reduce_lr_callback])
plot_curves(history)
classifier.load_weights("../models/multi-channel-LSTM-CNN/multi-channel-LSTM-CNN-epoch-16-val-acc-0.895767.h5")
results = np.argmax(classifier.predict(x_val_padded), axis=-1)
acc, precision, recall, f1 = classification_report(y_val, results)
print("Validation Accuracy: ", acc)
print("\nPrecision: ", precision)
print("Average Precision: ", np.mean(precision))
print("\nRecall: ", recall)
print("Average Recall: ", np.mean(recall))
print("\nF1-Score: ", f1)
print("Average F1-Score: ", np.mean(f1))
predictions = np.argmax(classifier.predict(x_test_padded), axis=-1)
len(predictions)
original_labels = list(le.inverse_transform(predictions))
len(original_labels)
df = pd.DataFrame(list(zip(test_data, original_labels)), columns=['text', 'predicted_label'])
df
df.predicted_label.value_counts()
df.to_csv("../results/marathi-multi-channel-CNN-BiLSTM-attention-parallel-predictions.tsv", sep='\t', index=False)
###Output
_____no_output_____ |
2020-stats_alpha.ipynb | ###Markdown
PSD Analysis Alpha R Load necessary librariesIf any of these don't load, you'll need to install them. Assuming you installed Jupyter through Anaconda, you would do the following to install a package`conda install -c r r-[pkgName]`e.g., to install ggplot2 you would do:`conda install -c r r-ggplot2`
###Code
R.home()
R.version
library(ggplot2)
library(mgcv)
library(parallel)
library(plyr)
library(tidyr)
library(data.table)
library(viridis)
# library(ggthemes)
library(nlme)
###Output
Loading required package: nlme
This is mgcv 1.8-29. For overview type 'help("mgcv-package")'.
Loading required package: viridisLite
###Markdown
Load Data
###Code
topdir = getwd()
source(paste(topdir,'/NCIL_functions.R',sep=""))
num_cores = 4
dat = read.csv("osc_data/alpha.csv")
head(dat)
summary(dat)
###Output
_____no_output_____
###Markdown
Run initial full model to identify and remove outliers Now run the model
###Code
m0 <- bam(PSD ~ Stim * Condition
+ s(Subj, bs="re"),
data = dat,
samfrac=0.1)
dat <- romr.fnc(m0, dat, trim=2.5)$data
m1 <- bam(PSD ~ Stim * Condition
+ s(Subj, bs="re"),
data = dat,
samfrac=0.1)
###Output
n.removed = 1075
percent.removed = 1.496693
###Markdown
Find and remove outliers, then update model
###Code
gam.check(m0)
gam.check(m1)
###Output
Method: fREML Optimizer: perf newton
full convergence after 11 iterations.
Gradient range [-1.254582e-05,1.247255e-05]
(score 205619.4 & scale 19.57557).
Hessian positive definite, eigenvalue range [0.4980751,35371].
Model rank = 9 / 11
Basis dimension (k) checking results. Low p-value (k-index<1) may
indicate that k is too low, especially if edf is close to k'.
k' edf k-index p-value
s(Subj) 1.000 0.998 0.65 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
###Markdown
Compute LME based on model StimType * MentalState- We will start by clustering around MW1 Standard- We see the original amplified P2 effect disappear- It is possible that this was an effect of the contrasts between conditions- When MW, oddball responses are high; oddballs are significantly lower when on task- Differences might be greater at Fz based on preliminary analysis of grand averages
###Code
bdat <- dat
dat <- bdat
dat <- subset(bdat, Region == 'occipital') #change this as needed
# relevel data to focus on standard and MW1
dat[,'Condition'] <- relevel(dat[,'Condition'],'MW1')
dat[,'Stim'] <- relevel(dat[,'Stim'],'standard')
summary(dat)
###Output
_____no_output_____
###Markdown
Try many models
###Code
num_cores = 4
cl <- makeCluster(num_cores)
m1r <- bam(PSD ~ Stim * Condition
+ s(Subj, bs="re")
+ s(Electrode_by_Subj, bs="re"),
data = dat,
samfrac=0.1, cluster=cl, gc.level=2)
m2r <- bam(PSD ~ Stim * Condition
+ s(Subj, bs="re")
+ s(Stim_by_Subj, bs="re"),
data = dat,
samfrac=0.1, cluster=cl, gc.level=2)
m3r <- bam(PSD ~ Stim * Condition
+ s(Subj, bs="re")
+ s(Cond_by_Subj, bs="re"),
data = dat,
samfrac=0.1, cluster=cl, gc.level=2)
m4r <- bam(PSD ~ Stim * Condition
+ s(Subj, bs="re")
+ s(Electrode_by_Subj, bs="re")
+ s(Stim_by_Subj, bs="re"),
data = dat,
samfrac=0.1, cluster=cl, gc.level=2)
m5r <- bam(PSD ~ Stim * Condition
+ s(Subj, bs="re")
+ s(Electrode_by_Subj, bs="re")
+ s(Cond_by_Subj, bs="re"),
data = dat,
samfrac=0.1, cluster=cl, gc.level=2)
m6r <- bam(PSD ~ Stim * Condition
+ s(Subj, bs="re")
+ s(Stim_by_Subj, bs="re")
+ s(Cond_by_Subj, bs="re"),
data = dat,
samfrac=0.1, cluster=cl, gc.level=2)
m7r <- bam(PSD ~ Stim # adding this to control for condition
+ s(Condition, bs="re")
+ s(Subj, bs="re")
+ s(Stim_by_Subj, bs="re")
+ s(Cond_by_Subj, bs="re"),
data = dat,
samfrac=0.1, cluster=cl, gc.level=2)
stopCluster(cl)
###Output
_____no_output_____
###Markdown
Select best model based on AIC
###Code
AICtab = as.data.frame(AIC(m0,m1r,m2r,m3r,m4r,m5r,m6r,m7r))
minAIC = min(AIC(m0,m1r,m2r,m3r,m4r,m5r,m6r,m7r)[2])
AICtab$deltaAIC = lapply(AICtab$AIC, deltaAICfunc)
AICtab$deltaAIC = as.numeric(AICtab$deltaAIC)
AICtab$L= lapply(AICtab$deltaAIC, f)
AICtab$L = as.numeric(AICtab$L)
sumlike = sum(AICtab$L)
AICtab$wAIC = lapply(AICtab$L, wAICfunc)
AICtab$wAIC = as.numeric(AICtab$wAIC)
# compute relative likelihood of each model relative to model with smallest AIC/max wAIC
# So, xBetter is interpreted as "the best model is x times more likely than this model"
wAICmax = max(AICtab$wAIC)
AICtab$xBetter = lapply(AICtab$wAIC, xBetterfunc)
AICtab$xBetter = as.numeric(AICtab$xBetter)
AICtab = AICtab[order(AICtab$deltaAIC),]
AICtab[,c('df','AIC','deltaAIC','xBetter')]
###Output
_____no_output_____
###Markdown
Get summary of the best modelMain effects and interactions.
###Code
mod = m5r
mod_summary = anova(mod)
mod_summary
summary(mod)
###Output
_____no_output_____
###Markdown
Visualize these results
###Code
res <- t(summary(mod)$p.table[3,])
res <- as.data.frame(res)
res$Condition = paste("2 (Somewhat OT)")
posthocs <- res
res <- t(summary(mod)$p.table[4,])
res <- as.data.frame(res)
res$Condition = paste("3 (Niether MW nor OT)")
posthocs <- rbind(posthocs, res)
res <- t(summary(mod)$p.table[5,])
res <- as.data.frame(res)
res$Condition = paste("4 (Somewhat MW)")
posthocs <- rbind(posthocs, res)
res <- t(summary(mod)$p.table[6,])
res <- as.data.frame(res)
res$Condition = paste("5 (Completely MW)")
posthocs <- rbind(posthocs, res)
colnames(posthocs)[2] <- 'SE'
colnames(posthocs)[4] <- 'p (raw)'
# CIs
ncomp <- dim(posthocs)[1] #-2 # The -2 is bc the age x polynomial contrasts are repeated for each group, but are teh same
thr <- adjust.se(alpha=0.05, df=1000, ncomp=ncomp)
posthocs$CIup <- round(posthocs$Estimate + thr * posthocs$SE, 2)
posthocs$CIdown <- round(posthocs$Estimate - thr * posthocs$SE, 2)
# Round for pretty table
posthocs[,'Estimate'] = round(posthocs[,'Estimate'],2)
posthocs[,'SE'] = round(posthocs[,'SE'],3)
posthocs[,'t value'] = round(posthocs[,'t value'],2)
posthocs[,'p (raw)'] = round(posthocs[,'p (raw)'],5)
# Reorder columns
posthocs = posthocs[,c('Condition', 'Estimate','SE','CIup','CIdown','t value','p (raw)')]
# Multiple comparison correction
posthocs$'p (Holm)' <- round(p.adjust(posthocs$'p (raw)', method='holm', n <- ncomp), 4)
# write.csv(posthocs, file=paste(topdir, '/', expt, '_output/', 'stats ', CurTimeWin,
# ' posthocs 4way BxGxVxR.csv' ,sep=''))
posthocs
ggplot(posthocs, aes(x=Condition, y=Estimate)) +
geom_bar(position='dodge', stat='identity', fill='indianred' ) +
geom_errorbar(aes(ymin = CIdown, ymax = CIup),
size = 1, width = .5,
position = position_dodge(width = .9),
color = 'grey3') +
ylim(-2,3) +
ggtitle("Occipital alpha (8-12 Hz; standard stimuli)") +
theme(plot.title = element_text(hjust=0.5)) +
xlab("Comparison")
ggsave(filename='standard-alpha.png', dpi=600)
###Output
Saving 6.67 x 6.67 in image
###Markdown
Compare MW1 oddball instead
###Code
# relevel data to focus on standard and MW1
dat[,'Condition'] <- relevel(dat[,'Condition'],'MW1')
dat[,'Stim'] <- relevel(dat[,'Stim'],'oddball')
cl <- makeCluster(num_cores)
m7r <- bam(PSD ~ Stim * Condition
+ s(Subj, bs="re")
+ s(Electrode_by_Subj, bs="re")
+ s(Cond_by_Subj, bs="re"),
data = dat,
samfrac=0.1, cluster=cl, gc.level=2)
stopCluster(cl)
mod = m7r
mod_summary = anova(mod)
mod_summary
summary(mod)
###Output
_____no_output_____
###Markdown
Visualize the results
###Code
res <- t(summary(mod)$p.table[3,])
res <- as.data.frame(res)
res$Condition = paste("2 (Somewhat OT)")
posthocs <- res
res <- t(summary(mod)$p.table[4,])
res <- as.data.frame(res)
res$Condition = paste("3 (Niether MW nor OT)")
posthocs <- rbind(posthocs, res)
res <- t(summary(mod)$p.table[5,])
res <- as.data.frame(res)
res$Condition = paste("4 (Somewhat MW)")
posthocs <- rbind(posthocs, res)
res <- t(summary(mod)$p.table[6,])
res <- as.data.frame(res)
res$Condition = paste("5 (Completely MW)")
posthocs <- rbind(posthocs, res)
colnames(posthocs)[2] <- 'SE'
colnames(posthocs)[4] <- 'p (raw)'
# CIs
ncomp <- dim(posthocs)[1] #-2 # The -2 is bc the age x polynomial contrasts are repeated for each group, but are teh same
thr <- adjust.se(alpha=0.05, df=1000, ncomp=ncomp)
posthocs$CIup <- round(posthocs$Estimate + thr * posthocs$SE, 2)
posthocs$CIdown <- round(posthocs$Estimate - thr * posthocs$SE, 2)
# Round for pretty table
posthocs[,'Estimate'] = round(posthocs[,'Estimate'],2)
posthocs[,'SE'] = round(posthocs[,'SE'],3)
posthocs[,'t value'] = round(posthocs[,'t value'],2)
posthocs[,'p (raw)'] = round(posthocs[,'p (raw)'],5)
# Reorder columns
posthocs = posthocs[,c('Condition', 'Estimate','SE','CIup','CIdown','t value','p (raw)')]
# Multiple comparison correction
posthocs$'p (Holm)' <- round(p.adjust(posthocs$'p (raw)', method='holm', n <- ncomp), 4)
# write.csv(posthocs, file=paste(topdir, '/', expt, '_output/', 'stats ', CurTimeWin,
# ' posthocs 4way BxGxVxR.csv' ,sep=''))
posthocs
ggplot(posthocs, aes(x=Condition, y=Estimate)) +
geom_bar(position='dodge', stat='identity', fill='cornflowerblue' ) +
geom_errorbar(aes(ymin = CIdown, ymax = CIup),
size = 1, width = .5,
position = position_dodge(width = .9),
color = 'grey3') +
ggtitle("Occipital alpha (8-12 Hz; oddball stimuli)") +
theme(plot.title = element_text(hjust=0.5)) +
xlab("Comparison") +
ylim(-2,3)
ggsave(filename='oddball-alpha.png', dpi=600)
###Output
Saving 6.67 x 6.67 in image
###Markdown
Compare standards and oddballs for each conditionCould have put this in a loop, but this is the path of least resistance
###Code
# set up initial posthoc
dat <- subset(bdat, Region == 'occipital') #change this as needed
dat[,'Condition'] <- relevel(dat[,'Condition'],'MW1')
dat[,'Stim'] <- relevel(dat[,'Stim'],'standard')
cl <- makeCluster(num_cores)
m8r <- bam(PSD ~ Stim * Condition
+ s(Subj, bs="re")
+ s(Electrode_by_Subj, bs="re")
+ s(Cond_by_Subj, bs="re"),
data = dat,
samfrac=0.1, cluster=cl, gc.level=2)
stopCluster(cl)
mod = m8r
res <- t(summary(mod)$p.table[2,])
res <- as.data.frame(res)
res$Condition = paste("1 (Completely OT)")
posthocs <- res
# include the subsequent levels, looping through
mw_levels <- c('MW2','MW3','MW4','MW5')
axis_labels <- c('2 (Somewhat OT)', '3 (Neither MW nor OT)', '4 (Somewhat MW)', '5 (Completely MW)')
for(i in 1:4){
dat[,'Condition'] <- relevel(dat[,'Condition'],mw_levels[i])
dat[,'Stim'] <- relevel(dat[,'Stim'],'standard')
cl <- makeCluster(num_cores)
m8r <- bam(PSD ~ Stim * Condition
+ s(Subj, bs="re")
+ s(Electrode_by_Subj, bs="re")
+ s(Cond_by_Subj, bs="re"),
data = dat,
samfrac=0.1, cluster=cl, gc.level=2)
stopCluster(cl)
mod = m8r
res <- t(summary(mod)$p.table[2,])
res <- as.data.frame(res)
res$Condition = paste(axis_labels[i])
posthocs <- rbind(posthocs, res)
}
## Clean up posthocs
colnames(posthocs)[2] <- 'SE'
colnames(posthocs)[4] <- 'p (raw)'
# CIs
ncomp <- dim(posthocs)[1] #-2 # The -2 is bc the age x polynomial contrasts are repeated for each group, but are teh same
thr <- adjust.se(alpha=0.05, df=1000, ncomp=ncomp)
posthocs$CIup <- round(posthocs$Estimate + thr * posthocs$SE, 2)
posthocs$CIdown <- round(posthocs$Estimate - thr * posthocs$SE, 2)
# Round for pretty table
posthocs[,'Estimate'] = round(posthocs[,'Estimate'],2)
posthocs[,'SE'] = round(posthocs[,'SE'],3)
posthocs[,'t value'] = round(posthocs[,'t value'],2)
posthocs[,'p (raw)'] = round(posthocs[,'p (raw)'],5)
# Reorder columns
posthocs = posthocs[,c('Condition', 'Estimate','SE','CIup','CIdown','t value','p (raw)')]
# Multiple comparison correction
posthocs$'p (Holm)' <- round(p.adjust(posthocs$'p (raw)', method='holm', n <- ncomp), 4)
# write.csv(posthocs, file=paste(topdir, '/', expt, '_output/', 'stats ', CurTimeWin,
# ' posthocs 4way BxGxVxR.csv' ,sep=''))
posthocs
ggplot(posthocs, aes(x=Condition, y=Estimate)) +
geom_bar(position='dodge', stat='identity', fill='darkgray' ) +
geom_errorbar(aes(ymin = CIdown, ymax = CIup),
size = 1, width = .5,
position = position_dodge(width = .9),
color = 'grey3') +
ggtitle("Occipital alpha (8-12 Hz; difference between oddball and standard by condition)") +
theme(plot.title = element_text(hjust=0.5)) +
xlab("Comparison") +
ylim(-2,3)
ggsave(filename='oddball-difference-alpha.png', dpi=600)
###Output
Saving 6.67 x 6.67 in image
|
notebooks/pytorch/inference.ipynb | ###Markdown
Loading the data
###Code
# input batch size for training (default: 64)
batch_size = 64
# input batch size for testing (default: 1000)
test_batch_size = 1000
# number of epochs to train (default: 10)
epochs = 10
# learning rate (default: 0.01)
lr = 0.01
# SGD momentum (default: 0.5)
momentum = 0.5
# disables CUDA training
no_cuda = True
# random seed (default: 1)
seed = 1
# how many batches to wait before logging training status
log_interval = 10
# Setting seed for reproducibility.
torch.manual_seed(seed)
cuda = not no_cuda and torch.cuda.is_available()
print("CUDA: {}".format(cuda))
if cuda:
torch.cuda.manual_seed(seed)
cudakwargs = {'num_workers': 1, 'pin_memory': True} if cuda else {}
mnist_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,)) # Precalcualted values.
])
train_set = datasets.MNIST(
root='data',
train=True,
transform=mnist_transform,
download=True,
)
test_set = datasets.MNIST(
root='data',
train=False,
transform=mnist_transform,
download=True,
)
train_loader = torch.utils.data.DataLoader(
dataset=train_set,
batch_size=batch_size,
shuffle=True,
**cudakwargs
)
test_loader = torch.utils.data.DataLoader(
dataset=test_set,
batch_size=test_batch_size,
shuffle=True,
**cudakwargs
)
def test(model, loader):
model.eval()
test_loss = 0
correct = 0
for data, target in loader:
if cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data, volatile=True), Variable(target)
output = model(data)
test_loss += F.cross_entropy(output, target).data[0]
pred = output.data.max(1)[1] # get the index of the max log-probability
correct += pred.eq(target.data).cpu().sum()
test_loss = test_loss
test_loss /= len(loader) # loss function already averages over batch size
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(loader.dataset),
100. * correct / len(loader.dataset)))
###Output
_____no_output_____
###Markdown
Method 1If only the `state_dict` was saved, we still need the source code for the model.
###Code
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv2d_1 = nn.Conv2d(1, 32, kernel_size=3)
self.conv2d_2 = nn.Conv2d(32, 32, kernel_size=3)
self.dense_1 = nn.Linear(3872, 64)
self.dense_2 = nn.Linear(64, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv2d_1(x), kernel_size=2))
x = F.relu(self.conv2d_2(x))
x = F.dropout(x, training=self.training)
x = x.view(-1, 3872)
x = F.relu(self.dense_1(x))
x = F.dropout(x, training=self.training)
x = self.dense_2(x)
return F.log_softmax(x)
# Create the model.
model = Net()
model.load_state_dict(
torch.load('torch_mnist.pth')
)
test(model, test_loader)
###Output
Test set: Average loss: 0.0856, Accuracy: 9732/10000 (97%)
###Markdown
Method 2If the model and the parameters were saved we should in theory just need to load one file. However, this will fail, if the `Net` class was not defined before.
###Code
model = torch.load('torch_mnist.pth.tar')
test(model, test_loader)
###Output
Test set: Average loss: 0.0856, Accuracy: 9732/10000 (97%)
|
notebooks/Day2_1-Scikit-Learn.ipynb | ###Markdown
Introduction to scikit-learnThe `scikit-learn` package is an open-source library that provides a robust set of machine learning algorithms for Python. It is built upon the core Python scientific stack (*i.e.* NumPy, SciPy, Cython), and has a simple, consistent API, making it useful for a wide range of statistical learning applications. What is Machine Learning?Machine Learning (ML) is about coding programs that automatically adjust their performance from exposure to information encoded in data. This learning is achieved via **tunable parameters** that are automatically adjusted according to performance criteria.Machine Learning can be considered a subfield of Artificial Intelligence (AI).There are three major classes of ML:**Supervised learning**: Algorithms which learn from a training set of *labeled* examples (exemplars) to generalize to the set of all possible inputs. Examples of supervised learning include regression and support vector machines.**Unsupervised learning**: Algorithms which learn from a training set of *unlableled* examples, using the features of the inputs to categorize inputs together according to some statistical criteria. Examples of unsupervised learning include k-means clustering and kernel density estimation.**Reinforcement learning**: Algorithms that learn via reinforcement from a *critic* that provides information on the quality of a solution, but not on how to improve it. Improved solutions are achieved by iteratively exploring the solution space. We will not cover RL in this course. Representing Data in scikit-learnMost machine learning algorithms implemented in scikit-learn expect data to be stored in a**two-dimensional array or matrix**. The arrays can beeither ``numpy`` arrays, or in some cases ``scipy.sparse`` matrices.The size of the array is expected to be `[n_samples, n_features]`- **n_samples:** The number of samples: each sample is an item to process (e.g. classify). A sample can be a document, a picture, a sound, a video, an astronomical object, a row in database or CSV file, or whatever you can describe with a fixed set of quantitative traits.- **n_features:** The number of features or distinct traits that can be used to describe each item in a quantitative manner. Features are generally real-valued, but may be boolean or discrete-valued in some cases.The number of features must be fixed in advance. However it can be very high dimensional(e.g. millions of features) with most of them being zeros for a given sample. This is a casewhere `scipy.sparse` matrices can be useful, in that they aremuch more memory-efficient than numpy arrays. Example: Iris morphometricsOne of the datasets included with `scikit-learn` is a set of measurements for flowers, each being a member of one of three species: *Iris Setosa*, *Iris Versicolor* or *Iris Virginica*.
###Code
from sklearn.datasets import load_iris
iris = load_iris()
###Output
_____no_output_____
###Markdown
The data is stored as a `dict` with elements corresponding to the predictors (`data`), the species name (`target`), as well as labels associated with these values.
###Code
iris.keys()
n_samples, n_features = iris.data.shape
n_samples, n_features
###Output
_____no_output_____
###Markdown
Here is a sample row of the data, with the corresponding labels.
###Code
iris.data[0]
iris.feature_names
###Output
_____no_output_____
###Markdown
The information about the class of each sample is stored in the ``target`` attribute of the dataset:
###Code
iris.target
iris.target_names
###Output
_____no_output_____
###Markdown
We probably want to convert the data into a more convenient structure, namely, a `DataFrame`.
###Code
import pandas as pd
iris_df = pd.DataFrame(iris.data, columns=iris.feature_names).assign(species=iris.target_names[iris.target])
###Output
_____no_output_____
###Markdown
Looking at the data, there appears to be information in the predictors to distinguish among the species labels.
###Code
%matplotlib inline
import seaborn as sns
sns.pairplot(iris_df, hue='species', height=1.5);
###Output
_____no_output_____
###Markdown
scikit-learn interfaceAll objects within scikit-learn share a uniform common basic API consisting of three complementary interfaces: * **estimator** interface for building and fitting models* **predictor** interface for making predictions* **transformer** interface for converting data.The estimator interface is at the core of the library. It defines instantiation mechanisms of objects and exposes a fit method for learning a model from training data. All supervised and unsupervised learning algorithms (*e.g.*, for classification, regression or clustering) are offered as objects implementing this interface. Machine learning tasks like feature extraction, feature selection or dimensionality reduction are also provided as estimators.The consistent interface across machine learning methods makes it easy to switch between different approaches without drastically changing the form of the data or the supporting code, making experimentation and prototyping fast and easy.Scikit-learn strives to have a uniform interface across all methods. For example, a typical **estimator** follows this template: ```pythonclass Estimator(object): def fit(self, X, y=None): """Fit model to data X (and y)""" self.some_attribute = self.some_fitting_method(X, y) return self def predict(self, X_test): """Make prediction based on passed features""" pred = self.make_prediction(X_test) return pred ``` For a given scikit-learn **estimator** object named `model`, several methods are available. Irrespective of the type of **estimator**, there will be a `fit` method:- `model.fit` : fit training data. For supervised learning applications, this accepts two arguments: the data `X` and the labels `y` (e.g. `model.fit(X, y)`). For unsupervised learning applications, this accepts only a single argument, the data `X` (e.g. `model.fit(X)`).> During the fitting process, the state of the **estimator** is stored in attributes of the estimator instance named with a trailing underscore character (\_). For example, the sequence of regression trees `sklearn.tree.DecisionTreeRegressor` is stored in `estimators_` attribute.The **predictor** interface extends the notion of an estimator by adding a `predict` method that takes an array `X_test` and produces predictions based on the learned parameters of the estimator. In the case of supervised learning estimators, this method typically returns the predicted labels or values computed by the model. Some unsupervised learning estimators may also implement the predict interface, such as k-means, where the predicted values are the cluster labels.**supervised estimators** are expected to have the following methods:- `model.predict` : given a trained model, predict the label of a new set of data. This method accepts one argument, the new data `X_new` (e.g. `model.predict(X_new)`), and returns the learned label for each object in the array.- `model.predict_proba` : For classification problems, some estimators also provide this method, which returns the probability that a new observation has each categorical label. In this case, the label with the highest probability is returned by `model.predict()`.- `model.score` : for classification or regression problems, most (all?) estimators implement a score method. Scores are between 0 and 1, with a larger score indicating a better fit.Since it is common to modify or filter data before feeding it to a learning algorithm, some estimators in the library implement a **transformer** interface which defines a `transform` method. It takes as input some new data `X_test` and yields as output a transformed version. Preprocessing, feature selection, feature extraction and dimensionality reduction algorithms are all provided as transformers within the library.**unsupervised estimators** will always have these methods:- `model.transform` : given an unsupervised model, transform new data into the new basis. This also accepts one argument `X_new`, and returns the new representation of the data based on the unsupervised model.- `model.fit_transform` : some estimators implement this method, which more efficiently performs a fit and a transform on the same input data. Regression AnalysisTo demonstrate how `scikit-learn` is used, let's conduct a logistic regression analysis on a dataset for very low birth weight (VLBW) infants.Data on 671 infants with very low (less than 1600 grams) birth weight from 1981-87 were collected at Duke University Medical Center by [OShea *et al.* (1992)](http://www.ncbi.nlm.nih.gov/pubmed/1635885). Of interest is the relationship between the outcome intra-ventricular hemorrhage and the predictors birth weight, gestational age, presence of pneumothorax, mode of delivery, single vs. multiple birth, and whether the birth occurred at Duke or at another hospital with later transfer to Duke. A secular trend in the outcome is also of interest.The metadata for this dataset can be found [here](http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/Cvlbw.html).
###Code
import pandas as pd
vlbw = pd.read_csv("../data/vlbw.csv", index_col=0)
subset = vlbw[['ivh', 'gest', 'bwt', 'delivery', 'inout',
'pltct', 'lowph', 'pneumo', 'twn', 'apg1']].dropna()
# Extract response variable
y = subset.ivh.replace({'absent':0, 'possible':1, 'definite':1})
# Standardize some variables
X = subset[['gest', 'bwt', 'pltct', 'lowph']]
X0 = (X - X.mean(axis=0)) / X.std(axis=0)
# Recode some variables
X0['csection'] = subset.delivery.replace({'vaginal':0, 'abdominal':1})
X0['transported'] = subset.inout.replace({'born at Duke':0, 'transported':1})
X0[['pneumo', 'twn', 'apg1']] = subset[['pneumo', 'twn','apg1']]
X0.head()
###Output
_____no_output_____
###Markdown
We split the data into a training set and a testing set. By default, 25% of the data is reserved for testing. This is the first of multiple ways that we will see to do this.
###Code
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X0, y)
###Output
_____no_output_____
###Markdown
The `LogisticRegression` model in scikit-learn employs a regularization coefficient `C`, which defaults to 1. The amount of regularization is lower with larger values of C.Regularization penalizes the values of regression coefficients, while smaller ones let the coefficients range widely. Scikit-learn includes two penalties: a **l2** penalty which penalizes the sum of the squares of the coefficients (the default), and a **l1** penalty which penalizes the sum of the absolute values.The reason for doing regularization is to let us to include more covariates than our data might otherwise allow. We only have a few coefficients, so we will set `C` to a large value.
###Code
from sklearn.linear_model import LogisticRegression
lrmod = LogisticRegression(C=1000)
lrmod
###Output
_____no_output_____
###Markdown
The `__repr__` method of `scikit-learn` models prints out all of the hyperparameter values used when running the model. It is recommended to inspect these prior to running the model, as the can strongly influence the resulting estimates and predictions.
###Code
lrmod.fit(X_train, y_train)
pred_train = lrmod.predict(X_train)
pred_test = lrmod.predict(X_test)
pd.crosstab(y_train, pred_train,
rownames=["Actual"], colnames=["Predicted"])
pd.crosstab(y_test, pred_test,
rownames=["Actual"], colnames=["Predicted"])
###Output
_____no_output_____
###Markdown
The regression coefficients can be inspected in the `coef_` attribute that the fitting procedure attached to the model object.
###Code
for name, value in zip(X0.columns, lrmod.coef_[0]):
print('{0}:\t{1:.2f}'.format(name, value))
###Output
_____no_output_____
###Markdown
`scikit-learn` does not calculate confidence intervals for the model coefficients, but we can bootstrap some in just a few lines of Python:
###Code
import numpy as np
n = 1000
boot_samples = np.empty((n, len(lrmod.coef_[0])))
for i in np.arange(n):
boot_ind = np.random.randint(0, len(X0), len(X0))
y_i, X_i = y.values[boot_ind], X0.values[boot_ind]
lrmod_i = LogisticRegression(C=1000)
lrmod_i.fit(X_i, y_i)
boot_samples[i] = lrmod_i.coef_[0]
boot_samples.sort(axis=0)
boot_se = boot_samples[[25, 975], :].T
import matplotlib.pyplot as plt
coefs = lrmod.coef_[0]
plt.plot(coefs, 'r.')
for i in range(len(coefs)):
plt.errorbar(x=[i,i], y=boot_se[i], color='red')
plt.xlim(-0.5, 8.5)
plt.xticks(range(len(coefs)), X0.columns.values, rotation=45)
plt.axhline(0, color='k', linestyle='--')
###Output
_____no_output_____ |
examples/pst_demo.ipynb | ###Markdown
The Pst classThe `pst_handler` module contains the `Pst` class for dealing with pest control files. It relies heavily on `pandas` to deal with tabular sections, such as parameters, observations, and prior information.
###Code
from __future__ import print_function
import os
import numpy as np
import pyemu
from pyemu import Pst
###Output
_____no_output_____
###Markdown
We need to pass the name of a pest control file to instantiate:
###Code
pst_name = os.path.join("henry","pest.pst")
p = Pst(pst_name)
###Output
_____no_output_____
###Markdown
All of the relevant parts of the pest control file are attributes of the `pst` class with the same name:
###Code
p.parameter_data.head()
p.observation_data.head()
p.prior_information.head()
###Output
_____no_output_____
###Markdown
A residual file (`.rei` or `res`) can also be passed to the `resfile` argument at instantiation to enable some simple residual analysis and weight adjustments. If the residual file is in the same directory as the pest control file and has the same base name, it will be accessed automatically:
###Code
p.res
###Output
_____no_output_____
###Markdown
The `pst` class has some `@decorated` convience methods related to the residuals:
###Code
print(p.phi,p.phi_components)
###Output
_____no_output_____
###Markdown
Some additional `@decorated` convience methods:
###Code
print(p.npar,p.nobs,p.nprior)
print(p.par_groups,p.obs_groups)
print(type(p.par_names)) # all parameter names
print(type(p.adj_par_names)) # adjustable parameter names
print(type(p.obs_names)) # all observation names
print(type(p.nnz_obs_names)) # non-zero weight observations
###Output
_____no_output_____
###Markdown
The "control_data" section of the pest control file is accessible in the `Pst.control_data` attribute:
###Code
print('jacupdate = {0}'.format(p.control_data.jacupdate))
print('numlam = {0}'.format(p.control_data.numlam))
p.control_data.numlam = 100
print('numlam has been changed to --> {0}'.format(p.control_data.numlam))
###Output
_____no_output_____
###Markdown
The `Pst` class also exposes a method to get a new `Pst` instance with a subset of parameters and or obseravtions. Note this method does not propogate prior information to the new instance:
###Code
pnew = p.get(p.par_names[:10],p.obs_names[-10:])
print(pnew.prior_information)
###Output
_____no_output_____
###Markdown
You can also write a pest control file with altered parameters, observations, and/or prior information:
###Code
pnew.write("test.pst")
###Output
_____no_output_____
###Markdown
Some other methods in `Pst` include:
###Code
# add preferred value regularization with weights proportional to parameter bounds
pyemu.utils.helpers.zero_order_tikhonov(pnew)
pnew.prior_information
# add preferred value regularization with unity weights
pyemu.utils.helpers.zero_order_tikhonov(pnew,parbounds=False)
pnew.prior_information
###Output
_____no_output_____
###Markdown
Some more `res` functionality
###Code
# adjust observation weights to account for residual phi components
#pnew = p.get()
print(p.phi, p.nnz_obs, p.phi_components)
p.adjust_weights_discrepancy()
print(p.phi, p.nnz_obs, p.phi_components)
###Output
_____no_output_____
###Markdown
adjust observation weights by an arbitrary amount by groups:
###Code
print(p.phi, p.nnz_obs, p.phi_components)
grp_dict = {"head":100}
p.adjust_weights(obsgrp_dict=grp_dict)
print(p.phi, p.nnz_obs, p.phi_components)
###Output
_____no_output_____
###Markdown
adjust observation weights by an arbitrary amount by individual observations:
###Code
print(p.phi, p.nnz_obs, p.phi_components)
obs_dict = {"h_obs01_1":25}
p.adjust_weights(obs_dict=obs_dict)
print(p.phi, p.nnz_obs, p.phi_components)
###Output
_____no_output_____
###Markdown
setup weights inversely proportional to the observation values
###Code
p.adjust_weights_discrepancy()
print(p.phi, p.nnz_obs, p.phi_components)
p.proportional_weights(fraction_stdev=0.1,wmax=20.0)
print(p.phi, p.nnz_obs, p.phi_components)
###Output
_____no_output_____
###Markdown
The Pst classThe `pst_handler` module contains the `Pst` class for dealing with pest control files. It relies heavily on `pandas` to deal with tabular sections, such as parameters, observations, and prior information.
###Code
from __future__ import print_function
import os
import numpy as np
import pyemu
from pyemu import Pst
###Output
_____no_output_____
###Markdown
We need to pass the name of a pest control file to instantiate:
###Code
pst_name = os.path.join("henry","pest.pst")
p = Pst(pst_name)
###Output
_____no_output_____
###Markdown
All of the relevant parts of the pest control file are attributes of the `pst` class with the same name:
###Code
p.parameter_data.head()
p.observation_data.head()
p.prior_information.head()
###Output
_____no_output_____
###Markdown
A residual file (`.rei` or `res`) can also be passed to the `resfile` argument at instantiation to enable some simple residual analysis and weight adjustments. If the residual file is in the same directory as the pest control file and has the same base name, it will be accessed automatically:
###Code
p.res
###Output
_____no_output_____
###Markdown
The `pst` class has some `@decorated` convience methods related to the residuals:
###Code
print(p.phi,p.phi_components)
###Output
1855.6874378297073 {'conc': 197.05822096106502, 'regul_m': 0.0, 'regul_p': 0.0, 'head': 1658.6292168686423}
###Markdown
Some additional `@decorated` convience methods:
###Code
print(p.npar,p.nobs,p.nprior)
print(p.par_groups,p.obs_groups)
print(type(p.par_names)) # all parameter names
print(type(p.adj_par_names)) # adjustable parameter names
print(type(p.obs_names)) # all observation names
print(type(p.nnz_obs_names)) # non-zero weight observations
###Output
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
###Markdown
The "control_data" section of the pest control file is accessible in the `Pst.control_data` attribute:
###Code
print('jacupdate = {0}'.format(p.control_data.jacupdate))
print('numlam = {0}'.format(p.control_data.numlam))
p.control_data.numlam = 100
print('numlam has been changed to --> {0}'.format(p.control_data.numlam))
###Output
jacupdate = 999
numlam = 10
numlam has been changed to --> 100
###Markdown
The `Pst` class also exposes a method to get a new `Pst` instance with a subset of parameters and or obseravtions. Note this method does not propogate prior information to the new instance:
###Code
pnew = p.get(p.par_names[:10],p.obs_names[-10:])
print(pnew.prior_information)
###Output
equation obgnme pilbl weight names
pilbl
mult1 1.0 * log(mult1) = 0.000000 regul_m mult1 1.0 [mult1]
kr01c01 1.0 * log(kr01c01) = 0.0 regul_p kr01c01 1.0 [kr01c01]
kr01c02 1.0 * log(kr01c02) = 0.0 regul_p kr01c02 1.0 [kr01c02]
kr01c03 1.0 * log(kr01c03) = 0.0 regul_p kr01c03 1.0 [kr01c03]
kr01c04 1.0 * log(kr01c04) = 0.0 regul_p kr01c04 1.0 [kr01c04]
kr01c05 1.0 * log(kr01c05) = 0.0 regul_p kr01c05 1.0 [kr01c05]
kr01c06 1.0 * log(kr01c06) = 0.0 regul_p kr01c06 1.0 [kr01c06]
kr01c07 1.0 * log(kr01c07) = 0.0 regul_p kr01c07 1.0 [kr01c07]
###Markdown
You can also write a pest control file with altered parameters, observations, and/or prior information:
###Code
pnew.write("test.pst")
###Output
/Users/jwhite/anaconda/lib/python3.5/site-packages/pandas/core/indexing.py:337: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[key] = _infer_fill_value(value)
/Users/jwhite/anaconda/lib/python3.5/site-packages/pandas/core/indexing.py:517: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[item] = s
###Markdown
Some other methods in `Pst` include:
###Code
# add preferred value regularization with weights proportional to parameter bounds
pyemu.utils.helpers.zero_order_tikhonov(pnew)
pnew.prior_information
# add preferred value regularization with unity weights
pyemu.utils.helpers.zero_order_tikhonov(pnew,parbounds=False)
pnew.prior_information
###Output
_____no_output_____
###Markdown
Some more `res` functionality
###Code
# adjust observation weights to account for residual phi components
#pnew = p.get()
print(p.phi, p.nnz_obs, p.phi_components)
p.adjust_weights_resfile()
print(p.phi, p.nnz_obs, p.phi_components)
###Output
1855.6874378297073 36 {'conc': 197.05822096106502, 'regul_m': 0.0, 'regul_p': 0.0, 'head': 1658.6292168686423}
36.0 36 {'conc': 15.000000000000004, 'regul_m': 0.0, 'regul_p': 0.0, 'head': 21.0}
###Markdown
adjust observation weights by an arbitrary amount by groups:
###Code
print(p.phi, p.nnz_obs, p.phi_components)
grp_dict = {"head":100}
p.adjust_weights(obsgrp_dict=grp_dict)
print(p.phi, p.nnz_obs, p.phi_components)
###Output
36.0 36 {'conc': 15.000000000000004, 'regul_m': 0.0, 'regul_p': 0.0, 'head': 21.0}
114.99999999999997 36 {'conc': 15.000000000000004, 'regul_m': 0.0, 'regul_p': 0.0, 'head': 99.99999999999997}
###Markdown
adjust observation weights by an arbitrary amount by individual observations:
###Code
print(p.phi, p.nnz_obs, p.phi_components)
obs_dict = {"h_obs01_1":25}
p.adjust_weights(obs_dict=obs_dict)
print(p.phi, p.nnz_obs, p.phi_components)
###Output
114.99999999999997 36 {'conc': 15.000000000000004, 'regul_m': 0.0, 'regul_p': 0.0, 'head': 99.99999999999997}
138.82580701146588 36 {'conc': 15.000000000000004, 'regul_m': 0.0, 'regul_p': 0.0, 'head': 123.82580701146588}
###Markdown
setup weights inversely proportional to the observation values
###Code
p.adjust_weights_resfile()
print(p.phi, p.nnz_obs, p.phi_components)
p.proportional_weights(fraction_stdev=0.1,wmax=20.0)
print(p.phi, p.nnz_obs, p.phi_components)
###Output
36.0 36 {'conc': 14.999999999999998, 'regul_m': 0.0, 'regul_p': 0.0, 'head': 21.0}
222.96996562151 36 {'conc': 194.30909581453392, 'regul_m': 0.0, 'regul_p': 0.0, 'head': 28.66086980697609}
|
notebooks/ClusteredMarker_and_FeatureGroup.ipynb | ###Markdown
create a group with the name of every filter
###Code
feature_group_active = folium.FeatureGroup(name='Active')
feature_group_unactive = folium.FeatureGroup(name='Unactive')
###Output
_____no_output_____
###Markdown
separate each of them in their own markerCluster
###Code
marker_cluster_active = folium.MarkerCluster()
marker_cluster_unactive =folium.MarkerCluster()
for site in data_sites:
if(site["status"]=="is_active"):
marker_active = folium.Marker(site["coordinates"],popup="OK",icon = folium.Icon(color='green',icon='ok-sign'))
marker_cluster_active.add_child(marker_active)
else:
marker_unactive = folium.Marker(site["coordinates"],popup="KO",icon = folium.Icon(color='red',icon='exclamation-sign'))
marker_cluster_unactive.add_child(marker_unactive)
###Output
_____no_output_____
###Markdown
add filter to specific cluster
###Code
feature_group_active.add_child(marker_cluster_active)
feature_group_unactive.add_child(marker_cluster_unactive)
###Output
_____no_output_____
###Markdown
add filter to map
###Code
map_1.add_child(feature_group_active)
map_1.add_child(feature_group_unactive)
###Output
_____no_output_____
###Markdown
toogle to display some marker
###Code
map_1.add_child(folium.LayerControl())
map_1
###Output
_____no_output_____ |
Restricted Boltzmann Machines/RBM.ipynb | ###Markdown
IMPORTING LIBRARIES
###Code
import numpy as np
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
IMPORTING DATASETS
###Code
data = np.load("train_images.npy")
###Output
_____no_output_____
###Markdown
RBM ARCHITECTURE
###Code
class RBM():
def __init__(self, v_size=784, h_size=256, k=1, lr=0.1):
super(RBM, self).__init__()
self.v = np.random.randn(1, v_size)
self.h = np.random.randn(1, h_size)
self.W = np.random.randn(h_size, v_size)
self.v_bias = np.zeros((1, v_size))
self.h_bias = np.zeros((1, h_size))
self.k = k
self.lr = lr
def sigmoid(self, x):
return 1.0/(1 + np.exp(-x))
def sample_h_given_v(self, vis):
htensor = np.matmul(vis, self.W.T) + self.h_bias
activation = self.sigmoid(htensor)
sampled_h = np.random.binomial(size=activation.shape, n = 1, p = activation)
return activation, sampled_h
def sample_v_given_h(self, hid):
vtensor = np.matmul(hid, self.W) + self.v_bias
activation = self.sigmoid(vtensor)
sampled_v = np.random.binomial(size=activation.shape, n = 1, p = activation)
return activation, sampled_v
def energy(self, vis):
_, hidden = self.sample_h_given_v(vis)
val = -np.matmul(vis, self.v_bias.T)-np.matmul(hidden, self.h_bias.T)-np.matmul(np.matmul(hidden, self.W), vis.T)
return val
def contrastive_divergence(self,input_data):
sample_v = input_data
for i in range(self.k):
pre_h, sample_h = self.sample_h_given_v(sample_v)
pre_v, sample_v = self.sample_v_given_h(sample_h)
pre_h_tilde, sample_h_tilde = self.sample_h_given_v(pre_v)
self.W += self.lr * (np.matmul(pre_h.T, input_data) - np.matmul(pre_h_tilde.T, pre_v))
self.v_bias += self.lr * (input_data - pre_v)
self.h_bias += self.lr*(pre_h - pre_h_tilde)
return pre_v
def train(self, data, epochs=1):
for epoch in range(epochs):
print("Epoch: ",epoch+1)
for i,image in enumerate(data):
image = image/255
image = np.reshape(image,(1,784))
_ = self.contrastive_divergence(image)
if i%1000 == 0:
print(i," ",self.energy(image))
def reconstruct(self, test_img):
for i in range(self.k):
pre_h, sample_h = self.sample_h_given_v(test_img)
pre_v, sample_v = self.sample_v_given_h(sample_h)
return sample_v
###Output
_____no_output_____
###Markdown
TESTING
###Code
rbm = RBM(k=1)
rbm.train(data[:20000],epochs=1)
b = data[1000]
b = b.reshape(1,784)
b.shape
plt.imshow(np.reshape(b,(28,28)),cmap='gray')
new_b = rbm.reconstruct(b)
plt.imshow(np.reshape(new_b,(28,28)),cmap='gray')
c = data[1004]
c = c.reshape(1,784)
c.shape
plt.imshow(np.reshape(c,(28,28)),cmap='gray')
new_c = rbm.reconstruct(c)
plt.imshow(np.reshape(new_c,(28,28)),cmap='gray')
b = data[1000]
b = b.reshape(1,784)
b.shape
plt.imshow(np.reshape(b,(28,28)),cmap='gray')
clip_b = [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 146,
254, 255, 251, 95, 6, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 97,
234, 254, 254, 232, 254, 254, 35, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 89,
140, 254, 254, 174, 67, 33, 200, 254, 190, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
108, 253, 254, 235, 51, 1, 0, 0, 12, 254, 253, 56, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 12, 216, 254, 244, 55, 0, 0, 0, 0, 6, 213, 254,
57, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 25, 254, 254, 132, 0, 0, 0, 0, 0, 0,
168, 254, 57, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 45, 254, 243, 34, 0, 0, 0, 0,
0, 0, 168, 254, 57, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 128, 254, 157, 0, 0, 0,
0, 0, 0, 0, 168, 254, 57, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 19, 228, 254, 105, 0,
0, 0, 0, 0, 0, 7, 0, 0, 57, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, 254, 254,
87, 0, 0, 0, 0, 0, 0, 10, 0, 0, 47, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58,
0, 0, 9, 0, 0, 0, 0, 0, 0, 10, 0, 210, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 58, 0, 0, 9, 0, 0, 0, 0, 0, 0, 105, 0,
91, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 5, 0, 0, 9, 0, 0, 0, 0, 0, 24,
0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0,
0, 84, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0]]
plt.imshow(np.reshape(clip_b,(28,28)),cmap='gray')
reconstruct_b = rbm.reconstruct(clip_b)
plt.imshow(np.reshape(reconstruct_b,(28,28)),cmap='gray')
###Output
C:\Users\vasuk\AppData\Roaming\Python\Python36\site-packages\ipykernel_launcher.py:14: RuntimeWarning: overflow encountered in exp
|
Basic Data Types & Objects.ipynb | ###Markdown
Numbers
###Code
a = 10
b = 10.3
type(a)
type(b)
c =12
a*b
a/b
a//b
d=34
d//a
d%a
2**3
###Output
_____no_output_____
###Markdown
Strings
###Code
'Hello'
"Hello"
print ("Hello World!")
a="Kumaran"
a[3]
a[1:]
a[-1]
a[:-1]
a[:]
a[::-1]
a[::2]
a[::3]
a.count('a')
a.title()
a="kumaran systems"
a.title()
a.format()
a.find()
a.encode()
a='KuMaRan'
a.format()
help(a.find())
a.find('a')
print(a)
a="Kumaran System"
print(a)
a.split('m')
'insert some value in the string : {}'.format('The formated String')
'insert some value in the string : {} {} {}'.format(12,13,14)
###Output
_____no_output_____
###Markdown
List Objects
###Code
my_list=['a','b','c','d','e','f']
print(my_list)
my_list.append(1)
my_list
my_list.pop()
my_list
my_list.pop()
my_list.append('f')
my_list
help(my_list.index)
my_list.count('e')
my_list[::-2]
my_list[:1]
my_list=[[1,2,3],[4,5,6],[7,8,9]]
[row[1] for row in my_list]
###Output
_____no_output_____
###Markdown
Dictionary
###Code
my_dict = {"key1":"value1","key2":2,"key3":[4,5,6], "key4":True}
my_dict.items()
my_dict
my_dict.keys()
my_dict.values()
type(my_dict.get('ke1'))
my_dict('key1')
###Output
_____no_output_____
###Markdown
Tuples
###Code
t=(1,2,3,4)
t.count(1)
t.index(1)
t[1]
a=(my_list)
a
###Output
_____no_output_____
###Markdown
Sets
###Code
my_set={1,2,3,4,5,6,1,2,3}
my_set
my_set.difference()
my_set.difference_update()
my_set
my_set.symmetric_difference('7')
my_set.issuperset('2')
###Output
_____no_output_____
###Markdown
Boolean
###Code
True
False
not True
not False
###Output
_____no_output_____
###Markdown
Numbers
###Code
#"Basic Arithmetic Operation"
a=10
b=10.3
type(b)
c=12
a+b
a*b
a/b
d=34
d//a
d%a
10**2
"Hello"
a='kumran'
a[1:]
a[3]
a[-1:]
a[:]
a[::1]
a.count('k')
a.split('u')
a.lower()
a.upper()
a.replace('u','F')
a.translate('KRISHNA')
a.index('u')
'test string {}'.format([1,100])
print('LIST OBJECTS')
my_list = ['a','f','c','d','e','b']
my_list.sort()
my_list
my_list.pop(1)
my_list
my_list.extend([1,2,3,4,5])
my_list = [[1,2,3],[4,5,6],[7,9,9]]
[row[0] for row in my_list]
#Dictionary
my_dict = {"key1":"value","key2":2,"key3":[4,5,6],"key4":True}
my_dict['key1']
my_dict['key4']
my_dict2 ={'key5':100.00}
my_dict.update(my_dict2)
my_dict
my_dict.keys()
my_dict.items()
my_tuple = (1,2,3,4)
my_tuple.count(False)
my_set = {1,2,2,3,4,5,6,7,8,9}
my_set2 = {10,11,11,12,13}
my_set.update(my_set2)
my_set
my_set.intersection(my_set2)
#Boolean
my_bool = False
not my_bool
my_bool
my_bool.bit_length()
###Output
_____no_output_____
###Markdown
Number
###Code
12
any_number = 45
my_num = 56
any_number + my_num
any_number - my_num
any_number * my_num
my_num / any_number
type(any_number)
my_float_num = 12.45
type(my_float_num)
my_float_an_num = 12.78
my_float_num * my_float_an_num
###Output
_____no_output_____
###Markdown
Strings
###Code
my_str = "hi Friends, How are you All ?"
my_str
my_str[0]
my_str[::-1]
#String Slicing & Addressing
_initalAddress_ = 0
_EndingAddress_ = -1
_increment_ = 1
my_str[_initalAddress_:_EndingAddress_:_increment_]
cipher = "HXA IAB FZC CVN SAI"
cipher[0::4]
my_str = "hi Friends, How are you All ?"
my_str
my_str = my_str.capitalize()
my_str.
help(my_str.isspace)
ny_str = " "
ny_str.isspace()
my_num = "23.3"
my_num.islower()
my_str
my_str.partition('i')
my_str.split('i')
my_str = "Hi Friends, How Are You All ?"
my_str.strip('')
my_str.istitle()
my_str.swapcase()
my_str
type(my_str)
my_en_str = my_str.encode()
type(my_en_str)
my_en_str
my_de_str = my_en_str.decode()
type(my_de_str)
my_de_str
len(my_str)
help(my_str.translate)
###Output
Help on built-in function translate:
translate(table, /) method of builtins.str instance
Replace each character in the string using the given translation table.
table
Translation table, which must be a mapping of Unicode ordinals to
Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a
dictionary or list. If this operation raises LookupError, the character is
left untouched. Characters mapped to None are deleted.
###Markdown
Lists
###Code
my_list = [1,2,3,4,5,6,7,8,9,10]
len(my_list)
my_list[0]
my_list[::-1]
###Output
_____no_output_____
###Markdown
Dicts
###Code
my_dicts = {"key1":"value1","key2":23,"key3":56.7,
"key4":[1,25,3,[8,9]]}
my_dicts.get("key4")[3][1]
my_dicts['key4'][3][1]
my_dicts.fromkeys("key",67)
my_list = ["key1","key2","key3"]
my_Vlist = 45
my_dicts.fromkeys(my_list,my_Vlist)
my_dicts
my_dicts1.update(my_dicts)
###Output
_____no_output_____ |
Experiments/Asteroid_3DOF/Asteroid_PV_sphere/MLP-sphere-test_nutation.ipynb | ###Markdown
Test Recurrent Policy with Extreme Parameter Variation
###Code
import numpy as np
import os,sys
sys.path.append('../../../RL_lib/Agents/PPO')
sys.path.append('../../../RL_lib/Utils')
sys.path.append('../../../RL_lib/Models')
sys.path.append('../../../Asteroid3dof_env')
%load_ext autoreload
%load_ext autoreload
%autoreload 2
%matplotlib nbagg
import os
print(os.getcwd())
%%html
<style>
.output_wrapper, .output {
height:auto !important;
max-height:1000px; /* your desired max-height here */
}
.output_scroll {
box-shadow:none !important;
webkit-box-shadow:none !important;
}
</style>
###Output
_____no_output_____
###Markdown
Optimize Policy
###Code
from env import Env
import env_utils as envu
from dynamics_model_wo import Dynamics_model
from lander_model import Lander_model
from ic_gen_sphere import Landing_icgen
import rl_utils
from arch_policy_vf import Arch
from model import Model
from policy import Policy
from value_function import Value_function
import pcm_model_nets as model_nets
import policy_nets as policy_nets
import valfunc_nets as valfunc_nets
from agent import Agent
import torch.nn as nn
from flat_constraint import Flat_constraint
from glideslope_constraint import Glideslope_constraint
from reward_terminal_mdr import Reward
logger = rl_utils.Logger()
dynamics_model = Dynamics_model(landing_target=np.asarray([0., 0., 250.]))
lander_model = Lander_model(apf_tau1=300, apf_tau2=300, apf_vf1=-0.2, apf_vf2=-0.01, apf_atarg=20, apf_v0=1.0,
sensor_bias_range=(-0.0,0.0))
lander_model.min_thrust = 0
lander_model.max_thrust = 2
lander_model.get_state_agent = lander_model.get_state_agent2
lander_model.apf_pot = lander_model.apf_pot2
obs_dim = 4
act_dim = 3
recurrent_steps = 1
reward_object = Reward(landing_coeff=10.0, landing_rlimit=1, landing_vlimit=0.2,
tracking_coeff=-1.00, fuel_coeff=-0.01, landing_gslimit=-1)
glideslope_constraint = Glideslope_constraint(gs_limit=-1.0)
shape_constraint = Flat_constraint()
env = Env(lander_model,dynamics_model,logger,
reward_object=reward_object,
glideslope_constraint=glideslope_constraint,
shape_constraint=shape_constraint,
tf_limit=5000.0,print_every=10,
nav_period=6)
min_w = -1.0e-3
max_w = 1.0e-3
env.ic_gen = Landing_icgen(adjust_apf_v0=False,
position_theta=(0,np.pi/4),
min_mass = 450, max_mass=500,
min_w=(min_w,min_w,min_w), max_w=(max_w,max_w,max_w))
env.ic_gen.show()
arch = Arch()
policy = Policy(policy_nets.MLP1(obs_dim, act_dim), shuffle=True,
kl_targ=0.001,epochs=20, beta=0.1, servo_kl=True, max_grad_norm=30,
init_func=rl_utils.xn_init, discretize=True)
value_function = Value_function(valfunc_nets.MLP1(obs_dim),
shuffle=True, batch_size=256, max_grad_norm=30)
agent = Agent(arch, policy, value_function, None, env, logger,
policy_episodes=30, policy_steps=3000, gamma1=0.95, gamma2=0.995, lam=0.98,
recurrent_steps=recurrent_steps, monitor=env.rl_stats)
fname = "MLP-sphere"
policy.load_params(fname)
value_function.load_params(fname)
###Output
3-dof dynamics model
lander model apf
Glideslope Constraint: delta = 3
Flat Constraint
###Markdown
Test Policy
###Code
print(1)
policy.test_mode=True
env.test_policy_batch(agent,10000,print_every=100)
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
def plot_trajectories(trajectory_list, linewidth=0.1,
min_axislimit=(-1200.,-1200.,-600.), max_axislimit=(1200,1200,1200),
r_ast=250., target_loc=np.asarray([0.,0.,250.])):
plt.clf()
fig = plt.figure(11)
ax = fig.gca(projection='3d')
pi = np.pi
phi, theta = np.mgrid[0.0:pi:100j, 0.0:2.0*pi:100j]
x = r_ast*np.sin(phi)*np.cos(theta)
y = r_ast*np.sin(phi)*np.sin(theta)
z = r_ast*np.cos(phi)
ax.plot_surface( x,y,z, linewidth=0, antialiased=False, shade=True, color='gray')
rf_list = []
vf_list = []
ff_list = []
for i in range(len(trajectory_list)):
plot_traj( ax, trajectory_list[i],target_loc, linewidth=linewidth)
rf_list.append(trajectory_list[i]['norm_rf'][-1])
vf_list.append(trajectory_list[i]['norm_vf'][-1] * 100.)
#print('foo: ', trajectory_list[i]['norm_vf'][-1])
ff_list.append(trajectory_list[i]['fuel'][-1])
#print(np.asarray(vf_list))
ax.legend
fig.canvas.draw()
plt.show()
ax.set_xlim3d(min_axislimit[0], max_axislimit[0])
ax.set_ylim3d(min_axislimit[1], max_axislimit[1])
ax.set_zlim3d(min_axislimit[2], max_axislimit[2])
ax.set_xlabel('X (m)')
ax.set_ylabel('Y (m)')
ax.set_zlabel('Z (m)')
#s = '100 Random Trajectories Executed in \nEnvironment with Unknown Dynamics'
#plt.figtext(0.25,0.3, s , style='normal',fontsize=11,
# bbox={'facecolor':'white', 'alpha':1.0, 'pad':10})
def plot_traj( ax, trajectory, target_loc, linewidth=0.1):
pos = np.asarray(trajectory['position'])
pos += target_loc
ax.plot(pos[:,0],pos[:,1],pos[:,2],linewidth=linewidth)
plot_trajectories(lander_model.trajectory_list,linewidth=0.5)
len(lander_model.trajectory_list)
traj_list = lander_model.trajectory_list[0:100]
len(traj_list)
np.save(fname + '_100traj',traj_list)
envu.plot_rf_vf(env.rl_stats.history)
policy.test_mode=True
env.ic_gen.min_w=(-1.1e-3,-1.1e-3,1.1e-3)
v1 = -0.05
v2 = -0.05
v3 = 0.05
env.ic_gen.velocity_x=(v1,v1)
env.ic_gen.velocity_y=(v2,v2)
env.ic_gen.velocity_z=(v3,v3)
env.ic_gen.M = (20e10,20e10)
env.ic_gen.max_w = env.ic_gen.min_w
env.test_policy_batch(agent,1000,print_every=100)
print(np.linalg.norm(dynamics_model.max_disturbance))
###Output
Dynamics: Max Disturbance (m/s^2): [0.00346957 0.00323558 0.00388835] 0.006134020850947553
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
i : 100
Cumulative Stats (mean,std,max,argmax)
thrust | 1.69 | 1.20 | 0.00 | 3.46 | 0
glideslope |10.747 |24.017 | 0.086 |273.633 | 78
sc_margin |100.000 | 0.000 |100.000 |100.000 | 0
Final Stats (mean,std,min,max)
norm_vf | 0.021 | 0.008 | 0.005 | 0.046
norm_rf | 0.1 | 0.0 | 0.0 | 0.2
position | 0.0 0.0 -0.0 | 0.1 0.1 0.0 | -0.1 -0.1 -0.0 | 0.2 0.1 -0.0
velocity | -0.003 0.002 -0.015 | 0.011 0.011 0.006 | -0.030 -0.035 -0.031 | 0.025 0.029 -0.003
fuel | 1.40 | 0.16 | 1.05 | 1.77
glideslope | 4.15 | 3.97 | 1.05 | 26.74
Dynamics: Max Disturbance (m/s^2): [0.00356067 0.00323558 0.00388835] 0.006186007801595387
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
Dynamics: Max Disturbance (m/s^2): [0.00357417 0.00323558 0.00388835] 0.006193785202431892
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
i : 200
Cumulative Stats (mean,std,max,argmax)
thrust | 1.68 | 1.20 | 0.00 | 3.46 | 0
glideslope |11.342 |24.796 | 0.086 |464.168 | 134
sc_margin |100.000 | 0.000 |100.000 |100.000 | 0
Final Stats (mean,std,min,max)
norm_vf | 0.020 | 0.008 | 0.004 | 0.046
norm_rf | 0.1 | 0.0 | 0.0 | 0.2
position | 0.0 0.0 -0.0 | 0.1 0.1 0.0 | -0.1 -0.1 -0.0 | 0.2 0.2 -0.0
velocity | -0.003 0.002 -0.014 | 0.010 0.010 0.007 | -0.030 -0.035 -0.031 | 0.025 0.030 -0.001
fuel | 1.40 | 0.16 | 0.90 | 1.77
glideslope | 4.38 | 4.44 | 1.05 | 38.46
Dynamics: Max Disturbance (m/s^2): [0.00357417 0.00324243 0.00391065] 0.006211378204973071
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
i : 300
Cumulative Stats (mean,std,max,argmax)
thrust | 1.68 | 1.20 | 0.00 | 3.46 | 0
glideslope |11.565 |25.162 | 0.086 |464.571 | 241
sc_margin |100.000 | 0.000 |100.000 |100.000 | 0
Final Stats (mean,std,min,max)
norm_vf | 0.020 | 0.007 | 0.004 | 0.046
norm_rf | 0.1 | 0.0 | 0.0 | 0.2
position | 0.0 0.0 -0.0 | 0.1 0.0 0.0 | -0.1 -0.1 -0.0 | 0.2 0.2 -0.0
velocity | -0.004 0.001 -0.014 | 0.010 0.010 0.006 | -0.030 -0.035 -0.031 | 0.025 0.030 -0.000
fuel | 1.41 | 0.16 | 0.90 | 1.77
glideslope | 4.35 | 4.45 | 1.03 | 38.46
Dynamics: Max Disturbance (m/s^2): [0.00357417 0.00324243 0.00391065] 0.006211378204973071
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
i : 400
Cumulative Stats (mean,std,max,argmax)
thrust | 1.68 | 1.20 | 0.00 | 3.46 | 0
glideslope |11.631 |27.904 | 0.073 |2018.901 | 340
sc_margin |100.000 | 0.000 |100.000 |100.000 | 0
Final Stats (mean,std,min,max)
norm_vf | 0.020 | 0.007 | 0.004 | 0.046
norm_rf | 0.1 | 0.0 | 0.0 | 0.2
position | 0.0 0.0 -0.0 | 0.1 0.0 0.0 | -0.1 -0.1 -0.0 | 0.2 0.2 -0.0
velocity | -0.003 0.001 -0.014 | 0.010 0.010 0.007 | -0.030 -0.036 -0.031 | 0.025 0.030 -0.000
fuel | 1.40 | 0.15 | 0.90 | 1.77
glideslope | 4.30 | 4.38 | 0.96 | 38.46
Dynamics: Max Disturbance (m/s^2): [0.0035857 0.00324531 0.00391065] 0.0062195248201067695
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
i : 500
Cumulative Stats (mean,std,max,argmax)
thrust | 1.69 | 1.20 | 0.00 | 3.46 | 0
glideslope |11.412 |27.213 | 0.073 |2018.901 | 340
sc_margin |100.000 | 0.000 |100.000 |100.000 | 0
Final Stats (mean,std,min,max)
norm_vf | 0.020 | 0.007 | 0.004 | 0.046
norm_rf | 0.1 | 0.0 | 0.0 | 0.2
position | 0.0 0.0 -0.0 | 0.1 0.0 0.0 | -0.1 -0.1 -0.0 | 0.2 0.2 -0.0
velocity | -0.003 -0.000 -0.014 | 0.010 0.011 0.007 | -0.030 -0.036 -0.032 | 0.025 0.030 -0.000
fuel | 1.41 | 0.15 | 0.90 | 1.77
glideslope | 4.17 | 4.13 | 0.96 | 38.46
Dynamics: Max Disturbance (m/s^2): [0.0035857 0.00324531 0.00391065] 0.0062195248201067695
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
i : 600
Cumulative Stats (mean,std,max,argmax)
thrust | 1.68 | 1.20 | 0.00 | 3.46 | 0
glideslope |11.474 |27.072 | 0.073 |2018.901 | 340
sc_margin |100.000 | 0.000 |100.000 |100.000 | 0
Final Stats (mean,std,min,max)
norm_vf | 0.020 | 0.007 | 0.004 | 0.046
norm_rf | 0.1 | 0.0 | 0.0 | 0.2
position | 0.0 0.0 -0.0 | 0.1 0.0 0.0 | -0.1 -0.1 -0.0 | 0.2 0.2 -0.0
velocity | -0.003 -0.000 -0.014 | 0.010 0.011 0.006 | -0.030 -0.036 -0.032 | 0.025 0.030 -0.000
fuel | 1.40 | 0.15 | 0.90 | 1.77
glideslope | 4.35 | 4.52 | 0.96 | 41.37
Dynamics: Max Disturbance (m/s^2): [0.0035857 0.00324531 0.00391065] 0.0062195248201067695
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
i : 700
Cumulative Stats (mean,std,max,argmax)
thrust | 1.68 | 1.20 | 0.00 | 3.46 | 0
glideslope |11.523 |30.281 | 0.073 |5846.014 | 694
sc_margin |100.000 | 0.000 |100.000 |100.000 | 0
Final Stats (mean,std,min,max)
norm_vf | 0.020 | 0.007 | 0.004 | 0.046
norm_rf | 0.1 | 0.0 | 0.0 | 0.2
position | 0.0 0.0 -0.0 | 0.1 0.0 0.0 | -0.1 -0.1 -0.0 | 0.2 0.2 -0.0
velocity | -0.003 -0.000 -0.014 | 0.010 0.011 0.006 | -0.030 -0.036 -0.032 | 0.025 0.030 -0.000
fuel | 1.40 | 0.15 | 0.90 | 1.77
glideslope | 4.31 | 4.41 | 0.96 | 41.37
Dynamics: Max Disturbance (m/s^2): [0.0035857 0.00328068 0.00391065] 0.006238054321431894
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
i : 800
Cumulative Stats (mean,std,max,argmax)
thrust | 1.68 | 1.20 | 0.00 | 3.46 | 0
glideslope |11.394 |29.556 | 0.073 |5846.014 | 694
sc_margin |100.000 | 0.000 |100.000 |100.000 | 0
Final Stats (mean,std,min,max)
norm_vf | 0.020 | 0.007 | 0.004 | 0.046
norm_rf | 0.1 | 0.0 | 0.0 | 0.2
position | 0.0 0.0 -0.0 | 0.1 0.0 0.0 | -0.1 -0.1 -0.0 | 0.2 0.2 -0.0
velocity | -0.003 -0.000 -0.014 | 0.010 0.011 0.007 | -0.030 -0.036 -0.032 | 0.025 0.030 -0.000
fuel | 1.40 | 0.15 | 0.90 | 1.77
glideslope | 4.30 | 4.41 | 0.87 | 41.37
Dynamics: Max Disturbance (m/s^2): [0.0035931 0.00328068 0.00391065] 0.006242312017234802
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
Dynamics: Max Disturbance (m/s^2): [0.0035931 0.00328354 0.00398555] 0.006290991235254056
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
i : 900
Cumulative Stats (mean,std,max,argmax)
thrust | 1.68 | 1.20 | 0.00 | 3.46 | 0
glideslope |11.265 |28.960 | 0.073 |5846.014 | 694
sc_margin |100.000 | 0.000 |100.000 |100.000 | 0
Final Stats (mean,std,min,max)
norm_vf | 0.020 | 0.007 | 0.002 | 0.046
norm_rf | 0.1 | 0.0 | 0.0 | 0.2
position | 0.0 0.0 -0.0 | 0.1 0.0 0.0 | -0.1 -0.1 -0.0 | 0.2 0.2 -0.0
velocity | -0.003 -0.000 -0.014 | 0.010 0.011 0.006 | -0.030 -0.036 -0.032 | 0.028 0.030 -0.000
fuel | 1.40 | 0.15 | 0.90 | 1.82
glideslope | 4.26 | 4.47 | 0.87 | 45.93
Dynamics: Max Disturbance (m/s^2): [0.0035931 0.00329028 0.00398555] 0.006294512242000453
Dynamics: Max w: [-0.0011 -0.0011 0.0011]
Cumulative Stats (mean,std,max,argmax)
thrust | 1.68 | 1.20 | 0.00 | 3.46 | 0
glideslope |11.324 |28.576 | 0.073 |5846.014 | 694
sc_margin |100.000 | 0.000 |100.000 |100.000 | 0
Final Stats (mean,std,min,max)
norm_vf | 0.020 | 0.007 | 0.002 | 0.046
norm_rf | 0.1 | 0.0 | 0.0 | 0.2
position | 0.0 0.0 -0.0 | 0.0 0.0 0.0 | -0.1 -0.1 -0.0 | 0.2 0.2 -0.0
velocity | -0.003 -0.000 -0.014 | 0.010 0.010 0.006 | -0.032 -0.036 -0.032 | 0.028 0.030 -0.000
fuel | 1.40 | 0.15 | 0.90 | 1.82
glideslope | 4.34 | 4.70 | 0.87 | 45.93
Initial Stats (mean,std,min,max)
|
coco_extract_subset.ipynb | ###Markdown
Extract annotations from COCO Dataset annotation fileThis notebook was created to answer a question from stackoverflow: [https://stackoverflow.com/questions/69722538/extract-annotations-from-coco-dataset-annotation-file](https://stackoverflow.com/questions/69722538/extract-annotations-from-coco-dataset-annotation-file)> I want to train on a subset of COCO dataset. For the images, I have created a folder of first 30k images of train2017 folder. Now I need annotations of those 30k images (extracted from instances_train2017.json) in a separate json file so that I can train it. How can I do it?The reason for the question is that Coco stores all of the annotations in one long json file, so there is no simple way to extract only the ones that you need. PyLabel can help with this task by importing the dataset, filtering the annotations to the images you care about, and then exporting back to a coco json file.
###Code
import logging
logging.getLogger().setLevel(logging.CRITICAL)
!pip install pylabel > /dev/null
from pylabel import importer
###Output
_____no_output_____
###Markdown
Download sample dataset For this example we can use a sample dataset stored in coco format. The general approach can later be applied to the full coco dataset.
###Code
import os
import zipfile
#Download and import sample coco dataset
os.makedirs("data", exist_ok=True)
!wget "https://github.com/pylabelalpha/notebook/blob/main/BCCD_coco.zip?raw=true" -O data/BCCD_coco.zip
with zipfile.ZipFile("data/BCCD_coco.zip", 'r') as zip_ref:
zip_ref.extractall("data")
#Specify path to the coco.json file
path_to_annotations = "data/BCCD_Dataset.json"
#Specify the path to the images (if they are in a different folder than the annotations)
path_to_images = ""
#Import the dataset into the pylable schema
dataset = importer.ImportCoco(path_to_annotations, path_to_images=path_to_images, name="BCCD_coco")
dataset.df.head(5)
###Output
--2021-11-01 07:52:48-- https://github.com/pylabelalpha/notebook/blob/main/BCCD_coco.zip?raw=true
Resolving github.com (github.com)... 192.30.255.112
Connecting to github.com (github.com)|192.30.255.112|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://github.com/pylabelalpha/notebook/raw/main/BCCD_coco.zip [following]
--2021-11-01 07:52:48-- https://github.com/pylabelalpha/notebook/raw/main/BCCD_coco.zip
Reusing existing connection to github.com:443.
HTTP request sent, awaiting response... 302 Found
Location: https://raw.githubusercontent.com/pylabelalpha/notebook/main/BCCD_coco.zip [following]
--2021-11-01 07:52:48-- https://raw.githubusercontent.com/pylabelalpha/notebook/main/BCCD_coco.zip
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 7625693 (7.3M) [application/zip]
Saving to: ‘data/BCCD_coco.zip’
data/BCCD_coco.zip 100%[===================>] 7.27M 21.2MB/s in 0.3s
2021-11-01 07:52:50 (21.2 MB/s) - ‘data/BCCD_coco.zip’ saved [7625693/7625693]
###Markdown
PyLabel imports the annotations into a pandas dataframe. Now you can filter this dataframe to the rows related to the images that you care about. There are 364 images in this dataset.
###Code
print(f"Number of images: {dataset.analyze.num_images}")
print(f"Class counts:\n{dataset.analyze.class_counts}")
###Output
Number of images: 364
Class counts:
RBC 4155
WBC 372
Platelets 361
Name: cat_name, dtype: int64
###Markdown
Extract imagesLets copy some images to another directory to to represent the images that we care about.
###Code
#Copy 100 images from the BCCD_Dataset/BCCD/JPEGImages/ to BCCD_Dataset/BCCD/100Images/
!mkdir data/100Images/
!ls data/*.jpg | head -100 | xargs -I{} cp {} data/100Images/
###Output
mkdir: data/100Images/: File exists
###Markdown
Create a list with all of the files in this directory.
###Code
#Store a list of all of the files in the directory
files = sorted(os.listdir('data/100Images/'))
print(f"{len(files)} files including {files[0]}")
###Output
100 files including BloodImage_00000.jpg
###Markdown
Now filter the dataframe to only images in the list of files.
###Code
dataset.df = dataset.df[dataset.df.img_filename.isin(files)].reset_index()
print(f"Number of images {dataset.df.img_filename.nunique()}")
###Output
Number of images 100
###Markdown
Export annotations back as a coso json file
###Code
dataset.path_to_annotations = 'data/100Images/'
dataset.name = '100Images_coco'
dataset.export.ExportToCoco()
###Output
_____no_output_____ |
exercises/zero/solutions/Damenproblem_Musterloesung.ipynb | ###Markdown
DamenproblemQuelle: https://de.wikipedia.org/wiki/DamenproblemEs sollen jeweils $m$ Damen auf einem $n$ x $n$-Schachbrett so aufgestellt werden, dass keine zwei Damen einander gemäß ihren in den Schachregeln definierten Zugmöglichkeiten schlagen können. Hilfsfunktionen
###Code
def buchstaben(n):
return [(chr(ord('A') + i)) for i in range(n)]
def zahlen(n):
return range(1, n + 1)
def schachbrett(n):
spielfeld = set()
for zahl in zahlen(n):
spielfeld = spielfeld.union(
tuple(zip(buchstaben(n), [zahl for i in range(n)])))
return spielfeld
def geschlagene_felder(dame=('A', 1), schachbrett=schachbrett(8)):
# Damen schlagen sich, wenn x1 == x2 oder y1 == y2 oder |x1 - x2| == |y1 -y2|
x1 = ord(dame[0])
y1 = dame[1]
felder = set()
for feld in schachbrett:
x2 = ord(feld[0])
y2 = feld[1]
if x1 == x2 or y1 == y2 or abs(x1 - x2) == abs(y1 - y2):
felder.add(feld)
return felder
###Output
_____no_output_____
###Markdown
Ihre Lösung
###Code
def damenproblem(damen=8, schachbrett=schachbrett(8), positionen=set()):
"""
Findet eine Lösung des Damenproblems.
> damenproblem(damen=2, schachbrett=schachbrett(4))
('A1', 'B3')
"""
if damen == 0: # sind alle Damen platziert?
return positionen
if len(schachbrett) == 0: # gibt es noch Platz? Wenn nicht, war dieser Zweig eine Sackgasse.
return False
for dame in schachbrett: # auf allen freien Positionen versuchen wir nun, eine Dame zu platzieren
spielfeld_neu = schachbrett.copy()
spielfeld_neu.remove(dame)
positionen_neu = positionen.copy()
positionen_neu.add(dame) # und diese Position speichern
geschlagen = geschlagene_felder(dame, spielfeld_neu)
spielfeld_neu = spielfeld_neu.difference(geschlagen) # Restspielfeld berechnen, indem geschlagene Felder entfernt werden
gefunden = damenproblem(damen-1, spielfeld_neu, positionen_neu) # wir suchen nur eine Lösung, deshalb brechen wir die Schleife dann ab.
if gefunden: break
return gefunden
run_docstring_examples(damenproblem, locals())
###Output
_____no_output_____
###Markdown
Lösung anwenden
###Code
m = 8
n = 8
loesung = damenproblem(m, schachbrett(n))
print("Eine Lösung, um {m} Damen auf einem Schachfeld der Grösse {n}x{n} zu platzieren, lautet:\n{loesung}".format(m=m, n=n, loesung=loesung))
###Output
_____no_output_____ |
basic-python/basic-python-start.ipynb | ###Markdown
Print statementDisplays output in our notebook.Print a single number
###Code
print(5)
###Output
5
###Markdown
Print words, in quoted strings
###Code
print('Hello World!')
print('Hello "Han"')
print("Can't do that")
print('I said "that\'s crazy"')
print('If I was British, I would quote \'hello\' but in in the U.S. of A. I would say "howdy"')
###Output
If I was British, I would quote 'hello' but in in the U.S. of A. I would say "howdy"
###Markdown
You can also print variables, coming up next. VariablesLike variables in math: you can store numbers
###Code
x = 12.3
print(x)
###Output
12.3
###Markdown
You can store words
###Code
word = 'petal width'
print(word)
###Output
petal width
###Markdown
ListsA list hold a sequence of variables all at once. You make a list of values in square brackets separated by commas. You can print them if they are short enough.
###Code
my_lst = [7, 8, 9, 10, 42]
print(my_lst)
###Output
[7, 8, 9, 10, 42]
###Markdown
You can access individual variables directly with indexes starting at 0 and ending the length - 1.
###Code
print(my_lst[2])
my_long_lst = list(range(100))
my_long_lst[89:]
my_long_lst[:10]
my_long_lst[11:25:3]
###Output
_____no_output_____
###Markdown
`for` loops`for` loops iterate over every element of a list (and many other data structures) in turn.This colon and indentation scheme is how Python keeps track of blocks of code that contain multiple lines, and is seen throughout the language.
###Code
# [7, 8, 9, 10, 42]
for x in my_lst:
print(x ** 2)
print(x * 2)
###Output
49
14
64
16
81
18
100
20
1764
84
###Markdown
`import` necessary softwareSometimes we need code we didn't write ourselves. So we import it from elsewhere. NumPy can generate random numbers for us, so first we need to import it.
###Code
from numpy import random
###Output
_____no_output_____
###Markdown
Then we can make a NumPy array (similar to the list we just discussed) with 5 random values.
###Code
random_numbers = random.rand(5)
print(random_numbers)
###Output
[ 0.80444845 0.67021436 0.08480299 0.03013219 0.26564605]
###Markdown
Matplotlib+ Is created to make data visualizations+ Creates histograms, scatter, line chart, and many more.First we need to set it up to use in Jupyter
###Code
import matplotlib.pyplot as plt
%matplotlib inline
###Output
_____no_output_____
###Markdown
Simple scatter plot: the code Let's make a scatter plot, which just prints x, y pairs. Both axes are normal distributions with means of μ=0, and standard deviation σ=1, with 50 numbers each.
###Code
xs = random.normal(0, 0.001, 50)
ys = random.normal(0, 1, 50)
fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x=xs, y=ys)
ax.set_xlabel('xs', size=15)
ax.set_ylabel('ys', size=15)
###Output
_____no_output_____ |
DataProject_OurGroupname.ipynb | ###Markdown
Data presentation This project is analyzing data of the five largest most popular tech stocks FAANG which are Facebook, Apple, Amazon, Netflix and Google and comparing it to S&P-500. We illustrate the historical relationship between volatility and average returns and assess whether active stock-picking would have been beneficial over the last five years.
###Code
#Import stok data from IEX
import pandas as pd
import pandas_datareader
import datetime
import matplotlib.pyplot as plt
start = datetime.datetime(2014,1,1)
end = datetime.datetime(2019,1,1)
firms = []
for i,stock_name in enumerate(['FB','AAPL', 'GOOGL', 'NFLX', 'AMZN', 'SPY']):
firm_stock = pandas_datareader.iex.daily.IEXDailyReader(stock_name, start, end).read()
firm_stock['firm'] = stock_name
firms.append(firm_stock)
stocks = pd.concat(firms)
# Convert index from type 'O' to 'datetime'
stocks.index = pd.to_datetime(stocks.index)
# Mean Closing Price Calculation
stocks.groupby('firm').mean()
###Output
_____no_output_____
###Markdown
Empirical Analysis To do so, we have been using trade data from The Investors Exchange containing open, high, low, close and volume for the period April 1st, 2014 to January 1st, 2019. Table 1(under data description) presents the mean prices for FAANG + S&P-500 in USD. Figure 1 shows the closing price evolution for Facebook, Apple, Amazon, Netflix, Google and S&P-500 from April 1st, 2014 to January 1st, 2019. The general tendency is that the closing prices i.e. the stock values are increasing over the period.
###Code
#Plot Raw Data - absolute growth for each stock
fig,ax = plt.subplots()
stocks.groupby('firm')['close'].plot(legend=True);
ax.set_ylabel('Price USD');
ax.set_title('Figure 1: Closing price 2014-2019');
###Output
_____no_output_____
###Markdown
In the first period from 2014-2017 stocks closing prices are growing steadily. From 2017 to mid-2018 the growth increases for all the stocks before the FAANG stocks suddenly decreases by more than 20 pct. The reason for the decrease in mid-2018 is as shown as S&P-500 in the graph generally decreases due to fear that the nine-year bull market was losing steam. However, the tech stocks that had been seen as a safe bet decreased even more than the general market due to disappointing market forecasts, which lead to fear of a new tech bubble.The main positive outlier is Amazon which experiences much higher growth rates than the other stocks but also a steeper decline in absolute values.The main negative outlier is Facebook who suffered especially hard with the stock falling more than 38 pct. From its all-time high in July, this was due to scandals regarding data breaches and general immoral business tactics coupled together with slowing growths.
###Code
#Plot Demeaned Data
stocks3 = stocks.copy()
# Split - Apply - Combine (de-meaning)
stocks3['close_demeaned'] = stocks3.groupby('firm')['close'].transform(lambda x: x - x.mean())
# Plot
stocks3.groupby('firm')['close_demeaned'].plot(legend=True);
plt.title('Figure 2: Demeaned stock prices');
###Output
_____no_output_____
###Markdown
Figure 2 shows the demeaned stock prices. The demeaned stock prices are found by subtracting the sample mean from each observation for each stock and S&P-500, which makes it possible to look at the stock deviations from the mean, which in figure 2 is illustrated as zero. It is noted that both Amazon and Google are quite volatile around their own means whereas the remaining stocks are more centered around their own means - volatility is a measure of dispersion around the mean or average return of a security. The standard deviation for each stock and S&P-500 has been calculated in Table 3, which shows standard deviation of the closing price in the period 2014 to 2019.
###Code
#Calculating the standard deviation for each stock
print(stocks3.groupby('firm')['close'].std())
###Output
firm
AAPL 36.960497
AMZN 475.704568
FB 39.303316
GOOGL 212.389259
NFLX 96.542952
SPY 34.215521
Name: close, dtype: float64
###Markdown
The results are that Apple€™s standard deviation is 38, Amazons is 478, Facebooks is 40, Googles is 214, Netflixs is 97 and S&P-500s is 35. The results from Amazon and Google are in line with our results from Figure 2 which showed that they were the two most volatile stocks. The results also show that S&P-500 has the lowest standard deviation which supports our financial theory that a lower expected return should yield a lower standard deviation, which also can be seen in figure 4 where Netflix and Amazon have had a growth rate above 400 pr. Cent and nearly 350 pr. Cent respectively. While S&P-500 have had the lowest growth rate for the same time period just below 50 pct. Comparing the table with standard deviation and figure 4, note especially Google: this stock has a relative high standard deviation but comes with the lowest growth rate for the FAANG-stocks, implying high risk – low return. Google has only grown less than double of the safest stock S&P-500, whereas Netflix has the highest growth rate but with much lower standard deviation making this stock much preferable compared to Google. Lastly we note that Apple and S&P-500 have the lowest and somehow the same standard deviation but Apple has grown almost the double of S&P-500. This imply that you can get almost the double return for the same risk as S&P-500 stock-picking Apple.
###Code
#Find first and last closing price for all stocks to obtain Figure 4
print(firms)
#Use first and last observation of each stock to calculate growth rate over the period.
# Growth rate 2014-2019 Facebook
x_first = 62.62
x_last = 131.09
growth_rate_FB = (x_last - x_first)/x_first * 100
print(growth_rate_FB)
# Growth rate 2014-2019 Apple
x_first = 71.1359
x_last = 157.0663
growth_rate_AAPL = (x_last - x_first)/x_first * 100
print(growth_rate_AAPL)
# Growth rate 2014-2019 Google
x_first = 568.0124
x_last = 1044.9600
growth_rate_GOOGL = (x_last - x_first)/x_first * 100
print(growth_rate_GOOGL)
# Growth rate 2014-2019 Amazon
x_first = 342.990
x_last = 1501.970
growth_rate_AMZN = (x_last - x_first)/x_first * 100
print(growth_rate_AMZN)
# Growth rate 2014-2019 Netflix
x_first = 52.0985
x_last = 267.66
growth_rate_NFLX = (x_last - x_first)/x_first * 100
print(growth_rate_NFLX)
# Growth rate 2014-2019 SP500
x_first = 170.4958
x_last = 248.8239
growth_rate_SPY = (x_last - x_first)/x_first * 100
print(growth_rate_SPY)
#Plot the growth rates against each other
import numpy as np
import matplotlib.pyplot as plt
# data to plot
n_groups = 6
growth_rate = (growth_rate_SPY, growth_rate_NFLX, growth_rate_AAPL, growth_rate_GOOGL, growth_rate_FB, growth_rate_AMZN)
# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8
rects1 = plt.bar(index, growth_rate, bar_width,
alpha=opacity,
color='m',
label='Growth Rate')
plt.xlabel('Firm')
plt.ylabel('Percentage')
plt.title('Figure 4: Growth Rate 2014 - 2019')
plt.xticks(index + bar_width, ('SPY', 'NFLX', 'AAPL', 'GOOGL', 'FB', 'AMZN'))
plt.legend()
plt.tight_layout()
plt.show()
###Output
_____no_output_____
###Markdown
Further looking at figure 3, which show the first-difference we clearly see that Google and Amazon shows biggest differences, which support our conclusion that these stocks are more unsafe implying a higher risk if stock-picking comparing to choosing the other FAANG-stocks or the S&P-500 index. Especially for the last observations the risk becomes higher.
###Code
#Using df.groupby('firm').var.diff(1) to calculate the first differences of closing prices.
stocks['diff_close'] = stocks.groupby('firm').close.diff(1)
stocks.groupby('firm')['diff_close'].plot(legend=True);
plt.title('Figure 3: First-diff of the close value of each stock');
###Output
_____no_output_____ |
DLND-your-first-network/.ipynb_checkpoints/keyboard-shortcuts-checkpoint.ipynb | ###Markdown
Keyboard shortcutsIn this notebook, you'll get some practice using keyboard shortcuts. These are key to becoming proficient at using notebooks and will greatly increase your work speed.First up, switching between edit mode and command mode. Edit mode allows you to type into cells while command mode will use key presses to execute commands such as creating new cells and openning the command palette. When you select a cell, you can tell which mode you're currently working in by the color of the box around the cell. In edit mode, the box and thick left border are colored green. In command mode, they are colored blue. Also in edit mode, you should see a cursor in the cell itself.By default, when you create a new cell or move to the next one, you'll be in command mode. To enter edit mode, press Enter/Return. To go back from edit mode to command mode, press Escape.> **Exercise:** Click on this cell, then press Enter + Shift to get to the next cell. Switch between edit and command mode a few times.
###Code
# mode practice
###Output
_____no_output_____
###Markdown
Help with commandsIf you ever need to look up a command, you can bring up the list of shortcuts by pressing `H` in command mode. The keyboard shortcuts are also available above in the Help menu. Go ahead and try it now. Creating new cellsOne of the most common commands is creating new cells. You can create a cell above the current cell by pressing `A` in command mode. Pressing `B` will create a cell below the currently selected cell. > **Exercise:** Create a cell above this cell using the keyboard command. > **Exercise:** Create a cell below this cell using the keyboard command. Switching between Markdown and codeWith keyboard shortcuts, it is quick and simple to switch between Markdown and code cells. To change from Markdown to cell, press `Y`. To switch from code to Markdown, press `M`.> **Exercise:** Switch the cell below between Markdown and code cells.
###Code
## Practice here
def fibo(n): # Recursive Fibonacci sequence!
if n == 0:
return 0
elif n == 1:
return 1
return fibo(n-1) + fibo(n-2)
###Output
_____no_output_____
###Markdown
Line numbersA lot of times it is helpful to number the lines in your code for debugging purposes. You can turn on numbers by pressing `L` (in command mode of course) on a code cell.> **Exercise:** Turn line numbers on and off in the above code cell. Deleting cellsDeleting cells is done by pressing `D` twice in a row so `D`, `D`. This is to prevent accidently deletions, you have to press the button twice!> **Exercise:** Delete the cell below. Saving the notebookNotebooks are autosaved every once in a while, but you'll often want to save your work between those times. To save the book, press `S`. So easy! The Command PaletteYou can easily access the command palette by pressing Shift + Control/Command + `P`. > **Note:** This won't work in Firefox and Internet Explorer unfortunately. There is already a keyboard shortcut assigned to those keys in those browsers. However, it does work in Chrome and Safari.This will bring up the command palette where you can search for commands that aren't available through the keyboard shortcuts. For instance, there are buttons on the toolbar that move cells up and down (the up and down arrows), but there aren't corresponding keyboard shortcuts. To move a cell down, you can open up the command palette and type in "move" which will bring up the move commands.> **Exercise:** Use the command palette to move the cell below down one position.
###Code
# Move this cell down
# below this cell
###Output
_____no_output_____ |
experiments/1_incident_points_3_ambo/.ipynb_checkpoints/10_qambo_noisy_bagging_3dqn-checkpoint.ipynb | ###Markdown
Noisy Bagging Duelling Double Deep Q Learning - A simple ambulance dispatch point allocation model Reinforcement learning introduction RL involves:* Trial and error search* Receiving and maximising reward (often delayed)* Linking state -> action -> reward* Must be able to sense something of their environment* Involves uncertainty in sensing and linking action to reward* Learning -> improved choice of actions over time* All models find a way to balance best predicted action vs. exploration Elements of RL* *Environment*: all observable and unobservable information relevant to us* *Observation*: sensing the environment* *State*: the perceived (or perceivable) environment * *Agent*: senses environment, decides on action, receives and monitors rewards* *Action*: may be discrete (e.g. turn left) or continuous (accelerator pedal)* *Policy* (how to link state to action; often based on probabilities)* *Reward signal*: aim is to accumulate maximum reward over time* *Value function* of a state: prediction of likely/possible long-term reward* *Q*: prediction of likely/possible long-term reward of an *action** *Advantage*: The difference in Q between actions in a given state (sums to zero for all actions)* *Model* (optional): a simulation of the environment Types of model* *Model-based*: have model of environment (e.g. a board game)* *Model-free*: used when environment not fully known* *Policy-based*: identify best policy directly* *Value-based*: estimate value of a decision* *Off-policy*: can learn from historic data from other agent* *On-policy*: requires active learning from current decisions Duelling Deep Q Networks for Reinforcement LearningQ = The expected future rewards discounted over time. This is what we are trying to maximise.The aim is to teach a network to take the current state observations and recommend the action with greatest Q.Duelling is very similar to Double DQN, except that the policy net splits into two. One component reduces to a single value, which will model the state *value*. The other component models the *advantage*, the difference in Q between different actions (the mean value is subtracted from all values, so that the advtantage always sums to zero). These are aggregated to produce Q for each action. Q is learned through the Bellman equation, where the Q of any state and action is the immediate reward achieved + the discounted maximum Q value (the best action taken) of next best action, where gamma is the discount rate.$$Q(s,a)=r + \gamma.maxQ(s',a')$$ Key DQN components General method for Q learning:Overall aim is to create a neural network that predicts Q. Improvement comes from improved accuracy in predicting 'current' understood Q, and in revealing more about Q as knowledge is gained (some rewards only discovered after time). Target networks are used to stabilise models, and are only updated at intervals. Changes to Q values may lead to changes in closely related states (i.e. states close to the one we are in at the time) and as the network tries to correct for errors it can become unstable and suddenly lose signficiant performance. Target networks (e.g. to assess Q) are updated only infrequently (or gradually), so do not have this instability problem. Training networksDouble DQN contains two networks. This ammendment, from simple DQN, is to decouple training of Q for current state and target Q derived from next state which are closely correlated when comparing input features.The *policy network* is used to select action (action with best predicted Q) when playing the game.When training, the predicted best *action* (best predicted Q) is taken from the *policy network*, but the *policy network* is updated using the predicted Q value of the next state from the *target network* (which is updated from the policy network less frequently). So, when training, the action is selected using Q values from the *policy network*, but the the *policy network* is updated to better predict the Q value of that action from the *target network*. The *policy network* is copied across to the *target network* every *n* steps (e.g. 1000). Bagging (Bootstrap Aggregation)Each network is trained from the same memory, but have different starting weights and are trained on different bootstrap samples from that memory. In this example actions are chosen randomly from each of the networks (an alternative could be to take the most common action recommended by the networks, or an average output). This bagging method may also be used to have some measure of uncertainty of action by looking at the distribution of actions recommended from the different nets. Bagging may also be used to aid exploration during stages where networks are providing different suggested action. Noisy layersNoisy layers are an alternative to epsilon-greedy exploration (here, we leave the epsilon-greedy code in the model, but set it to reduce to zero immediately after the period of fully random action choice).For every weight in the layer we have a random value that we draw from the normal distribution. This random value is used to add noise to the output. The parameters for the extent of noise for each weight, sigma, are stored within the layer and get trained as part of the standard back-propogation.A modification to normal nosiy layers is to use layers with ‘factorized gaussian noise’. This reduces the number of random numbers to be sampled (so is less computationally expensive). There are two random vectors, one with the size of the input, and the other with the size of the output. A random matrix is created by calculating the outer product of the two vectors. ReferencesDouble DQN: van Hasselt H, Guez A, Silver D. (2015) Deep Reinforcement Learning with Double Q-learning. arXiv:150906461 http://arxiv.org/abs/1509.06461Bagging:Osband I, Blundell C, Pritzel A, et al. (2016) Deep Exploration via Bootstrapped DQN. arXiv:160204621 http://arxiv.org/abs/1602.04621Noisy networks:Fortunato M, Azar MG, Piot B, et al. (2019) Noisy Networks for Exploration. arXiv:170610295 http://arxiv.org/abs/1706.10295Code for the nosiy layers comes from:Lapan, M. (2020). Deep Reinforcement Learning Hands-On: Apply modern RL methods to practical problems of chatbots, robotics, discrete optimization, web automation, and more, 2nd Edition. Packt Publishing. Code structure
###Code
################################################################################
# 1 Import packages #
################################################################################
from amboworld.environment import Env
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import functional as F
# Use a double ended queue (deque) for memory
# When memory is full, this will replace the oldest value with the new one
from collections import deque
# Supress all warnings (e.g. deprecation warnings) for regular use
import warnings
warnings.filterwarnings("ignore")
################################################################################
# 2 Define model parameters #
################################################################################
# Set whether to display on screen (slows model)
DISPLAY_ON_SCREEN = False
# Discount rate of future rewards
GAMMA = 0.99
# Learing rate for neural network
LEARNING_RATE = 0.003
# Maximum number of game steps (state, action, reward, next state) to keep
MEMORY_SIZE = 10000000
# Sample batch size for policy network update
BATCH_SIZE = 5
# Number of game steps to play before starting training (all random actions)
REPLAY_START_SIZE = 50000
# Number of steps between policy -> target network update
SYNC_TARGET_STEPS = 1000
# Exploration rate (epsilon) is probability of choosing a random action
EXPLORATION_MAX = 1.0
EXPLORATION_MIN = 0.0
# Reduction in epsilon with each game step
EXPLORATION_DECAY = 0.0
# Training episodes
TRAINING_EPISODES = 50
# Set number of parallel networks
NUMBER_OF_NETS = 5
# Results filename
RESULTS_NAME = 'bagging_noisy_d3qn'
# SIM PARAMETERS
RANDOM_SEED = 42
SIM_DURATION = 5000
NUMBER_AMBULANCES = 3
NUMBER_INCIDENT_POINTS = 1
INCIDENT_RADIUS = 2
NUMBER_DISPTACH_POINTS = 25
AMBOWORLD_SIZE = 50
INCIDENT_INTERVAL = 60
EPOCHS = 2
AMBO_SPEED = 60
AMBO_FREE_FROM_HOSPITAL = False
################################################################################
# 3 Define DQN (Duelling Deep Q Network) class #
# (Used for both policy and target nets) #
################################################################################
"""
Code for nosiy layers comes from:
Lapan, M. (2020). Deep Reinforcement Learning Hands-On: Apply modern RL methods
to practical problems of chatbots, robotics, discrete optimization,
web automation, and more, 2nd Edition. Packt Publishing.
"""
class NoisyLinear(nn.Linear):
"""
Noisy layer for network.
For every weight in the layer we have a random value that we draw from the
normal distribution.Paraemters for the noise, sigma, are stored within the
layer and get trained as part of the standard back-propogation.
'register_buffer' is used to create tensors in the network that are not
updated during back-propogation. They are used to create normal
distributions to add noise (multiplied by sigma which is a paramater in the
network).
"""
def __init__(self, in_features, out_features,
sigma_init=0.017, bias=True):
super(NoisyLinear, self).__init__(
in_features, out_features, bias=bias)
w = torch.full((out_features, in_features), sigma_init)
self.sigma_weight = nn.Parameter(w)
z = torch.zeros(out_features, in_features)
self.register_buffer("epsilon_weight", z)
if bias:
w = torch.full((out_features,), sigma_init)
self.sigma_bias = nn.Parameter(w)
z = torch.zeros(out_features)
self.register_buffer("epsilon_bias", z)
self.reset_parameters()
def reset_parameters(self):
std = math.sqrt(3 / self.in_features)
self.weight.data.uniform_(-std, std)
self.bias.data.uniform_(-std, std)
def forward(self, input):
self.epsilon_weight.normal_()
bias = self.bias
if bias is not None:
self.epsilon_bias.normal_()
bias = bias + self.sigma_bias * \
self.epsilon_bias.data
v = self.sigma_weight * self.epsilon_weight.data + self.weight
return F.linear(input, v, bias)
class NoisyFactorizedLinear(nn.Linear):
"""
NoisyNet layer with factorized gaussian noise. This reduces the number of
random numbers to be sampled (so less computationally expensive). There are
two random vectors. One with the size of the input, and the other with the
size of the output. A random matrix is create by calculating the outer
product of the two vectors.
'register_buffer' is used to create tensors in the network that are not
updated during back-propogation. They are used to create normal
distributions to add noise (multiplied by sigma which is a paramater in the
network).
"""
def __init__(self, in_features, out_features,
sigma_zero=0.4, bias=True):
super(NoisyFactorizedLinear, self).__init__(
in_features, out_features, bias=bias)
sigma_init = sigma_zero / math.sqrt(in_features)
w = torch.full((out_features, in_features), sigma_init)
self.sigma_weight = nn.Parameter(w)
z1 = torch.zeros(1, in_features)
self.register_buffer("epsilon_input", z1)
z2 = torch.zeros(out_features, 1)
self.register_buffer("epsilon_output", z2)
if bias:
w = torch.full((out_features,), sigma_init)
self.sigma_bias = nn.Parameter(w)
def forward(self, input):
self.epsilon_input.normal_()
self.epsilon_output.normal_()
func = lambda x: torch.sign(x) * torch.sqrt(torch.abs(x))
eps_in = func(self.epsilon_input.data)
eps_out = func(self.epsilon_output.data)
bias = self.bias
if bias is not None:
bias = bias + self.sigma_bias * eps_out.t()
noise_v = torch.mul(eps_in, eps_out)
v = self.weight + self.sigma_weight * noise_v
return F.linear(input, v, bias)
class DQN(nn.Module):
"""Deep Q Network. Udes for both policy (action) and target (Q) networks."""
def __init__(self, observation_space, action_space):
"""Constructor method. Set up neural nets."""
# nerurones per hidden layer = 2 * max of observations or actions
neurons_per_layer = 2 * max(observation_space, action_space)
# Set starting exploration rate
self.exploration_rate = EXPLORATION_MAX
# Set up action space (choice of possible actions)
self.action_space = action_space
# First layerswill be common to both Advantage and value
super(DQN, self).__init__()
self.feature = nn.Sequential(
nn.Linear(observation_space, neurons_per_layer),
nn.ReLU()
)
# Advantage has same number of outputs as the action space
self.advantage = nn.Sequential(
NoisyFactorizedLinear(neurons_per_layer, neurons_per_layer),
nn.ReLU(),
NoisyFactorizedLinear(neurons_per_layer, action_space)
)
# State value has only one output (one value per state)
self.value = nn.Sequential(
nn.Linear(neurons_per_layer, neurons_per_layer),
nn.ReLU(),
nn.Linear(neurons_per_layer, 1)
)
def act(self, state):
"""Act either randomly or by redicting action that gives max Q"""
# Act randomly if random number < exploration rate
if np.random.rand() < self.exploration_rate:
action = random.randrange(self.action_space)
else:
# Otherwise get predicted Q values of actions
q_values = self.forward(torch.FloatTensor(state))
# Get index of action with best Q
action = np.argmax(q_values.detach().numpy()[0])
return action
def forward(self, x):
x = self.feature(x)
advantage = self.advantage(x)
value = self.value(x)
action_q = value + advantage - advantage.mean()
return action_q
################################################################################
# 4 Define policy net training function #
################################################################################
def optimize(policy_net, target_net, memory):
"""
Update model by sampling from memory.
Uses policy network to predict best action (best Q).
Uses target network to provide target of Q for the selected next action.
"""
# Do not try to train model if memory is less than reqired batch size
if len(memory) < BATCH_SIZE:
return
# Reduce exploration rate (exploration rate is stored in policy net)
policy_net.exploration_rate *= EXPLORATION_DECAY
policy_net.exploration_rate = max(EXPLORATION_MIN,
policy_net.exploration_rate)
# Sample a random batch from memory
batch = random.sample(memory, BATCH_SIZE)
for state, action, reward, state_next, terminal in batch:
state_action_values = policy_net(torch.FloatTensor(state))
# Get target Q for policy net update
if not terminal:
# For non-terminal actions get Q from policy net
expected_state_action_values = policy_net(torch.FloatTensor(state))
# Detach next state values from gradients to prevent updates
expected_state_action_values = expected_state_action_values.detach()
# Get next state action with best Q from the policy net (double DQN)
policy_next_state_values = policy_net(torch.FloatTensor(state_next))
policy_next_state_values = policy_next_state_values.detach()
best_action = np.argmax(policy_next_state_values[0].numpy())
# Get target net next state
next_state_action_values = target_net(torch.FloatTensor(state_next))
# Use detach again to prevent target net gradients being updated
next_state_action_values = next_state_action_values.detach()
best_next_q = next_state_action_values[0][best_action].numpy()
updated_q = reward + (GAMMA * best_next_q)
expected_state_action_values[0][action] = updated_q
else:
# For termal actions Q = reward (-1)
expected_state_action_values = policy_net(torch.FloatTensor(state))
# Detach values from gradients to prevent gradient update
expected_state_action_values = expected_state_action_values.detach()
# Set Q for all actions to reward (-1)
expected_state_action_values[0] = reward
# Set network to training mode
policy_net.train()
# Reset net gradients
policy_net.optimizer.zero_grad()
# calculate loss
loss_v = nn.MSELoss()(state_action_values, expected_state_action_values)
# Backpropogate loss
loss_v.backward()
# Update network gradients
policy_net.optimizer.step()
return
################################################################################
# 5 Define memory class #
################################################################################
class Memory():
"""
Replay memory used to train model.
Limited length memory (using deque, double ended queue from collections).
- When memory full deque replaces oldest data with newest.
Holds, state, action, reward, next state, and episode done.
"""
def __init__(self):
"""Constructor method to initialise replay memory"""
self.memory = deque(maxlen=MEMORY_SIZE)
def remember(self, state, action, reward, next_state, done):
"""state/action/reward/next_state/done"""
self.memory.append((state, action, reward, next_state, done))
################################################################################
# 6 Define results plotting function #
################################################################################
def plot_results(run, exploration, score, mean_call_to_arrival,
mean_assignment_to_arrival):
"""Plot and report results at end of run"""
# Set up chart (ax1 and ax2 share x-axis to combine two plots on one graph)
fig = plt.figure(figsize=(6,6))
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
# Plot results
lns1 = ax1.plot(
run, exploration, label='exploration', color='g', linestyle=':')
lns2 = ax2.plot(run, mean_call_to_arrival,
label='call to arrival', color='r')
lns3 = ax2.plot(run, mean_assignment_to_arrival,
label='assignment to arrival', color='b', linestyle='--')
# Get combined legend
lns = lns1 + lns2 + lns3
labs = [l.get_label() for l in lns]
ax1.legend(lns, labs, loc='upper center', bbox_to_anchor=(0.5, -0.1), ncol=3)
# Set axes
ax1.set_xlabel('run')
ax1.set_ylabel('exploration')
ax2.set_ylabel('Response time')
filename = 'output/' + RESULTS_NAME +'.png'
plt.savefig(filename, dpi=300)
plt.show()
################################################################################
# 7 Main program #
################################################################################
def qambo():
"""Main program loop"""
############################################################################
# 8 Set up environment #
############################################################################
sim = Env(
random_seed = RANDOM_SEED,
duration_incidents = SIM_DURATION,
number_ambulances = NUMBER_AMBULANCES,
number_incident_points = NUMBER_INCIDENT_POINTS,
incident_interval = INCIDENT_INTERVAL,
number_epochs = EPOCHS,
number_dispatch_points = NUMBER_DISPTACH_POINTS,
incident_range = INCIDENT_RADIUS,
max_size = AMBOWORLD_SIZE,
ambo_kph = AMBO_SPEED,
ambo_free_from_hospital = AMBO_FREE_FROM_HOSPITAL
)
# Get number of observations returned for state
observation_space = sim.observation_size
# Get number of actions possible
action_space = sim.action_number
############################################################################
# 9 Set up policy and target nets #
############################################################################
# Set up policy and target neural nets
policy_nets = [DQN(observation_space, action_space)
for i in range(NUMBER_OF_NETS)]
target_nets = [DQN(observation_space, action_space)
for i in range(NUMBER_OF_NETS)]
best_nets = [DQN(observation_space, action_space)
for i in range(NUMBER_OF_NETS)]
# Set optimizer, copy weights from policy_net to target, and
for i in range(NUMBER_OF_NETS):
# Set optimizer
policy_nets[i].optimizer = optim.Adam(
params=policy_nets[i].parameters(), lr=LEARNING_RATE)
# Copy weights from policy -> target
target_nets[i].load_state_dict(policy_nets[i].state_dict())
# Set target net to eval rather than training mode
target_nets[i].eval()
############################################################################
# 10 Set up memory #
############################################################################
# Set up memomry
memory = Memory()
############################################################################
# 11 Set up + start training loop #
############################################################################
# Set up run counter and learning loop
run = 0
all_steps = 0
continue_learning = True
best_reward = -np.inf
# Set up list for results
results_run = []
results_exploration = []
results_score = []
results_mean_call_to_arrival = []
results_mean_assignment_to_arrival = []
# Continue repeating games (episodes) until target complete
while continue_learning:
########################################################################
# 12 Play episode #
########################################################################
# Increment run (episode) counter
run += 1
########################################################################
# 13 Reset game #
########################################################################
# Reset game environment and get first state observations
state = sim.reset()
# Reset total reward and rewards list
total_reward = 0
rewards = []
# Reshape state into 2D array with state obsverations as first 'row'
state = np.reshape(state, [1, observation_space])
# Continue loop until episode complete
while True:
####################################################################
# 14 Game episode loop #
####################################################################
####################################################################
# 15 Get action #
####################################################################
# Get actions to take (use evalulation mode)
actions = []
for i in range(NUMBER_OF_NETS):
policy_nets[i].eval()
actions.append(policy_nets[i].act(state))
# Randomly choose an action from net actions
random_index = random.randint(0, NUMBER_OF_NETS - 1)
action = actions[random_index]
####################################################################
# 16 Play action (get S', R, T) #
####################################################################
# Act
state_next, reward, terminal, info = sim.step(action)
total_reward += reward
# Update trackers
rewards.append(reward)
# Reshape state into 2D array with state observations as first 'row'
state_next = np.reshape(state_next, [1, observation_space])
# Update display if needed
if DISPLAY_ON_SCREEN:
sim.render()
####################################################################
# 17 Add S/A/R/S/T to memory #
####################################################################
# Record state, action, reward, new state & terminal
memory.remember(state, action, reward, state_next, terminal)
# Update state
state = state_next
####################################################################
# 18 Check for end of episode #
####################################################################
# Actions to take if end of game episode
if terminal:
# Get exploration rate
exploration = policy_nets[0].exploration_rate
# Clear print row content
clear_row = '\r' + ' ' * 79 + '\r'
print(clear_row, end='')
print(f'Run: {run}, ', end='')
print(f'Exploration: {exploration: .3f}, ', end='')
average_reward = np.mean(rewards)
print(f'Average reward: {average_reward:4.1f}, ', end='')
mean_assignment_to_arrival = np.mean(info['assignment_to_arrival'])
print(f'Mean assignment to arrival: {mean_assignment_to_arrival:4.1f}, ', end='')
mean_call_to_arrival = np.mean(info['call_to_arrival'])
print(f'Mean call to arrival: {mean_call_to_arrival:4.1f}, ', end='')
demand_met = info['fraction_demand_met']
print(f'Demand met {demand_met:0.3f}')
# Add to results lists
results_run.append(run)
results_exploration.append(exploration)
results_score.append(total_reward)
results_mean_call_to_arrival.append(mean_call_to_arrival)
results_mean_assignment_to_arrival.append(mean_assignment_to_arrival)
# Save model if best reward
total_reward = np.sum(rewards)
if total_reward > best_reward:
best_reward = total_reward
# Copy weights to best net
for i in range(NUMBER_OF_NETS):
best_nets[i].load_state_dict(policy_nets[i].state_dict())
################################################################
# 18b Check for end of learning #
################################################################
if run == TRAINING_EPISODES:
continue_learning = False
# End episode loop
break
####################################################################
# 19 Update policy net #
####################################################################
# Avoid training model if memory is not of sufficient length
if len(memory.memory) > REPLAY_START_SIZE:
# Update policy net
for i in range(NUMBER_OF_NETS):
optimize(policy_nets[i], target_nets[i], memory.memory)
################################################################
# 20 Update target net periodically #
################################################################
# Use load_state_dict method to copy weights from policy net
if all_steps % SYNC_TARGET_STEPS == 0:
for i in range(NUMBER_OF_NETS):
target_nets[i].load_state_dict(
policy_nets[i].state_dict())
############################################################################
# 21 Learning complete - plot and save results #
############################################################################
# Target reached. Plot results
plot_results(results_run, results_exploration, results_score,
results_mean_call_to_arrival, results_mean_assignment_to_arrival)
# SAVE RESULTS
run_details = pd.DataFrame()
run_details['run'] = results_run
run_details['exploration '] = results_exploration
run_details['mean_call_to_arrival'] = results_mean_call_to_arrival
run_details['mean_assignment_to_arrival'] = results_mean_assignment_to_arrival
filename = 'output/' + RESULTS_NAME + '.csv'
run_details.to_csv(filename, index=False)
############################################################################
# Test best model #
############################################################################
print()
print('Test Model')
print('----------')
for i in range(NUMBER_OF_NETS):
best_nets[i].eval()
best_nets[i].exploration_rate = 0
# Set up results dictionary
results = dict()
results['call_to_arrival'] = []
results['assign_to_arrival'] = []
results['demand_met'] = []
# Replicate model runs
for run in range(30):
# Reset game environment and get first state observations
state = sim.reset()
state = np.reshape(state, [1, observation_space])
# Continue loop until episode complete
while True:
# Get actions to take (use evalulation mode)
actions = []
for i in range(NUMBER_OF_NETS):
actions.append(best_nets[i].act(state))
# Randomly choose an action from net actions
random_index = random.randint(0, NUMBER_OF_NETS - 1)
action = actions[random_index]
# Act
state_next, reward, terminal, info = sim.step(action)
# Reshape state into 2D array with state observations as first 'row'
state_next = np.reshape(state_next, [1, observation_space])
# Update state
state = state_next
if terminal:
print(f'Run: {run}, ', end='')
mean_assignment_to_arrival = np.mean(info['assignment_to_arrival'])
print(f'Mean assignment to arrival: {mean_assignment_to_arrival:4.1f}, ', end='')
mean_call_to_arrival = np.mean(info['call_to_arrival'])
print(f'Mean call to arrival: {mean_call_to_arrival:4.1f}, ', end='')
demand_met = info['fraction_demand_met']
print(f'Demand met: {demand_met:0.3f}')
# Add to results
results['call_to_arrival'].append(mean_call_to_arrival)
results['assign_to_arrival'].append(mean_assignment_to_arrival)
results['demand_met'].append(demand_met)
# End episode loop
break
results = pd.DataFrame(results)
filename = './output/results_' + RESULTS_NAME +'.csv'
results.to_csv(filename, index=False)
print()
print(results.describe())
return run_details
######################## MODEL ENTRY POINT #####################################
# Run model and return last run results
last_run = qambo()
###Output
Run: 1, Exploration: 1.000, Average reward: -728.0, Mean assignment to arrival: 25.0, Mean call to arrival: 30.6, Demand met 1.000
Run: 2, Exploration: 1.000, Average reward: -723.2, Mean assignment to arrival: 24.9, Mean call to arrival: 31.5, Demand met 1.000
Run: 3, Exploration: 1.000, Average reward: -707.7, Mean assignment to arrival: 24.6, Mean call to arrival: 29.8, Demand met 1.000
Run: 4, Exploration: 1.000, Average reward: -719.2, Mean assignment to arrival: 24.8, Mean call to arrival: 30.4, Demand met 1.000
Run: 5, Exploration: 1.000, Average reward: -713.5, Mean assignment to arrival: 24.8, Mean call to arrival: 30.8, Demand met 1.000
Run: 6, Exploration: 1.000, Average reward: -724.5, Mean assignment to arrival: 24.8, Mean call to arrival: 30.6, Demand met 1.000
Run: 7, Exploration: 1.000, Average reward: -701.9, Mean assignment to arrival: 24.5, Mean call to arrival: 30.3, Demand met 1.000
Run: 8, Exploration: 1.000, Average reward: -731.0, Mean assignment to arrival: 25.0, Mean call to arrival: 30.2, Demand met 1.000
Run: 9, Exploration: 1.000, Average reward: -705.0, Mean assignment to arrival: 24.6, Mean call to arrival: 30.1, Demand met 1.000
Run: 10, Exploration: 1.000, Average reward: -710.1, Mean assignment to arrival: 24.7, Mean call to arrival: 30.9, Demand met 1.000
|
tests/artifacts/JMA-observed_catalog/dateStringParsing.ipynb | ###Markdown
Strange(?) stuff while pasing a JMA CSV catalog file
###Code
import datetime
_tsTpl = '%Y-%m-%dT%H:%M:%S.%f%z'
x = '1969-09-25T10:49:57.220000+0900'
10. * 10. * 10. * datetime.datetime.strptime(x, _tsTpl).timestamp()
10. * 10. * datetime.datetime.strptime(x, _tsTpl).timestamp() * 10.
10. * datetime.datetime.strptime(x, _tsTpl).timestamp() * 10. * 10.
datetime.datetime.strptime(x, _tsTpl).timestamp() * 10. * 10. * 10.
datetime.datetime.strptime(x, _tsTpl).timestamp() * 1000.
10. * datetime.datetime.strptime(x, _tsTpl).timestamp() * 100.
datetime.datetime.strptime(x, _tsTpl).timestamp()
###Output
_____no_output_____ |
pandas_alura_extra.ipynb | ###Markdown
Conteúdo extra Importando html
###Code
import pandas as pd
###Output
_____no_output_____
###Markdown
https://www.federalreserve.gov/releases/h3/current/default.htm
###Code
df_html = pd.read_html('https://www.federalreserve.gov/releases/h3/current/default.htm')
len(df_html)
df_html[0].head()
df_html[1].head()
df_html[2].head()
data = [1 , 2, 3, 4 ,5]
s = pd.Series(data)
s
index = ['Linha' + str(i) for i in range(5)]
index
s = pd.Series(data= data, index=index)
s
data = {'linha' + str(i) : i +1 for i in range(5)}
data
s = pd.Series(data)
s
s1 = s+1
s1
s2 = s + s1
s2
###Output
_____no_output_____
###Markdown
DataFrame
###Code
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
data
df1 = pd.DataFrame(data= data)
df1
index = ['linha' + str(i) for i in range(3)]
df1 = pd.DataFrame(data=data, index=index)
df1
columns = ['coluna' + str(i) for i in range(3)]
df1 = pd.DataFrame(data=data, index=index, columns=columns)
df1
data = {'coluna0': {'linha0': 1, 'linha1': 4, 'linha2': 7},
'coluna1': {'linha0': 2, 'linha1': 5, 'linha2': 8},
'coluna2': {'linha0': 3, 'linha1': 6, 'linha2': 9}
}
data
df2 = pd.DataFrame(data=data)
df2
data = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
df3 = pd.DataFrame(data=data, index=index, columns=columns)
df3
df1[df1 > 0] = 'A'
df1
df2[df2 > 0] = 'B'
df2
df3[df3 > 0] = 'C'
df3
df4 = pd.concat([df1, df2, df3])
df4
df4 = pd.concat([df1, df2, df3], axis=1)
df4
###Output
_____no_output_____
###Markdown
Organizando Dataframe
###Code
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
data
list('321')
df = pd.DataFrame(data, list('321'), list('zyx'))
df
df.sort_index(inplace=True)
df
df.sort_index(inplace=True, axis=1)
df
df.sort_values(by='x', inplace=True)
df
df.sort_values(by='3', axis=1, inplace=True)
df
df.sort_values(by=['x', 'y'], inplace=True)
df
###Output
_____no_output_____
###Markdown
Formas de seleção
###Code
data = [(1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)]
df = pd.DataFrame(data, 'l1 l2 l3 l4'.split(), 'c1 c2 c3 c4'.split())
df
df['c1']
df[['c3', 'c1']]
df[1:3]
df[1:3][['c3', 'c1']]
df.loc['l3']
df.loc[['l3', 'l2']]
df.loc['l1', 'c2']
df.iloc[0 , 1]
df.loc[['l3', 'l1'], ['c4', 'c1']]
df.iloc[[2, 0], [3, 0]]
###Output
_____no_output_____
###Markdown
Métodos de interpolação
###Code
data = [0.5, None, None, 0.52, 0.54, None, None, 0.59, 0.6, None, 0.7]
s = pd.Series(data)
s
s.fillna(0)
s.fillna(method='ffill')
s.fillna(method='bfill')
s.fillna(s.mean())
s_1 = s.fillna(method='ffill', limit=1, )
s_1
s_1.fillna(method='bfill', limit=1)
###Output
_____no_output_____
###Markdown
contadores
###Code
s = pd.Series(list('asdasdasedadeasdesasdes'))
s
s.unique()
s.value_counts()
m1 = 'CCcCCccCCCccCcCccCcCcCCCcCCcccCCcCcCcCcccCCcCcccCc'
m2 = 'CCCCCccCccCcCCCCccCccccCccCccCCcCccCcCcCCcCccCccCc'
m3 = 'CccCCccCcCCCCCCCCCCcccCccCCCCCCccCCCcccCCCcCCcccCC'
m4 = 'cCCccCCccCCccCCccccCcCcCcCcCcCcCCCCccccCCCcCCcCCCC'
m5 = 'CCCcCcCcCcCCCcCCcCcCCccCcCCcccCccCCcCcCcCcCcccccCc'
eventos = {'m1': list(m1),
'm2': list(m2),
'm3': list(m3),
'm4': list(m4),
'm5': list(m5)}
moedas = pd.DataFrame(eventos)
df = pd.DataFrame(data = ['Cara', 'Coroa'],
index = ['c', 'C'],
columns = ['Faces'])
for item in moedas:
df = pd.concat([df, moedas[item].value_counts()],
axis = 1)
df
moedas
###Output
_____no_output_____ |
notebooks/with_config_file_input.ipynb | ###Markdown
This notebook shows how to run btk from with an input config yaml file. The config file contains information on how to simulate the blend scene, which detecteion/deblending algorithm to run and where to load from/save to "./data". The config file is parsed by `btk_input.py` for end-to-end analysis; from image simulation to saving the measurement output to file. To perfoem comparitive analysis across different algorithms:1. Make a copy of the config file `..btk/btk-config.yaml`2. Modify entries under `user_input:` to run your desired detection algorithm. `measure_function` and `metrics_function` must be either None (to select Default) or should be classes defined in `utils_filename`.The detection and metric outputs will be saved inside "output_dir/output_name". The simulation parameters in `..btk/btk-config.yaml` must remain the same when comparing algorithms. For this example however, we use an input config file `../input/example-config.yaml`, with fewer test runs. The config values are:```user_input: Enter location to load dataset from (relative to where you open the yaml file) data_dir: data Enter location where btk test output should be saved output_dir: example-output Enter file name containing user function to perform detection/deblending/measurement utils_filename: If None use btk/utils.py output_name: trial btk output will be saved in a directory with this name inside output_dir Enter name of functions to perform detection/deblending/measurement. utils_input: measure_function: SEP_params metrics_function: None```The config directs btk to perform detections with SEP band-coadd images by specifying `measure_function: SEP_params` defined in `btk.utils`. The config entry `metrics_function: None`, specifies that the `Basic_measure_params` in `btk.utils` computes the detection metrics.
###Code
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
sys.path.insert(0,os.path.dirname(os.getcwd()))
import btk
import btk.plot_utils, btk.utils
import astropy.table
import dill
###Output
_____no_output_____
###Markdown
The config file contains parametrs for three types of input test images:1. two-galaxy blend created randomly from CatSim galaxies2. Upto 10 galaxy blends created randomly from CatSim galaxies3. blends as galaxy "groups" from a pre-processed wld output 1. Two-galaxy blend created randomly from CatSim galaxies `btk_input.py` input arg `--two_gal` simulates galaxy blends using the `btk.utils.default_sampling` function with maximum of 2 sources per blend. The yaml config file is input with the `--configfile` arg. The class name with functons on how to run the detection algorithm is input with `utils_input.measure_function`. The class that processes output from the detectection algorithm and computes metrics is input with `utils_input.metrics_function`
###Code
# The following command runs SEP detection and metrics computation with `two-gal` simulation.
!python3 ../btk_input.py --simulation two_gal --configfile ../input/example-config.yaml
!ls example-output/trial
###Output
two_gal_config.yaml two_gal_metrics_results.dill
###Markdown
Simulation, input user config values saved as "two_gal_config.yaml". Blend images, detection results and metrics computed saved in "two_gal_metrics_results.dill"
###Code
filename = 'example-output/trial/two_gal_metrics_results.dill'
with open(filename, 'rb') as handle:
results= dill.load(handle)
true_table, detected_table, detection_summary = results['detection']
num = np.array(detection_summary).max()
_, ax = plt.subplots(1,3,figsize=(15,5))
plt.subplots_adjust(wspace=0.3, hspace=0.3)
#match1
det_summary = np.array(detection_summary)
tot = np.sum(det_summary[:, 0])
det = np.sum(det_summary[:, 1])
spur = np.sum(det_summary[:, 3])
print("match1", "precision: ", float(det/(det + spur)), "recall: ", float(det/(tot)))
btk.plot_utils.plot_metrics_summary(det_summary, num, ax=ax[0])
ax[0].set_title('match1')
# match 2
summ = np.array(detection_summary)
det_summary = np.concatenate([summ[:, 0, np.newaxis], summ[:, 5:]], axis=1)
tot = np.sum(det_summary[:, 0])
det = np.sum(det_summary[:, 1])
spur = np.sum(det_summary[:, 3])
print("match2", "precision: ", float(det/(det + spur)), "recall: ", float(det/(tot)))
btk.plot_utils.plot_metrics_summary(det_summary, num, ax=ax[1])
ax[1].set_title('match2')
summ = np.array(detection_summary)
det_summary = np.concatenate([summ[:, 0, np.newaxis], summ[:, 5:]], axis=1)
det_summary[:, 1] += det_summary[:, 3] +det_summary[:, 4]
btk.plot_utils.plot_metrics_summary(det_summary, num, ax=ax[2])
ax[2].set_title('Blend')
ax[2].set_ylabel('# detected objects')
_, axs = plt.subplots(1,3,figsize=(10,4))
plt.subplots_adjust(wspace=0.5, hspace=0.)
mag_bins = np.linspace(18, 30, 20)
size_bins = np.linspace(0, 15, 20)
dist_bins = np.linspace(0, 15, 20)
# match1
true_table['min_dist'][np.isinf(true_table['min_dist'])] =128
q_detected, = np.where(true_table['num_detections1'] ==1)
# Plot by magnitude
btk.plot_utils.plot_cumulative(true_table[q_detected], 'i_ab', axs[0],
mag_bins, color='r', xlabel='i mag', label='match1')
# Plot by size
btk.plot_utils.plot_cumulative(true_table[q_detected], 'size', axs[1],
size_bins, color='r', xlabel='size (pixels)', label='match1')
# Plot by min dist to neighbor
btk.plot_utils.plot_cumulative(true_table[q_detected], 'min_dist', axs[2],
dist_bins, color='r', xlabel='nearsest neighbor (pixels)', label='match1')
# match2
true_table['min_dist'][np.isinf(true_table['min_dist'])] = 128
q_detected, = np.where(true_table['num_detections2'] ==1)
# Plot by magnitude
btk.plot_utils.plot_cumulative(true_table[q_detected], 'i_ab', axs[0],
mag_bins, color='g', xlabel='i mag', label='match2')
# Plot by size
btk.plot_utils.plot_cumulative(true_table[q_detected], 'size', axs[1],
size_bins, color='g', xlabel='size (pixels)', label='match2')
# Plot by min dist to neighbor
btk.plot_utils.plot_cumulative(true_table[q_detected], 'min_dist', axs[2],
dist_bins, color='g', xlabel='nearsest neighbor (pixels)', label='match2')
#true entries
# Plot by magnitude
btk.plot_utils.plot_cumulative(true_table, 'i_ab', axs[0],
mag_bins, color='blue', xlabel='i mag', label='true')
# Plot by size
btk.plot_utils.plot_cumulative(true_table, 'size', axs[1],
size_bins, color='blue', xlabel='size (pixels)', label='true')
# Plot by min dist to neighbor
btk.plot_utils.plot_cumulative(true_table, 'min_dist', axs[2],
dist_bins, color='blue', xlabel='nearsest neighbor (pixels)', label='true')
axs[2].legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
axs[0].set_title("Detected objects")
axs[1].set_title("Detected objects")
axs[2].set_title("Detected objects")
plt.show()
###Output
_____no_output_____
###Markdown
Similarly, detectection metrics can be computed for two other simultion parametrs 2. Upto 10 galaxy blends created randomly from CatSim galaxies `btk_input.py` input arg `--multi_gal` simulates galaxy blends using the `btk.utils.default_sampling` function with maximum of 10 galaxies per blend.
###Code
!python3 ../btk_input.py --simulation multi_gal --configfile ../input/example-config.yaml
###Output
_____no_output_____
###Markdown
3. Blends as galaxy "groups" from a pre-processed wld output
###Code
!python3 ../btk_input.py --simulation group --configfile ../input/example-config.yaml
###Output
_____no_output_____
###Markdown
`btk_input.py` input arg `--multi_gal` simulates galaxy blends using the `btk.utils.group_sampling_function` function with maximum of 6 galaxies per blend.
###Code
If `/btk_input.py` is run with input arg `--simulation all` then all three simulations :two-gal, multi-gal, group are run.
###Output
_____no_output_____ |
08 - Speech.ipynb | ###Markdown
Voce
Sempre più spesso, ci aspettiamo di poter comunicare con i sistemi di intelligenza artificiale (IA) parlando loro, spesso con l'aspettativa di una risposta parlata.

Il *riconoscimento vocale* (un sistema di AI che interpreta il linguaggio parlato) e la *sintesi vocale* (un sistema di AI che genera una risposta parlata) sono i componenti chiave di una soluzione di AI con abilitazione vocale.
Crea una risorsa di servizi cognitivi
Per sviluppare un software in grado di interpretare una voce udibile e rispondere verbalmente, è possibile utilizzare il servizio cognitivo **Voce**, che fornisce un modo semplice per trascrivere il linguaggio parlato in testo e viceversa.
Se non ne hai già una, procedi come segue per creare una risorsa di **Servizi Cognitivi** nella tua sottoscrizione di Azure:
> **Nota**: Se disponi già di una risorsa di Servizi Cognitivi, basta aprire la sua pagina **Avvio rapido** nel portale di Azure e copiare la sua chiave e l'endpoint nella cella seguente. Altrimenti, procedi come segue per crearne una.
1. In un'altra scheda del browser, apri il portale di Azure all'indirizzo https://portal.azure.com, accedendo con il tuo account Microsoft.
2. Fai clic sul pulsante **&65291;Crea una risorsa**, cerca *Servizi cognitivi* e crea una risorsa di **Servizi cognitivi** con le impostazioni seguenti:
- **Sottoscrizione**: *La tua sottoscrizione di Azure*.
- **Gruppo di risorse**: *Seleziona o crea un gruppo di risorse con un nome univoco*.
- **Area geografica**: *Scegli una qualsiasi area disponibile*:
- **Nome**: *Immetti un nome univoco*.
- **Piano tariffario**: S0
- **Confermo di aver letto e compreso gli avvisi**: Selezionato.
3. Attendi il completamento della distribuzione. Vai quindi alla tua risorsa di servizi cognitivi e, nella pagina **Panoramica**, fai clic sul link per gestire le chiavi per il servizio. Avrai bisogno della chiave e della posizione per connetterti alla tua risorsa di servizi cognitivi dalle applicazioni client.
Ottieni la chiave e la posizione per la tua risorsa di Servizi cognitivi
Per usare la risorsa di servizi cognitivi, le applicazioni client hanno bisogno della chiave di autenticazione e della posizione:
1. Nel portale di Azure, nella pagina **Chiavi ed endpoint** per la tua risorsa di servizio cognitivo, copia la **Key1** per la tua risorsa e incollala nel codice sottostante, sostituendo **YOUR_COG_KEY**.
2. Copia la **Posizione** per la tua risorsa e incollala nel codice sottostante, sostituendo **YOUR_COG_LOCATION**.
>**Nota**: Rimani nella pagina **Chiavi ed endpoint** e copia la **Posizione** da questa pagina (esempio: _westus_). Non aggiungere spazi tra le parole per il campo Posizione.
3. Esegui il codice seguente facendo clic sul pulsante **Esegui cella** (&9655;) a sinistra della cella.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Riconoscimento vocale
Supponiamo che tu voglia creare un sistema di automazione domestica che accetti istruzioni vocali, come "accendi la luce" o "spegni la luce". La tua applicazione deve essere in grado di prendere l'input basato sull'audio (la tua istruzione parlata), e interpretarlo trascrivendolo in testo che può poi analizzare.
È tutto pronto per trascrivere una voce. L'input può venire da un **microfono**o da un **file audio**.
Riconoscimento vocale con un file audio
Esegui la cella seguente per vedere il servizio di riconoscimento vocale in azione con un **file audio**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Sintesi vocale
Dunque ora hai visto in che modo è possibile usare il servizio Voce per trascrivere il parlato in testo; e per quanto riguarda il contrario? Come si converte il testo in parlato?
Supponiamo che il tuo sistema domotico abbia interpretato un comando per accendere la luce. Una risposta appropriata potrebbe essere quella di confermare verbalmente il comando (oltre a eseguire effettivamente il compito richiesto)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
SpeechIncreasingly, we expect to be able to communicate with artificial intelligence (AI) systems by talking to them, often with the expectation of a spoken response.*Speech recognition* (an AI system interpreting spoken language) and *speech synthesis* (an AI system generating a spoken response) are the key components of a speech-enabled AI solution. Create a Cognitive Services resourceTo build software that can interpret audible speech and respond verbally, you can use the **Speech** cognitive service, which provides a simple way to transcribe spoken language into text and vice-versa.If you don't already have one, use the following steps to create a **Cognitive Services** resource in your Azure subscription:> **Note**: If you already have a Cognitive Services resource, just open its **Quick start** page in the Azure portal and copy its key and endpoint to the cell below. Otherwise, follow the steps below to create one.1. In another browser tab, open the Azure portal at https://portal.azure.com, signing in with your Microsoft account.2. Click the **&65291;Create a resource** button, search for *Cognitive Services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Your Azure subscription*. - **Resource group**: *Select or create a resource group with a unique name*. - **Region**: *Choose any available region*: - **Name**: *Enter a unique name*. - **Pricing tier**: S0 - **I confirm I have read and understood the notices**: Selected.3. Wait for deployment to complete. Then go to your cognitive services resource, and on the **Overview** page, click the link to manage the keys for the service. You will need the key and location to connect to your cognitive services resource from client applications. Get the Key and Location for your Cognitive Services resourceTo use your cognitive services resource, client applications need its authentication key and location:1. In the Azure portal, on the **Keys and Endpoint** page for your cognitive service resource, copy the **Key1** for your resource and paste it in the code below, replacing **YOUR_COG_KEY**.2. Copy the **Location** for your resource and and paste it in the code below, replacing **YOUR_COG_LOCATION**.>**Note**: Stay on the **Keys and Endpoint** page and copy the **Location** from this page (example: _westus_). Please _do not_ add spaces between words for the Location field. 3. Run the code below by clicking the **Run cell** (&9655;) button to the left of the cell.
###Code
cog_key = 'YOUR_COG_ENDPOINT'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
Ready to use cognitive services in southeastasia using key 2336de0ef3b84486b880df8d17665a71
###Markdown
Speech recognitionSuppose you want to build a home automation system that accepts spoken instructions, such as "turn the light on" or "turn the light off". Your application needs to be able to take the audio-based input (your spoken instruction), and interpret it by transcribing it to text that it can then parse and analyze.Now you're ready to transcribe some speech. The input can be from a **microphone** or an **audio file**. Speech Recognition with an audio fileRun the cell below to see the Speech Recognition service in action with an **audio file**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
#file_name = 'light-off.wav'
#audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location, speech_recognition_language='id-ID')
#audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
audio_config = AudioConfig(use_default_microphone=True)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
#playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
Hai ayu tuh kalau.
###Markdown
Speech synthesisSo now you've seen how the Speech service can be used to transcribe speech into text; but what about the opposite? How can you convert text into speech?Well, let's assume your home automation system has interpreted a command to turn the light on. An appropriate response might be to acknowledge the command verbally (as well as actually performing the commanded task!)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
会話
話しかけると、話し言葉で応答してくれるような人工知能 (AI) システムとのコミュニケーションの実現に向けて、期待が高まっています。

*音声認識* (話し言葉を解釈する AI システム) と*音声合成* (音声応答を生成する AI システム) は、会話を実現する AI ソリューションの重要なコンポーネントです。
Cognitive Services リソースを作成する
**Speech** Cognitive Service を使用すると、聞こえてくる言葉を解釈して、音声で応答できるソフトウェアを構築できます。このサービスを使用すると、話し言葉をテキストに変換したり、その逆に変換したりすることが簡単に行えます。
まだリソースを作成していない場合は、次の手順で Azure サブスクリプションに **Cognitive Services** リソースを作成します。
> **注**: Cognitive Services リソースが既にある場合は、Azure portal で**クイック スタート**ページを開き、キーとエンドポイントを以下のセルにコピーするだけで作成できます。それ以外の場合は、以下の手順に従って作成してください。
1. ブラウザーの新しいタブで Azure portal (https://portal.azure.com) を開き、Microsoft アカウントでサインインします。
2. 「**&65291;リソースの作成**」 ボタンをクリックし、*Cognitive Services* を検索して、以下の設定で **Cognitive Services** リソースを作成します。
- **サブスクリプション**: *使用する Azure サブスクリプション*
- **リソース グループ**: *一意の名前のリソース グループを選択または作成します*
- **リージョン**: *利用可能な任意のリージョンを選択します*。
- **名前**: *一意の名前を入力します*。
- **価格レベル**: S0
- **注意事項を読み理解しました**: 選択されています。
3. デプロイが完了するまで待ちます。そのあと Cognitive Services リソースに移動し、「**概要**」 ページでリンクをクリックしてサービスのキーを管理します。クライアント アプリケーションから Cognitive Services リソースに接続するには、キーと場所が必要です。
Cognitive Services リソースのキーと場所を取得する
Cognitive Services リソースを使用するには、クライアント アプリケーションに認証キーと場所が必要です。
1. Azure portalで、Cognitive Services リソースの 「**キーとエンドポイント**」 ページからリソースの 「**キー 1**」 の値をコピーし、以下のコードに貼り付けます (**YOUR_COG_KEY** と置き換える)。
2. リソースの**場所**をコピーして以下のコードに貼り付けます (**YOUR_COG_LOCATION** を置き換える)。
>**注**: 「**キーとエンドポイント**」 ページにとどまり、このページから**場所**をコピーします (例: _westus_)。「場所」 フィールドの単語の間には空白を入れ _ないで_ ください。
3. セルの左側にある 「**セルの実行**」 (&9655;) ボタンをクリックして、以下のコードを実行します。
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
音声認識
「明かりをつけて」や「明かりを消して」などの音声指示に対応できるホーム オートメーション システムを構築するとします。アプリケーションは、音声ベースの入力 (話された指示) を受け取り、それをテキストに書き起こして認識し、構文解析と意味を分析できる必要があります。
これで、音声を書き写す準備が整いました。入力は、**マイク**または**音声ファイル**から行うことができます。
音声ファイルを使用した音声認識
以下のセルを実行し、**音声ファイル**を使用して Speech Recognition サービスが稼働していることを確認します。
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
音声合成
これで、Speech サービスを使用して音声をテキストに変換する方法を確認できました。ただし、逆の変換はまだです。テキストを音声に変換するにはどうすればよいでしょうか?
ホーム オートメーション システムが明かりをつける指示を解釈したとします。適切な応答とは、指示されたことを口頭で確認したり、指示されたタスクを実際に実行したりすることでしょう。
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
語音
我們愈發期望能夠透過與 AI 對話來與人工智慧 (AI) 系統交談,我們通常懷著對語音回應的期待。

*語音辨識* (解譯語音語言的 AI 系統) 和*語音合成* (生成語音回應的 AI 系統) 是啟用語音的 AI 解決方案的關鍵元件。
建立認知服務資源
若要組建可以解譯聲音語音和口頭回應的軟體,您可以使用**語音**認知服務,它提供一種直接將語音語言轉譯為文字的方法 (反之亦然)。
如果您還沒有該資源,請使用以下步驟在您的 Azure 訂用帳戶中建立一個**認知服務**資源:
> **備註**:若您已經有認知服務資源,只需在 Azure 入口網站中開啟其 **[快速入門]** 頁面並將其金鑰和端點複製到下面的儲存格。否則,可追隨下面的步驟來建立一個認知服務資源。
1. 在其它瀏覽器索引標籤中,透過 https://portal.azure.com 開啟 Azure 入口網站,並用您的 Microsoft 帳戶登入。
2. 按一下 **[&65291; 建立資源]** 按鈕,搜尋*認知服務*,並建立包含以下設定的**認知服務**資源:
- **訂用帳戶**: *您的 Azure 訂用帳戶*。
- **資源群組**: *選取或建立具有唯一名稱的資源群組*。
- **區域**: *選擇任一可用區域*:
- **名稱**: *輸入唯一名稱*。
- **定價層**:S0
- **我確認已閱讀通知並理解通知內容**:已選取。
3. 等待部署完成。然後前往您的認知服務資源,在 **[概觀]** 頁面上,按一下連結以管理服務金鑰。您將需要金鑰和位置以便從用戶端應用程式連線到您的認知服務資源。
獲取適用於認知服務資源的金鑰和位置
若要使用您的認知服務資源,用戶端應用程式需要其驗證金鑰和位置:
1. 在 Azure 入口網站中,您的認知服務資源之 **[金鑰和端點]** 頁面上,複製您的資源之**金鑰 1** 並將其貼上到下面的程式碼,取代 **YOUR_COG_KEY**。
2. 複製您的資源之**位置**並將其貼上到下面的程式碼中,取代 **YOUR_COG_LOCATION**。
>**備註**:留在 **[金鑰和端點]** 頁面並從此頁面複製**位置**(範例:_westus_)。請 _勿_ 在 [位置] 欄位的文字之間增加空格。
3. 透過按一下儲存格左側的 **[執行儲存格]** (&9655;) 按鈕執行下方程式碼。
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
語音辨識
假設您想要組建接受語音指示 (例如「開燈」或「關燈」) 的首頁自動化系統。您的應用程式需要能夠接受以音訊為基礎的輸入 (您的語音指示),並透過將其轉譯成可以剖析和分析的文字來解譯它。
現在您可以準備轉譯若干語音。輸入可以來自**麥克風**或**音訊檔案**。
語音辨識和音訊檔案
執行下方儲存格來查看使用**音訊檔案**的語音辨識服務。
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
語音合成
那麼現在您已經看過語音服務是怎樣把語音轉譯為文字的,但是反過來又是怎樣的呢?您該怎樣把文字轉換成語音呢?
那麼,讓我們假設您的首頁自動化系統已經解譯了開燈命令。適用的回應也許可以確認口頭命令 (以及實際執行命令的任務!)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
SpeechIncreasingly, we expect to be able to communicate with artificial intelligence (AI) systems by talking to them, often with the expectation of a spoken response.*Speech recognition* (an AI system interpreting spoken language) and *speech synthesis* (an AI system generating a spoken response) are the key components of a speech-enabled AI solution. Create a Cognitive Services resourceTo build software that can interpret audible speech and respond verbally, you can use the **Speech** cognitive service, which provides a simple way to transcribe spoken language into text and vice-versa.If you don't already have one, use the following steps to create a **Cognitive Services** resource in your Azure subscription:> **Note**: If you already have a Cognitive Services resource, just open its **Quick start** page in the Azure portal and copy its key and endpoint to the cell below. Otherwise, follow the steps below to create one.1. In another browser tab, open the Azure portal at https://portal.azure.com, signing in with your Microsoft account.2. Click the **&65291;Create a resource** button, search for *Cognitive Services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Your Azure subscription*. - **Resource group**: *Select or create a resource group with a unique name*. - **Region**: *Choose any available region*: - **Name**: *Enter a unique name*. - **Pricing tier**: S0 - **I confirm I have read and understood the notices**: Selected.3. Wait for deployment to complete. Then go to your cognitive services resource, and on the **Overview** page, click the link to manage the keys for the service. You will need the key and location to connect to your cognitive services resource from client applications. Get the Key and Location for your Cognitive Services resourceTo use your cognitive services resource, client applications need its authentication key and location:1. In the Azure portal, on the **Keys and Endpoint** page for your cognitive service resource, copy the **Key1** for your resource and paste it in the code below, replacing **YOUR_COG_KEY**.2. Copy the **Location** for your resource and and paste it in the code below, replacing **YOUR_COG_LOCATION**.>**Note**: Stay on the **Keys and Endpoint** page and copy the **Location** from this page (example: _westus_). Please _do not_ add spaces between words for the Location field. 3. Run the code below by clicking the **Run cell** (&9655;) button to the left of the cell.
###Code
cog_key = '866f45546cd44c0ab9d96b383a529f80'
cog_location = 'westeurope'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
Ready to use cognitive services in westeurope using key 866f45546cd44c0ab9d96b383a529f80
###Markdown
Speech recognitionSuppose you want to build a home automation system that accepts spoken instructions, such as "turn the light on" or "turn the light off". Your application needs to be able to take the audio-based input (your spoken instruction), and interpret it by transcribing it to text that it can then parse and analyze.Now you're ready to transcribe some speech. The input can be from a **microphone** or an **audio file**. Speech Recognition with an audio fileRun the cell below to see the Speech Recognition service in action with an **audio file**.
###Code
pip install azure-cognitiveservices-speech
pip install playsound
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Show transcribed text from audio file
print(speech.text)
###Output
Turn the light on.
###Markdown
Speech synthesisSo now you've seen how the Speech service can be used to transcribe speech into text; but what about the opposite? How can you convert text into speech?Well, let's assume your home automation system has interpreted a command to turn the light on. An appropriate response might be to acknowledge the command verbally (as well as actually performing the commanded task!)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
# Get text to be spoken
response_text = 'Turning the light off.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
###Output
_____no_output_____
###Markdown
Fala
Cada vez mais, esperamos ser capazes de nos comunicar com sistemas de inteligência artificial (IA) falando com eles, frequentemente com a expectativa de receber uma resposta falada.

O *Reconhecimento de fala* (um sistema de IA que interpreta a linguagem falada) e a *Síntese de fala* (um sistema de IA que gera uma resposta falada) são os principais componentes de uma solução de IA habilitada para a fala.
Criar um recurso dos Serviços Cognitivos
Para criar um software que consiga interpretar fala audível e responder verbalmente, é possível usar o serviço cognitivo de **Fala**, que proporciona uma maneira simples de transformar linguagem falada em texto e vice-versa.
Caso você ainda não tenha um, use as etapas a seguir para criar um recurso dos **Serviços Cognitivos** na sua assinatura do Azure:
> **Observação**: Se você já tiver um recurso dos Serviços Cognitivos, abra a página de **Início Rápido** no portal do Azure e copie a respectiva chave e o ponto de extremidade para a célula abaixo. Caso contrário, siga as etapas abaixo para criar um.
1. Em outra guia do navegador, abra o portal do Azure em https://portal.azure.com, entrando com sua conta Microsoft.
2. Clique no botão **&65291;Criar um recurso**, procure *Serviços Cognitivos* e crie um recurso dos **Serviços Cognitivos** com as configurações abaixo:
- **Assinatura**: *sua assinatura do Azure*.
- **Grupo de recursos**: *Selecione ou crie um grupo de recursos com um nome exclusivo*.
- **Região**: *Escolha qualquer região disponível*:
- **Nome**: *Insira um nome exclusivo*.
- **Tipo de preço**: S0
- **Confirmo que li e entendi os avisos**: Selecionado.
3. Aguarde até que a implantação seja concluída. Depois, entre em seu recurso dos Serviços Cognitivos e, na página **Visão geral**, clique no link para gerenciar as chaves do serviço. Você precisará da chave e da localização para se conectar aos seus recursos dos Serviços Cognitivos em aplicativos clientes.
Obter a chave e a localização do seu recurso dos Serviços Cognitivos
Para usar seu recurso dos Serviços Cognitivos, os aplicativos clientes precisam da chave de autenticação e da localização:
1. No portal do Azure, na página **Chaves e ponto de extremidade** do seu recurso dos Serviços Cognitivos, copie a **Chave 1** do recurso e cole no código abaixo, substituindo **YOUR_COG_KEY**.
2. Copie a **Localização** do recurso e cole no código abaixo, substituindo **YOUR_COG_LOCATION**.
>**Observação**: continue na página **Chave e ponto de extremidade** e copie a **Localização** desta página (por exemplo: _westus_). _Não_ adicione espaços entre as palavras no campo Localização.
3. Execute o código abaixo clicando no botão **Executar célula** (&9655;) à esquerda.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Reconhecimento de fala
Suponha que você queira construir um sistema de automação residencial que aceite instruções faladas, como "acender a luz" ou "apagar a luz". Seu aplicativo precisará ser capaz de receber a entrada baseada em áudio (sua instrução falada) e interpretá-la, transformando o comando em um texto que possa ser analisado.
Agora você está pronto para transcrever falas. A entrada pode vir de um **microfone** ou um **arquivo de áudio**.
Reconhecimento de fala com um arquivo em áudio
Execute a célula abaixo para ver o serviço de Reconhecimento de fala em ação com um **arquivo de áudio**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Sintetização de voz
Agora você já viu como o serviço de Fala pode ser usado para transformar fala em texto, mas e o inverso? Como fazer a conversão de texto em fala?
Bom, vamos supor que o seu sistema de automação residencial tenha interpretado o comando para acender a luz. Uma resposta apropriada seria reconhecer o comando verbalmente (além de realizar a tarefa solicitada!).
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
SpeechIncreasingly, we expect to be able to communicate with artificial intelligence (AI) systems by talking to them, often with the expectation of a spoken response.*Speech recognition* (an AI system interpreting spoken language) and *speech synthesis* (an AI system generating a spoken response) are the key components of a speech-enabled AI solution. Create a Cognitive Services resourceTo build software that can interpret audible speech and respond verbally, you can use the **Speech** cognitive service, which provides a simple way to transcribe spoken language into text and vice-versa.If you don't already have one, use the following steps to create a **Cognitive Services** resource in your Azure subscription:> **Note**: If you already have a Cognitive Services resource, just open its **Quick start** page in the Azure portal and copy its key and endpoint to the cell below. Otherwise, follow the steps below to create one.1. In another browser tab, open the Azure portal at https://portal.azure.com, signing in with your Microsoft account.2. Click the **&65291;Create a resource** button, search for *Cognitive Services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Your Azure subscription*. - **Resource group**: *Select or create a resource group with a unique name*. - **Region**: *Choose any available region*: - **Name**: *Enter a unique name*. - **Pricing tier**: S0 - **I confirm I have read and understood the notices**: Selected.3. Wait for deployment to complete. Then go to your cognitive services resource, and on the **Overview** page, click the link to manage the keys for the service. You will need the key and location to connect to your cognitive services resource from client applications. Get the Key and Location for your Cognitive Services resourceTo use your cognitive services resource, client applications need its authentication key and location:1. In the Azure portal, on the **Keys and Endpoint** page for your cognitive service resource, copy the **Key1** for your resource and paste it in the code below, replacing **YOUR_COG_KEY**.2. Copy the **Location** for your resource and and paste it in the code below, replacing **YOUR_COG_LOCATION**.>**Note**: Stay on the **Keys and Endpoint** page and copy the **Location** from this page (example: _westus_). Please _do not_ add spaces between words for the Location field. 3. Run the code below by clicking the **Run cell** (&9655;) button to the left of the cell.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Speech recognitionSuppose you want to build a home automation system that accepts spoken instructions, such as "turn the light on" or "turn the light off". Your application needs to be able to take the audio-based input (your spoken instruction), and interpret it by transcribing it to text that it can then parse and analyze.Now you're ready to transcribe some speech. The input can be from a **microphone** or an **audio file**. Speech Recognition with an audio fileRun the cell below to see the Speech Recognition service in action with an **audio file**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(subscription=cog_key, endpoint=cog_location)
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Speech synthesisSo now you've seen how the Speech service can be used to transcribe speech into text; but what about the opposite? How can you convert text into speech?Well, let's assume your home automation system has interpreted a command to turn the light on. An appropriate response might be to acknowledge the command verbally (as well as actually performing the commanded task!)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(subscription=cog_key, endpoint=cog_location)
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
SpeechIncreasingly, we expect to be able to communicate with artificial intelligence (AI) systems by talking to them, often with the expectation of a spoken response.*Speech recognition* (an AI system interpreting spoken language) and *speech synthesis* (an AI system generating a spoken response) are the key components of a speech-enabled AI solution. Create a Cognitive Services resourceTo build software that can interpret audible speech and respond verbally, you can use the **Speech** cognitive service, which provides a simple way to transcribe spoken language into text and vice-versa.If you don't already have one, use the following steps to create a **Cognitive Services** resource in your Azure subscription:> **Note**: If you already have a Cognitive Services resource, just open its **Quick start** page in the Azure portal and copy its key and endpoint to the cell below. Otherwise, follow the steps below to create one.1. In another browser tab, open the Azure portal at https://portal.azure.com, signing in with your Microsoft account.2. Click the **&65291;Create a resource** button, search for *Cognitive Services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Your Azure subscription*. - **Resource group**: *Select existing resource group with name AI900-deploymentID*. - **Region**: *Choose any available region*: - **Name**: *speech-deploymentID*. - **Pricing tier**: S0 - **I confirm I have read and understood the notices**: Selected.3. Wait for deployment to complete. Then go to your cognitive services resource, and on the **Overview** page, click the link to manage the keys for the service. You will need the key and location to connect to your cognitive services resource from client applications. Get the Key and Location for your Cognitive Services resourceTo use your cognitive services resource, client applications need its authentication key and location:1. In the Azure portal, on the **Keys and Endpoint** page for your cognitive service resource, copy the **Key1** for your resource and paste it in the code below, replacing **YOUR_COG_KEY**.2. Copy the **Location** for your resource and and paste it in the code below, replacing **YOUR_COG_LOCATION**.>**Note**: Stay on the **Keys and Endpoint** page and copy the **Location** from this page (example: _westus_). Please _do not_ add spaces between words for the Location field. 3. Run the code below by clicking the **Run cell** (&9655;) button to the left of the cell.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Speech recognitionSuppose you want to build a home automation system that accepts spoken instructions, such as "turn the light on" or "turn the light off". Your application needs to be able to take the audio-based input (your spoken instruction), and interpret it by transcribing it to text that it can then parse and analyze.Now you're ready to transcribe some speech. The input can be from a **microphone** or an **audio file**. Speech Recognition with an audio fileRun the cell below to see the Speech Recognition service in action with an **audio file**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Speech synthesisSo now you've seen how the Speech service can be used to transcribe speech into text; but what about the opposite? How can you convert text into speech?Well, let's assume your home automation system has interpreted a command to turn the light on. An appropriate response might be to acknowledge the command verbally (as well as actually performing the commanded task!)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
Voz
Cada vez será más habitual comunicarnos con sistemas de inteligencia artificial (IA) mediante nuestra voz y, a menudo, esperaremos una respuesta hablada.

*Reconocimiento de voz* (un sistema de IA que interpreta el lenguaje hablado) y *Síntesis de voz* (un sistema de IA que genera una respuesta hablada) son los componentes principales de una solución de IA habilitada por voz.
Crear un recurso de Cognitive Services
Para crear un software que pueda interpretar el lenguaje hablado y responder de la misma manera, puede usar **Voz** de Cognitive Services, que permite convertir lenguaje hablado en texto y viceversa.
Si no tiene uno, siga estos pasos para crear un recurso de **Cognitive Services** en su suscripción de Azure:
> **Nota**: Si ya tiene un recurso de Cognitive Services, abra su página de **Inicio rápido** en Azure Portal y copie la clave y el punto de conexión en la siguiente celda. En caso contrario, siga estos pasos para crear uno.
1. En la pestaña de otro explorador, abra Azure Portal (https://portal.azure.com) e inicie sesión con su cuenta de Microsoft.
2. Haga clic en el botón **&65291;Crear un recurso**, busque *Cognitive Services* y cree un recurso de **Cognitive Services** con esta configuración:
- **Suscripción**: *su suscripción de Azure*.
- **Grupo de recursos**: *seleccione o cree un grupo de recursos con un nombre único.*
- **Región**: *seleccione cualquier región disponible*:
- **Nombre**: *escriba un nombre único*.
- **Plan de tarifa**: S0
- **Confirmo que he leído y comprendido las notificaciones**: seleccionado.
3. Espere a que la implementación finalice. Vaya al recurso de Cognitive Services y, en la página **Información general**, haga clic en el vínculo para administrar las claves del servicio. Necesitará la clave y la ubicación para conectarse a su recurso de Cognitive Services desde aplicaciones de cliente.
Obtener la clave y la ubicación de un recurso de Cognitive Services
Para usar su recurso de Cognitive Services, las aplicaciones de cliente necesitan su clave de autenticación y su ubicación:
1. En Azure Portal, en la página **Claves y punto de conexión** de su recurso de Cognitive Services, copie la **Key1** de su recurso y péguela en el siguiente código, en sustitución de **YOUR_COG_KEY**.
2. Copie la **Ubicación** de su recurso y péguela en el siguiente código, en sustitución de **YOUR_COG_LOCATION**.
>**Nota**: Quédese en la página **Claves y punto de conexión** y copie la **Ubicación** desde esta página, (ejemplo: _westus_). No_agregue_espacios entre las palabras del campo Ubicación.
3. Ejecute el código siguiente. Para ello, haga clic en **Run cell** (&9655;) a la izquierda de la celda.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Reconocimiento de voz
Digamos que quiere crear un sistema de automatización del hogar que acepte instrucciones habladas, como “turn the light on” para encender la luz y “turn the light off” para apagarla. Su aplicación debe ser capaz de reconocer el audio de su voz (su instrucción hablada), interpretarlo y convertirlo en texto para, después, procesarlo y analizarlo.
Ya está listo para transcribir audio. La entrada de audio puede recibirse a través de un **micrófono** o mediante un **archivo de audio**.
Reconocimiento de voz con un archivo de audio
Ejecute la celda siguiente para ver cómo funciona el servicio Reconocimiento de voz con un **archivo de audio**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Síntesis de voz
Ya hemos visto cómo usar el servicio Voz para transcribir el lenguaje hablado, pero ¿qué pasa si queremos convertir el texto en voz? ¿Cómo podemos hacerlo?
Supongamos que su sistema de automatización del hogar ha interpretado un comando para encender la luz (“turn the light on”). Lo esperado sería que el sistema respondiera al comando y que, además, realizase la acción solicitada.
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
SpeechIncreasingly, we expect to be able to communicate with artificial intelligence (AI) systems by talking to them, often with the expectation of a spoken response.*Speech recognition* (an AI system interpreting spoken language) and *speech synthesis* (an AI system generating a spoken response) are the key components of a speech-enabled AI solution. Create a Cognitive Services resourceTo build software that can interpret audible speech and respond verbally, you can use the **Speech** cognitive service, which provides a simple way to transcribe spoken language into text and vice-versa.If you don't already have one, use the following steps to create a **Cognitive Services** resource in your Azure subscription:> **Note**: If you already have a Cognitive Services resource, just open its **Quick start** page in the Azure portal and copy its key and endpoint to the cell below. Otherwise, follow the steps below to create one.1. In another browser tab, open the Azure portal at https://portal.azure.com, signing in with your Microsoft account.2. Click the **&65291;Create a resource** button, search for *Cognitive Services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Your Azure subscription*. - **Resource group**: *Select or create a resource group with a unique name*. - **Region**: *Choose any available region*: - **Name**: *Enter a unique name*. - **Pricing tier**: S0 - **I confirm I have read and understood the notices**: Selected.3. Wait for deployment to complete. Then go to your cognitive services resource, and on the **Overview** page, click the link to manage the keys for the service. You will need the key and location to connect to your cognitive services resource from client applications. Get the Key and Location for your Cognitive Services resourceTo use your cognitive services resource, client applications need its authentication key and location:1. In the Azure portal, on the **Keys and Endpoint** page for your cognitive service resource, copy the **Key1** for your resource and paste it in the code below, replacing **YOUR_COG_KEY**.2. Copy the **Location** for your resource and and paste it in the code below, replacing **YOUR_COG_LOCATION**.>**Note**: Stay on the **Keys and Endpoint** page and copy the **Location** from this page (example: _westus_). Please _do not_ add spaces between words for the Location field. 3. Run the code below by clicking the **Run cell** (&9655;) button to the left of the cell.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Speech recognitionSuppose you want to build a home automation system that accepts spoken instructions, such as "turn the light on" or "turn the light off". Your application needs to be able to take the audio-based input (your spoken instruction), and interpret it by transcribing it to text that it can then parse and analyze.Now you're ready to transcribe some speech. The input can be from a **microphone** or an **audio file**. Speech Recognition with an audio fileRun the cell below to see the Speech Recognition service in action with an **audio file**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Speech synthesisSo now you've seen how the Speech service can be used to transcribe speech into text; but what about the opposite? How can you convert text into speech?Well, let's assume your home automation system has interpreted a command to turn the light on. An appropriate response might be to acknowledge the command verbally (as well as actually performing the commanded task!)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
Ucapan
Semakin lama, kami berharap dapat berkomunikasi dengan sistem kecerdasan buatan (AI) dengan berbicara kepadanya, seringkali dengan harapan mendapatkan respons lisan.

*Pendahuluan ucapan* (sistem AI yang menafsirkan bahasa lisan) dan *sintesis ucapan* (sistem AI yang membuat respons lisan) adalah komponen penting dari solusi AI yang didukung oleh ucapan.
Membuat sumber daya Cognitive Services
Untuk membuat perangkat lunak yang dapat menafsirkan ucapan yang dapat didengar dan merespons secara verbal, Anda dapat menggunakan layanan kognitif **Ucapan**, yang menyediakan cara sederhana untuk mentranskripsikan bahasa lisan menjadi teks dan sebaliknya.
Jika Anda belum memilikinya, gunakan langkah-langkah berikut untuk membuat sumber daya **Cognitive Services** di langganan Azure Anda:
> **Catatan**: Jika Anda sudah memiliki sumber daya Cognitive Services, cukup buka halaman Mulai cepat di portal Microsoft Azure dan salin kunci dan titik akhirnya ke sel di bawah. Atau, ikuti langkah-langkah di bawah untuk membuatnya.
1. Di tab browser lain, buka portal Microsoft Azure di https://portal.azure.com, masuk menggunakan akun Microsoft Anda.
2. Klik tombol **&65291;Buat sumber daya**, cari *Cognitive Services*, dan buat sumber daya **Cognitive Services** dengan pengaturan berikut:
- **Langganan**: *Langganan Azure Anda*.
- **Grup sumber daya**: *Pilih atau buat grup sumber daya dengan nama unik*.
- **Wilayah**: *Pilih wilayah yang tersedia*:
- **Nama**: *Masukkan nama yang unik*.
- **Tingkat Harga**: S0
- **Saya mengonfirmasi bahwa saya telah membaca dan memahami pemberitahuan tersebut**: Dipilih.
3. Tunggu penyebaran hingga selesai. Lalu, buka sumber daya layanan kognitif, dan di halaman **Ringkasan**, klik tautan untuk mengelola kunci layanan. Anda akan memerlukan kunci dan lokasi untuk terhubung ke sumber daya layanan kognitif dari aplikasi klien.
Mendapatkan Kunci dan Lokasi untuk sumber daya Cognitive Services Anda
Untuk menggunakan sumber daya layanan kognitif, aplikasi klien memerlukan lokasi dan kunci autentikasinya:
1. Di portal Azure, di halaman **Kunci dan Titik Akhir** untuk sumber daya layanan kognitif Anda, salin **Kunci1** untuk sumber daya dan tempel pada kode di bawah, menggantikan **YOUR_COG_KEY**.
2. Salin **Lokasi** untuk sumber daya Anda dan tempel pada kode di bawah, menggantikan **YOUR_COG_LOCATION**.
>Catatan: Tetap di halaman **Kunci dan Titik Akhir** dan salin **Lokasi** dari halaman ini (contoh: _westus_). Jangan _tambahkan_ spasi di antara kata untuk bidang Lokasi.
3. Jalankan kode di bawah dengan mengeklik tombol **Jalankan sel** (&9655;) di sebelah kiri sel.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Pendahuluan ucapan
Misalkan Anda ingin membangun sistem otomatisasi rumah yang menerima instruksi lisan, seperti "nyalakan lampu" atau "matikan lampu". Aplikasi Anda harus dapat menerima input berbasis audio (instruksi lisan Anda), dan menafsirkannya dengan mentranskripsikannya ke teks yang kemudian dapat diuraikan dan dianalisis.
Sekarang Anda siap untuk mentranskripsikan beberapa ucapan. Input tersebut bisa berasal dari **mikrofon** atau **file audio**.
Pendahuluan Ucapan dengan file audio
Jalankan sel di bawah untuk melihat layanan Pendahuluan Ucapan bekerja dengan **file audio**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Sintesis ucapan
Jadi sekarang Anda telah melihat bagaimana layanan Ucapan dapat digunakan untuk mentranskripsikan ucapan menjadi teks; tapi bagaimana dengan sebaliknya? Bagaimana Anda dapat mengonversi teks menjadi ucapan?
Nah, mari kita asumsikan sistem otomatisasi rumah Anda telah menafsirkan perintah untuk menyalakan lampu. Respons yang sesuai bisa jadi mengetahui perintah secara verbal (serta melakukan tugas yang diperintahkan secara aktual!).
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
음성
대화를 통해 AI(인공 지능) 시스템과 커뮤니케이션할 수 있기를 바라는 기대치가 점점 커지고 있으며, 음성 응답을 기대하는 경우도 많습니다.

*음성 인식*(구어를 해석하는 AI 시스템)과 *음성 합성*(구어 응답을 생성하는 AI 시스템)은 음성 지원 AI 솔루션의 핵심 구성 요소입니다.
Cognitive Services 리소스 만들기
들리는 음성을 해석하고 구두로 응답하는 것이 가능한 소프트웨어를 만들기 위해 음성 언어를 텍스트로 혹은 그 반대로 변환하는 간단한 방법을 제공하는 **Speech** Cognitive Service를 사용할 수 있습니다.
아직 없다면 다음 단계를 따라 Azure 구독에서 **Cognitive Services** 리소스를 만듭니다.
> **참고**: 이미 Cognitive Services 리소스를 보유하고 있다면 Azure Portal에서 **빠른 시작** 페이지를 열고 키 및 엔드포인트를 아래의 셀로 복사하기만 하면 됩니다. 리소스가 없다면 아래의 단계를 따라 리소스를 만듭니다.
1. 다른 브라우저 탭에서 Azure Portal(https://portal.azure.com) 을 열고 Microsoft 계정으로 로그인합니다.
2. **&65291;리소스 만들기** 단추를 클릭하고, *Cognitive Services*를 검색하고, 다음 설정을 사용하여 **Cognitive Services** 리소스를 만듭니다.
- **구독**: *사용자의 Azure 구독*.
- **리소스 그룹**: *고유한 이름의 새 리소스 그룹을 선택하거나 만듭니다*.
- **지역**: *사용 가능한 지역을 선택합니다*.
- **이름**: *고유한 이름을 입력합니다*.
- **가격 책정 계층**: S0
- **알림을 읽고 이해했음을 확인합니다**. 선택됨.
3. 배포가 완료될 때까지 기다립니다. 그런 다음에 Cognitive Services 리소스로 이동하고, **개요** 페이지에서 링크를 클릭하여 서비스의 키를 관리합니다. 클라이언트 애플리케이션에서 Cognitive Services 리소스에 연결하려면 키 및 위치가 필요합니다.
Cognitive Services 리소스의 키 및 위치 가져오기
Cognitive Services 리소스를 사용하려면 클라이언트 애플리케이션에 인증 키 및 위치가 필요합니다.
1. Azure Portal에 있는 Cognitive Service 리소스의 **키 및 엔드포인트** 페이지에서 리소스의 **Key1**을 복사하고 아래 코드에 붙여 넣어 **YOUR_COG_KEY**를 대체합니다.
2. 리소스의 **위치**를 복사하고 아래 코드에 붙여 넣어 **YOUR_COG_LOCATION**를 대체합니다.
>**참고**: **키 및 엔드포인트** 페이지에 그대로 있으면서 이 페이지에서 **위치**를 복사하세요(예: _westus_). 위치 필드의 단어 사이에 공백을 추가해서는 _안 됩니다_.
3. 셀 왼쪽에 있는 **셀 실행**(&9655;) 단추를 클릭하여 아래의 코드를 실행합니다.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
음성 인식
"불 켜" 또는 "불 꺼"와 같은 음성 명령을 수신하는 홈 자동화 시스템을 구축하려고 한다고 가정해 보세요. 애플리케이션은 오디오 기반 입력(사용자의 음성 명령)을 가져오고, 구문 분석할 수 있는 텍스트로 필사하여 해석할 수 있어야 합니다.
이제 일부 음성을 필사할 준비가 되었습니다. 입력값은 **마이크** 또는 **오디오 파일**에서 가져올 수 있습니다.
오디오 파일을 통한 음성 인식
아래의 셀을 실행하여 Speech Recognition 서비스가 **오디오 파일**을 사용하는 것을 확인해 보세요.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
음성 합성
지금까지 Speech 서비스를 사용하여 음성을 텍스트로 필사하는 방법을 살펴봤습니다. 반대로 하려면 어떻게 해야 할까요? 어떻게 텍스트를 음성으로 변환할 수 있을까요?
홈 자동화 시스템이 불을 켜라는 명령을 해석했다고 가정해 보겠습니다. 적절한 응답은 명령된 작업을 수행하는 것은 물론 명령을 구두로 확인하는 것입니다.
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
Речь
Все чаще мы ожидаем, что сможем общаться с системами искусственного интеллекта, разговаривая с ними, часто с ожиданием разговорного ответа.

*Распознавание речи* (система ИИ, интерпретирующая разговорный язык) и *синтез речи* (система ИИ, генерирующая речевую реакцию) являются ключевыми компонентами решения ИИ по поддержке речи.
Создание ресурса Cognitive Services
Для создания программного обеспечения, которое может интерпретировать слышимую речь и отвечать на нее в устной форме, можно воспользоваться когнитивной службой **Речь**, которая предоставляет простой способ расшифровки разговорной речи в текст и наоборот.
Если у вас нет такого ресурса, воспользуйтесь следующими пошаговыми инструкциями для создания ресурса **Cognitive Services** в вашей подписке Azure:
> **Примечание**. Если у вас уже есть ресурс Cognitive Services, просто откройте его страницу **Быстрый запуск** и скопируйте его ключ и конечную точку в ячейку ниже. В противном случае следуйте приведенным ниже действиям для создания этого ресурса.
1. На другой вкладке браузера откройте портал Azure по адресу https://portal.azure.com, выполнив вход под своей учетной записью Microsoft.
2. Нажмите кнопку **&65291;Создать ресурс**, выполните поиск по строке *Cognitive Services* и создайте ресурс **Cognitive Services** со следующими настройками:
- **Подписка**. *Ваша подписка Azure*.
- **Группа ресурсов**. *Выберите или создайте группу ресурсов с уникальным именем*.
- **Регион**. *Выберите любой доступный регион:*
- **Имя**. *Введите уникальное имя*.
- **Ценовая категория**. S0
- **Подтверждаю, что прочитал и понял уведомления**. Выбрано.
3. Дождитесь завершения развертывания. Затем перейдите на свой ресурс Cognitive Services и на странице **Обзор** щелкните ссылку для управления ключами службы. Для подключения к вашему ресурсу когнитивных служб из клиентских приложений вам понадобятся ключ и месторасположение.
Получите ключ и расположение вашего ресурса Cognitive Services
Чтобы использовать свой ресурс Cognitive Services, клиентским приложениям требуется ключ проверки подлинности и расположение:
1. На портале Azure откройте страницу **Ключи и конечная точка** для вашего ресурса Cognitive Service, скопируйте **Ключ1** для вашего ресурса и вставьте его в приведенный ниже код, заменив подстановочный текст **YOUR_COG_KEY**.
2. Скопируйте **Расположение** для вашего ресурса и вставьте его в приведенный ниже код, заменив **YOUR_COG_LOCATION**.
> **Примечание**. На той же странице **Ключи и конечная точка** скопируйте значение **Расположение** на этой странице (пример: _westus_). _Не_ добавляйте пробелы между словами в поле «Расположение».
3. Выполните приведенный ниже код, нажав кнопку **Выполнить ячейку** (&9655;) слева от ячейки.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Распознавание речи
Предположим, вы хотите построить систему домашней автоматизации, которая принимает голосовые инструкции, такие как «включить свет» или «выключить свет». Ваше приложение должно уметь принимать аудиоввод (вашу устную инструкцию) и интерпретировать его, транскрибируя в текст, который затем можно будет разобрать и проанализировать.
Теперь все готово для расшифровки некоторой речи. Входной сигнал может быть с **микрофона** или из **аудиофайла**.
Распознавание речи с помощью аудиофайла
Выполните код из ячейки ниже, чтобы увидеть службу «Распознавание речи» в действии с **аудиофайлом**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Синтез речи
Итак, вы увидели, как служба «Речь» может быть использована для расшифровки речи в текст; а как насчет обратного? Как можно преобразовать текст в речь?
Предположим, что ваша система домашней автоматизации интерпретировала команду на включение света. Соответствующим ответом может быть признание команды устно (а также фактическое выполнение задания!).
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
语音
我们越来越希望能通过对人工智能 (AI) 系统说话的方式来与其进行交流,而且通常希望它们也能通过“说话”来进行回应。

*语音识别*(对口头语言进行解释的 AI 系统)和*语音合成*(生成语音响应的 AI 系统)是支持语音的 AI 解决方案的关键组件。
创建认知服务资源
要生成能解释语音并做出语音回应的软件,可以使用**语音**认知服务,该服务提供了一种在口头语言和文本之间相互转录的简单方法。
请按照以下步骤在 Azure 订阅中创建**认知服务**资源(如果还没有该资源):
> **备注**:如果已有认知服务资源,则只需在 Azure 门户中打开其“**快速入门**”页面,然后将其密钥和终结点复制到下面的单元格中即可。否则,请按照以下步骤创建认知服务资源。
1. 在另一个浏览器标签页中,打开 Azure 门户 (https://portal.azure.com) 并使用 Microsoft 帐户登录。
2. 单击“**&65291;创建资源**”按钮,搜索“*认知服务*”并以如下设置创建**认知服务**资源:
- **订阅**: *你的 Azure 订阅*。
- **资源组**: *选择或创建具有唯一名称的资源组*。
- **区域**: *选择任何可用区域*:
- **名称**: *输入一个唯一名称*。
- **定价层**:中的机器人 S0
- **我确认我已阅读并理解上述通知**:已选中。
3. 等待部署完成。然后转到认知服务资源,并单击“**概述**”页面上的链接以管理该服务的密钥。你将需要使用密钥和位置从客户端应用程序连接到认知服务资源。
获取认知服务资源的密钥和位置
要使用认知服务资源,需要向客户端应用程序提供其身份验证密钥和位置:
1. 进入 Azure 门户,在认知服务资源的“**密钥和终结点**”页面上复制资源的“**Key1**”,并将其粘贴到以下代码中,替换“**YOUR_COG_KEY**”。
2. 复制资源的**位置**并将其粘贴到以下代码中,替换“**YOUR_COG_LOCATION**”。
>**备注**:停留在“**密钥和终结点**”页面上,并从其中复制“**位置**”(例如:_westus_)。请*不要*在“位置”字段的字词之间添加空格。
3. 通过单击位于单元格左侧的“**运行单元格**”(&9655;) 按钮运行下方代码。
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
语音识别
假设你要构建一个家庭自动化系统,并使其能够接受语音指令,例如“turn the light on”或“turn the light off”。你的应用程序要能接收基于音频的输入(即语音指令),并将其转录为能被解析和分析的文本,从而对其进行解释。
现已准备好转录部分语音。可以通过**麦克风**或**音频**文件进行输入。
使用音频文件的语音识别
运行下面的单元格,查看使用**音频文件**进行输入的语音识别服务的运行情况。
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
语音合成
现在你已了解如何使用语音服务将语音转录成文本,那反过来该如何操作呢?如何将文本转换成语音?
让我们假设你的家庭自动化系统已经解释出了开灯命令。适当的回应可能是口头表明接受命令,当然也要实际执行命令的任务!
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
Parole
De plus en plus, nous nous attendons à pouvoir communiquer avec des systèmes d’intelligence artificielle (IA) en leur parlant, souvent dans l’attente d’une réponse orale.

La *reconnaissance vocale* (système d’IA interprétant le langage parlé) et la *synthèse vocale* (système d’IA générant une réponse orale) sont les composants clés d’une solution d’IA basée sur la parole.
Créer une ressource Cognitive Services
Pour créer un logiciel capable d’interpréter un discours audible et de répondre verbalement, vous pouvez utiliser le service cognitif **Parole**, qui offre un moyen simple de transcrire le langage parlé en texte et vice-versa.
Si vous n’en avez pas encore, suivez les étapes suivantes pour créer une ressource **Cognitive Services** dans votre abonnement Azure :
> **Remarque** : Si vous disposez déjà d’une ressource Cognitive Services, il suffit d’ouvrir sa page **Démarrage rapide** dans le portail Azure et de copier sa clé et son point de terminaison dans la cellule ci-dessous. Sinon, suivez les étapes ci-dessous pour en créer une.
1. Dans un autre onglet du navigateur, ouvrez le portail Azure à l’adresse https://portal.azure.com, en vous connectant avec votre compte Microsoft.
2. Cliquez sur le bouton **&65291; Créer une ressource**, recherchez *Cognitive Services* et créez une ressource **Cognitive Services** avec les paramètres suivants :
- **Abonnement** : *Votre abonnement Azure*.
- **Groupe de ressources** : *Sélectionnez ou créez un groupe de ressources portant un nom unique*.
- **Région** : *Choisissez une région disponible* :
- **Nom** : *Saisissez un nom unique*.
- **Niveau tarifaire** : S0
- **Je confirme avoir lu et compris les avis** : Sélectionné.
3. Attendez la fin du déploiement. Ensuite, accédez à votre ressource Cognitive Services et, sur la page **Aperçu**, cliquez sur le lien permettant de gérer les clés du service. Vous aurez besoin de la clé et de l’emplacement pour vous connecter à votre ressource Cognitive Services à partir d’applications clientes.
Obtenir la clé et l’emplacement de votre ressource Cognitive Services
Pour utiliser votre ressource Cognitive Services, les applications clientes ont besoin de sa clé d’authentification et de son emplacement :
1. Dans le portail Azure, sur la page **Clés et Point de terminaison** de votre ressource Cognitive Services, copiez la **Clé 1** de votre ressource et collez-la dans le code ci-dessous, en remplaçant **YOUR_COG_KEY**.
2. Copiez **Emplacement** de votre ressource et collez-le dans le code ci-dessous, en remplaçant **YOUR_COG_LOCATION**.
>**Remarque** : Restez sur la page **Clés et Point de terminaison** et copiez **Emplacement** de cette page (exemple : _westus_). N’ajoutez pas d’espaces entre les mots dans le champ Emplacement.
3. Exécutez le code ci-dessous en cliquant sur le bouton **Exécuter la cellule** (&9655;) à gauche de la cellule.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Reconnaissance vocale
Supposons que vous vouliez construire un système domotique qui accepte les instructions vocales, telles que « allumer la lumière » ou « éteindre la lumière ». Votre application doit être capable de prendre l’entrée audio (vos instructions vocales) et de l’interpréter en la transcrivant en texte qu’elle peut ensuite analyser.
Vous êtes maintenant prêt à transcrire la parole. L’entrée peut provenir d’un **microphone** ou d’un **fichier audio**.
Reconnaissance vocale avec un fichier audio
Exécutez la cellule ci-dessous pour voir le service Reconnaissance vocale en action avec un **fichier audio**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Synthèse vocale
Vous avez maintenant vu comment le service Parole peut être utilisé pour transcrire la parole en texte ; mais qu’en est-il de l’inverse ? Comment convertir du texte en parole ?
Eh bien, supposons que votre système domotique ait interprété une commande d’allumage de la lampe. Une réponse appropriée pourrait être de reconnaissance verbale de la commande (et d’effectuer la tâche commandée !).
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
SpeechIncreasingly, we expect to be able to communicate with artificial intelligence (AI) systems by talking to them, often with the expectation of a spoken response.*Speech recognition* (an AI system interpreting spoken language) and *speech synthesis* (an AI system generating a spoken response) are the key components of a speech-enabled AI solution. Create a Cognitive Services resourceTo build software that can interpret audible speech and respond verbally, you can use the **Speech** cognitive service, which provides a simple way to transcribe spoken language into text and vice-versa.If you don't already have one, use the following steps to create a **Cognitive Services** resource in your Azure subscription:> **Note**: If you already have a Cognitive Services resource, just open its **Quick start** page in the Azure portal and copy its key and endpoint to the cell below. Otherwise, follow the steps below to create one.1. In another browser tab, open the Azure portal at https://portal.azure.com, signing in with your Microsoft account.2. Click the **&65291;Create a resource** button, search for *Cognitive Services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Your Azure subscription*. - **Resource group**: *Select or create a resource group with a unique name*. - **Region**: *Choose any available region*: - **Name**: *Enter a unique name*. - **Pricing tier**: S0 - **I confirm I have read and understood the notices**: Selected.3. Wait for deployment to complete. Then go to your cognitive services resource, and on the **Overview** page, click the link to manage the keys for the service. You will need the key and location to connect to your cognitive services resource from client applications. Get the Key and Location for your Cognitive Services resourceTo use your cognitive services resource, client applications need its authentication key and location:1. In the Azure portal, on the **Keys and Endpoint** page for your cognitive service resource, copy the **Key1** for your resource and paste it in the code below, replacing **YOUR_COG_KEY**.2. Copy the **Location** for your resource and and paste it in the code below, replacing **YOUR_COG_LOCATION**.>**Note**: Stay on the **Keys and Endpoint** page and copy the **Location** from this page (example: _westus_). Please _do not_ add spaces between words for the Location field. 3. Run the code below by clicking the **Run cell** (&9655;) button to the left of the cell.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Speech recognitionSuppose you want to build a home automation system that accepts spoken instructions, such as "turn the light on" or "turn the light off". Your application needs to be able to take the audio-based input (your spoken instruction), and interpret it by transcribing it to text that it can then parse and analyze.Now you're ready to transcribe some speech. The input can be from a **microphone** or an **audio file**. Speech Recognition with an audio fileRun the cell below to see the Speech Recognition service in action with an **audio file**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Speech synthesisSo now you've seen how the Speech service can be used to transcribe speech into text; but what about the opposite? How can you convert text into speech?Well, let's assume your home automation system has interpreted a command to turn the light on. An appropriate response might be to acknowledge the command verbally (as well as actually performing the commanded task!)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
SpeechIncreasingly, we expect to be able to communicate with artificial intelligence (AI) systems by talking to them, often with the expectation of a spoken response.*Speech recognition* (an AI system interpreting spoken language) and *speech synthesis* (an AI system generating a spoken response) are the key components of a speech-enabled AI solution. Create a Cognitive Services resourceTo build software that can interpret audible speech and respond verbally, you can use the **Speech** cognitive service, which provides a simple way to transcribe spoken language into text and vice-versa.1. In an browser tab, open the Azure portal at https://portal.azure.com, sign in with the lab credentials.2. Click the **&65291;Create a resource** button, search for *Cognitive Services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Select the existing subscription where you are performing the lab*. - **Resource group**: *Select the existing resource group*. - **Region**: *Choose any available region or the region where the resource group is deployed*. - **Name**: *speech-uniqueID* , You can find the uniqueID value in the Lab Environment-> Environment details tab - **Pricing tier**: S0 - **I confirm I have read and understood the notices**: Selected.3. Click on **Review+Create**. After the template has passed the validation click **create** to create the Cognitive Service.4. Wait for deployment to complete. Then go to your cognitive services resource, and on the **Overview** page, click the link to manage the keys for the service. You will need the endpoint and keys to connect to your cognitive services resource from client applications. Get the Key and Endpoint for your Cognitive Services resourceTo use your cognitive services resource, client applications need its endpoint and authentication key:1. In the Azure portal, on the **Keys and Endpoint** page for your cognitive service resource, copy the **Key1** for your resource and paste it in the code below, replacing **YOUR_COG_KEY**.2. Copy the **Endpoint** for your resource and and paste it in the code below, replacing **YOUR_COG_ENDPOINT**.3. Copy the **Location** for your resource and and paste it in the code below, replacing **YOUR_COG_LOCATION**.4. Run the code below by clicking the **Run cell** (&9655;) button to the left of the cell.
###Code
#Replace YOUR_COG_KEY and YOUR_COG_LOCATION with the cognitive service key and location values.
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Speech recognitionSuppose you want to build a home automation system that accepts spoken instructions, such as "turn the light on" or "turn the light off". Your application needs to be able to take the audio-based input (your spoken instruction), and interpret it by transcribing it to text that it can then parse and analyze.Now you're ready to transcribe some speech. The input can be a microphone or an audio file. Speech Recognition with a microphoneRun the cell below and **immediately** say out loud **"turn the light on"**. The speech-to-text capabilities of the Speech service will transcribe the audio. The output should be your speech in text.
###Code
import os
import IPython
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
# Have students say "turn the light on"
speech_recognizer = SpeechRecognizer(speech_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
print(speech.text)
###Output
_____no_output_____
###Markdown
(!) Check InWere you able to run the cell and translate your speech to text? If the above cell does not give a text output (example output: _Turn the light on._), try running the cell again and **immediately** say out loud "turn the light on". Speech Recognition with an audio fileIf the cell above does not give a text output, your microphone may not be set up to accept input. Instead, run the cell below to see the Speech Recognition service in action with an audio file instead of microphone input.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play audio and show transcribed text
playsound(audio_file)
print(speech.text)
###Output
_____no_output_____
###Markdown
Speech synthesisSo now you've seen how the Speech service can be used to transcribe speech into text; but what about the opposite? How can you convert text into speech?Well, let's assume your home automation system has interpreted a command to turn the light on. An appropriate response might be to acknowledge the command verbally (as well as actually performing the commanded task!)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
会話
話しかけると、話し言葉で応答してくれるような人工知能 (AI) システムとのコミュニケーションの実現に向けて、期待が高まっています。

*音声認識* (話し言葉を解釈する AI システム) と*音声合成* (音声応答を生成する AI システム) は、会話を実現する AI ソリューションの重要なコンポーネントです。
Cognitive Services リソースを作成する
**Speech** Cognitive Service を使用すると、聞こえてくる言葉を解釈して、音声で応答できるソフトウェアを構築できます。このサービスを使用すると、話し言葉をテキストに変換したり、その逆に変換したりすることが簡単に行えます。
まだリソースを作成していない場合は、次の手順で Azure サブスクリプションに **Cognitive Services** リソースを作成します。
> **注**: Cognitive Services リソースが既にある場合は、Azure portal で**クイック スタート**ページを開き、キーとエンドポイントを以下のセルにコピーするだけで作成できます。それ以外の場合は、以下の手順に従って作成してください。
1. ブラウザーの新しいタブで Azure portal (https://portal.azure.com) を開き、Microsoft アカウントでサインインします。
2. 「**&65291;リソースの作成**」 ボタンをクリックし、*Cognitive Services* を検索して、以下の設定で **Cognitive Services** リソースを作成します。
- **サブスクリプション**: *使用する Azure サブスクリプション*
- **リソース グループ**: *一意の名前のリソース グループを選択または作成します*
- **リージョン**: *利用可能な任意のリージョンを選択します*。
- **名前**: *一意の名前を入力します*。
- **価格レベル**: S0
- **注意事項を読み理解しました**: 選択されています。
3. デプロイが完了するまで待ちます。そのあと Cognitive Services リソースに移動し、「**概要**」 ページでリンクをクリックしてサービスのキーを管理します。クライアント アプリケーションから Cognitive Services リソースに接続するには、キーと場所が必要です。
Cognitive Services リソースのキーと場所を取得する
Cognitive Services リソースを使用するには、クライアント アプリケーションに認証キーと場所が必要です。
1. Azure portalで、Cognitive Services リソースの 「**キーとエンドポイント**」 ページからリソースの 「**キー 1**」 の値をコピーし、以下のコードに貼り付けます (**YOUR_COG_KEY** と置き換える)。
2. リソースの**場所**をコピーして以下のコードに貼り付けます (**YOUR_COG_LOCATION** を置き換える)。
>**注**: 「**キーとエンドポイント**」 ページにとどまり、このページから**場所**をコピーします (例: _westus_)。「場所」 フィールドの単語の間には空白を入れ _ないで_ ください。
3. セルの左側にある 「**セルの実行**」 (&9655;) ボタンをクリックして、以下のコードを実行します。
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
音声認識
「明かりをつけて」や「明かりを消して」などの音声指示に対応できるホーム オートメーション システムを構築するとします。アプリケーションは、音声ベースの入力 (話された指示) を受け取り、それをテキストに書き起こして認識し、構文解析と意味を分析できる必要があります。
これで、音声を書き写す準備が整いました。入力は、**マイク**または**音声ファイル**から行うことができます。
音声ファイルを使用した音声認識
以下のセルを実行し、**音声ファイル**を使用して Speech Recognition サービスが稼働していることを確認します。
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
音声合成
これで、Speech サービスを使用して音声をテキストに変換する方法を確認できました。ただし、逆の変換はまだです。テキストを音声に変換するにはどうすればよいでしょうか?
ホーム オートメーション システムが明かりをつける指示を解釈したとします。適切な応答とは、指示されたことを口頭で確認したり、指示されたタスクを実際に実行したりすることでしょう。
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
SpeechIncreasingly, we expect to be able to communicate with artificial intelligence (AI) systems by talking to them, often with the expectation of a spoken response.*Speech recognition* (an AI system interpreting spoken language) and *speech synthesis* (an AI system generating a spoken response) are the key components of a speech-enabled AI solution. Create a Cognitive Services resourceTo build software that can interpret audible speech and respond verbally, you can use the **Speech** cognitive service, which provides a simple way to transcribe spoken language into text and vice-versa.If you don't already have one, use the following steps to create a **Cognitive Services** resource in your Azure subscription:> **Note**: If you already have a Cognitive Services resource, just open its **Quick start** page in the Azure portal and copy its key and endpoint to the cell below. Otherwise, follow the steps below to create one.1. In another browser tab, open the Azure portal at https://portal.azure.com, signing in with your Microsoft account.2. Click the **&65291;Create a resource** button, search for *Cognitive Services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Your Azure subscription*. - **Resource group**: *Select or create a resource group with a unique name*. - **Region**: *Choose any available region*: - **Name**: *speech-deploymentID*. - **Pricing tier**: S0 - **I confirm I have read and understood the notices**: Selected.3. Wait for deployment to complete. Then go to your cognitive services resource, and on the **Overview** page, click the link to manage the keys for the service. You will need the key and location to connect to your cognitive services resource from client applications. Get the Key and Location for your Cognitive Services resourceTo use your cognitive services resource, client applications need its authentication key and location:1. In the Azure portal, on the **Keys and Endpoint** page for your cognitive service resource, copy the **Key1** for your resource and paste it in the code below, replacing **YOUR_COG_KEY**.2. Copy the **Location** for your resource and and paste it in the code below, replacing **YOUR_COG_LOCATION**.>**Note**: Stay on the **Keys and Endpoint** page and copy the **Location** from this page (example: _westus_). Please _do not_ add spaces between words for the Location field. 3. Run the code below by clicking the **Run cell** (&9655;) button to the left of the cell.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Speech recognitionSuppose you want to build a home automation system that accepts spoken instructions, such as "turn the light on" or "turn the light off". Your application needs to be able to take the audio-based input (your spoken instruction), and interpret it by transcribing it to text that it can then parse and analyze.Now you're ready to transcribe some speech. The input can be from a **microphone** or an **audio file**. Speech Recognition with an audio fileRun the cell below to see the Speech Recognition service in action with an **audio file**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Speech synthesisSo now you've seen how the Speech service can be used to transcribe speech into text; but what about the opposite? How can you convert text into speech?Well, let's assume your home automation system has interpreted a command to turn the light on. An appropriate response might be to acknowledge the command verbally (as well as actually performing the commanded task!)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
SpeechIncreasingly, we expect to be able to communicate with artificial intelligence (AI) systems by talking to them, often with the expectation of a spoken response.*Speech recognition* (an AI system interpreting spoken language) and *speech synthesis* (an AI system generating a spoken response) are the key components of a speech-enabled AI solution. Create a Cognitive Services resourceTo build software that can interpret audible speech and respond verbally, you can use the **Speech** cognitive service, which provides a simple way to transcribe spoken language into text and vice-versa.If you don't already have one, use the following steps to create a **Cognitive Services** resource in your Azure subscription:> **Note**: If you already have a Cognitive Services resource, just open its **Quick start** page in the Azure portal and copy its key and endpoint to the cell below. Otherwise, follow the steps below to create one.1. In another browser tab, open the Azure portal at https://portal.azure.com, signing in with your Microsoft account.2. Click the **&65291;Create a resource** button, search for *Cognitive Services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Your Azure subscription*. - **Resource group**: *Select or create a resource group with a unique name*. - **Region**: *Choose any available region*: - **Name**: *Enter a unique name*. - **Pricing tier**: S0 - **I confirm I have read and understood the notices**: Selected.3. Wait for deployment to complete. Then go to your cognitive services resource, and on the **Overview** page, click the link to manage the keys for the service. You will need the key and location to connect to your cognitive services resource from client applications. Get the Key and Location for your Cognitive Services resourceTo use your cognitive services resource, client applications need its authentication key and location:1. In the Azure portal, on the **Keys and Endpoint** page for your cognitive service resource, copy the **Key1** for your resource and paste it in the code below, replacing **YOUR_COG_KEY**.2. Copy the **Location** for your resource and and paste it in the code below, replacing **YOUR_COG_LOCATION**.>**Note**: Stay on the **Keys and Endpoint** page and copy the **Location** from this page (example: _westus_). Please _do not_ add spaces between words for the Location field. 3. Run the code below by clicking the **Run cell** (&9655;) button to the left of the cell.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Speech recognitionSuppose you want to build a home automation system that accepts spoken instructions, such as "turn the light on" or "turn the light off". Your application needs to be able to take the audio-based input (your spoken instruction), and interpret it by transcribing it to text that it can then parse and analyze.Now you're ready to transcribe some speech. The input can be from a **microphone** or an **audio file**. Speech Recognition with an audio fileRun the cell below to see the Speech Recognition service in action with an **audio file**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Speech synthesisSo now you've seen how the Speech service can be used to transcribe speech into text; but what about the opposite? How can you convert text into speech?Well, let's assume your home automation system has interpreted a command to turn the light on. An appropriate response might be to acknowledge the command verbally (as well as actually performing the commanded task!)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
SpeechIncreasingly, we expect to be able to communicate with artificial intelligence (AI) systems by talking to them, often with the expectation of a spoken response.*Speech recognition* (an AI system interpreting spoken language) and *speech synthesis* (an AI system generating a spoken response) are the key components of a speech-enabled AI solution. Create a Cognitive Services resourceTo build software that can interpret audible speech and respond verbally, you can use the **Speech** cognitive service, which provides a simple way to transcribe spoken language into text and vice-versa.If you don't already have one, use the following steps to create a **Cognitive Services** resource in your Azure subscription:> **Note**: If you already have a Cognitive Services resource, just open its **Quick start** page in the Azure portal and copy its key and endpoint to the cell below. Otherwise, follow the steps below to create one.1. In another browser tab, open the Azure portal at https://portal.azure.com, signing in with your Microsoft account.2. Click the **&65291;Create a resource** button, search for *Cognitive Services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Your Azure subscription*. - **Resource group**: *Select or create a resource group with a unique name*. - **Region**: *Choose any available region*: - **Name**: *Enter a unique name*. - **Pricing tier**: S0 - **I confirm I have read and understood the notices**: Selected.3. Wait for deployment to complete. Then go to your cognitive services resource, and on the **Overview** page, click the link to manage the keys for the service. You will need the key and location to connect to your cognitive services resource from client applications. Get the Key and Location for your Cognitive Services resourceTo use your cognitive services resource, client applications need its authentication key and location:1. In the Azure portal, on the **Keys and Endpoint** page for your cognitive service resource, copy the **Key1** for your resource and paste it in the code below, replacing **YOUR_COG_KEY**.2. Copy the **Location** for your resource and and paste it in the code below, replacing **YOUR_COG_LOCATION**.>**Note**: Stay on the **Keys and Endpoint** page and copy the **Location** from this page (example: _westus_). Please _do not_ add spaces between words for the Location field. 3. Run the code below by clicking the **Run cell** (&9655;) button to the left of the cell.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Speech recognitionSuppose you want to build a home automation system that accepts spoken instructions, such as "turn the light on" or "turn the light off". Your application needs to be able to take the audio-based input (your spoken instruction), and interpret it by transcribing it to text that it can then parse and analyze.Now you're ready to transcribe some speech. The input can be from a **microphone** or an **audio file**. Speech Recognition with a microphoneLet's try with a microphone input first. Run the cell below and **immediately** say out loud **"turn the light on"**. The speech-to-text capabilities of the Speech service will transcribe the audio. The output should be your speech in text.
###Code
import os
import IPython
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
# Have students say "turn the light on"
speech_recognizer = SpeechRecognizer(speech_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
print(speech.text)
###Output
_____no_output_____
###Markdown
(!) Check InWere you able to run the cell and translate your speech to text? If the above cell does not give a text output (example output: _Turn the light on._), try running the cell again and **immediately** say out loud "turn the light on". Speech Recognition with an audio fileIf the cell above does not give a text output, your microphone may not be set up to accept input. Instead, run the cell below to see the Speech Recognition service in action with an **audio file** instead of **microphone input**.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play audio and show transcribed text
playsound(audio_file)
print(speech.text)
###Output
_____no_output_____
###Markdown
Speech synthesisSo now you've seen how the Speech service can be used to transcribe speech into text; but what about the opposite? How can you convert text into speech?Well, let's assume your home automation system has interpreted a command to turn the light on. An appropriate response might be to acknowledge the command verbally (as well as actually performing the commanded task!)
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____
###Markdown
Speech
Wir erwarten immer öfter, mit KI-Systemen (Künstliche Intelligenz) kommunizieren zu können, indem wir mit ihnen sprechen, und erwarten oft auch eine gesprochene Antwort.

*Spracherkennung* (ein KI-System, das gesprochene Sprache interpretiert) und *Sprachsynthese* (ein KI-System, das eine gesprochene Antwort generiert) sind die wichtigsten Komponenten einer KI-Lösung mit Sprachunterstützung.
Erstellen einer Cognitive Services-Ressource
Um eine Software zu erstellen, die gesprochene Sprache interpretiert und verbal antwortet, können Sie den Cognitive Service **Speech** verwenden, der einfache Methoden zum Transkribieren von gesprochener Sprache zu Text und umgekehrt bereitstellt.
Falls noch nicht geschehen, führen Sie die folgenden Schritte aus, um eine **Cognitive Services**-Ressource in Ihrem Azure-Abonnement zu erstellen:
> **Hinweis**: Falls Sie bereits eine Cognitive Services-Ressource haben, können Sie die entsprechende **Schnellstart**-Seite im Azure-Portal öffnen und den Schlüssel und den Endpunkt der Ressource unten in die Zelle kopieren. Führen Sie andernfalls die folgenden Schritte aus, um eine Ressource zu erstellen.
1. Öffnen Sie das Azure-Portal unter „https://portal.azure.com“ in einer neuen Browserregisterkarte, und melden Sie sich mit Ihrem Microsoft-Konto an.
2. Klicken Sie auf die Schaltfläche **&65291;Ressource erstellen**, suchen Sie nach *Cognitive Services*, und erstellen Sie eine **Cognitive Services**-Ressource mit den folgenden Einstellungen:
- **Abonnement**: *Ihr Azure-Abonnement*
- **Ressourcengruppe**: *Wählen Sie eine Ressourcengruppe aus, oder erstellen Sie eine Ressourcengruppe mit einem eindeutigen Namen.*
- **Region**: *Wählen Sie eine verfügbare Region aus*:
- **Name**: *Geben Sie einen eindeutigen Namen ein.*
- **Tarif**: S0
- **Ich bestätige, dass ich die Hinweise gelesen und verstanden habe**: Ausgewählt
3. Warten Sie, bis die Bereitstellung abgeschlossen ist. Öffnen Sie anschließend Ihre Cognitive Services-Ressource, und klicken Sie auf der Seite **Übersicht** auf den Link zur Schlüsselverwaltung für den Dienst. Sie benötigen den Schlüssel und den Speicherort, um sich aus Clientanwendungen heraus mit Ihrer Cognitive Services-Ressource zu verbinden.
Abrufen des Schlüssels und des Speicherorts für Ihre Cognitive Services-Ressource
Um Ihre Cognitive Services-Ressource verwenden zu können, benötigen Clientanwendungen deren Authentifizierungsschlüssel und Speicherort:
1. Kopieren Sie im Azure-Portal auf der Seite **Schlüssel und Endpunkt** für Ihre Cognitive Service-Ressource den **Schlüssel1** für Ihre Ressource, und fügen Sie ihn im unten stehenden Code anstelle von **YOUR_COG_KEY** ein.
2. Kopieren Sie den **Speicherort** für Ihre Ressource, und fügen Sie ihn unten im Code anstelle von **YOUR_COG_LOCATION** ein.
>**Hinweis**: Bleiben Sie auf der Seite **Schlüssel und Endpunkt**, und kopieren Sie den **Speicherort** von dieser Seite (Beispiel: _westus_). Fügen Sie KEINE Leerzeichen zwischen den Wörtern im Feld „Speicherort“ ein.
3. Führen Sie den folgenden Code aus, indem Sie links neben der Zelle auf die Schaltfläche **Zelle ausführen** (&9655;) klicken.
###Code
cog_key = 'YOUR_COG_KEY'
cog_location = 'YOUR_COG_LOCATION'
print('Ready to use cognitive services in {} using key {}'.format(cog_location, cog_key))
###Output
_____no_output_____
###Markdown
Spracherkennung
Angenommen, Sie möchten ein Gebäudeautomatisierungssystem entwickeln, das Sprachbefehle wie etwa „Licht einschalten“ oder „Licht ausschalten“ erkennt. Ihre Anwendung muss in der Lage sein, audiobasierte Eingaben (Ihre Sprachbefehle) zu interpretieren, indem sie sie zu Text transkribiert, der anschließend gelesen und analysiert werden kann.
Jetzt können Sie damit anfangen, Spracheingaben zu transkribieren. Die Eingabe kann entweder von einem **Mikrofon** oder aus einer **Audiodatei** stammen.
Spracherkennung mit einer Audiodatei
Führen Sie die folgende Zelle aus, um den Spracherkennungsdienst mit einer **Audiodatei** zu testen.
###Code
import os
from playsound import playsound
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, AudioConfig
# Get spoken command from audio file
file_name = 'light-on.wav'
audio_file = os.path.join('data', 'speech', file_name)
# Configure speech recognizer
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
audio_config = AudioConfig(filename=audio_file) # Use file instead of default (microphone)
speech_recognizer = SpeechRecognizer(speech_config, audio_config)
# Use a one-time, synchronous call to transcribe the speech
speech = speech_recognizer.recognize_once()
# Play the original audio file
playsound(audio_file)
# Show transcribed text from audio file
print(speech.text)
###Output
_____no_output_____
###Markdown
Sprachsynthese
Sie haben also gesehen, wie der Speech-Dienst gesprochene Wörter zu Text transkribieren kann, aber funktioniert dies auch umgekehrt? Wie können Sie Text zu Sprache konvertieren?
Angenommen, Ihr Gebäudeautomatisierungssystem hat einen Befehl erhalten, das Licht einzuschalten. Eine passende Antwort wäre beispielsweise eine verbale Bestätigung des Befehls (und natürlich die Ausführung des Befehls).
###Code
import os
import matplotlib.pyplot as plt
from PIL import Image
from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioConfig
%matplotlib inline
# Get text to be spoken
response_text = 'Turning the light on.'
# Configure speech synthesis
speech_config = SpeechConfig(cog_key, cog_location)
speech_config.speech_synthesis_voice_name = 'en-US-ChristopherNeural'
speech_synthesizer = SpeechSynthesizer(speech_config)
# Transcribe text into speech
result = speech_synthesizer.speak_text(response_text)
# Display an appropriate image
file_name = response_text.lower() + "jpg"
img = Image.open(os.path.join("data", "speech", file_name))
plt.axis('off')
plt. imshow(img)
###Output
_____no_output_____ |
2-1_Matrix_Analysis.ipynb | ###Markdown
Refresher Course on Matrix Analysis and OptimizationFranck Iutzeler Jerome Malick Fall. 2018 Chap. 2 - Refresher Course ``1. Matrix Analysis``--- Package check and StylingOutline a) Linear Systems Resolution with applications to Regression b) Singular Value Decomposition and Image Compression c) PageRank and the Power Method a) Linear Systems Resolution with applications to Regression Go to topIn this example, we use linear algebra to extract information from data; more precisely, we predict final notes of a group of student from their profiles with the [Student Performance dataset](https://archive.ics.uci.edu/ml/datasets/Student+Performance) which includes secondary education students of two Portuguese schools.Profiles include features such as student grades, demographic, social and school related features and were collected by using school reports and questionnaires. There are $m = 395$ students (examples) and we selected $n = 27$ features (see data/student.txt for the features description and datat/student-mat.csv for the csv dataset.)Our goal is to predict a target feature (the $28$-th) which is the final grade of the student from the other features (the first $27$). We assume that the final grade can be explained by a linear combination of the other features. We are going to learn from this data using linear regression over the $m_{learn} = 300$ students (called the *learning set*). We will check our prediction by comparing the results for the other $m_{test} = 95$ students (the *testing set*).
###Code
import numpy as np
# File reading
dat_file = np.load('data/student.npz')
A_learn = dat_file['A_learn']
b_learn = dat_file['b_learn']
A_test = dat_file['A_test']
b_test = dat_file['b_test']
m = 395 # number of read examples (total:395)
n = 27 # features
m_learn = 300
###Output
_____no_output_____
###Markdown
Mathematically, from the $m_{learn} \times (n+1)$ *learning matrix* (the number of columns is $n+1$ as a column of ones, called *intercept* for statistical reasons). $A_{learn}$ comprising of the features values of each training student in line, and the vector of the values of the target features $b_{learn}$; we seek a size-$n+1$ *regression vector* that minimizes the squared error between $A_{learn} x$ and $b_{learn}$. This problem boils down to the following least square problem:$$ \min_{x\in\mathbb{R}^{n+1}} \| A_{learn} x - b_{learn} \|_2^2 . $$ Question 1: Observe the rank of the $m_{learn} \times (n+1)$ matrix $A_{learn}$. Does it have full row rank? full column rank? Conclude about the existence and uniqueness of solutions of the problem.
###Code
rank_A_learn = 0 #.........................................
#print('Rank of matrix A_learn ({:d} rows, {:d} cols.): {:d}\n'.format(m_learn,n+1,rank_A_learn))
###Output
_____no_output_____
###Markdown
Question 2:Compute the solution of the minimization problem using the Singular Value Decomposition. * **hint:** use the option full_matrices=False of Numpy's SVD command to get the compact SVD.*
###Code
x_reg = np.linalg.lstsq(A_learn,b_learn)[0]
U, s, Vt = np.linalg.svd(A_learn, full_matrices=False)
A_pinv_svd = 0 #.........................................
x_reg_svd = 0 #.........................................
###Output
_____no_output_____
###Markdown
Question 3: In order to test the goodness of our predictor x_reg, we use the rest of the data to compare our predictions with the actual observations. The test matrix $A_{test}$ has $m_{test} = 95$ rows (students) and $n+1 = 28$ columns (features+intercept). Construct the predicted grades from x_reg and compare with the actual observed grades in $b_{test}$ (set SHOW_PREDICTION = True in the code).
###Code
predict = 0 #.........................................
SHOW_PREDICTION = False
if SHOW_PREDICTION:
print('\n\n Predicted | True value')
for i in range(predict.size):
print('\t{:2d} {:2d} '.format(int(predict[i]),int(b_test[i])))
###Output
_____no_output_____
###Markdown
Question 4: Compare the relative values of the coefficients of the predictor x_reg (set SHOW_PREDICTION = True in the code). What can you observe about the relative importance of the features?
###Code
SHOW_PREDICTOR = False
if SHOW_PREDICTOR:
filename = 'data/student.txt'
f = open(filename, 'r')
f.readline() # read the first (description) line
for i in range(n):
print("{:2.3f} \t-- {:s}".format(x_reg[i],f.readline()))
print("{:2.3f} \t-- Intercept".format(x_reg[n]))
f.close()
###Output
_____no_output_____
###Markdown
b) Singular Value Decomposition and Image Compression Go to topThe goal of this exercise is to investigate the computational aspects of the SVD; and, more importantly, observing the fact that the greater the magnitude of the singular value, the greater the importance of the associated vectors in the matrix coefficients. Investigating on this latter property will be done through the SVD of the following image seen as an array of grayscale values.
###Code
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm
%matplotlib inline
#### IMAGE
img = mpimg.imread('img/flower.png')
img_gray = 0.2989 * img[:,:,0] + 0.5870 * img[:,:,1] + 0.1140 * img[:,:,2] # Apparently these are "good" coefficients to convert to grayscale
#########
###Output
_____no_output_____
###Markdown
Indeed, in matrix decomposition every part is bearer of information and even though eigenvalues provide useful informations on some properties of the matrix, the associated eigenvectors are needed for a full reconstruction.
###Code
# SVD
U, s, Vt = np.linalg.svd(img_gray, full_matrices=False)
###Output
_____no_output_____
###Markdown
Question 1: In this question, we will put n\_to\_zero = 360 of the singular values (this corresponds to $75\%$ of the singular values) to zero while leaving the others unchanged; and construct new images from the modified singular values and the former matrices $U$ and $V$. In img_i, you will put the *smallest* singular values to zero; in img_ii, the greatest; and in img_iii, random ones. Observe the difference between these three modifications. What do you notice?
###Code
# Compression percentage: number of eigenvalues set to zero - To modify
Compression = 75.0 # in percents
nb_to_zero = int(np.ceil(len(s)*Compression/100)) # Number of singular values to put to zero
# (i) Nulling the smallest singular values
img_i = 0 #.........................................
# (ii) Nulling the greatest singular values
img_ii = 0 #.........................................
# (iii) Nulling random singular values
img_iii = 0 #.........................................
###############################################
## SHOW THE FIGURES
print('The image is {:d}x{:d}\n - it has {:d} singular values between {:.3f} and {:.3f}'.format( img_gray.shape[0], img_gray.shape[1] , len(s) , np.min(s) , np.max(s) ))
print(' - {:.1f}% of the singular values are set to zero ({:d}/{:d})'.format(Compression , int(nb_to_zero) , len(s) ))
plt.figure()# new figure
plt.subplot(2,2,1)
plt.xticks([]),plt.yticks([])
plt.title("Original")
plt.imshow(img_gray, cmap = cm.Greys_r)
plt.subplot(2,2,2)
plt.xticks([]),plt.yticks([])
plt.title("(i) smallest")
#plt.imshow(img_i, cmap = cm.Greys_r)
plt.subplot(2,2,3)
plt.xticks([]),plt.yticks([])
plt.title("(ii) greatest")
#plt.imshow(img_ii, cmap = cm.Greys_r)
plt.subplot(2,2,4)
plt.xticks([]),plt.yticks([])
plt.title("(iii) random")
#plt.imshow(img_iii, cmap = cm.Greys_r)
plt.show() #show the window
###############################################
###Output
_____no_output_____
###Markdown
Question 2: Compute the sum of the singular values for the original image and the three modified images. What can you conclude about the visual information provided by the singular values? c) PageRank and the Power Method Go to topIn this part, we will compute the PageRank ordering of the following graph.In PageRank, the score $x_i$ of page $i$ is equal to the sum over the pages $j$ pointing toward $i$ of their scores $x_j$ divided by their number of outgoing links $n_j$. This leads to a ranking matrix $R$ defined from the scoring method as$$ x = Rx.$$
###Code
import numpy as np
import matplotlib.pyplot as plt
#### Graph matrix
A = np.array([[0,1,1,0,1],[0,0,0,1,1],[1,0,0,1,0],[0,0,1,0,1],[0,1,0,0,0]])
####
###Output
_____no_output_____
###Markdown
Question 1: Explain how the ranking matrix $R$ is generated from adjacence matrix $A$ in the following code.
###Code
# column stochatic normalization
R = np.dot( A , np.diag(1.0/np.sum(A,0)) )
###Output
_____no_output_____
###Markdown
Question 2: Check numerically that $\|R\| = 1$ for some matrix norm and that the spectral radius of $R$ is equal to $1$.
###Code
sp_rad = 0 #.........................................
#print("Spectral radius: {:f}".format( sp_rad ) )
###Output
_____no_output_____
###Markdown
Question 3: Iterate the matrix $R$ a large number of times and check if the matrix is primitive. What do you notice on the eigenvalues and eigenvectors? How is defined the rank 1 matrix that you obtain? This manner of computing eigenvectors/values is called the *power method*.
###Code
k = 100
R_pow = 0 #.........................................
eig_val_pow,eig_vec_pow = 0,0 #.........................................
#print("R^{0} = {1}".format(k,R_pow))
#print("eigenvalues: {0}".format(eig_val_pow))
###Output
_____no_output_____
###Markdown
Question 4: Recover the *Perron* eigenvector of matrix $R$. The entries of this vector are the PageRank scores of the nodes/pages of the graph. Give the PageRank ordering of the pages of the graph.
###Code
v = 0 #.........................................
#print("Perron vector: {0}".format(v))
###Output
_____no_output_____
###Markdown
Question 5: (to go further) In this exercise, the graph we took led to a *primitive* matrix as seen above; this is necessary for the power method to work as the eigenvalue $1$ has to be the only one of modulus $1$. This is actually the case when the graph is strongly connected, that is when you can go from any node to any other node by following the edges, with *enough* loops. When it is not the case, our problem becomes ill posed. To overcome this problem, the ranking matrix $R$ is replaced by $$ M = (1-\alpha) R + \alpha J, ~~~~~~~~ \alpha\in]0,1[ $$where is $J$ is the $5\times 5$ matrix whose entries are all $1/5$. The value of $\alpha$ originally used by Google is $0.15$. * * * Show that $M$ is column-stochastic provided that $R$ is. * Show that the problem is now well-posed. * Compute the ranking for the original graph but where the link from $2$ to $5$ is suppressed.
###Code
#### New Graph matrix
A_2 = np.array([[0,1,1,0,1],[0,0,0,1,1],[1,0,0,1,0],[0,0,1,0,1],[0,0,0,0,0]])
####
###Output
_____no_output_____
###Markdown
--- Package Check and StylingGo to top
###Code
import lib.notebook_setting as nbs
packageList = ['IPython', 'numpy', 'scipy', 'matplotlib', 'cvxopt']
nbs.packageCheck(packageList)
nbs.cssStyling()
###Output
_____no_output_____ |
examples/Notebooks/06_Kaggle_Allstate_Claims_Severity/notebooks/02_Allstate_Claim_Severity_Gradient_boosting.ipynb | ###Markdown
[Allstate Claims Severity](https://goo.gl/1DwHVy) -- Predictions using machine learning: Author: Dr. Rahul Remanan, CEO and Chief Imagination Officer [Moad Computer](https://www.moad.computer)The [Allstate Corporation](https://en.wikipedia.org/wiki/Allstate) is the one of the largest insurance providers in the United States and one of the largest that is publicly held. The company also has personal lines insurance operations in Canada. Allstate was founded in 1931 as part of Sears, Roebuck and Co., and was spun off in 1993.[1](https://goo.gl/ce2JJ2) The company has had its headquarters in Northfield Township, Illinois, near Northbrook since 1967.[2](https://goo.gl/oX4kfZ),[3](https://goo.gl/mcTd3y)As part of Allstate's ongoing efforts to develop automated methods of predicting the cost, and hence severity, of claims, they releasd a claims severity assessment dataset on Kaggle.[4](https://goo.gl/1DwHVy) In this challenge, datascientists were invited to show off their creativity and flex their technical chops by creating an algorithm which accurately predicts claims severity. The goal of this challenge was to help aspiring competitors demonstrate their insight into better ways of predicting claims severity.We will be using this dataset to build a machine learning model using gradient boosting. Part 02 -- Machine learning prediction using [Gradient Boosting](https://en.wikipedia.org/wiki/Gradient_boosting):
###Code
library('ggplot2')
library('caret')
library('dplyr')
trainRAW <- read.csv("./data/train.csv", na.strings = c("", "NA"))
testRAW <- read.csv("./data/test.csv")
summary(trainRAW)
###Output
_____no_output_____
###Markdown
Generating histogram plot:The numeric attributes are already between [0,1]:
###Code
sum(is.na(trainRAW))
hist(log(trainRAW$loss))
###Output
_____no_output_____
###Markdown
Data cleaning-up:Removing columns that nlevels_train data is different from the nlevels_test data and removing columns that have nlevels > 5
###Code
cols <- rep(TRUE, length(names(testRAW)))
for (i in 1:length(names(testRAW))){
if (class(testRAW[[i]]) == "factor"){
if (!isTRUE(all.equal(levels(trainRAW[[i]]), levels(testRAW[[i]]))) | nlevels(testRAW[[i]]) > 5){
cols[i] <- FALSE
}
}
}
trainMOD <- trainRAW[,cols]
testMOD <- testRAW[,cols]
###Output
_____no_output_____
###Markdown
Creating dummies:
###Code
dummies <- dummyVars( ~., data = testMOD)
trainDUM <- data.frame((predict(dummies, newdata = trainMOD)), loss = trainMOD$loss)
testDUM <- data.frame((predict(dummies, newdata = testMOD)))
rm(dummies)
rm(trainMOD)
rm(testMOD)
###Output
_____no_output_____
###Markdown
Check for NearZeroValues:
###Code
nz <- nearZeroVar(trainDUM, saveMetrics = TRUE)
nznames <- rownames(nz[nz$nzv == TRUE,])
trainNZ <- trainDUM[,!(names(trainDUM) %in% nznames)]
testNZ <- testDUM[,!(names(testDUM) %in% nznames)]
trainNZ$loss <- log(trainNZ$loss)
rm(trainDUM)
rm(testDUM)
gc()
gc(TRUE)
###Output
_____no_output_____
###Markdown
Implementing a prediction algorith using [Gradient Boosting (GBM)](https://en.wikipedia.org/wiki/Gradient_boosting):
###Code
inTrain <- createDataPartition(y=trainRAW$loss, p=0.7, list = FALSE)
rm (trainRAW)
gc()
trainingGBM <- trainNZ[inTrain,]
testingGBM <- trainNZ[-inTrain,]
modfit <- train(loss ~., method = "gbm", data = trainingGBM, verbose = TRUE)
prediction <- predict(modfit, testingGBM)
###Output
_____no_output_____
###Markdown
Generating predictions formatted for Kaggle submission:
###Code
prediction.test <- exp(predict(modfit, testNZ))
predictionDF <- data.frame(id = testRAW$id, loss = prediction.test)
write.csv(predictionDF, file = '../output/prediction_test_GBM.csv', row.names = F)
rm(modfit)
rm(testNZ)
rm(testRAW)
gc()
###Output
_____no_output_____
###Markdown
Generate loss function plot:
###Code
plot(prediction, testingGBM$loss, pch = 19)
error <- prediction/testingGBM$loss - 1
summary(error)
boxplot(error, main = "Testing Error (Prediction/test.loss -1)", ylab = "Absolute error")
###Output
_____no_output_____ |
metadata/probe-to-timezone.ipynb | ###Markdown
================================
###Code
p[p['timezone'].isnull()]
if not p[p['timezone'].isnull()].empty:
# lat, long
niigata = (37.90222, 139.02361)
shizuoka = (34.97695, 138.38306)
p.iloc[13]['timezone'] = tz.tzNameAt(niigata[0], niigata[1])
p.iloc[19]['timezone'] = tz.tzNameAt(shizuoka[0], shizuoka[1])
p[p['timezone'].isnull()]
p
p.to_csv('probes-timezones.csv', sep=';', index=False, header=True)
###Output
_____no_output_____ |
notebooks/02-jupyter-notebook-interface.ipynb | ###Markdown
Jupyter Notebook Interface Cell Types
###Code
print("This is a code cell")
###Output
_____no_output_____
###Markdown
This is a markdown cell, with some _formatted_ **text**
###Code
This is a raw cell
###Output
_____no_output_____
###Markdown
Editing Cells
###Code
a = 2
print(a)
a = a + 2
print(a)
###Output
_____no_output_____ |
Python_program_to_find_PRIME_NUMBERS_between_1_and_n.ipynb | ###Markdown
###Code
# Python program to find PRIME NUMBERS between 1 and n.
# Written by F1607-alibey
n = int(input('n = '))
prime_numbers = []
for i in range(2, n+1):
if i > 1:
for ii in range(2,i):
if (i % ii) == 0:
break
else:
prime_numbers.append(i)
print('Prime numbers between 1 and', n, 'are = ', prime_numbers)
###Output
n = 25
Prime numbers between 1 and 25 are = [2, 3, 5, 7, 11, 13, 17, 19, 23]
|
ray-serve/11-Ray-Serve-Tune-and-XGBoost-Fraud.ipynb | ###Markdown
Ray Tune - An end-to-end Credit Card Fraud example of using XGBoost with Ray Tune and Ray Serve© 2019-2022, Anyscale. All Rights ReservedThis example illustrates how you can use Ray Libraries for an end-to-end example. 1. Use XGBoost to train a baseline model, using default hyperparameters2. Use XGBoost to train another model, using "guessed" hyperparemeters3. Use Tune to HPO and train the best XGBoost model4. Use ASHAscheduler to use early-stopping5. Save the best trial model6. Fetch the best saved model7. Run some predicitons8. Deploy the best trained model to Ray Serve8. Send requests for inferenceXGBoost is currently one of the most popular machine learning algorithms for regression and classification. It performs very well on a large selection of tasks, and is the key to success in many Kaggle competitions.Derived maily from [documentaton](https://docs.ray.io/en/latest/tune/tutorials/tune-xgboost.html), this tutorial will give you a quick introduction to XGBoost, show you how to train an XGBoost model, and then guide you on how to optimize XGBoost parameters using Ray Tune to get the best performance. In particular, we will cover the following: * What is XGBoost * Training a simple XGBoost classifier * XGBoost Hyperparameters * Tuning the configuration parameters * Early stopping * Conclusion * Further References What is XGBoostXGBoost is an acronym for eXtreme Gradient Boosting. Internally, XGBoost uses decision trees. Instead of training just one large decision tree, XGBoost and other related algorithms train many small decision trees. The intuition behind this is that even though single decision trees can be inaccurate and suffer from high variance, combining the output of a large number of these weak learners can actually lead to strong learner, resulting in better predictions and less variance. A single decision tree (left) might be able to get to an accuracy of 70% for a binary classification task. By combining the output of several small decision trees, an ensemble learner (right) might end up with a higher accuracy of 90%.¶Boosting algorithms start with a single small decision tree and evaluate how well it predicts the given examples. When building the next tree, those samples that have been misclassified before have a higher chance of being used to generate the tree. This is useful because it avoids overfitting to samples that can be easily classified and instead tries to come up with models that are able to classify hard examples, too. Please [see here](https://towardsdatascience.com/ensemble-methods-bagging-boosting-and-stacking-c9214a10a205) for a more thorough introduction to bagging and boosting algorithms.There are many boosting algorithms. In their core, they are all very similar. XGBoost uses second-level derivatives to find splits that maximize the **gain** (the inverse of the **loss**) - hence the name. In practice, there really is no drawback in using XGBoost over other boosting algorithms - in fact, it usually shows the best performance. Training a simple XGBoost classifierLet’s first see how a simple XGBoost classifier can be trained. We’ll use the `breast_cancer` dataset included in the sklearn dataset collection. This is a `binary classification` dataset. Given 30 different input features, our task is to learn to identify subjects with breast cancer and those without. Use credit card dataPublic anonymized [credit card data](https://www.kaggle.com/mlg-ulb/creditcardfraud?select=creditcard.csv) from ULB on Kaggle.**NOTE**: Downlad the `creditcard.csv` from Kaggle and place it in the directory where you running this notebook
###Code
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
CREDITCARD_DATA_FILE=os.path.join(os.getcwd(), "creditcard.csv")
import sklearn.metrics
from sklearn.model_selection import train_test_split
import xgboost as xgb
import numpy as np
import pandas as pd
class DataUtils:
@staticmethod
def get_data(fname):
df = pd.read_csv(fname)
return df
@staticmethod
def get_training_data(df):
X = df.drop('Class', axis=1)
y = df['Class']
# Split into train and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=7)
return X_train, X_test, y_train, y_test
@staticmethod
def get_scoring_data(df, n_lines=1):
# fraud list
lst_1 = dataset.loc[dataset['Class'] == 1].head(n_lines)
lst_1.drop('Class', axis=1, inplace=True)
f_list = lst_1. to_json(orient='records', lines=True).splitlines()
# non-fraud list
lst_2 = dataset.loc[dataset['Class'] == 0].head(n_lines)
lst_2.drop('Class', axis=1, inplace=True)
s_list = lst_2.to_json(orient='records', lines=True).splitlines()
return [f.replace("'", '') for f in f_list], [s.replace("'", '') for s in s_list]
###Output
_____no_output_____
###Markdown
Load dataUse the data utility class
###Code
global dataset, X_train, X_test, y_train, y_test
dataset = DataUtils.get_data(CREDITCARD_DATA_FILE)
X_train, X_test, y_train, y_test = DataUtils.get_training_data(dataset)
###Output
_____no_output_____
###Markdown
Step 1: Train the base line modelLet's define our standard or regular XGBoost trainer (function). It takes in XGBoost configuration parameters.
###Code
def train_fraud_model(config):
# Build input DMatrices for XGBoost
train_set = xgb.DMatrix(X_train, label=y_train)
test_set = xgb.DMatrix(X_test, label=y_test)
# Train the classifier
results = {}
bst = xgb.train(
config,
train_set,
evals=[(test_set, "eval")],
evals_result=results,
verbose_eval=True)
return results
###Output
_____no_output_____
###Markdown
Define our basic minimal and default configurations for XGBoost
###Code
configs = {
"objective": "binary:logistic",
"eval_metric": ["logloss", "error"]
}
###Output
_____no_output_____
###Markdown
Train the basic model
###Code
results = train_fraud_model(configs)
accuracy = 1. - results["eval"]["error"][-1]
print(f"Accuracy: {accuracy:.4f}")
###Output
/usr/local/anaconda3/envs/anyscale-academy/lib/python3.8/site-packages/xgboost/data.py:262: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.
elif isinstance(data.columns, (pd.Int64Index, pd.RangeIndex)):
###Markdown
As you can see, the code is quite simple. First, the dataset is loaded and split into a test and train set. The XGBoost model is trained with `xgb.train()`. XGBoost automatically evaluates metrics we specified on the test set. In our case it calculates the `logloss` and the prediction error, which is the percentage of misclassified examples. To calculate the accuracy, we just have to subtract the error from 1.0. Even in this simple example, most runs result in a good accuracy of over 0.90.What if you want further accuracy, or want to use XGBoost's additional parameters? XGBoost HyperparametersEven with the default settings, XGBoost was able to get to a good accuracy on the breast cancer dataset. However, as in many machine learning algorithms, there are many knobs to tune which might lead to even better performance. Let’s explore some of them below. Maximum tree depthRemember that XGBoost internally uses many decision tree models to come up with predictions. When training a decision tree, we need to tell the algorithm how large the tree may get. The parameter for this is called the tree depth.In this image, the left tree has a depth of 2, and the right tree a depth of 3. Note that with each level, 2(𝑑−1) splits are added, where d is the depth of the tree.¶Tree depth is a property that concerns the model complexity. If you only allow short trees, the models are likely not very precise - they underfit the data. If you allow very large trees, the single models are likely to overfit to the data. In practice, a number between 2 and 6 is often a good starting point for this parameter.XGBoost’s default value is 3. Minimum child weightWhen a decision tree creates new leaves, it splits up the remaining data at one node into two groups. If there are only few samples in one of these groups, it often doesn’t make sense to split it further. One of the reasons for this is that the model is harder to train when we have fewer samples.In this example, we start with 100 examples. At the first node, they are split into 4 and 96 samples, respectively. In the next step, our model might find that it doesn’t make sense to split the 4 examples more. It thus only continues to add leaves on the right side.The parameter used by the model to decide if it makes sense to split a node is called the minimum child weight. In the case of linear regression, this is just the absolute number of nodes requried in each child. In other objectives, this value is determined using the weights of the examples, hence the name.The larger the value, the more constrained the trees are and the less deep they will be. This parameter thus also affects the model complexity. Values can range between 0 and infinity and are dependent on the sample size. For our ca. 500 examples in the breast cancer dataset, values between 0 and 10 should be sensible.XGBoost’s default value is 1. Subsample sizeEach decision tree we add is trained on a subsample of the total training dataset. The probabilities for the samples are weighted according to the XGBoost algorithm, but we can decide on which fraction of the samples we want to train each decision tree on.Setting this value to 0.7 would mean that we randomly sample 70% of the training dataset before each training iteration.XGBoost’s default value is 1. Learning rate / EtaRemember that XGBoost sequentially trains many decision trees, and that later trees are more likely trained on data that has been misclassified by prior trees. In effect this means that earlier trees make decisions for easy samples (i.e. those samples that can easily be classified) and later trees make decisions for harder samples. It is then sensible to assume that the later trees are less accurate than earlier trees.To address this fact, XGBoost uses a parameter called Eta, which is sometimes called the learning rate. Don’t confuse this with learning rates from gradient descent!Typical values for this parameter are between `0.01 and 0.3`.XGBoost’s default value is 0.3. Number of boost roundsLastly, we can decide on how many boosting rounds we perform, which means how many decision trees we ultimately train. When we do heavy subsampling or use small learning rate, it might make sense to increase the number of boosting rounds.XGBoost’s default value is 10. Putting it togetherLet’s see how this looks like in code! We just need to adjust our config dict. Step 2: Use some guessed hyperparameters
###Code
config = {
"objective": "binary:logistic",
"eval_metric": ["logloss", "error"],
"max_depth": 4,
"min_child_weight": 0,
"subsample": 0.8,
"eta": 0.2
}
results = train_fraud_model(config)
accuracy = 1. - results["eval"]["error"][-1]
print(f"Accuracy: {accuracy:.4f}")
###Output
[0] eval-logloss:0.51344 eval-error:0.00059
[1] eval-logloss:0.39263 eval-error:0.00057
[2] eval-logloss:0.30605 eval-error:0.00053
[3] eval-logloss:0.24167 eval-error:0.00052
[4] eval-logloss:0.19251 eval-error:0.00049
[5] eval-logloss:0.15441 eval-error:0.00048
[6] eval-logloss:0.12448 eval-error:0.00045
[7] eval-logloss:0.10075 eval-error:0.00045
[8] eval-logloss:0.08188 eval-error:0.00046
[9] eval-logloss:0.06672 eval-error:0.00045
Accuracy: 0.9996
###Markdown
**Note**: The accuracy is slightly lower than the default parameters used above because we randomly chose the parameters.What if we want to get the best combination of all the parameters? This is where tuning hyperparameters helps. Step 3: Tuning the configuration parameters for HPOXGBoosts default parameters already lead to a good accuracy, and even our guesses in the last section should result in accuracies well above 90%. However, our guesses were just that: guesses. Often we do not know what combination of parameters would actually lead to the best results on a machine learning task.Unfortunately, there are infinitely many combinations of hyperparameters we could try out. Should we combine `max_depth=3` with `subsample=0.8` or with `subsample=0.9?` What about the other parameters?This is where hyperparameter tuning comes into play. By using tuning libraries such as Ray Tune, we can try out combinations of hyperparameters. Using sophisticated search strategies, these parameters can be selected so that they are likely to lead to good results (avoiding an expensive exhaustive search). Also, trials that do not perform well can be preemptively stopped to reduce waste of computing resources. Lastly, Ray Tune also takes care of training these runs in parallel, greatly increasing search speed.Let’s start with a basic example on how to use Tune for this. We just need to make a few changes to our code-block:
###Code
from ray import tune
###Output
_____no_output_____
###Markdown
Add tune report to our XGBoost training function
###Code
def train_tuned_model(config, checkpoint_dir=None):
# Build input DMatrices for XGBoost
train_set = xgb.DMatrix(X_train, label=y_train)
test_set = xgb.DMatrix(X_test, label=y_test)
# Train the classifier
results = {}
xgb.train(
config,
train_set,
evals=[(test_set, "eval")],
evals_result=results,
verbose_eval=False)
# Return prediction accuracy
accuracy = 1. - results["eval"]["error"][-1]
tune.report(mean_accuracy=accuracy, done=True)
###Output
_____no_output_____
###Markdown
Define our Hyperparameter Search Space
###Code
config = {
"objective": "binary:logistic",
"eval_metric": ["logloss", "error"],
"max_depth": tune.randint(1, 9),
"min_child_weight": tune.choice([1, 2, 3]),
"subsample": tune.uniform(0.5, 1.0),
"eta": tune.loguniform(1e-4, 1e-1)
}
###Output
_____no_output_____
###Markdown
Use Ray Tune parallelize our Hyperparameters tuningThis is automatically launch a Ray cluster on your laptop and schedule tasks. The `num_samples=10` option we pass to tune.run() means that we sample 10 different hyperparameter configurations from this search space, run across 10 CPUs
###Code
analysis = tune.run(train_tuned_model,
resources_per_trial={"cpu": 10},
config=config,
mode="min",
verbose=1,
num_samples=10)
print("Best Hyperparamter config: ", analysis.get_best_config(metric="mean_accuracy", mode="min"))
###Output
Best Hyperparamter config: {'objective': 'binary:logistic', 'eval_metric': ['logloss', 'error'], 'max_depth': 1, 'min_child_weight': 3, 'subsample': 0.5568204289810503, 'eta': 0.0013148931384499832}
###Markdown
Step 4: Early ASHAScheduler for early stoppingCurrently, in our example above, Tune samples 10 different hyperparameter configurations and trains a full XGBoost on all of them. In our small example, training is very fast. However, if training were done on a large datasetm it wouldtake much longer and a significant amount of computer resources would be spent on trials that would eventually show a bad performance, e.g., a low accuracy. It would be good if we could identify these trials early and stop them, so we don’t waste any resources.This is where Tune’s Schedulers shine. A Tune `TrialScheduler` is responsible for starting and stopping trials. Tune implements a number of different schedulers, each described in the Tune documentation. For our example, we will use the `AsyncHyperBandScheduler` or `ASHAScheduler`.The basic idea of this scheduler is simple. We sample a number of hyperparameter configurations. Each of these configurations is trained for a specific number of iterations. After these iterations, only the best performing hyperparameters are retained. These are selected according to some loss metric, usually an evaluation loss. This cycle is repeated until we end up with the best configuration.The `ASHAScheduler` needs to know three things: * Which metric should be used to identify badly performing trials? * Should this metric be maximized or minimized? * How many iterations does each trial train for?There are more parameters, which are explained in the [documentation](https://docs.ray.io/en/latest/tune/api_docs/schedulers.htmltune-schedulers).Lastly, we have to report the loss metric to Tune. We do this with a Callback that XGBoost accepts and calls after each evaluation round. Ray Tune comes with [two XGBoost callbacks](https://docs.ray.io/en/latest/tune/api_docs/integration.htmltune-integration-xgboost) we can use for this. The `TuneReportCallback` just reports the evaluation metrics back to Tune. The `TuneReportCheckpointCallback` also saves checkpoints after each evaluation round. We will just use the latter in this example so that we can retrieve the saved model later.These parameters from the `eval_metrics` configuration setting are then automatically reported to Tune via the callback. Here, the raw error will be reported, not the accuracy. To display the best reached accuracy, we will inverse it later.We will also load the best checkpointed model so that we can use it for predictions. The best model is selected with respect to the `metric` and `mode` parameters we pass to `tune.run()`.
###Code
from ray.tune.schedulers import ASHAScheduler
from ray.tune.integration.xgboost import TuneReportCheckpointCallback
###Output
_____no_output_____
###Markdown
Let's modify our training function and add our callbacks
###Code
def train_tuned_asha_model(config: dict):
# This is a simple training function to be passed into Tune
# Build input DMatrices for XGBoost
train_set = xgb.DMatrix(X_train, label=y_train)
test_set = xgb.DMatrix(X_test, label=y_test)
# Train the classifier, using the Tune callback
xgb.train(
config,
train_set,
evals=[(test_set, "eval")],
verbose_eval=False,
callbacks=[TuneReportCheckpointCallback(filename="creditcard_model.xgb")])
###Output
_____no_output_____
###Markdown
Write a helper function for loading callbacks and returning the best model with best configurationafter tuning
###Code
def get_best_model_checkpoint(analysis):
best_bst = xgb.Booster()
best_model_path = os.path.join(analysis.best_checkpoint, "creditcard_model.xgb")
best_bst.load_model(best_model_path)
accuracy = 1. - analysis.best_result["eval-error"]
print(f"Best model parameters: {analysis.best_config}")
print(f"Best model total accuracy: {accuracy:.4f}")
print(f"checkpoint best model path: {best_model_path}")
return best_bst
###Output
_____no_output_____
###Markdown
Wrapper around our trainer to do actual tuning: * define search space * define our ASHAScheduler * run `tune.run(...)` * return the ExperimentAnalysis object from `tune.run()`
###Code
def tune_xgboost():
search_space = {
# You can mix constants with search space objects.
"objective": "binary:logistic",
"eval_metric": ["logloss", "error"],
"max_depth": tune.randint(1, 9),
"min_child_weight": tune.choice([1, 2, 3]),
"subsample": tune.uniform(0.5, 1.0),
"eta": tune.loguniform(1e-4, 1e-1)
}
# This will enable aggressive early stopping of bad trials.
scheduler = ASHAScheduler(
max_t=10, # 10 training iterations
grace_period=1,
reduction_factor=2)
analysis = tune.run(
train_tuned_asha_model, # our training function
metric="eval-logloss", # eval metric
mode="min", # mode
# You can add "gpu": 0.1 to allocate GPUs
resources_per_trial={"cpu": 1},
config=search_space,
num_samples=10,
verbose=1,
scheduler=scheduler)
return analysis
###Output
_____no_output_____
###Markdown
Let's tune with our `ASHAScheduler`
###Code
analysis = tune_xgboost()
print("Best Hyperparamter config: ", analysis.get_best_config(metric="eval-logloss", mode="min"))
###Output
Best Hyperparamter config: {'objective': 'binary:logistic', 'eval_metric': ['logloss', 'error'], 'max_depth': 4, 'min_child_weight': 2, 'subsample': 0.5661827348603126, 'eta': 0.02607868366855465}
###Markdown
As you can see, most trials have been stopped only after a few iterations. Only the two most promising trials were run for the full 10 iterations.You can also ensure that all available resources are being used as the scheduler terminates trials, freeing them up. This can be done through the `ResourceChangingScheduler`. An example of this can be found here: [xgboost_dynamic_resources_example](https://docs.ray.io/en/latest/tune/examples/xgboost_dynamic_resources_example.html).
###Code
best_bst = get_best_model_checkpoint(analysis)
###Output
Best model parameters: {'objective': 'binary:logistic', 'eval_metric': ['logloss', 'error'], 'max_depth': 4, 'min_child_weight': 2, 'subsample': 0.5661827348603126, 'eta': 0.02607868366855465}
Best model total accuracy: 0.9995
checkpoint best model path: /Users/jules/ray_results/train_tuned_asha_model_2022-03-16_16-51-34/train_tuned_asha_model_0322e_00005_5_eta=0.026079,max_depth=4,min_child_weight=2,subsample=0.56618_2022-03-16_16-51-48/checkpoint_000005/creditcard_model.xgb
###Markdown
Step 5: Persist the best model
###Code
best_bst.save_model("best_model.json")
###Output
_____no_output_____
###Markdown
Get some test data for scoring
###Code
test_set = xgb.DMatrix(X_test, label=y_test)
###Output
/usr/local/anaconda3/envs/anyscale-academy/lib/python3.8/site-packages/xgboost/data.py:262: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.
elif isinstance(data.columns, (pd.Int64Index, pd.RangeIndex)):
###Markdown
Step 6: Load the best persisted model
###Code
bst_model = xgb.Booster()
bst_model.load_model("best_model.json")
###Output
_____no_output_____
###Markdown
Step 7: Test some predictions
###Code
pred = bst_model.predict(test_set)[:-1]
predictions = [round(value) for value in pred]
predictions[:25]
###Output
_____no_output_____
###Markdown
Step 8: Create Deployment and deploy to Ray Serve
###Code
from fastapi import FastAPI, Request
import ray
from ray import serve
@serve.deployment(num_replicas=2, route_prefix="/fraud")
class XGBFraudModel:
def __init__(self):
# Load the best saved model
self.bst_model = xgb.Booster()
self.bst_model.load_model("best_model.json")
print(type(self.bst_model))
print("Best saved model loaded")
async def __call__(self, starlette_request:Request):
payload = await starlette_request.json()
pred = xgb.DMatrix([np.array(list(payload.values()), dtype=np.float64)])
prediction = round(np.float64(self.bst_model.predict(pred)[0]))
return {"result": prediction}
serve.start()
XGBFraudModel.deploy()
###Output
[2m[36m(ServeController pid=66112)[0m 2022-03-16 16:52:15,501 INFO checkpoint_path.py:16 -- Using RayInternalKVStore for controller checkpoint and recovery.
[2m[36m(ServeController pid=66112)[0m 2022-03-16 16:52:15,606 INFO http_state.py:98 -- Starting HTTP proxy with name 'SERVE_CONTROLLER_ACTOR:VwlFXy:SERVE_PROXY_ACTOR-node:127.0.0.1-0' on node 'node:127.0.0.1-0' listening on '127.0.0.1:8000'
2022-03-16 16:52:16,575 INFO api.py:521 -- Started Serve instance in namespace 'b69cdb90-0ac8-4d42-b256-5d3ffc3f7cc8'.
2022-03-16 16:52:16,582 INFO api.py:262 -- Updating deployment 'XGBFraudModel'. component=serve deployment=XGBFraudModel
[2m[36m(HTTPProxyActor pid=66114)[0m INFO: Started server process [66114]
[2m[36m(ServeController pid=66112)[0m 2022-03-16 16:52:16,674 INFO deployment_state.py:920 -- Adding 2 replicas to deployment 'XGBFraudModel'. component=serve deployment=XGBFraudModel
[2m[36m(XGBFraudModel pid=66116)[0m /usr/local/anaconda3/envs/anyscale-academy/lib/python3.8/site-packages/xgboost/compat.py:36: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.
[2m[36m(XGBFraudModel pid=66116)[0m from pandas import MultiIndex, Int64Index
[2m[36m(XGBFraudModel pid=66117)[0m /usr/local/anaconda3/envs/anyscale-academy/lib/python3.8/site-packages/xgboost/compat.py:36: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.
[2m[36m(XGBFraudModel pid=66117)[0m from pandas import MultiIndex, Int64Index
2022-03-16 16:52:18,487 INFO api.py:274 -- Deployment 'XGBFraudModel' is ready at `http://127.0.0.1:8000/fraud`. component=serve deployment=XGBFraudModel
###Markdown
Step 9: Score the model by sending requests
###Code
fraud_list, safe_list = DataUtils.get_scoring_data(dataset)
import requests
import json
def send_requests(l):
for sri in l:
r = json.loads(sri)
response = requests.get("http://localhost:8000/fraud", json=r).json()
print(response)
for inference_data in [fraud_list, safe_list]:
send_requests(inference_data)
ray.shutdown()
###Output
_____no_output_____ |
Pandas Assignment.ipynb | ###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv("alumni.csv")
pd = alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
pd.head()
#b) (1)
pd.tail()
#c) (1)
pd.dtypes
#d) (1)
pd.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
savings = alumni['Savings ($)']
savings
alumni['Savings']
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
T = alumni['Gender'].str.replace('Male', 'M')
T.value_counts()
T1 = T.str.replace('M', 'Male')
T1.value_counts()
# b) (1)
#T1 is my new column with all data appearing as either 'male' or 'female'
T1.value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].median()
# b)(1)
alumni['Salary'].mean()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
paid_above_15000 = alumni[alumni['Fee']>15000]
paid_above_15000
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
import matplotlib as plt
Diploma = alumni.iloc[0:87,3]
Diploma.value_counts().plot(kind = 'bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
pd1 = alumni.iloc[:,[5,7]]
pd1
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
plt.hist(alumni['Salary', bins=12])
plt.show()
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info
# e) (1)
alumni.describe
### Question 3 : Cleaning the data set - part A (3 Marks)
a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
#a) (2)
alumni['Savings'] = alumni['Savings ($)'].apply(lambda x: clean_currency(x))
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'].str.replace('^M$','Male')
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni['Gender'] = alumni['Gender'].str.replace('^M$','Male')
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[(alumni.Gender=='M'),'Gender'] = 'Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].median()
# b)(1)
alumni['Salary'].mean()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni.Fee > 15000 ]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
diploma_type = alumni["Diploma Type"].unique()
val_counts = alumni["Diploma Type"].value_counts()
ax.bar(diploma_type,val_counts)
ax.set_title("Diploma Distribution")
ax.set_xlabel("Diploma Type")
ax.set_ylabel("Alumni")
plt.show()
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
data_to_plot = savings = [alumni["Savings"],alumni["Salary"]]
#ax.boxplot(savings)
ax.boxplot(data_to_plot)
plt.show()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
#create 12 bins
bins = np.linspace(alumni['Salary'].min(),alumni['Salary'].max(),12).round()
plt.hist(alumni['Salary'],bins, histtype = 'bar', rwidth=1)
plt.xlabel('Salary')
plt.ylabel('Count')
plt.title('Salary Histogram')
plt.show()
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
salary = alumni["Salary"]
savings = alumni["Savings"]
plt.scatter(salary,savings, color = 'g', marker = "x")
plt.xlabel('Salary')
plt.ylabel('Savings')
plt.title('Plot Comparing Salaru & Savings')
plt.show()
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni['Marital Status'], alumni['Defaulted'],margins=True, margins_name="Total")
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import os
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv("alumni.csv")
alumni.head()
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
alumni["Savings"] = alumni["Savings ($)"].apply(clean_currency)
alumni.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
alumni.dtypes
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].replace("M" , "^Male$")
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"]= alumni["Gender"].replace("M" , "Male")
alumni
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni["Fee"].head()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
alumni['Diploma Type'].value_counts()
alumni['Diploma Type'].value_counts().plot(kind='bar');
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
alumni.boxplot(column=['Savings', 'Salary'])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni.hist(column='Salary')
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot.scatter(x='Salary', y='Savings');
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
alumni_crosstab=pd.crosstab([])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import os
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv("./alumni.csv")
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
Savings = alumni["Savings ($)"].map(clean_currency)
alumni["Savings"] = Savings
alumni.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].str.replace(r'^M$',"Male", regex=True)
# b) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni_copy = alumni.copy(deep=True)
alumni["Gender"] = alumni["Gender"].str.replace(r'^M$',"Male", regex=True)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
print(alumni_copy["Gender"].value_counts())
alumni_copy.loc[alumni_copy["Gender"] == "M","Gender"]="Male"
print(alumni_copy["Gender"].value_counts())
###Output
Male 46
Female 39
M 3
Name: Gender, dtype: int64
Male 49
Female 39
Name: Gender, dtype: int64
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni.loc[alumni["Fee"] > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni["Diploma Type"].value_counts().plot(kind="bar")
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
fig = plt.figure(figsize=(18,6))
plt.subplot(1,2,1)
plt.boxplot(alumni["Savings"])
plt.title("Savings Boxplot")
plt.subplot(1,2,2)
plt.boxplot(alumni["Salary"])
plt.title("Salary Boxplot")
fig=plt.figure(figsize=(18,10))
sns.boxplot(data=alumni, x="Salary", y="Savings")
plt.title("Boxplot of Salary compared to Savings")
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
sns.set_style("darkgrid")
n_bins = 12
sns.displot(data=alumni, x="Salary", bins=n_bins)
plt.title("Salary Groups")
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
# fig = px.scatter(alumni, x="Salary", y="Savings", title="Comparison of Savings to Salary")
# fig.show()
sns.scatterplot(data=alumni, x="Salary", y="Savings")
plt.title("Comparison of Savings to Salary")
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
alumni.head()
# Q7 (2)
contingency = pd.crosstab(alumni["Marital Status"], alumni["Defaulted"])
contingency
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import os
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import seaborn as sns
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.DataFrame()
alumni=pd.read_csv("alumni.csv")
alumni.head(5) #five samples
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
alumni["Savings"] = alumni["Savings ($)"].apply(lambda x: f"{clean_currency(x)} ")
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
alumni['Savings']=pd.to_numeric(alumni['Savings']) #make float
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"] = alumni["Gender"].str.replace("(^M$)", "Male", regex=True)
#alumni["Gender"] = alumni["Gender"].str.replace("^[M]$", "Male")
alumni["Gender"]
# b) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"] = alumni["Gender"].str.replace("(^M$)", "Male", regex=True)
#alumni["Gender"] = alumni["Gender"].str.replace("^[M]$", "Male")
alumni["Gender"]
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[alumni.Gender== "M"] #identify the indexes
alumni.loc[[28,35,84], ["Gender"]] = "Male"
#alumni.loc[[28,35,84], ["Gender"]] = "Male"
alumni["Gender"]
#alumni.loc
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
paid_above_15000 = alumni[alumni["Fee"] >15000]
paid_above_15000.head()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni["Diploma Type"].value_counts().plot(kind="bar")
#fig = plt.figure(figsize=(10,7))
plt.xlabel("Diploma Type")
plt.ylabel("Counts")
plt.title("Plot Representing Diploma Type")
fig = plt.figure(figsize=(10,7))
#alumni["Diploma Type"].value_counts().plot(kind="bar")
#plt.xlabel("Diploma Type")
#plt.ylabel("Counts")
#plt.title(" Bar Chart Representing Diploma Types")
plt.show()
#layouts
#consistent layouts - template - font type, font family, colors, alignments
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
#alumni = pd.DataFrame(data = np.random.random(size=(4,2)), columns = ['Savings', 'Salary'])
#sns.boxplot(x="variable", y="value", data=pd.melt(alumni))
#plt.show()
#detect outliers
#whiskers -
#anomaly detection - regression problems
#numerical types - continuous variables
#discretized
data = alumni[["Savings", "Salary"]]
fig = plt.figure(figsize=(10,7))
plt.boxplot(data)
plt.show()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
#alumni.hist(column='Salary', bins=12)
#plt.show()
# identify distributions
# uniform, binomial, normal(gaussian), exponential
# normalized
#normal distribution - mean=0, unit variance =1
# biasness
#feature scaling
x = alumni.Savings
plt.hist(x, bins=12, histtype= "bar", rwidth = 0.5 )
plt.xlabel("Savings")
plt.ylabel(" Frequency")
plt.title(" Histogram Chart for Salary Distribution")
plt.show()
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
# scatterplot
#sns.scatterplot(data = alumni, x ="Salary", y = "Savings")
#plt.show()
#relationship - bar chart - quantities
# scatter plots - segments - clusters
x = alumni["Salary"]
y = alumni.Savings
plt.scatter(x,y, label= "Scatter", color= "magenta") #data
plt.xlabel("Salary")
plt.ylabel("Savings")
plt.title("Comparison of Salary and Savings: Scatter Plot")
plt.show()
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
alumni_crosstab = pd.crosstab(alumni['Defaulted'], alumni['Marital Status'])
print(alumni_crosstab)
###Output
Marital Status Divorced Married Single
Defaulted
No 8 19 9
Yes 11 16 25
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import seaborn as sns
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv("alumni.csv")
df = alumni.copy()
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
if isinstance(curr, str):
return float(curr.replace(",", "").replace("$", ""))
return curr.str.replace(",", "").str.replace("$", "").astype(float)
#a) (2)
alumni['Savings ($)'] = alumni['Savings ($)'].apply(clean_currency).astype('float')
alumni['Savings'] = alumni.apply(lambda x: x['Savings ($)'] if x['Savings ($)'] == 0 else x['Savings ($)'], axis=1)
alumni.loc[:,"Savings ($)"]
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"] = alumni["Gender"].str.replace('^.M', 'Male', case=False)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"] = np.where(alumni["Gender"]== "M", "Male", alumni["Gender"])
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[alumni.Gender == "Male", "Gender"] = "M"
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni.Salary.median()
# b)(1)
alumni.Salary.mean()
# c)(1)
alumni.Salary.std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni.Fee > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
ax = alumni['Diploma Type'].value_counts().plot(kind='bar',
figsize=(7,4),
title="Type of Diploma taken by each Student")
ax.set_xlabel("Diploma Type ")
ax.set_ylabel("Frequency")
plt.show()
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni.boxplot(column=["Salary", "Savings"])
plt.show()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni.hist(column='Salary', bins=12);
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot.scatter(x = 'Salary', y = 'Savings', s = 100);
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
alumni_crosstab = pd.crosstab(alumni['Marital Status'],
alumni['Defaulted'],
margins = True)
print(alumni_crosstab)
###Output
Defaulted No Yes All
Marital Status
Divorced 8 11 19
Married 19 16 35
Single 9 25 34
All 36 52 88
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
import pandas as pd
df = pd.read_csv('alumni.csv')
(df)
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
df.head(5)
df.tail()
df.dtypes
df.info()
df.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
df['Savings'] = df['Savings ($)'].apply(clean_currency)
df.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
df.dtypes
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
df["Gender"].value_counts()
df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
df[df['Gender'] == 'M'].replace(to_replace=r'^M.$', value='Male', regex=True)
# b) (1)
df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
df.loc[row_indexer,col_indexer] = value
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
print(df.median())
# b)(1)
print(df.mean())
# c)(1)
df.std(axis = 1, skipna = True)
###Output
C:\Users\HP\AppData\Local\Temp/ipykernel_8228/3895312714.py:2: FutureWarning: Dropping of nuisance columns in DataFrame reductions (with 'numeric_only=None') is deprecated; in a future version this will raise TypeError. Select only valid columns before calling the reduction.
df.std(axis = 1, skipna = True)
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
df.loc[df['Fee'] > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
import matplotlib.pyplot as plt
df['Diploma Type'].value_counts(sort=True).nlargest(5).plot.bar()
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
df.plot(x="Salary", y="Savings", kind="box")
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
df.hist(column='Salary', bins =10)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
df.plot(x="Salary", y="Savings", kind="scatter")
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
c_t = pd.crosstab(df['Marital Status'],df['Defaulted'],margins = False)
print(c_t)
###Output
Defaulted No Yes
Marital Status
Divorced 8 11
Married 19 16
Single 9 25
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
alumni
alumni["Savings ($)"]
clean_currency(alumni["Savings ($)"])
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].replace("M", "Male")
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"]= alumni["Gender"].replace("M", "Male")
alumni
#alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
df.loc[[],[]] = 'Male'
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].mean()
# b)(1)
alumni['Salary'].median()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
paid_above_15000 = alumni[alumni['Fee'] > 15000]
paid_above_15000.head()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
#alumni["Diploma Type"].describe()
alumni.info()
###Output
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 88 entries, 0 to 87
Data columns (total 8 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Year Graduated 88 non-null int64
1 Gender 88 non-null object
2 Marital Status 88 non-null object
3 Diploma Type 88 non-null object
4 Defaulted 88 non-null object
5 Salary 88 non-null int64
6 Fee 88 non-null int64
7 Savings ($) 88 non-null object
dtypes: int64(3), object(5)
memory usage: 5.6+ KB
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
frequency, bins = pd.histogram(alumni['Salary'], bins=12, range=[0, 100])
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import numpy as np
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
db= pd.read_csv('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
db.head()
#b) (1)
db.tail()
#c) (1)
db.dtypes
#d) (1)
db.info()
#e) (1)
db.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
db.rename(columns={"Savings ($)": "Savings"}, inplace=True)
db['Savings'] = db['Savings'].str.replace(r'\D', '')
db['Savings']=db['Savings'].astype(float, errors = 'raise')
db.dtypes
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
db.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
db['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
db['Gender']=db['Gender'].replace('M', 'Male')
db['Gender'].value_counts()
# b) (1)
db['Gender']=db['Gender'].replace(to_replace='^M$', value='male', regex=True)
db['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
db['Salary'].median()
# b)(1)
db['Salary'].mean()
# c)(1)
db['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
db.loc[db['Fee']>15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
import seaborn as sns
import matplotlib.pyplot as plt
sns.countplot(data=db, x='Diploma Type')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
ax=sns.catplot(data=db, x='Salary', y='Savings', kind= 'box', height=15, aspect=1)
#ax.set_xticklabels(rotation=30)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
sns.histplot(data=db, x='Salary', bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
sns.scatterplot(data=db, x ='Salary', y='Savings')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
db.head()
pd.crosstab(index=db['Marital Status'], columns=db['Defaulted'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni=pd.read_csv('Assignments/ADS-Assignment-1/alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
#a) (2)
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
alumni['Savings']=alumni['Savings ($)'].apply(clean_currency)
alumni.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].replace("M","Male")
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni['Gender']=alumni["Gender"].replace("M","Male")
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].median()
# b)(1)
alumni['Salary'].mean()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni['Fee'].gt(15000).value_counts()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
#alumni['Diploma Type'].value_counts()
import seaborn as sns
sns.set_style('darkgrid')
sns.barplot(x=alumni['Diploma Type'],y=alumni['Diploma Type'].value_counts(),color='g')
plt.show()
#alumni['Diploma Type']
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
sns.boxplot(x='Savings',y='Salary',data=alumni)
plt.show()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
sns.histplot(x='Salary',data=alumni,bins=12)
plt.show()
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
sns.scatterplot(x='Salary',y='Savings',data=alumni)
plt.show()
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv("alumni.csv")
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni["Savings"] = alumni["Savings ($)"].str.replace("$","").str.replace(",","")
alumni["Savings"] = pd.to_numeric(alumni["Savings"])
alumni["Savings"]
###Output
<ipython-input-13-f59909446ff8>:2: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will*not* be treated as literal strings when regex=True.
alumni["Savings"] = alumni["Savings ($)"].str.replace("$","").str.replace(",","")
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].replace("M","Male", inplace=True)
# b) (1)
alumni["Gender"]
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"].replace("M","Male", inplace=True)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
df.loc["M","Gender"] = Male
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni ["Salary"].median()
# b)(1)
alumni ["Salary"].mean()
# c)(1)
alumni ["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
paid_above_15000 = alumni [alumni["Fee"] > 15000]
paid_above_15000
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni["Diploma Type"].value_counts().plot(kind = "bar")
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
boxplot = alumni.boxplot(column =["Salary","Savings"])
boxplot
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni.hist (column = "Salary", bins = 12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot.scatter(x='Salary', y='Savings')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab (alumni["Marital Status"], alumni["Defaulted"])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni= pd.read_csv("alumni.csv")
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
df=alumni
df.head()
#b) (1)
df.tail()
#c) (1)
alumni.dtypes()
#d) (1)
df.info()
#e) (1)
df.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
Savings= "$66,000"
Savings.replace(", ","").replace("$", "")
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni[Gender].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
# b)(1)
# c)(1)
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
ls
#q1 (1)
alumni = pd.read_csv ('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni['Savings'] = alumni ['Savings ($)'].apply(clean_currency)
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'].str.replace('^[M]$' , 'Male')
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni['Gender'] = alumni['Gender'].str.replace('^[M]$' , 'Male')
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni [alumni ["Gender"] == 'M']['Gender']
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni ['Salary'].median()
# b)(1)
alumni ['Salary'].mean()
# c)(1)
alumni ['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni.Fee > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot (kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni [['Savings' , 'Salary']].plot (kind = 'box')
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni['Salary'].plot(kind = 'hist' , bins = 12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot(kind= 'scatter', x = 'Savings', y= 'Salary')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
alumni['Marital Status'].value_counts()
alumni['Defaulted'].value_counts()
pd.crosstab(index = alumni ['Marital Status'], columns = alumni['Defaulted'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import os
import matplotlib.pyplot as plt
import seaborn as sns
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
df= pd.DataFrame()
alumni_df = pd.read_csv("alumni.csv")
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (Head)
alumni_df.head()
#b) (tail)
alumni_df.tail()
#c) (Info)
alumni_df.info()
#d) (data types)
alumni_df.dtypes
#e) (describe)
alumni_df.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
###alumni_df.head()
#a) (2)
alumni_df ['Savings']= alumni_df ['Savings ($)'].apply(clean_currency)
alumni_df.head()
alumni_df.tail()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni_df.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male' b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# a) (1)
alumni_df["Gender"].value_counts()
# a)(1)
###alumni_df ["Gender"].str.replace ('M','Male')
###Output
_____no_output_____
###Markdown
0 Male1 Male2 Female3 Male4 Female ... 83 Male84 Male85 Male86 Female87 MaleName: Gender, Length: 88, dtype: object
###Code
alumni_df.loc[[28,35,84],["Gender"]] = "Male"
# b) (1)
alumni_df.head()
alumni_df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###alumni_df['Gender'] = alumni_df['Gender'].str.replace('Male','M')
alumni_df.head()
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni_df.loc[[28,35,84],["Gender"]] = "Male"
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni_df.head()
alumni_df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni_df['Salary'].median()
# b)(1)
alumni_df['Salary'].mean()
# c)(1)
alumni_df['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni_df[alumni_df['Fee'] >= 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni_df['Diploma Type'].value_counts().plot.bar()
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b)
alumni_df.boxplot(column=['Savings','Salary'])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c)
alumni_df.hist(column='Salary', bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni_df.plot(kind= "scatter", x='Salary', y='Savings', color='r')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7
pd.crosstab(alumni_df['Defaulted'], alumni_df['Marital Status'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
!pip install pandas
import pandas as pd
import seaborn as sns
###Output
Requirement already satisfied: pandas in c:\users\hp\anaconda3\lib\site-packages (1.1.3)
Requirement already satisfied: pytz>=2017.2 in c:\users\hp\anaconda3\lib\site-packages (from pandas) (2020.1)
Requirement already satisfied: numpy>=1.15.4 in c:\users\hp\anaconda3\lib\site-packages (from pandas) (1.19.2)
Requirement already satisfied: python-dateutil>=2.7.3 in c:\users\hp\anaconda3\lib\site-packages (from pandas) (2.8.1)
Requirement already satisfied: six>=1.5 in c:\users\hp\anaconda3\lib\site-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('alumni.csv')
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni["Savings"] = alumni["Savings ($)"].apply(clean_currency)
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
# b) (1)
#alumni.replace(regex=[r'^ba.$', 'M'], value='male')
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.iloc[0:1, 3] = "male"
alumni.head()
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
paid_more = alumni[alumni["Fee"] >15000]
paid_more.head()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni.boxplot(column='Savings', by='Salary')
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni['Salary'].plot(kind='hist',bins=12);
#df.hist(column='Test1', bins=200);
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot(kind='scatter', x='Salary', y='Savings', title="Salary and Savings columns");
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni['Marital Status'], alumni['Defaulted'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import os
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
df = pd.read_csv("ADS-Assignment-1/alumni.csv")
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
df.head()
#b) (1)
df.tail()
#c) (1)
df.dtypes
#d) (1)
df.info()
#e) (1)
df.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
if isinstance(curr, str):
return float(curr.replace("$" , " ").replace(",",""))
clean_currency("$66,000")
#a) (2)
df['Savings ($)'] = df['Savings ($)'].apply(clean_currency).astype('float')
df['Savings'] = df['Savings ($)'].apply(lambda curr: type(curr).__name__)
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
df.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
df['Gender'].str.replace('^M$', 'Male')
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
df["Gender"]=df['Gender'].replace(['M',], 'Male')
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
df.loc[[84],['Gender']]="Male"
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
df['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
df['Salary'].median()
# b)(1)
df['Salary'].mean()
# c)(1)
df['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
above_15000=df[df['Fee']>15000]
above_15000
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
df['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
df[['Savings','Salary']].plot.box()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
df['Salary'].plot(kind='hist', bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
df.plot(kind='scatter', x='Salary', y='Savings')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(index=df['Marital Status'],columns=df['Defaulted'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import numpy as np
import seaborn as sns
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('alumni.csv')
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni['Savings'] = alumni['Savings ($)'].apply(lambda x: f"{clean_currency(x)}")
alumni.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
gender = alumni['Gender']
# Trying to replace on series first
gender = gender.replace('M', 'Male')
gender.value_counts()
# b) (1)
alumni['Gender'] = alumni['Gender'].replace('M','Male')
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
df = alumni['Gender']
df.value_counts()
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].median()
# b)(1)
alumni['Salary'].mean()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
fee_more_15000 = alumni[alumni['Fee'] > 15000]
fee_more_15000.head()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
ax = alumni['Diploma Type'].value_counts().plot(kind = 'bar', rot = 0, width = 0.5)
ax.set_ylabel('Number of alumni')
ax.set_title('Number of alumni per Diploma Type')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
sns.catplot(x="Salary", y="Savings", data=alumni, kind="box")
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
ax = sns.histplot(x = "Salary", data = alumni, bins = 12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
#g = sns.relplot(x="Salary", y="Savings", hue="Defaulted", data=alumni) or
sns.scatterplot(x="Salary", y="Savings", data=alumni, hue ="Defaulted")
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
myTable = pd.crosstab(index = alumni['Marital Status'], columns = alumni['Defaulted'])
myTable.columns = ["Defaulted", "Completed Course"]
myTable
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import re
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 Loading the csv file
alumni = pd.read_csv("alumni.csv")
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) The first 5 rows
alumni.head()
#b) The last 5 rows
alumni.tail()
#c) Data types we are dealing with
alumni.dtypes
#d) To get data types we are dealing with
alumni.info()
#e) To get a statistical summary of the dataframe
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) Adding Savings column
alumni["Savings"] = alumni["Savings ($)"].apply(lambda x:f"{clean_currency(x)}")
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
alumni.dtypes
#Convert Savings column into float
alumni["Savings"] = pd.to_numeric(alumni["Savings"])
#Checking the data type of the Savings column
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b)
alumni["Gender"].str.replace("M","Male")
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"] = alumni["Gender"].str.replace("M","Male")
alumni
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) Using df.loc to replace a string
alumni.loc[alumni.Gender == "M", "Gender"] = "Male"
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a) Median of Salary column
alumni.Salary.median()
# b)Mean of the Salary
alumni.Salary.mean()
# c)Standard deviation of salary
alumni.Salary.std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d)
alumni_paid_above_15000 = alumni[alumni["Fee"]>15000]
alumni_paid_above_15000
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) Bar plot
alumni["Diploma Type"].value_counts().plot(kind = "bar")
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) Box plot
alumni[["Savings","Salary"]].plot.box()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c)
alumni.hist(column = "Salary", bins = 12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) scatter plot
alumni.plot.scatter(x = "Salary", y = "Savings")
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2) Creating a contingency table
contingency_table = pd.crosstab(alumni["Marital Status"], alumni["Defaulted"])
contingency_table
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import os
import seaborn as sns
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
import pandas as pd
alumni = pd.read_csv('C:/Users/USER/Desktop/New folder/ADS-Assignment-1/alumni.csv')
print(alumni)
###Output
Year Graduated Gender Marital Status Diploma Type Defaulted \
0 2004 Male Single Standard Diploma Yes
1 2005 Male Married College Prep Diploma No
2 2006 Female Single Standard Diploma Yes
3 2007 Male Married Standard Diploma No
4 2006 Female Divorced Standard Diploma Yes
.. ... ... ... ... ...
83 2007 Male Single Standard Diploma No
84 2008 M Single College Prep Diploma Yes
85 2009 Male Married Standard Diploma No
86 2005 Female Divorced Standard Diploma Yes
87 2006 Male Married Standard Diploma Yes
Salary Fee Savings ($)
0 125000 10869 $86,000
1 100000 10869 $116,000
2 70000 10869 $52,000
3 120000 10869 $76,000
4 95000 11948 $52,000
.. ... ... ...
83 75000 12066 $16,000
84 65000 12066 $72,000
85 75000 12066 $46,000
86 100000 12067 $32,000
87 75000 12067 $67,000
[88 rows x 8 columns]
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head(5)
#b) (1)
alumni.tail(6)
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
def clean_currency(x):
if isinstance(x, str):
return(x.replace('$', '').replace(',', ''))
return(x)
alumni['Savings ($)'] = alumni['Savings ($)'].apply(clean_currency).astype('float')
alumni['Savings'] = alumni['Savings ($)'].apply(lambda x: type(x).__name__)
alumni['Savings'] = alumni['Savings ($)']
print(alumni)
###Output
Year Graduated Gender Marital Status Diploma Type Defaulted \
0 2004 Male Single Standard Diploma Yes
1 2005 Male Married College Prep Diploma No
2 2006 Female Single Standard Diploma Yes
3 2007 Male Married Standard Diploma No
4 2006 Female Divorced Standard Diploma Yes
.. ... ... ... ... ...
83 2007 Male Single Standard Diploma No
84 2008 Male Single College Prep Diploma Yes
85 2009 Male Married Standard Diploma No
86 2005 Female Divorced Standard Diploma Yes
87 2006 Male Married Standard Diploma Yes
Salary Fee Savings ($) Savings
0 125000 10869 86000.0 86000.0
1 100000 10869 116000.0 116000.0
2 70000 10869 52000.0 52000.0
3 120000 10869 76000.0 76000.0
4 95000 11948 52000.0 52000.0
.. ... ... ... ...
83 75000 12066 16000.0 16000.0
84 65000 12066 72000.0 72000.0
85 75000 12066 46000.0 46000.0
86 100000 12067 32000.0 32000.0
87 75000 12067 67000.0 67000.0
[88 rows x 9 columns]
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'] = alumni['Gender'].str.replace('^[M]$', 'Male')
print(alumni['Gender'])
alumni['Gender'].value_counts()
# b) (1)
alumni['Gender'] = alumni['Gender'].str.replace('^[M]$', 'Male')
print(alumni['Gender'])
alumni['Gender'].value_counts()
###Output
0 Male
1 Male
2 Female
3 Male
4 Female
...
83 Male
84 Male
85 Male
86 Female
87 Male
Name: Gender, Length: 88, dtype: object
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
def alumni_gender(alumniGender):
alumni['Gender'] = alumni['Gender'].str.replace('^[M]$', 'Male')
return alumni['Gender']
print(alumni['Gender'])
alumni['Gender'].value_counts()
###Output
0 Male
1 Male
2 Female
3 Male
4 Female
...
83 Male
84 Male
85 Male
86 Female
87 Male
Name: Gender, Length: 88, dtype: object
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[[10, 16, 19, 44], ['Gender']] = alumni['Gender'].str.replace('^[M]$', ('Male'))
###Output
<ipython-input-16-682e05b74ccc>:2: FutureWarning: The default value of regex will change from True to False in a future version.
alumni.loc[[10, 16, 19, 44], ['Gender']] = alumni['Gender'].str.replace('^[M]$', ('Male'))
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].median()
# b)(1)
alumni['Salary'].mean()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
fee_above_15k = alumni[alumni["Fee"] >15000]
fee_above_15k.head()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
import matplotlib.pyplot as plt
x = alumni['Salary']
y = alumni['Savings']
plt.boxplot(x)
plt.boxplot(y)
plt.show()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
import matplotlib.pyplot as plt
x = alumni['Salary']
bins = 12
plt.hist(x,bins,histtype='bar', rwidth=0.5)
#plt.xlabel('marks')
#plt.ylabel('count')
plt.show()
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
x = alumni['Salary']
y = alumni['Savings']
# Creating plot
plt.scatter(x,y, color='k', s=500, marker="+")
plt.xlabel('x')
plt.ylabel('y')
plt.title('Salary v Savings')
plt.legend()
plt.show()
###Output
No handles with labels found to put in legend.
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
contigency_table = pd.crosstab(alumni['Marital Status'],
alumni['Defaulted'],
margins = False)
print(contigency_table)
###Output
Defaulted No Yes
Marital Status
Divorced 8 11
Married 19 16
Single 9 25
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import os
import pandas as pd
os.getcwd()
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni_df= pd.read_csv("alumni.csv")
#read the top 5
alumni_df.head()
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni_df.head()
#b) (1)
alumni_df.tail()
#c) (1)
alumni_df.dtypes
#d) (1)
alumni_df.describe()
#e) (1)
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
#def clean_currency(curr):
#return float(curr.replace(",", "").replace("$", ""))
#clean_currency("$66,000")
#a) (2)
savings = alumni_df['Savings ($)'].str.replace(',', '').str.replace('$', '').astype(float)
alumni_df["Savings"]= savings
alumni_df["Savings"].head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni_df.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni_df["Gender"].value_counts()
alumni_df["Gender"]
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni_df["Gender"].str.replace("^M$", "Male", case =False)
###Output
<ipython-input-17-a2728cd10e4a>:2: FutureWarning: The default value of regex will change from True to False in a future version.
alumni_df["Gender"].str.replace("^M$", "Male", case =False)
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni_df["Gender"]= alumni_df["Gender"].str.replace("^M$", "Male", case =False)
###Output
<ipython-input-18-d8a83d8e3210>:2: FutureWarning: The default value of regex will change from True to False in a future version.
alumni_df["Gender"]= alumni_df["Gender"].str.replace("^M$", "Male", case =False)
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni_df.iloc[alumni_df.iloc[:88, 1] == "^M$"] = "Male"
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni_df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni_df['Salary'].median()
# b)(1)
alumni_df['Salary'].mean()
# c)(1)
alumni_df['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni_df[alumni_df.Fee== alumni_df.Fee.max()]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni_df['Diploma Type'].value_counts().plot.bar();
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni_df.boxplot(column =['Savings', 'Salary']);
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni_df.hist(column= 'Salary', bins= 12);
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni_df.plot.scatter (x= 'Salary' , y= 'Savings' );
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni_df['Marital Status'], alumni_df.Defaulted)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
import pandas as pd
df = pd.read_csv('alumni.csv')
df
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
df.head()
#b) (1)
df.tail()
#c) (1)
df.dtypes
#d) (1)
df.info()
#e) (1)
df.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
savings = []
for s in df['Savings ($)']:
savings.append(clean_currency(s))
savings
df['Savings'] = savings
df
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
df.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
import pandas as pd
df = pd.read_csv('alumni.csv')
df["Gender"]= df["Gender"].replace('M','Male')
df
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
import pandas as pd
df = pd.read_csv('alumni.csv')
df['Gender'] = df['Gender'].str.replace('Male','M')
df['Gender'] = df['Gender'].str.replace('M','Male')
df
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
df['Salary'].median()
# b)(1)
df['Salary'].mean()
# c)(1)
df["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
df[df.Fee > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
df['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
boxplot = df.boxplot(column=['Savings', 'Salary'])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
plt.hist(df['Salary'], bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
ax = df.plot.scatter(x="Salary", y="Savings")
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(index=df['Defaulted'], columns=df['Marital Status'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv ('D:/ADS/Assignment 1/ADS-Assignment-1-main/alumni.csv')
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head ()
#b) (1)
alumni.tail ()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info ()
#e) (1)
alumni.describe ()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
alumni["Savings"] = alumni["Savings ($)"].apply(clean_currency).astype("float")
#a) (2)
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'].str.replace('^M$', 'Male',regex = True)
# b) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"]=alumni["Gender"].str.replace('^M%','Male',regex = True)
Ms= alumni[ alumni["Gender"].isin(['M']) ]
Ms.head()
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.iloc[[28,35,84], 1] = "Male"
alumni
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
Scored_MoreThan_15000=alumni[alumni["Fee"]>15000]
Scored_MoreThan_15000
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni["Diploma Type"].value_counts().plot(kind="bar")
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni.boxplot(column=['Savings','Salary'])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
import matplotlib.pyplot as plt
data = alumni['Salary']
plt.hist(data, bins = 12)
plt.show()
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
Salary=alumni['Salary']
Savings=alumni['Savings']
plt.scatter(Salary,Savings)
plt.show()
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni['Marital Status'], alumni['Defaulted'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
alumni = pd.read_csv("alumni.csv")
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
type(alumni)
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni['Savings']= alumni['Savings ($)']
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'].str.replace('M', 'Male')
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni['Gender'].replace('M', 'Male')
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[]
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].median()
# b)(1)
alumni['Salary'].mean()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
paidmorethan1500 = alumni[alumni['Fee']>15000]
paidmorethan1500
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni[['Salary', 'Savings']].plot(kind='box')
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni.hist('Salary', bins = 12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot.scatter(x = 'Salary', y = 'Savings')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni.Martial Status, alumni.Defaulted)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import numpy as np, pandas as pd, seaborn as sns, matplotlib.pyplot as plt
%matplotlib inline
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
# Check for & drop NaN values
alumni = alumni.dropna(axis=0)
alumni['Savings'] = alumni['Savings ($)'].apply(lambda x: clean_currency(x))
alumni.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
import re
re = r'^M$'
# b) (1)
alumni['Gender'].replace(to_replace=re, value='Male', regex=True)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"] = alumni['Gender'].replace(to_replace=re, value='Male', regex=True)
alumni.Gender.value_counts()
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[alumni['Gender'] == 'M'] = 'Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni.Gender.value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni.Salary.astype('float32').mean()
# b)(1)
alumni.Salary.mean()
# c)(1)
alumni.Salary.std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni.loc[alumni.Fee > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
diploma_series = alumni['Diploma Type'].value_counts()
diploma_series.plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
plot_data = [alumni.Salary.dropna(), alumni.Savings.dropna()]
fig = plt.figure(figsize=(10, 5))
ax = fig.add_axes([0, 0, 1, 1])
bp = ax.boxplot(plot_data, labels=["Salary", 'Savings',],)
ax.set_ylabel('Distribution ($)')
ax.set_title = "Savings v. Salary Comparison"
plt.show()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
bins = np.arange(0, 120000, 10000)
plt.hist(alumni.Salary.dropna(), bins, histtype='bar', rwidth=0.8)
plt.xlabel('Salary')
plt.ylabel('Alumni Frequency')
plt.title('Histogram of Alumni Salaries')
plt.show()
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
salary = alumni.Salary.dropna()
savings = alumni.Savings.dropna()
plt.scatter(salary, savings, c='red', marker='.')
plt.title('Salary & Savings scatter plot comparison')
plt.xlabel('Salary')
plt.ylabel('Savings')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
alumni.info()
contingency = alumni.iloc[:, [2, 4]]
contingency.dropna()
pd.crosstab(contingency["Marital Status"], contingency["Defaulted"])
###Output
<class 'pandas.core.frame.DataFrame'>
Int64Index: 88 entries, 0 to 87
Data columns (total 9 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Year Graduated 88 non-null object
1 Gender 88 non-null object
2 Marital Status 88 non-null object
3 Diploma Type 88 non-null object
4 Defaulted 88 non-null object
5 Salary 88 non-null object
6 Fee 88 non-null object
7 Savings ($) 88 non-null object
8 Savings 88 non-null float64
dtypes: float64(1), object(8)
memory usage: 6.9+ KB
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
df = pd.read_csv(r'./alumni.csv')
print(df)
###Output
Year Graduated Gender Marital Status Diploma Type Defaulted \
0 2004 Male Single Standard Diploma Yes
1 2005 Male Married College Prep Diploma No
2 2006 Female Single Standard Diploma Yes
3 2007 Male Married Standard Diploma No
4 2006 Female Divorced Standard Diploma Yes
.. ... ... ... ... ...
83 2007 Male Single Standard Diploma No
84 2008 M Single College Prep Diploma Yes
85 2009 Male Married Standard Diploma No
86 2005 Female Divorced Standard Diploma Yes
87 2006 Male Married Standard Diploma Yes
Salary Fee Savings ($)
0 125000 10869 $86,000
1 100000 10869 $116,000
2 70000 10869 $52,000
3 120000 10869 $76,000
4 95000 11948 $52,000
.. ... ... ...
83 75000 12066 $16,000
84 65000 12066 $72,000
85 75000 12066 $46,000
86 100000 12067 $32,000
87 75000 12067 $67,000
[88 rows x 8 columns]
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
df.head()
#b) (1)
df.tail()
#c) (1)
df.dtypes
#d) (1)
df.info
#e) (1)
df.describe
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
import pandas as pd
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
import pandas as pd
df1 = pd.read_csv(r'./alumni.csv')
df1 = alumni["Gender"].value_counts()
df1
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
import pandas as pd
df = pd.read_csv(r'./alumni.csv')
med = pd.DataFrame(data=med)
med = df['Salary'].med()
print ('Median salary: ' + str(med))
# b)(1)
import pandas as pd
df = pd.read_csv(r'./alumni.csv')
mea = pd.DataFrame(data=mea)
mea = df['Salary'].mea()
print ('Mean Salary: ' + str(mea))
# c)(1)
import pandas as pd
df = pd.read_csv(r'./alumni.csv')
stdev = pd.DataFrame(data=stdev)
stdev = df['Salary'].std()
print ('Std of salaries: ' + str(stdev))
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
import pandas as pd
df = pd.read_csv(r'./alumni.csv')
df = pd.DataFrame(data=df)
df = alumni[alumni['Fee'] >15000]
df
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('C:/Users/jmtey/Desktop/DataScience_Course/ADS-Assignment-1-main/alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes()
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
# b)(1)
# c)(1)
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv("alumni.csv")
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
#alumni["Savings"] = alumni["Savings ($)"].str.replace(",", "").str.replace("$", "").astype(int)
#alumni
'''Let's the above
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency()
and tweak to avoid type error'''
def clean_currency(curr):
if isinstance(curr, str):
return float(curr.replace(",", "").replace("$", ""))
return curr.str.replace(",", "").str.replace("$", "").astype(float)
alumni["Savings"] = clean_currency(alumni["Savings ($)"])
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
Gender = alumni["Gender"].str.replace('(^M$)','Male')
Gender
# b) (1)
Gender.value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"]= alumni["Gender"].replace('M','Male')
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[alumni.Gender =='M']= 'Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni.Salary.median()
# b)(1)
alumni.Salary.mean()
# c)(1)
alumni.Salary.std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni.Fee < 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni["Diploma Type"].value_counts().plot(kind="bar")
plt.xlabel('Diploma Type')
plt.ylabel('Value Count')
plt.title(' Bar chart Graph')
plt.show()
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
#alumni.boxplot(by= 'Salary', column = ['Savings'], grid = False, vert=False)
sns.boxplot(y= 'Salary', x='Savings', data=alumni, width=1, palette="colorblind", linewidth=1.5, orient="h")
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
x = alumni["Salary"]
plt.hist(x, bins=12, histtype='bar', rwidth=0.8)
plt.xlabel('Salary')
plt.ylabel('Count')
plt.title(' Grapg Histogram')
plt.show()
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
x = alumni.Salary
y = alumni.Savings
plt.scatter(x, y)
plt.xlabel('Salary')
plt.ylabel('Savings')
plt.title(' Scatter Plot')
plt.show()
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni["Marital Status"], alumni["Defaulted"])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
import pandas as pd
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni=pd.read_csv('data/alumni.csv')
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
def clean_currency(curr):
return float(curr.replace(',','').replace('$',''))
alumni['Savings']=alumni['Savings ($)'].apply(clean_currency)
alumni['Savings']
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'].str.replace("^M$","Male")
alumni
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[alumni.Marital_Status=='Male']='Single'
alumni.loc[alumni.Diploma_Type=='Male']='College Prep Diploma'
alumni.loc[alumni.Defaulted=='Male']='Yes'
alumni.loc[alumni.Salary=='Male']='65000'
alumni.loc[alumni.Fee=='Male']='12066'
alumni.loc[alumni.Savings=='Male']='72,000.0'
alumni
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)1
# b)(1)
# c)(1)
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni_rst = alumni.loc[alumni['Fee']>15000]
alumni_rst
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
import seaborn as sns
import matplotlib.pyplot as plt
sns.displot(data=alumni, x="Diploma Type")
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
plt.hist(alumni['Salary'],bins=12,histtype='bar', rwidth=0.8)
plt.xlabel('Salary')
plt.ylabel('count')
plt.title(' Graph Histogram')
plt.show()
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
alumni = pd.read_csv("alumni.csv")
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#d) (1)
alumni.dtypes
#e) (1)
alumni.info()
#f) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#)b
alumni['Savings'] = applyaalumni['Savings $']
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
alumni.dtypes
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"] = alumni["Gender"].str[0:1]
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"] = alumni["Gender"].str.replace("M", "Male")
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d)
alumni[alumni["Fee"] >15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
sns.boxplot(x=alumni["Salary"])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
sns.histplot(data=alumni, x="Salary")
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
sns.scatterplot(data=alumni, x="Salary" ,hue="Gender" )
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Marital Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(index=alumni['Defaulted'], columns=['Marital status'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('alumni.csv')
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
savings = []
for saving in alumni["Savings ($)"]:
savings.append(clean_currency(saving))
alumni["Savings"]=savings
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
gender = alumni["Gender"].str.replace('(^M$)','Male', regex=True)
# b) (1)
gender.value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"] = alumni["Gender"].str.replace('(^M$)','Male', regex=True)
alumni
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[alumni['Gender'] == 'M'] = 'Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni["Fee"] > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
diploma_type = alumni.groupby('Diploma Type')
diplomas=[ diploma for diploma, data in diploma_type]
value_counts=alumni['Diploma Type'].value_counts()
plt.bar(diplomas,value_counts)
plt.xlabel("Diploma Type")
plt.ylabel("Diploma Level")
plt.title("Diploma level by type")
plt.xticks(diplomas,rotation='vertical',size=8)
plt.show
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni.boxplot(["Savings", "Salary"])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
plt.hist(alumni["Salary"], bins=12, histtype='bar', rwidth=0.8)
plt.xlabel('Salary')
plt.ylabel('Counts')
plt.title('Salary Comparision')
plt.show()
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
plt.scatter(alumni["Salary"], alumni["Savings"], label='Salary vs Savings')
plt.xlabel('Salary')
plt.ylabel('Savings')
plt.title('Salary vs Savings')
plt.show()
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni["Marital Status"], alumni["Defaulted"])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni=pd.read_csv('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni['Savings']=alumni.apply(lambda x: clean_currency(x['Savings ($)']), axis=1)
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'].replace(r'^M$',"Male",regex=True)
# b) (1)
alumni["Gender"]
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"]=alumni['Gender'].replace(r'^M$',"Male",regex=True)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[[28,35,84],['Gender']] ="Male"
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni['Fee']>15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar', title='Diploma Type')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
boxplot=alumni.boxplot(column=['Savings','Salary'])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni['Salary'].plot(kind="hist", bins=12, title='Salary')
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot(kind='scatter',x='Salary', y='Savings', title='Comparison of Salary and Savings', c='DarkBlue')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni['Marital Status'],alumni['Defaulted'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
from google.colab import drive
drive.mount('/content/gdrive', force_remount= True)
import sys
sys.path.append('/content/gdrive/My Drive/DataScienceSchool/ADS-Assignment-1')
# Imports needed to complete this assignment
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni_df = pd.read_csv("/content/gdrive/My Drive/DataScienceSchool/ADS-Assignment-1/alumni.csv")
alumni_df.head()
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni_df.head()
#b) (1)
alumni_df.tail()
#c) (1)
alumni_df.dtypes
#d) (1)
alumni_df.info
#e) (1)
alumni_df.describe
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni_df['Savings'] = alumni_df['Savings ($)'].apply(clean_currency)
alumni_df
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni_df.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni_df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni_df["Gender"].str.replace("M","Male")
# b) (1)
alumni_df["Gender"].str.replace("^[M]$","Male")
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni_df["Gender"] = alumni_df["Gender"].str.replace("^[M]$","Male")
alumni_df["Gender"]
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni_df.loc[[1, 2,3], "Gender"] = "Male"
alumni_df["Gender"]
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni_df.value_counts
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni_df.median
# b)(1)
alumni_df.mean
# c)(1)
alumni_df.std
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni_df[alumni_df.Fee >15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni_df["Diploma Type"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni_df["Diploma Type"].value_counts().plot(kind = "bar")
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni_df["Salary"].plot(kind = "hist" , bins = 10)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni_df.plot(kind = "scatter", x = "Savings", y = "Salary")
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
alumni_df["Marital Status"].value_counts()
alumni_df["Defaulted"].value_counts()
pd.crosstab(index=alumni_df["Marital Status"], columns=alumni_df["Defaulted"])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni=pd.read_csv('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni["Savings"]=alumni["Savings ($)"].apply(clean_currency)
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
tom="My name is Tom M"
t2=tom.replace("M","Male")
t2
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[(alumni.Gender=='M'),'Gender']='Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
feemorethan15k=alumni[alumni["Fee"]>15000]
feemorethan15k
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni["Diploma Type"].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni.boxplot(column=["Savings","Salary"])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni['Salary'].plot.hist(bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot(kind='scatter', y='Salary', x='Savings', title='Salary vs Savings')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(index=alumni['Marital Status'],columns=alumni['Defaulted'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
#reading csv
alumni = pd.read_csv("alumni.csv")
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
#head:shows first 5 records
alumni.head()
#b) (1)
#tail:shows last 5 recods
alumni.tail()
#c) (1)
#dtypes:data types of features/columns
alumni.dtypes
#d) (1)
#info:full dataframe summary
alumni.info()
#e) (1)
#describe:shows basic statistical details of numerical columns
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
#method1
alumni['Savings'] = alumni['Savings ($)'].apply(lambda saving: clean_currency(saving))
alumni
#method 2
#initializing an empty array
savings = []
#for loop to clean all values in Savings ($) and append the clean values to array
for saving in alumni['Savings ($)']:
savings.append(clean_currency(saving))
#creating a new column Savings and assigning the clean values
alumni["Savings"] = savings
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'].str.replace('^M$','Male')
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni['Gender'] = alumni['Gender'].str.replace('^M$','Male')
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[alumni['Gender'] =='M', 'Gender']='Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
#median
alumni['Salary'].median()
# b)(1)
#mean
alumni['Salary'].mean()
# c)(1)
#std
alumni.Salary.std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni['Fee'] >15000]
#alumni whose row index is 18
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
#bar plot
alumni['Diploma Type'].value_counts().plot(kind = 'bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
#combined box plot
alumni[['Savings','Salary']].plot(kind = 'box')
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
#histogram
alumni['Salary'].plot(kind = 'hist', bins = 12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
#scatter plot
alumni.plot(kind = 'scatter', x = 'Savings', y = 'Salary')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
#shows the frequency with which certain groups of data appear
pd.crosstab(alumni['Marital Status'], alumni['Defaulted'])
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni["Gender"]=alumni.loc[alumni.Gender=='M','Gender']='Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].mean()
# b)(1)
alumni["Salary"].median()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni.loc[(alumni.Fee>15000)]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar');
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
g=sns.catplot(x="Salary", y="Savings",
data=alumni, kind="box");
g.set_xticklabels(rotation=45)
sns.set(rc={'figure.figsize':(20,15)})
plt.show()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
sns.distplot(alumni['Salary'],bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
sns.scatterplot(data=alumni,x="Salary",y="Savings")
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni['Marital Status'],alumni.Defaulted)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
#b) (1)
#c) (1)
#d) (1)
#e) (1)
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
# b)(1)
# c)(1)
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv("./alumni.csv")
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni["Savings"] = alumni["Savings ($)"]
#Savings.head()
def clean_currency(Savings):
return ((Savings).str.replace(",", "").str.replace("$", ""))
clean_currency(alumni["Savings"])
#alumni["Savings"] = Savings.replace(",", "")
#alumni
###Output
<ipython-input-16-8cb3a93f4bb6>:5: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will*not* be treated as literal strings when regex=True.
return ((Savings).str.replace(",", "").str.replace("$", ""))
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
Gender = alumni["Gender"].str.replace("^M$","Male")
Gender
# b) (1)
alumni
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"] = Gender.replace("^M$","Male")
alumni
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc["M", "Gender"]= "Male"
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[(alumni["Fee"] > 15000)]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumniData = pd.read_csv("alumni.csv")
df_alumni = pd.DataFrame(data=alumniData)
df_alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
df_alumni.head()
#b) (1)
df_alumni.tail()
#c) (1)
df_alumni.dtypes
#d) (1)
df_alumni.info()
#e) (1)
df_alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
df_alumni["Savings"] = df_alumni["Savings ($)"].apply(lambda row:clean_currency(row))
df_alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
df_alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
df_alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
def clean_gender(gender):
if gender == "M":
return gender.replace("M","Male")
else:
return gender
# b) (1)
clean_gender("M")
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
#alumniData["Savings"] = alumniData["Savings ($)"].apply(lambda row:clean_currency(row))
df_alumni["Gender"] = df_alumni["Gender"].apply(lambda row:clean_gender(row))
df_alumni
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
df_alumni.loc[[0,1,2,3,4],["Gender","Marital Status", "Salary", "Defaulted"]]
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
df_alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
df_alumni["Salary"].median()
# b)(1)
df_alumni["Salary"].mean()
# c)(1)
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
paid_above_15000 = df_alumni[df_alumni["Fee"] > 15000]
paid_above_15000
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
df_alumni.plot(x= 'Diploma Type', kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
df_alumni.plot(x= 'Savings', y= 'Salary', kind='box')
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
df_alumni.plot(x= 'Year Graduated', y= 'Salary', kind='hist')
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
df_alumni.plot(x= 'Salary', y= 'Savings', kind='scatter')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
#marital_defaulted = df_alumni[["Marital Status", "Defaulted"]]
marital_defaulted = df_alumni.groupby(["Marital Status", "Defaulted"]).count()
marital_defaulted
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
alumni['Savings']=alumni['Savings ($)'].apply(lambda x: f"{clean_currency(x)}")
alumni.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].str.replace('^M$', 'Male')
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"]= alumni["Gender"].str.replace('^M$', 'Male')
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.iloc[:, 1].str.replace('^M$', 'Make')
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].median()
# b)(1)
alumni['Salary'].mean()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni.loc[alumni['Fee'] > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
Savings = alumni['Savings']
Salary = alumni['Salary']
data_to_plot = [Savings, Salary]
data_to_plot
fig = plt.figure()
# Create an axes instance
ax = fig.add_axes([0,0,1,1])
# Create the boxplot
fig.canvas.draw()
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = 'Savings'
labels[1] = 'Salary'
ax.set_xticklabels(labels)
bp = ax.boxplot(data_to_plot)
plt.show()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
plt.hist(alumni['Salary'], bins=12,)
plt.xlabel('Salary')
plt.ylabel('count')
plt.title(' Grapg Histogram')
plt.show()
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
plt.scatter(alumni['Salary'],alumni['Savings'], label='something', color='b', s=200, marker=".")
plt.xlabel('Salary')
plt.ylabel('Savings')
plt.title('Relationship between Salary and Saving')
plt.show()
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
crosstab = pd.crosstab(alumni['Marital Status'],alumni['Defaulted'], margins = False)
crosstab
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
paid_above_15000 = alumni[alumni["Fee"] >15000]
paid_above_15000.head()
paid_above_15000.count()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
alumni.boxplot(by ='Salary', column =['Savings'], grid = False)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
alumni.hist(column='Salary')
#c) (1)
ax = alumni.hist(column='Salary', bins=12)
ax = ax[0]
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
sns.scatterplot(x='Savings',y='Salary',data=alumni)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)'
pd.crosstab(index=alumni['Marital Status'],columns=alumni['Defaulted'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv("alumni.csv")
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
if isinstance(curr, str):
return float(curr.replace(",", "").replace("$", ""))
return curr.str.replace(",", "").str.replace("$", "").astype(float)
clean_currency("$66,000")
#a) (2)
alumni["Savings"] = clean_currency(alumni["Savings ($)"])
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].str.replace('M','Male')
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Savings"].median()
# b)(1)
alumni["Savings"].mean()
# c)(1)
alumni["Savings"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
x = alumni["Fee"]>15000
x.value_counts()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
diploma = alumni["Diploma Type"]
diploma.value_counts(normalize=True).plot.barh()
plt.xlabel("Number of Diploma Types")
_ = plt.title("Diploma Type distribution")
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni.boxplot(column=['Savings', 'Salary'])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
pick = alumni["Salary"]
pick.plot.hist(bins=12, edgecolor="black")
plt.xlabel("Salary $")
_ = plt.title("Distribution of the Salary")
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
plt.style.use('seaborn')
plt.scatter(alumni.Salary,alumni.Savings, c=alumni.Savings, cmap='Spectral', edgecolor='black')
plt.colorbar();
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
import pandas as pd
alumni = pd.read_csv('./alumni.csv')
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail(12)
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
import pandas as pd
alumni = pd.read_csv('./alumni.csv')
alumni["Savings"] = alumni["Savings ($)"]
alumni["Savings"]= alumni["Savings"].str.replace(",","").str.replace("$","")
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) 1)
alumni['Gender'].str.replace('M','Male')
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc['Male','Gender'] = "M"
alumni
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].median()
# b)(1)
alumni['Salary'].mean()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
Fee_more_than_15000 = alumni['Fee']> 15000
Fee_more_than_15000
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
import seaborn as sns
sns.catplot(x='Diploma Type',y='Year Graduated', hue ="Diploma Type",data= alumni, kind="bar")
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
import seaborn as sns
sns.catplot(x='Savings',y="Salary",hue='Diploma Type',data=alumni, kind='box')
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
import seaborn as sns
sns.distplot(alumni['Salary'], bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
alumni = sns.load_dataset("alumni")
ax = sns.scatterplot(x="Salary", y="Savings", data=alumni)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
import pandas as pd
alumni = pd.read_csv("alumni.csv")
status = pd.crosstab(alumni['Marital Status'],alumni['Defaulted'],margins = False)
print(status)
###Output
Defaulted No Yes
Marital Status
Divorced 8 11
Married 19 16
Single 9 25
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv ('./alumni.csv')
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
def clean_currency(curr):
if isinstance(curr, str):
return float(curr.replace(",", "").replace("$", ""))
return curr.str.replace(",", "").str.replace("$", "").astype(float)
alumni['Savings'] = clean_currency(alumni['Savings ($)'])
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'].str.replace('^M$', 'Male')
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"] = alumni['Gender'].str.replace('^M$', 'Male')
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[:,'Gender'] = alumni['Gender'].str.replace('^M$', 'Male')
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
Salary=alumni['Salary']
Salary
Salary.median()
# b)(1)
Salary.mean()
# c)(1)
Salary.std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
Fee=alumni[alumni['Fee']>15000]
Fee
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
plt.show()
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni.boxplot(by ='Salary', column =['Savings'], grid = False)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
plt.hist(Salary, bins = 12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
plt.scatter(alumni['Salary'], alumni['Savings'])
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni['Marital Status'], alumni['Diploma Type'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
#e) (1)
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni['Savings'] = alumni['Savings ($)'].apply(lambda x: clean_currency(x))
alumni.info
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
alumni.describe
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"]=alumni["Gender"].str.replace('M$', 'Male', regex=True)
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"]=alumni["Gender"].str.replace('M$', 'Male', regex=True)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[:,'Gender']=alumni["Gender"].str.replace('M$', 'Male', regex=True)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni.loc[alumni['Fee'] > 15000,:]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar');
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1
alumni.boxplot(column=["Savings", "Salary"])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni.hist(column='Salary', bins=12, grid=False, figsize=(12,8), color='#86bf91', zorder=2, rwidth=0.9)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot.scatter(x = 'Salary', y = 'Savings', s = 100);
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni['Marital Status'], alumni['Defaulted'], normalize='all')
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
### Question 1 : Import CSV file (1 Mark)
#Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
alumni = pd.read_csv('alumni.csv')
print(alumni)
###Output
Year Graduated Gender Marital Status Diploma Type Defaulted \
0 2004 Male Single Standard Diploma Yes
1 2005 Male Married College Prep Diploma No
2 2006 Female Single Standard Diploma Yes
3 2007 Male Married Standard Diploma No
4 2006 Female Divorced Standard Diploma Yes
.. ... ... ... ... ...
83 2007 Male Single Standard Diploma No
84 2008 M Single College Prep Diploma Yes
85 2009 Male Married Standard Diploma No
86 2005 Female Divorced Standard Diploma Yes
87 2006 Male Married Standard Diploma Yes
Salary Fee Savings ($)
0 125000 10869 $86,000
1 100000 10869 $116,000
2 70000 10869 $52,000
3 120000 10869 $76,000
4 95000 11948 $52,000
.. ... ... ...
83 75000 12066 $16,000
84 65000 12066 $72,000
85 75000 12066 $46,000
86 100000 12067 $32,000
87 75000 12067 $67,000
[88 rows x 8 columns]
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
def clean_currency(x):
if isinstance(x, str):
return(x.replace('$', '').replace(',', ''))
return(x)
alumni['Savings'] = alumni['Savings ($)'].apply(clean_currency).astype('float')
alumni.head()
alumni.to_csv('newalumni.csv')
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni.value_counts(['Gender'])
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'].str.replace('^M$','Male',regex=True)
# b) (1)
alumni.value_counts(['Gender'])
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni['Gender']= alumni['Gender'].str.replace('^M$','Male',regex=True)
alumni.value_counts(['Gender'])
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni['Gender']=alumni.iloc[0:,1].str.replace('^M$','Male',regex=True)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni.value_counts(['Gender'])
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].median()
# b)(1)
alumni['Salary'].mean()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni.loc[(alumni['Fee']>(15000))]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
import seaborn as sns
from matplotlib.pyplot import figure
sns.boxplot(data=alumni, x='Salary',y='Savings')
fig = plt.gcf()
fig.set_size_inches(12, 8)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
import matplotlib.pyplot as plt
plt.hist(alumni['Salary'],bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
plt.scatter(x=alumni['Savings'], y=alumni['Salary'])
plt.xlabel ('Savings')
plt.ylabel ('Salary')
plt.show()
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
import numpy as np
pd.crosstab(alumni['Marital Status'],alumni['Defaulted'],margins = False)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
#b) (1)
#c) (1)
#d) (1)
#e) (1)
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
# b)(1)
# c)(1)
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni=pd.read_csv("alumni.csv")
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
Salary=alumni["Salary"]
Salary.median()
# b)(1)
Salary.mean()
# c)(1)
Salary.std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni["Fee"] > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni.boxplot(by ='Savings', column =['Salary'], grid = False)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import numpy as np
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('alumni.csv')
alumni.head()
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head(2)
#b) (1)
alumni.tail(3)
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
'$86,000'.replace(",", "").replace("$", "")
#a) (2)
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
alumni['Savings'] = alumni['Savings ($)'].apply(lambda x: f"{clean_currency(x)}")
alumni.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
alumni.head()
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
'Male'.replace("a", "t")
# b) (1)
df1=alumni[alumni['Gender'].str[0:1]=='M'].replace("M", "Male")
df1.head()
df1['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni=alumni[alumni['Gender'].str[0:1]=='M'].replace("M", "Male")
alumni.head()
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
df2=alumni[alumni['Gender'].str[0:1]=='M']
df2
alumni.iloc[[28, 35, 84],[1]] = "Male"
alumni.head(30)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
alumni['Savings']=pd.to_numeric(alumni['Savings'])
# a)(1)
alumni.info()
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
paid_above_15000 = alumni[alumni["Fee"] >15000]
paid_above_15000
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni["Diploma Type"].value_counts()
alumni["Diploma Type"].value_counts().plot(kind='bar');
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni.boxplot(column=['Savings', 'Salary'])
salary = alumni['Salary']
salary
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni.hist(column='Salary',bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot.scatter(x="Salary", y="Savings", c="blue")
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
ed=pd.crosstab(alumni['Marital Status'], ['Defaulted'])
ed
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni=pd.read_csv('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency('$66,000')
#a) (2)
alumni['Savings']=alumni["Savings ($)"].apply(lambda x: (clean_currency(x)))
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].replace("M","Male")
# b) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"]=alumni["Gender"].replace("M","Male")
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[alumni.Gender=='M','Gender']='Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].mean()
# b)(1)
alumni['Salary'].median()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni_more=alumni[alumni["Fee"]>15000]
alumni_more
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni[['Salary','Savings']].plot.box()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni['Salary'].plot(kind='hist',bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot.scatter('Salary','Savings')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
contingency=pd.crosstab(alumni['Marital Status'],alumni['Defaulted'])
contingency
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import numpy as np
import seaborn as sns
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.DataFrame()
alumni = pd.read_csv('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.describe
#e) (1)
alumni.info()
alumni.columns
alumni.rename(columns = {'Savings ($)':'Savings'}, inplace = True)
alumni.columns
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
def clean_currency(curr):
return float(curr.replace(',','').replace('$',''))
clean_currency('$16000')
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'],str.replace
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[(alumni.Gender == 'M')] = 'Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
Salary.median()
# b)(1)
alumni.mean()
# c)(1)
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
sns.boxplot(x = 'Savings', y = 'Salary', data = alumni)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni = alumni.hist(column='Salary', bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot.scatter(x='Salary',y='Savings')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
data_crosstab = pd.crosstab(alumni['Marital Status'],
alumni['Defaulted'],
margins = False)
print(data_crosstab)
###Output
Defaulted No Yes
Marital Status
Divorced 8 11
Married 19 16
Single 9 25
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import os
import seaborn as sns
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
alumni=pd.read_csv("alumni.csv")
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2
alumni["Savings"]=alumni["Savings ($)"].apply(clean_currency)
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
Maleale
Male
# b) (1)
str.replace(alumni('Maleale'),('Male'))
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import os
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni=pd.read_csv("alumni.csv")
print(alumni)
###Output
Year Graduated Gender Marital Status Diploma Type Defaulted \
0 2004 Male Single Standard Diploma Yes
1 2005 Male Married College Prep Diploma No
2 2006 Female Single Standard Diploma Yes
3 2007 Male Married Standard Diploma No
4 2006 Female Divorced Standard Diploma Yes
.. ... ... ... ... ...
83 2007 Male Single Standard Diploma No
84 2008 M Single College Prep Diploma Yes
85 2009 Male Married Standard Diploma No
86 2005 Female Divorced Standard Diploma Yes
87 2006 Male Married Standard Diploma Yes
Salary Fee Savings ($)
0 125000 10869 $86,000
1 100000 10869 $116,000
2 70000 10869 $52,000
3 120000 10869 $76,000
4 95000 11948 $52,000
.. ... ... ...
83 75000 12066 $16,000
84 65000 12066 $72,000
85 75000 12066 $46,000
86 100000 12067 $32,000
87 75000 12067 $67,000
[88 rows x 8 columns]
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
number = 1235
c = '$1,235'
print(type(c), type(number))
def clean_currency(c):
float(c.replace(',', '').replace('$', ''))
###Output
<class 'str'> <class 'int'>
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
'alumni["Gender"].value_counts()'
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni['Gender'].str.replace(r'^M$', "Male")
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni['Gender']=.str.replace(r'^M$', "Male")
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
import pandas as pd
df['Salary'].median()
# b)(1)
>>> print(df['Salary'].mean())
# c)(1)
>>> print(df['Salary'].std())
###Output
21234.128008173615
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni=df=pd.read_csv('alumni.csv')
paid_above_15000 = alumni[alumni["Fee"] >15000]
paid_above_15000.head()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni= pd.read_csv("alumni.csv")
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni['Savings']=alumni['Savings ($)'].apply(clean_currency)
alumni.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].str.replace('M$','Male')
# b) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"]=alumni["Gender"].str.replace('M$','Male')
alumni["Gender"]
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni[alumni.loc[:,"Gender"]=='M']
# applying the change using the ' df.loc[row_indexer,columns_indexer=value]'
alumni.loc[[28,35,84],'Gender']='Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni['Salary'].median()
# b)(1)
alumni['Salary'].mean()
# c)(1)
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni['Fee']>15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts()
import matplotlib.pyplot as plt
%matplotlib inline
alumni['Diploma Type'].value_counts().plot(kind='bar')
plt.title('Diploma Type Bar Graph')
plt.xlabel('Diploma Type')
plt.ylabel('Value Count')
plt.show()
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
%matplotlib inline
import matplotlib.pyplot as plt
boxplot=alumni.boxplot(column=['Savings','Salary'])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
%matplotlib inline
import matplotlib.pyplot as plt
alumni['Salary'].hist(bins=12, rwidth=0.8)
plt.xlabel('Salary')
plt.ylabel('Count')
plt.title('Histogram Graph')
plt.show
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
#scatter plot
import matplotlib.pyplot as plt
plt.scatter(alumni['Salary'], alumni['Savings'])
plt.xlabel('Salary')
plt.ylabel('Savings')
plt.title('Scatter Plot Graph')
plt.show()
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni['Marital Status'],alumni['Defaulted'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni= pd.read_csv('alumni.csv')
df=pd.DataFrame(alumni)
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head(10)
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$71,000")
#a) (2)
alumni["savings"]= alumni["Savings ($)"].apply(lambda x: f"{clean_currency(x)}")
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
def replace_m(curr):
return (curr.replace("^M$","Male",3))
# b) (1)
alumni["Gender"]=alumni["Gender"].apply(lambda x:f"{replace_m(x)}")
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"]=alumni["Gender"].replace(to_replace="M", value="Male")
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc["^M$","Gender"]="Male"
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].mean()
# b)(1)
alumni.Salary.median()
# c)(1)
alumni.Salary.std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni.loc[alumni["Fee"]>15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
sns.barplot(x=alumni["Diploma Type"].value_counts().index, y=alumni["Diploma Type"].value_counts())
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
plt.rcParams["figure.figsize"]=(12,9)
sns.boxplot(data=alumni, x="Salary", y="savings")
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni.hist(column="Salary", bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
plt.scatter(alumni["Salary"], alumni["savings"])
plt.xlabel("Salary")
plt.ylabel("Savings")
plt.show()
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
crt=pd.crosstab(alumni["Marital Status"], alumni["Defaulted"])
crt
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
pd.read_csv("alumni.csv")
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni = pd.read_csv("alumni.csv")
alumni.head ()
#b) (1)
alumni.tail ()
#c) (1)
alumni.dtypes()
#d) (1)
alumni.info ()
#e) (1)
alumni.describe ()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni["Savings"] = alumni["Savings ($)"].apply(clean_currency)
alumni.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"] = alumni["Gender"].str.replace("M", "Male", "^[A-Z]{3}$")
# b) (1)
alumni["Gender"].replace(to_replace="M", value="Male")
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"] = alumni["Gender"].replace(["M"], "Male")
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
import pandas as pd
import numpy as np
alumni = pd.read_csv("alumni.csv")
alumni["Salary"].agg([np.median])
# b)(1)
alumni["Salary"].agg([np.mean])
# c)(1)
alumni["Salary"].agg([np.std])
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni["Fee"]>15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
import matplotlib.pyplot as plt
alumni = pd.read_csv("alumni.csv")
alumni.plot ()
#a) (1)
alumni["Diploma Type"].plot.bar ()
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni["Savings"] = alumni["Savings ($)"].apply(clean_currency)
alumni.plot(x="Salary", y="Savings", kind="box")
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni.hist(column="Salary", bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot(x="Salary", y="Savings", kind="scatter")
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
import numpy as np
import pandas as pd
import matplotlib as plt
alumni = pd.read_csv("alumni.csv")
alumni_crosstab = pd.crosstab(alumni["Marital Status"],alumni["Defaulted"],margins = False)
print(alumni_crosstab)
###Output
Defaulted No Yes
Marital Status
Divorced 8 11
Married 19 16
Single 9 25
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv("alumni.csv")
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency(" $66,000")
#a) (2)
alumni["Savings"]= alumni["Savings ($)"].apply(clean_currency)
alumni.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
# Question 4 : Cleaning the data set - part B (5 Marks)
#a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
# a) (1)
alumni["Gender"].value_counts()
#b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
# b) (1)
alumni["Gender"]=alumni["Gender"].str.replace("^[M]$","Male")
#c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=<replace command>', show how this is done below
# c) (1)
alumni.reset_index(drop=True)
# d)You can set it directly by using the df.loc command, show how this can be done by using the'df.loc[row_indexer,col_indexer]= value' command to convert the 'M' to 'Male'#
#d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
x=alumni[alumni["Fee"]>15000].index.values.astype(int)[0]
x
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
plt.rcParams["figure.figsize"]=(5,5)
alumni['Diploma Type'].value_counts().plot(kind='bar')
plt.ylabel('Number of people')
plt.xlabel('Diploma type')
plt.title("Bar Plot")
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
data = [alumni["Salary"], alumni["Savings"]]
fig = plt.figure(figsize =(5, 5))
ax = fig.add_axes([0, 0, 1, 1]
bp = ax.boxplot(data)
plt.show()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import numpy as np
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni['Savings'] = alumni['Savings ($)'].apply(lambda x: clean_currency(x))
alumni['Savings']
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].str.replace('^M$', 'Male')
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"] = alumni["Gender"].str.replace('^M$', 'Male')
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
row = 0
for val in alumni.Gender:
if val == 'M':
alumni.Gender.loc[row] = 'Male'
row += 1
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni.Salary.median()
# b)(1)
alumni.Salary.mean()
# c)(1)
alumni.Salary.std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni.Fee > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='barh');
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni.boxplot(column=['Savings', 'Salary']);
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni.Salary.plot.hist(bins=12);
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot.scatter(x='Salary', y='Savings');
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni['Marital Status'], alumni['Defaulted'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
df = pd.read_csv("./alumni.csv")
df
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
df.head()
#b) (1)
df.tail()
#c) (1)
df.dtypes
#d) (1)
df.info()
#e) (1)
df.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
if isinstance (curr, str):
return (curr.replace(",", "").replace("$", ""))
return (curr)
#a) (2)
df['Savings'] = df['Savings ($)'].apply(clean_currency).astype('float32')
df['Savings']
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
df.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
df['Gender'].str.replace('^M$', 'Male', regex = True)
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
df["Gender"] = df['Gender'].str.replace('^M$', 'Male', regex = True)
df["Gender"]
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
df.loc[[28, 35, 84],['Gender']] = 'Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
df['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
df['Salary'].median()
# b)(1)
df['Salary'].mean()
# c)(1)
df['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
more_than_15000 = df[df['Fee'] > 15000]
more_than_15000
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
df['Diploma Type'].value_counts().plot(kind = 'bar')
###Output
Matplotlib is building the font cache; this may take a moment.
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv("alumni.csv")
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni['Savings'] = alumni['Savings ($)'].apply(clean_currency)
alumni['Savings']
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].str.replace(r"^M$", "Male", regex = True)
alumni["Gender"].value_counts()
# b) (1)
alumni["Gender"]=alumni["Gender"].str.replace(r"^M$", "Male", regex = True)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[(alumni.Gender == 'M')] = 'Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni.Salary.median()
# b)(1)
alumni.Salary.mean()
# c)(1)
alumni.Salary.std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni.Fee > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni["Diploma Type"].value_counts().plot(kind ="bar")
plt.ylabel('No. of Students')
plt.xlabel('Diploma Type')
plt.show()
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
sns.boxplot(x = 'Savings', y = 'Salary', data = alumni)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni = alumni.hist(column='Salary', bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot.scatter(x='Salary',y='Savings')
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
data_crosstab = pd.crosstab(alumni['Marital Status'], alumni['Defaulted'], margins = False)
print(data_crosstab)
###Output
Defaulted No Yes
Marital Status
Divorced 8 11
Married 19 16
Single 9 25
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
import datetime as dt
# Imports needed to complete this assignment
#import Standard packages
import pandas as pd
import numpy as np
import seaborn as sns #lotting graphical objects
import matplotlib.pyplot as plt
import datetime as dt
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
#.read_csv
alumni = pd.read_csv('alumni.csv')
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
#view the first 2 columns
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni["Savings"] = alumni["Savings ($)"].apply(clean_currency)
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].str.replace('M$', 'Male',)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"] = alumni["Gender"].str.replace('M$', 'Male',)
alumni
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni.median()
# b)(1)
alumni.mean()
# c)(1)
alumni.std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
paid_Above_15000 = alumni[alumni["Fee"] >15000]
paid_Above_15000.head()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts. b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni = pd.read_csv('ADS-Assignment-1/alumni.csv')
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni["Salary"].max()
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
#a) (1)
def clean_currency(curr):
if isinstance(curr, str):
return(curr.replace(",", "").replace("$", ""))
return(curr)
clean_currency("$66,000")
#a) (2)
alumni = alumni.rename(columns={'Savings ($)': 'Savings'})
alumni
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni.replace(to_replace=r'^M.$', value='Male')
alumni
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni['Gender']=(['M']=='MALE')
alumni
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
alumni.loc[alumni['Gender'] == 'M','Gender'] = 'Male'
alumni
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni['Gender'].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
alumni["Salary"].median()
# b)(1)
alumni["Salary"].mean()
# c)(1)
alumni["Salary"].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
alumni[alumni['Fee'] > 15000].head()
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
alumni.boxplot(column = ['Savings','Salary'])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
alumni.hist(column='Salary', bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
alumni.plot(kind="scatter",x="Salary", y="Savings")
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(alumni['Marital Status'],alumni['Defaulted'])
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
import pandas as pd
alumni = pd.read_csv('alumni.csv')
alumni
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
#View the first 10 columns
import pandas as pd
alumni = pd.read_csv('alumni.csv')
alumni
alumni.head(10)
#b) (1)
#c) (1)
#d) (1)
#e) (1)
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
# b)(1)
# c)(1)
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
import pandas as pd
print(pd.__version__)
#code to load
alumni = pd.read_csv("alumni.csv")
print(alumni)
###Output
1.1.3
Year Graduated Gender Marital Status Diploma Type Defaulted \
0 2004 Male Single Standard Diploma Yes
1 2005 Male Married College Prep Diploma No
2 2006 Female Single Standard Diploma Yes
3 2007 Male Married Standard Diploma No
4 2006 Female Divorced Standard Diploma Yes
.. ... ... ... ... ...
83 2007 Male Single Standard Diploma No
84 2008 M Single College Prep Diploma Yes
85 2009 Male Married Standard Diploma No
86 2005 Female Divorced Standard Diploma Yes
87 2006 Male Married Standard Diploma Yes
Salary Fee Savings ($)
0 125000 10869 $86,000
1 100000 10869 $116,000
2 70000 10869 $52,000
3 120000 10869 $76,000
4 95000 11948 $52,000
.. ... ... ...
83 75000 12066 $16,000
84 65000 12066 $72,000
85 75000 12066 $46,000
86 100000 12067 $32,000
87 75000 12067 $67,000
[88 rows x 8 columns]
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
#head
alumni.head()
#b) (1)
#tail
alumni.tail()
#c) (1)
#datatypes
alumni.dtypes
#d) (1)
#information
alumni.info()
#e) (1)
#describe
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
# b)(1)
# c)(1)
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
conda install seaborn
# Imports needed to complete this assignment
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
#Loading alumni csv dataset
alumni=pd.read_csv("alumni.csv")
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
#printing head
alumni.head()
#b) (1)
#printing tail
alumni.tail()
#c) (1)
#datatypes
alumni.dtypes
#d) (1)
# info() prints the index dtype and column dtypes, non-null values and memory usage
alumni.info()
#e) (1)
#Statistical Summary of the data
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
#Creating a new column savings without commas and $
alumni["Savings"]=alumni["Savings ($)"]
alumni["Savings"]=alumni["Savings"].replace('[\$\,\,]','', regex=True).astype(float)
alumni.head()
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#data type has changed from int to float
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
#No of incorrect M fields
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
#Converting M fields
alumni["Gender"].replace('M','Male', regex=True)
# b) (1)
alumni["Gender"]
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
#Inorder to update the column we uncomment the lines of code below
#alumni["Gender"]=alumni["Gender"].replace('M','Male', regex=True)
#alumni["Gender"]
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
#Setting the values directly
#First, identify index values with M
print(alumni[alumni['Gender']=='M'].index.values)
#Convert M to Male
alumni.loc[[28, 35, 84], 'Gender'] = 'Male'
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
#Getting median
alumni['Salary'].median()
# b)(1)
#Getting mean
alumni['Salary'].mean()
# c)(1)
#Getting standard deviation
alumni['Salary'].std()
###Output
_____no_output_____
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
#alumni that paid more than $15000 in fees
paid_above_15000 = alumni[alumni['Fee'] >15000]
paid_above_15000
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
#Plotting bar graph
alumni['Diploma Type'].value_counts().plot(kind='bar')
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
#Boxplot
boxplot = alumni.boxplot(column=['Savings', 'Salary'])
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
#Histogram
bins = [0,15000,30000,45000,60000,75000,90000,105000,120000,135000,150000,165000]
plt.hist(alumni['Salary'], bins, histtype='bar', rwidth=0.8)
plt.xlabel('Salary')
plt.ylabel('count')
plt.title(' Salary Histogram')
plt.legend()
plt.show()
###Output
No handles with labels found to put in legend.
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
#Scatter Plot
plt.scatter(alumni['Salary'],alumni['Savings'], label='something', color='k', s=25, marker="*")
plt.xlabel('Salary')
plt.ylabel('Savings')
plt.title('Scatter Graph')
plt.legend()
plt.show()
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
#Contigency table
alumni_crosstab = pd.crosstab(alumni['Marital Status'],
alumni['Defaulted'],
margins = False)
print(alumni_crosstab)
###Output
Defaulted No Yes
Marital Status
Divorced 8 11
Married 19 16
Single 9 25
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
import matplotlib.pyplot as plt
import warnings
import seaborn as sns
warnings.filterwarnings('ignore')
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
alumni=pd.read_csv("alumni.csv")
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
alumni.head()
#b) (1)
alumni.tail()
#c) (1)
alumni.dtypes
#d) (1)
alumni.info()
#e) (1)
alumni.describe()
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
alumni["Savings"]=alumni["Savings ($)"].apply(lambda x: clean_currency(x))
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
alumni.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
alumni["Gender"].str.replace('M.*','Male')
# b) (1)
alumni["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
alumni["Gender"]=alumni["Gender"].str.replace('M.*','Male')
###Output
_____no_output_____
###Markdown
Pandas InstructionsThis assignment will be done completely inside this Jupyter notebook with answers placed in the cell provided.All python imports that are needed shown.Follow all the instructions in this notebook to complete these tasks. Make sure the CSV data files is in the same folder as this notebook - alumni.csv, groceries.csv
###Code
# Imports needed to complete this assignment
import pandas as pd
###Output
_____no_output_____
###Markdown
Question 1 : Import CSV file (1 Mark)Write code to load the alumni csv dataset into a Pandas DataFrame called 'alumni'.
###Code
#q1 (1)
df = pd.read_csv("alumni.csv")
df
###Output
_____no_output_____
###Markdown
Question 2 : Understand the data set (5 Marks)Use the following pandas commands to understand the data set: a) head, b) tail, c) dtypes, d) info, e) describe
###Code
#a) (1)
df = pd.read_csv("alumni.csv")
df.head()
#b) (1)
df.tail()
#c) (1)
df.info()
#d) (1)
df.describe()
#e) (1)
df.dtypes
###Output
_____no_output_____
###Markdown
Question 3 : Cleaning the data set - part A (3 Marks)a) Use clean_currency method below to strip out commas and dollar signs from Savings ($) column and put into a new column called 'Savings'.
###Code
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
#a) (2)
def clean_currency(curr):
return float(curr.replace(",", "").replace("$", ""))
clean_currency("$66,000")
savings = []
for s in df["Savings ($)"]:
savings.append(clean_currency(s))
savings
df["Savings"] = savings
df
###Output
_____no_output_____
###Markdown
b) Uncomment 'alumni.dtypes.Savings' to check that the type change has occurred
###Code
#b) (1)
#alumni.dtypes.Savings
df.dtypes.Savings
###Output
_____no_output_____
###Markdown
Question 4 : Cleaning the data set - part B (5 Marks)a) Run the 'alumni["Gender"].value_counts()' to see the incorrect 'M' fields that need to be converted to 'Male'
###Code
# a) (1)
df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
b) Now use a '.str.replace' on the 'Gender' column to covert the incorrect 'M' fields. Hint: We must use ^...$ to restrict the pattern to match the whole string.
###Code
# b) (1)
df = pd.read_csv("alumni.csv")
df["Gender"] = df["Gender"].replace("M", "Male")
df
# b) (1)
###Output
_____no_output_____
###Markdown
c) That didn't the set alumni["Gender"] column however. You will need to update the column when using the replace command 'alumni["Gender"]=', show how this is done below
###Code
# c) (1)
df = pd.read_csv("alumni.csv")
df["Gender"] = df["Gender"].str.replace("Male", "M")
df["Gender"] = df["Gender"].str.replace("M", "Male")
df
###Output
_____no_output_____
###Markdown
d) You can set it directly by using the df.loc command, show how this can be done by using the 'df.loc[row_indexer,col_indexer] = value' command to convert the 'M' to 'Male'
###Code
# d) (1)
import pandas as pd
df = pd.read_csv("alumni.csv")
"df.locrow_indexer,col_indexer = Gender"
df["Gender"] = df["Gender"].replace("M", "Male")
df
###Output
_____no_output_____
###Markdown
e) Now run the 'value_counts' for Gender again to see the correct columns - 'Male' and 'Female'
###Code
# e) (1)
df["Gender"].value_counts()
###Output
_____no_output_____
###Markdown
Question 5 : Working with the data set (4)a) get the median, b) mean and c) standard deviation for the 'Salary' column
###Code
# a)(1)
import numpy as np
import pandas as pd
print(df["Salary"].median())
# b)(1)
import numpy as np
import pandas as pd
print(df["Salary"].mean())
# c)(1)
import numpy as np
import pandas as pd
print(df["Salary"].std())
###Output
21234.128008173615
###Markdown
d) identify which alumni paid more than $15000 in fees, using the 'Fee' column
###Code
# d) (1)
import pandas as pd
import numpy as np
"paid_above_15000".count("15000")
df[df.Fee > 15000]
###Output
_____no_output_____
###Markdown
Question 6 : Visualise the data set (4 Marks)a) Using the 'Diploma Type' column, plot a bar chart and show its value counts.
###Code
#a) (1)
import matplotlib.pyplot as plt
df["Diploma Type"].value_counts().plot(kind = "bar")
###Output
_____no_output_____
###Markdown
b) Now create a box plot comparison between 'Savings' and 'Salary' columns
###Code
#b) (1)
import matplotlib.pyplot as plt
import pandas as pd
boxplot = df.boxplot(Column=["Salary", "Savings"])
plt.show()
###Output
_____no_output_____
###Markdown
c) Generate a histogram with the 'Salary' column and use 12 bins.
###Code
#c) (1)
plt.hist(df["Salary"], bins=12)
###Output
_____no_output_____
###Markdown
d) Generate a scatter plot comparing 'Salary' and 'Savings' columns.
###Code
#d) (1)
ax = df.plot.scatter(x="Salary", y="Savings")
###Output
_____no_output_____
###Markdown
Question 7 : Contingency Table (2 Marks)Using both the 'Martial Status' and 'Defaulted' create a contingency table. Hint: crosstab
###Code
# Q7 (2)
pd.crosstab(index=df["Defaulted"], columns=df["Marital Status"])
###Output
_____no_output_____ |
tutorials/compute-instance-quickstarts/quickstart-azureml-python-sdk/quickstart-azureml-python-sdk.ipynb | ###Markdown
 Quickstart: Learn how to submit batch jobs with the Azure Machine Learning Python SDKIn this quickstart, you learn how to submit a batch training job using the Python SDK. In this example, we submit the job to the 'local' machine (the compute instance you are running this notebook on). However, you can use exactly the same method to submit the job to different compute targets (for example, AKS, Azure Machine Learning Compute Cluster, Synapse, etc) by changing a single line of code. A full list of support compute targets can be viewed [here](https://docs.microsoft.com/en-us/azure/machine-learning/concept-compute-target). This quickstart trains a simple logistic regression using the [MNIST](https://docs.microsoft.com/azure/open-datasets/dataset-mnist) dataset and [scikit-learn](http://scikit-learn.org) with Azure Machine Learning. MNIST is a popular dataset consisting of 70,000 grayscale images. Each image is a handwritten digit of 28x28 pixels, representing a number from 0 to 9. The goal is to create a multi-class classifier to identify the digit a given image represents. You will learn how to:> * Download a dataset and look at the data> * Train an image classification model by submitting a batch job to a compute resource> * Use MLflow autologging to track model metrics and log the model artefact> * Review training results, find and register the best model Connect to your workspace and create an experimentYou start with importing some libraries and creating an experiment to track the runs in your workspace. A workspace can have multiple experiments, and all the users that have access to the workspace can collaborate on them.
###Code
from azureml.core import Workspace
from azureml.core import Experiment
# connect to your workspace
ws = Workspace.from_config()
experiment_name = "get-started-with-jobsubmission-tutorial"
exp = Experiment(workspace=ws, name=experiment_name)
###Output
_____no_output_____
###Markdown
The MNIST datasetUse Azure Open Datasets to get the raw MNIST data files. [Azure Open Datasets](https://docs.microsoft.com/azure/open-datasets/overview-what-are-open-datasets) are curated public datasets that you can use to add scenario-specific features to machine learning solutions for more accurate models. Each dataset has a corresponding class, `MNIST` in this case, to retrieve the data in different ways.Follow this [how-to](https://aka.ms/azureml/howto/createdatasets) if you want to learn more about Datasets and how to use them.
###Code
from azureml.opendatasets import MNIST
mnist_file_dataset = MNIST.get_file_dataset()
###Output
_____no_output_____
###Markdown
Define the EnvironmentAn Environment defines Python packages, environment variables, and Docker settings that are used in machine learning experiments. Here you will be using a curated environment that has already been made available through the workspace. Read [this article](https://docs.microsoft.com/azure/machine-learning/how-to-use-environments) if you want to learn more about Environments and how to use them.
###Code
from azureml.core.environment import Environment
# use a curated environment that has already been built for you
env = Environment.get(workspace=ws,
name="AzureML-Scikit-learn0.24-Cuda11-OpenMpi4.1.0-py36",
version=1)
###Output
_____no_output_____
###Markdown
Configure the training jobCreate a [ScriptRunConfig](https://docs.microsoft.com/python/api/azureml-core/azureml.core.script_run_config.scriptrunconfig?view=azure-ml-py) object to specify the configuration details of your training job, including your training script, environment to use, and the compute target to run on. Configure the ScriptRunConfig by specifying:* The directory that contains your scripts. All the files in this directory are uploaded into the cluster nodes for execution. * The compute target. In this case you will point to local compute* The training script name, train.py* An environment that contains the libraries needed to run the script* Arguments required from the training script. In this run we will be submitting to "local", which is the compute instance you are running this notebook. If you have another compute target (for example: AKS, Azure ML Compute Cluster, Azure Databricks, etc) then you just need to change the `compute_target` argument below. You can learn more about other compute targets [here](https://docs.microsoft.com/azure/machine-learning/how-to-set-up-training-targets).
###Code
from azureml.core import ScriptRunConfig
args = ["--data-folder", mnist_file_dataset.as_mount(), "--regularization", 0.5]
src = ScriptRunConfig(
source_directory="src",
script="train.py",
arguments=args,
compute_target="local",
environment=env,
)
###Output
_____no_output_____
###Markdown
Submit the jobRun the experiment by submitting the ScriptRunConfig object. After this there are many options for monitoring your run. Once submitted, you can either navigate to the experiment "get-started-with-jobsubmission-tutorial" in the left menu item __Experiments__ to monitor the run, or you can monitor the run inline as the `run.wait_for_completion(show_output=True)` will stream the logs of the run. You will see that the environment is built for you to ensure reproducibility - this adds a couple of minutes to the run time. On subsequent runs, the environment is re-used making the runtime shorter.
###Code
run = exp.submit(config=src)
run.wait_for_completion(show_output=True)
###Output
_____no_output_____
###Markdown
Register modelThe training script used the MLflow autologging feature and therefore the model was captured and stored on your behalf. Below we register the model into the Azure Machine Learning Model registry, which lets you keep track of all the models in your Azure Machine Learning workspace.Models are identified by name and version. Each time you register a model with the same name as an existing one, the registry assumes that it's a new version. The version is incremented, and the new model is registered under the same name.When you register the model, you can provide additional metadata tags and then use the tags when you search for models.
###Code
# register model
model = run.register_model(
model_name="sklearn_mnist", model_path="model/model.pkl"
)
print(model.name, model.id, model.version, sep="\t")
###Output
_____no_output_____
###Markdown
Quickstart: Learn how to submit batch jobs with the Azure Machine Learning Python SDKIn this quickstart, you learn how to submit a batch training job using the Python SDK. In this example, we submit the job to the 'local' machine (the compute instance you are running this notebook on). However, you can use exactly the same method to submit the job to different compute targets (for example, AKS, Azure Machine Learning Compute Cluster, Synapse, etc) by changing a single line of code. A full list of support compute targets can be viewed [here](https://docs.microsoft.com/en-us/azure/machine-learning/concept-compute-target). This quickstart trains a simple logistic regression using the [MNIST](https://docs.microsoft.com/azure/open-datasets/dataset-mnist) dataset and [scikit-learn](http://scikit-learn.org) with Azure Machine Learning. MNIST is a popular dataset consisting of 70,000 grayscale images. Each image is a handwritten digit of 28x28 pixels, representing a number from 0 to 9. The goal is to create a multi-class classifier to identify the digit a given image represents. You will learn how to:> * Download a dataset and look at the data> * Train an image classification model by submitting a batch job to a compute resource> * Use MLflow autologging to track model metrics and log the model artefact> * Review training results, find and register the best model Connect to your workspace and create an experimentYou start with importing some libraries and creating an experiment to track the runs in your workspace. A workspace can have multiple experiments, and all the users that have access to the workspace can collaborate on them.
###Code
from azureml.core import Workspace
from azureml.core import Experiment
# connect to your workspace
ws = Workspace.from_config(r"d:\hcchen\OneDrive\文件\Jupyter Notebooks\Azure\.azureml\config.json")
experiment_name = "get-started-with-jobsubmission-tutorial"
exp = Experiment(workspace=ws, name=experiment_name)
###Output
_____no_output_____
###Markdown
The MNIST datasetUse Azure Open Datasets to get the raw MNIST data files. [Azure Open Datasets](https://docs.microsoft.com/azure/open-datasets/overview-what-are-open-datasets) are curated public datasets that you can use to add scenario-specific features to machine learning solutions for more accurate models. Each dataset has a corresponding class, `MNIST` in this case, to retrieve the data in different ways.Follow this [how-to](https://aka.ms/azureml/howto/createdatasets) if you want to learn more about Datasets and how to use them.咱碰到這個問題: No module named 'azureml.opendatasets'。查 pip list | find "azureml" 還真的沒有。查 google [找到答案 on this tutorial repo's issue list.](https://github.com/Azure/MachineLearningNotebooks/issues/518)。結果這個 datasets 恐怕很大。。。 做吧! pip install azureml-opendatasets 這個 pip install 要連坐兩次才會成功。第一次的 error message 又是 pywin32 !! 如下: Installing collected packages: pywin32, py4j, pyspark, azureml-opendatasets Attempting uninstall: pywin32 Found existing installation: pywin32 303 Uninstalling pywin32-303: Successfully uninstalled pywin32-303 ERROR: Could not install packages due to an OSError: [WinError 5] 存取被拒。: 'C:\\Users\\hcche\\AppData\\Roaming\\Python\\Python38\\site-packages\\~-n32\\win32api.pyd' Check the permissions.
###Code
from azureml.opendatasets import MNIST
mnist_file_dataset = MNIST.get_file_dataset()
# 查看這個 dataset
%f mnist_file_dataset -->
%f mnist_file_dataset dir -->
###Output
mnist_file_dataset --> FileDataset
{
"source": [
"https://azureopendatastorage.blob.core.windows.net/mnist/*.gz"
],
"definition": [
"GetFiles",
"ExpressionAddColumn",
"StrReplace",
"ExpressionAddColumn",
"DropColumns",
"RenameColumns",
"DropColumns"
]
} (<class 'azureml.data.file_dataset.FileDataset'>)
mnist_file_dataset dir --> ['File', 'Tabular', 'add_tags', 'as_cache', 'as_download', 'as_hdfs', 'as_mount', 'as_named_input', 'data_changed_time', 'description', 'download', 'file_metadata', 'filter', 'get_all', 'get_by_id', 'get_by_name', 'get_partition_key_values', 'hydrate', 'id', 'mount', 'name', 'partition_keys', 'random_split', 'register', 'remove_tags', 'skip', 'tags', 'take', 'take_sample', 'to_path', 'unregister_all_versions', 'update', 'version'] (<class 'list'>)
###Markdown
Define the EnvironmentAn Environment defines Python packages, environment variables, and Docker settings that are used in machine learning experiments. Here you will be using a curated environment that has already been made available through the workspace. Read [this article](https://docs.microsoft.com/azure/machine-learning/how-to-use-environments) if you want to learn more about Environments and how to use them."Environment" 是個新字 to me. 我以為是前兩天在 AutoML studio 上玩過的 "Experiment" 非也。先照用就對了。。。
###Code
from azureml.core.environment import Environment
# use a curated environment that has already been built for you
env = Environment.get(workspace=ws,
name="AzureML-Scikit-learn0.24-Cuda11-OpenMpi4.1.0-py36",
version=1)
%f env --> #
%f env dir -->
###Output
env --> Environment(Name: AzureML-Scikit-learn0.24-Cuda11-OpenMpi4.1.0-py36,
Version: 1) (<class 'azureml.core.environment.Environment'>)
env dir --> ['add_private_pip_wheel', 'build', 'build_local', 'clone', 'databricks', 'docker', 'environment_variables', 'from_conda_specification', 'from_docker_image', 'from_dockerfile', 'from_existing_conda_environment', 'from_pip_requirements', 'get', 'get_image_details', 'inferencing_stack_version', 'label', 'list', 'load_from_directory', 'name', 'python', 'r', 'register', 'save_to_directory', 'spark', 'version'] (<class 'list'>)
###Markdown
Configure the training jobCreate a [ScriptRunConfig](https://docs.microsoft.com/python/api/azureml-core/azureml.core.script_run_config.scriptrunconfig?view=azure-ml-py) object to specify the configuration details of your training job, including your training script, environment to use, and the compute target to run on. Configure the ScriptRunConfig by specifying:* The directory that contains your scripts. All the files in this directory are uploaded into the cluster nodes for execution. * The compute target. In this case you will point to local compute* The training script name, train.py* An environment that contains the libraries needed to run the script* Arguments required from the training script. In this run we will be submitting to "local", which is the compute instance you are running this notebook. If you have another compute target (for example: AKS, Azure ML Compute Cluster, Azure Databricks, etc) then you just need to change the `compute_target` argument below. You can learn more about other compute targets [here](https://docs.microsoft.com/azure/machine-learning/how-to-set-up-training-targets). 心得:這算是有必要之惡,就是用個 object 來設定東西。
###Code
from azureml.core import ScriptRunConfig
args = ["--data-folder", mnist_file_dataset.as_mount(), "--regularization", 0.5]
src = ScriptRunConfig(
source_directory="src",
script="train.py",
arguments=args,
compute_target="local",
environment=env,
)
###Output
_____no_output_____
###Markdown
Submit the jobRun the experiment by submitting the ScriptRunConfig object. After this there are many options for monitoring your run. Once submitted, you can either navigate to the experiment "get-started-with-jobsubmission-tutorial" in the left menu item __Experiments__ to monitor the run (上 AutoML studio 網頁去查看), or you can monitor the run inline as the `run.wait_for_completion(show_output=True)` will stream the logs of the run. You will see that the environment is built for you to ensure reproducibility - this adds a couple of minutes to the run time. On subsequent runs, the environment is re-used making the runtime shorter.一 run 又失敗了,看不懂的 error message, 啥 conda? 咱 Desktop MinAn 有哇?: Activity Failed: { "error": { "code": "UserError", "message": "Unable to run conda package manager. AzureML uses conda to provision python\nenvironments from a dependency specification. To manage the python environment\nmanually instead, set userManagedDependencies to True in the python environment\nconfiguration. To use system managed python environments, install conda from: https://conda.io/miniconda.html", "messageParameters": {}, "details": [] }, "time": "2022-03-05T14:58:18.850729Z" }
###Code
run = exp.submit(config=src)
run.wait_for_completion(show_output=True)
###Output
RunId: get-started-with-jobsubmission-tutorial_1646492292_095b0179
Web View: https://ml.azure.com/runs/get-started-with-jobsubmission-tutorial_1646492292_095b0179?wsid=/subscriptions/c27e04e6-ca10-453d-9c80-1931b65eb245/resourcegroups/my_azure_AutoML_resource_group/workspaces/my_azure_AutoML_workspace&tid=de0795e0-d7c0-4eeb-b9bb-bc94d8980d3b
Streaming azureml-logs/60_control_log.txt
=========================================
[2022-03-05T14:58:16.722324] Using urllib.request Python 3.0 or later
Streaming log file azureml-logs/60_control_log.txt
Running: ['cmd.exe', '/c', 'C:\\Users\\hcche\\AppData\\Local\\Temp\\azureml_runs\\get-started-with-jobsubmission-tutorial_1646492292_095b0179\\azureml-environment-setup/conda_env_checker.bat']
Starting the daemon thread to refresh tokens in background for process with pid = 3240
Materialized conda environment not found on target: C:\Users\hcche/.azureml/envs/azureml_5fe324eb2cc5d6ab8afd92822e495375
[2022-03-05T14:58:16.949852] Logging experiment preparation status in history service.
Running: ['cmd.exe', '/c', 'C:\\Users\\hcche\\AppData\\Local\\Temp\\azureml_runs\\get-started-with-jobsubmission-tutorial_1646492292_095b0179\\azureml-environment-setup/conda_env_builder.bat']
Running: ['conda', '--version']
Failed to handle log line that was not ASCII!
Unable to run conda package manager. AzureML uses conda to provision python
environments from a dependency specification. To manage the python environment
manually instead, set userManagedDependencies to True in the python environment
configuration. To use system managed python environments, install conda from:
https://conda.io/miniconda.html
[2022-03-05T14:58:20.783407] Logging error in history service: Failed to run ['cmd.exe', '/c', 'C:\\Users\\hcche\\AppData\\Local\\Temp\\azureml_runs\\get-started-with-jobsubmission-tutorial_1646492292_095b0179\\azureml-environment-setup/conda_env_builder.bat']
Exit code 1
Details can be found in azureml-logs/60_control_log.txt log file.
Uploading control log...
Execution Summary
=================
RunId: get-started-with-jobsubmission-tutorial_1646492292_095b0179
Web View: https://ml.azure.com/runs/get-started-with-jobsubmission-tutorial_1646492292_095b0179?wsid=/subscriptions/c27e04e6-ca10-453d-9c80-1931b65eb245/resourcegroups/my_azure_AutoML_resource_group/workspaces/my_azure_AutoML_workspace&tid=de0795e0-d7c0-4eeb-b9bb-bc94d8980d3b
Warnings:
{
"error": {
"code": "ServiceError",
"severity": null,
"message": "Failed to run ['cmd.exe', '/c', 'C:\\\\Users\\\\hcche\\\\AppData\\\\Local\\\\Temp\\\\azureml_runs\\\\get-started-with-jobsubmission-tutorial_1646492292_095b0179\\\\azureml-environment-setup/conda_env_builder.bat'] \n Exit code 1 \nDetails can be found in azureml-logs/60_co",
"messageFormat": null,
"messageParameters": {},
"referenceCode": null,
"detailsUri": null,
"target": null,
"details": [],
"innerError": null,
"debugInfo": null,
"additionalInfo": null
},
"correlation": null,
"environment": null,
"location": null,
"time": "0001-01-01T00:00:00+00:00",
"componentName": null
}
###Markdown
Register modelThe training script used the MLflow autologging feature and therefore the model was captured and stored on your behalf. Below we register the model into the Azure Machine Learning Model registry, which lets you keep track of all the models in your Azure Machine Learning workspace.Models are identified by name and version. Each time you register a model with the same name as an existing one, the registry assumes that it's a new version. The version is incremented, and the new model is registered under the same name.When you register the model, you can provide additional metadata tags and then use the tags when you search for models.
###Code
# register model
model = run.register_model(
model_name="sklearn_mnist", model_path="model/model.pkl"
)
print(model.name, model.id, model.version, sep="\t")
###Output
_____no_output_____
###Markdown
You will now be able to see the model in the regsitry by selecting __Models__ in the left-hand menu of the Azure Machine Learning Studio. Control CostIf you want to control cost you can stop the compute instance this notebook is running on by clicking the "Stop compute" button next to the status dropdown in the menu above. Next StepsIn this quickstart, you have seen how to run jobs-based machine learning code in Azure Machine Learning. It is also possible to use automated machine learning in Azure Machine Learning service to find the best model in an automated fashion. To see how this works, we recommend that you follow the next quickstart in this series, [**Fraud Classification using Automated ML**](../quickstart-azureml-automl/quickstart-azureml-automl.ipynb). This quickstart is focused on AutoML using the Python SDK. The End
###Code
s = "Activity Failed:\n{\n \"error\": {\n \"code\": \"UserError\",\n \"message\": \"Unable to run conda package manager. AzureML uses conda to provision python\\nenvironments from a dependency specification. To manage the python environment\\nmanually instead, set userManagedDependencies to True in the python environment\\nconfiguration. To use system managed python environments, install conda from:\\nhttps://conda.io/miniconda.html\",\n \"messageParameters\": {},\n \"details\": []\n },\n \"time\": \"2022-03-05T14:58:18.850729Z\"\n}"
print(s)
###Output
Activity Failed:
{
"error": {
"code": "UserError",
"message": "Unable to run conda package manager. AzureML uses conda to provision python\nenvironments from a dependency specification. To manage the python environment\nmanually instead, set userManagedDependencies to True in the python environment\nconfiguration. To use system managed python environments, install conda from:\nhttps://conda.io/miniconda.html",
"messageParameters": {},
"details": []
},
"time": "2022-03-05T14:58:18.850729Z"
}
###Markdown
 Quickstart: Learn how to submit batch jobs with the Azure Machine Learning Python SDKIn this quickstart, you learn how to submit a batch training job using the Python SDK. In this example, we submit the job to the 'local' machine (the compute instance you are running this notebook on). However, you can use exactly the same method to submit the job to different compute targets (for example, AKS, Azure Machine Learning Compute Cluster, Synapse, etc) by changing a single line of code. A full list of support compute targets can be viewed [here](https://docs.microsoft.com/en-us/azure/machine-learning/concept-compute-target). This quickstart trains a simple logistic regression using the [MNIST](https://azure.microsoft.com/services/open-datasets/catalog/mnist/) dataset and [scikit-learn](http://scikit-learn.org) with Azure Machine Learning. MNIST is a popular dataset consisting of 70,000 grayscale images. Each image is a handwritten digit of 28x28 pixels, representing a number from 0 to 9. The goal is to create a multi-class classifier to identify the digit a given image represents. You will learn how to:> * Download a dataset and look at the data> * Train an image classification model by submitting a batch job to a compute resource> * Use MLflow autologging to track model metrics and log the model artefact> * Review training results, find and register the best model Connect to your workspace and create an experimentYou start with importing some libraries and creating an experiment to track the runs in your workspace. A workspace can have multiple experiments, and all the users that have access to the workspace can collaborate on them.
###Code
from azureml.core import Workspace
from azureml.core import Experiment
# connect to your workspace
ws = Workspace.from_config()
experiment_name = "get-started-with-jobsubmission-tutorial"
exp = Experiment(workspace=ws, name=experiment_name)
###Output
_____no_output_____
###Markdown
The MNIST datasetUse Azure Open Datasets to get the raw MNIST data files. [Azure Open Datasets](https://docs.microsoft.com/azure/open-datasets/overview-what-are-open-datasets) are curated public datasets that you can use to add scenario-specific features to machine learning solutions for more accurate models. Each dataset has a corresponding class, `MNIST` in this case, to retrieve the data in different ways.Follow this [how-to](https://aka.ms/azureml/howto/createdatasets) if you want to learn more about Datasets and how to use them.
###Code
from azureml.opendatasets import MNIST
mnist_file_dataset = MNIST.get_file_dataset()
###Output
_____no_output_____
###Markdown
Define the EnvironmentAn Environment defines Python packages, environment variables, and Docker settings that are used in machine learning experiments. Here you will be using a curated environment that has already been made available through the workspace. Read [this article](https://docs.microsoft.com/azure/machine-learning/how-to-use-environments) if you want to learn more about Environments and how to use them.
###Code
from azureml.core.environment import Environment
# use a curated environment that has already been built for you
env = Environment.get(workspace=ws,
name="AzureML-Scikit-learn0.24-Cuda11-OpenMpi4.1.0-py36",
version=1)
###Output
_____no_output_____
###Markdown
Configure the training jobCreate a [ScriptRunConfig](https://docs.microsoft.com/python/api/azureml-core/azureml.core.script_run_config.scriptrunconfig?view=azure-ml-py) object to specify the configuration details of your training job, including your training script, environment to use, and the compute target to run on. Configure the ScriptRunConfig by specifying:* The directory that contains your scripts. All the files in this directory are uploaded into the cluster nodes for execution. * The compute target. In this case you will point to local compute* The training script name, train.py* An environment that contains the libraries needed to run the script* Arguments required from the training script. In this run we will be submitting to "local", which is the compute instance you are running this notebook. If you have another compute target (for example: AKS, Azure ML Compute Cluster, Azure Databricks, etc) then you just need to change the `compute_target` argument below. You can learn more about other compute targets [here](https://docs.microsoft.com/azure/machine-learning/how-to-set-up-training-targets).
###Code
from azureml.core import ScriptRunConfig
args = ["--data-folder", mnist_file_dataset.as_mount(), "--regularization", 0.5]
src = ScriptRunConfig(
source_directory="src",
script="train.py",
arguments=args,
compute_target="local",
environment=env,
)
###Output
_____no_output_____
###Markdown
Submit the jobRun the experiment by submitting the ScriptRunConfig object. After this there are many options for monitoring your run. Once submitted, you can either navigate to the experiment "get-started-with-jobsubmission-tutorial" in the left menu item __Experiments__ to monitor the run, or you can monitor the run inline as the `run.wait_for_completion(show_output=True)` will stream the logs of the run. You will see that the environment is built for you to ensure reproducibility - this adds a couple of minutes to the run time. On subsequent runs, the environment is re-used making the runtime shorter.
###Code
run = exp.submit(config=src)
run.wait_for_completion(show_output=True)
###Output
_____no_output_____
###Markdown
Register modelThe training script used the MLflow autologging feature and therefore the model was captured and stored on your behalf. Below we register the model into the Azure Machine Learning Model registry, which lets you keep track of all the models in your Azure Machine Learning workspace.Models are identified by name and version. Each time you register a model with the same name as an existing one, the registry assumes that it's a new version. The version is incremented, and the new model is registered under the same name.When you register the model, you can provide additional metadata tags and then use the tags when you search for models.
###Code
# register model
model = run.register_model(
model_name="sklearn_mnist", model_path="model/model.pkl"
)
print(model.name, model.id, model.version, sep="\t")
###Output
_____no_output_____
###Markdown
 Quickstart: Learn how to get started with Azure ML Job SubmissionIn this quickstart, you train a machine learning model by submitting a Job to a compute target. When training, it is common to start on your local computer, and then later scale out to a cloud-based cluster. All you need to do is define the environment for each compute target within a script run configuration. Then, when you want to run your training experiment on a different compute target, specify the run configuration for that compute.This quickstart trains a simple logistic regression using the [MNIST](https://azure.microsoft.com/services/open-datasets/catalog/mnist/) dataset and [scikit-learn](http://scikit-learn.org) with Azure Machine Learning. MNIST is a popular dataset consisting of 70,000 grayscale images. Each image is a handwritten digit of 28x28 pixels, representing a number from 0 to 9. The goal is to create a multi-class classifier to identify the digit a given image represents. You will learn how to:> * Download a dataset and look at the data> * Train an image classification model by submitting a batch job to a compute resource> * Review training results, find and register the best model Connect to your workspace and create an experimentYou start with importing some libraries and creating an experiment to track the runs in your workspace. A workspace can have multiple experiments, and all the users that have access to the workspace can collaborate on them.
###Code
import numpy as np
import matplotlib.pyplot as plt
from azureml.core import Workspace
from azureml.core import Experiment
# connect to your workspace
ws = Workspace.from_config()
experiment_name = "get-started-with-jobsubmission-tutorial"
exp = Experiment(workspace=ws, name=experiment_name)
###Output
_____no_output_____
###Markdown
Import DataBefore you train a model, you need to understand the data that you are using to train it. In this section you will:* Download the MNIST dataset* Display some sample images Download the MNIST datasetUse Azure Open Datasets to get the raw MNIST data files. [Azure Open Datasets](https://docs.microsoft.com/azure/open-datasets/overview-what-are-open-datasets) are curated public datasets that you can use to add scenario-specific features to machine learning solutions for more accurate models. Each dataset has a corresponding class, `MNIST` in this case, to retrieve the data in different ways.Follow this [how-to](https://aka.ms/azureml/howto/createdatasets) if you want to learn more about Datasets and how to use them.
###Code
import os
from azureml.core import Dataset
from azureml.opendatasets import MNIST
data_folder = os.path.join(os.getcwd(), "data")
os.makedirs(data_folder, exist_ok=True)
mnist_file_dataset = MNIST.get_file_dataset()
mnist_file_dataset.download(data_folder, overwrite=True)
mnist_file_dataset = mnist_file_dataset.register(
workspace=ws,
name="mnist_opendataset",
description="training and test dataset",
create_new_version=True,
)
###Output
_____no_output_____
###Markdown
Take a look at the dataYou will load the compressed files into `numpy` arrays. Then use `matplotlib` to plot 30 random images from the dataset with their labels above them. Note this step requires a `load_data` function that's included in an `utils.py` file. This file is placed in the same folder as this notebook. The `load_data` function simply parses the compressed files into numpy arrays.
###Code
# make sure utils.py is in the same directory as this code
from src.utils import load_data
import glob
# note we also shrink the intensity values (X) from 0-255 to 0-1. This helps the model converge faster.
X_train = (
load_data(
glob.glob(
os.path.join(data_folder, "**/train-images-idx3-ubyte.gz"), recursive=True
)[0],
False,
)
/ 255.0
)
X_test = (
load_data(
glob.glob(
os.path.join(data_folder, "**/t10k-images-idx3-ubyte.gz"), recursive=True
)[0],
False,
)
/ 255.0
)
y_train = load_data(
glob.glob(
os.path.join(data_folder, "**/train-labels-idx1-ubyte.gz"), recursive=True
)[0],
True,
).reshape(-1)
y_test = load_data(
glob.glob(
os.path.join(data_folder, "**/t10k-labels-idx1-ubyte.gz"), recursive=True
)[0],
True,
).reshape(-1)
# now let's show some randomly chosen images from the training set.
count = 0
sample_size = 30
plt.figure(figsize=(16, 6))
for i in np.random.permutation(X_train.shape[0])[:sample_size]:
count = count + 1
plt.subplot(1, sample_size, count)
plt.axhline("")
plt.axvline("")
plt.text(x=10, y=-10, s=y_train[i], fontsize=18)
plt.imshow(X_train[i].reshape(28, 28), cmap=plt.cm.Greys)
plt.show()
###Output
_____no_output_____
###Markdown
Submit your training jobIn this quickstart you submit a job to run on the local compute, but you can use the same code to submit this training job to other compute targets. With Azure Machine Learning, you can run your script on various compute targets without having to change your training script. To submit a job you need:* A directory* A training script* Create a script run configuration* Submit the job Directory and training script You need a directory to deliver the necessary code from your computer to the remote resource. A directory with a training script has been created for you and can be found in the same folder as this notebook.Take a few minutes to examine the training script.
###Code
with open("./src/train.py", "r") as f:
print(f.read())
###Output
_____no_output_____
###Markdown
Notice how the script gets data and saves models:+ The training script reads an argument to find the directory containing the data. When you submit the job later, you point to the dataset for this argument:`parser.add_argument('--data-folder', type=str, dest='data_folder', help='data directory mounting point')`+ The training script saves your model into a directory named outputs. `joblib.dump(value=clf, filename='outputs/sklearn_mnist_model.pkl')`Anything written in this directory is automatically uploaded into your workspace. You'll access your model from this directory later in the tutorial.The file `utils.py` is referenced from the training script to load the dataset correctly. This script is also copied into the script folder so that it can be accessed along with the training script. Configure the training jobCreate a [ScriptRunConfig]() object to specify the configuration details of your training job, including your training script, environment to use, and the compute target to run on. Configure the ScriptRunConfig by specifying:* The directory that contains your scripts. All the files in this directory are uploaded into the cluster nodes for execution. * The compute target. In this case you will point to local compute* The training script name, train.py* An environment that contains the libraries needed to run the script* Arguments required from the training script. An Environment defines Python packages, environment variables, and Docker settings that are used in machine learning experiments. Here you will be using a curated environment that has already been made available through the workspace. Read [this article](https://docs.microsoft.com/azure/machine-learning/how-to-use-environments) if you want to learn more about Environments and how to use them.
###Code
from azureml.core.environment import Environment
from azureml.core.conda_dependencies import CondaDependencies
# use a curated environment that has already been built for you
env = Environment.get(workspace=ws, name="AzureML-Scikit-learn-0.20.3")
###Output
_____no_output_____
###Markdown
Create a [ScriptRunConfig](https://docs.microsoft.com/python/api/azureml-core/azureml.core.scriptrunconfig?preserve-view=true&view=azure-ml-py) object to specify the configuration details of your training job, including your training script, environment to use, and the compute target to run on. A script run configuration is used to configure the information necessary for submitting a training run as part of an experiment. In this case we will run this on a 'local' compute target, which is the compute instance you are running this notebook on.
Read more about configuring and submitting training runs [here](https://docs.microsoft.com/azure/machine-learning/how-to-set-up-training-targets).
###Code
from azureml.core import ScriptRunConfig
args = ["--data-folder", mnist_file_dataset.as_mount(), "--regularization", 0.5]
src = ScriptRunConfig(
source_directory="src",
script="train.py",
arguments=args,
compute_target="local",
environment=env,
)
###Output
_____no_output_____
###Markdown
Submit the jobRun the experiment by submitting the ScriptRunConfig object. After this there are many options for monitoring your run. You can either navigate to the experiment "get-started-with-jobsubmission-tutorial" in the left menu item Experiments to monitor the run (quick link to the run details page in the cell output below), or you can monitor the run inline in this notebook by using the Jupyter widget activated below.
###Code
run = exp.submit(config=src)
run
###Output
_____no_output_____
###Markdown
Jupyter widgetWatch the progress of the run with a Jupyter widget. Like the run submission, the widget is asynchronous and provides live updates every 10-15 seconds until the job completes.
###Code
from azureml.widgets import RunDetails
RunDetails(run).show()
###Output
_____no_output_____
###Markdown
if you want to cancel a run, you can follow [these instructions](https://aka.ms/aml-docs-cancel-run). Get log results upon completionModel training happens in the background. You can use `wait_for_completion` to block and wait until the model has completed training before running more code.
###Code
# specify show_output to True for a verbose log
run.wait_for_completion(show_output=True)
###Output
_____no_output_____
###Markdown
Display run resultsYou now have a trained model. Retrieve all the metrics logged during the run, including the accuracy of the model:
###Code
print(run.get_metrics())
###Output
_____no_output_____
###Markdown
Register modelThe last step in the training script wrote the file `outputs/sklearn_mnist_model.pkl` in a directory named `outputs` on the compute where the job is executed. `outputs` is a special directory in that all content in this directory is automatically uploaded to your workspace. This content appears in the run record in the experiment under your workspace. Hence, the model file is now also available in your workspace.
###Code
print(run.get_file_names())
###Output
_____no_output_____
###Markdown
Register the model in the workspace so that you (or your team members with access to the workspace) can later query, examine, and deploy this model.
###Code
# register model
model = run.register_model(
model_name="sklearn_mnist", model_path="outputs/sklearn_mnist_model.pkl"
)
print(model.name, model.id, model.version, sep="\t")
###Output
_____no_output_____ |
_programs/python/logistic/logistic_regression_02.ipynb | ###Markdown
モデルの訓練
###Code
images = load_images(train_image_file)
labels = load_labels(train_label_file)
onehot = to_onehot(labels)
num_data = len(images)
X = images.reshape((num_data, -1))
y = onehot.reshape((num_data, -1))
def softmax(x, axis=-1):
""" softmax関数 """
x = x - np.max(x, axis=axis, keepdims=True)
ex = np.exp(x)
return ex / np.sum(ex, axis=axis, keepdims=True)
def logsumexp(x, axis=-1):
""" logsumexp関数 """
x_max = np.max(x, axis=axis, keepdims=True)
x = x - x_max
return x_max + np.log(np.sum(np.exp(x), axis=axis, keepdims=True))
def log_softmax(x, axis=-1):
""" log-softmax関数 """
ex = np.exp(x)
return x - logsumexp(x, axis=axis)
# ミニバッチのサイズ
epochs = 6
batch_size = 32
# モメンタムSGDのパラメータ
alpha = 0.01
momentum = 0.9
# パラメータの初期化
in_features = X.shape[-1]
out_features = y.shape[-1]
AA = np.random.normal(size=(out_features, in_features)) / np.sqrt(0.5 * (out_features + in_features))
bb = np.zeros((out_features))
# エポック
grad_AA = np.zeros_like(AA)
grad_bb = np.zeros_like(bb)
for epoch in range(epochs):
# データの順番は偏りをなくすためにランダムシャッフルする
indices = np.random.permutation(np.arange(num_data))
for b in range(0, num_data, batch_size):
bs = min(batch_size, num_data - b)
X_batch = X[indices[b:b+bs], :]
y_batch = y[indices[b:b+bs], :]
loss = 0.0
acc = 0.0
grad_AA_new = np.zeros_like(AA)
grad_bb_new = np.zeros_like(bb)
# バッチ内の各データに対してロス、精度、勾配を求める
t = np.einsum('ij,bj->bi', AA, X_batch) + bb
log_y_pred = log_softmax(t)
losses = np.sum(-y_batch * log_y_pred, axis=-1, keepdims=True)
delta = np.identity(AA.shape[0])
y_pred = np.exp(log_y_pred)
dLdy = -y_batch / y_pred
dydt = np.einsum('bi,ij->bij', y_pred, delta) - np.einsum('bi,bj->bij', y_pred, y_pred)
dLdt = np.einsum('bi,bij->bj', dLdy, dydt)
dtdA = np.einsum('bk,ij->bijk', X_batch, delta)
dtdb = np.ones((bb.shape[-1], bb.shape[-1]))
dLdA = np.einsum('bi,bijk->bjk', dLdt, dtdA)
dLdb = np.einsum('bi,ij->bj', dLdt, dtdb)
y_pred_id = np.argmax(y_pred, axis=-1)
y_real_id = np.argmax(y_batch, axis=-1)
acc = np.mean(y_pred_id == y_real_id)
loss = np.mean(losses)
grad_AA_new = np.mean(dLdA, axis=0)
grad_bb_new = np.mean(dLdb, axis=0)
# 勾配の更新
grad_AA = grad_AA * momentum + grad_AA_new * (1.0 - momentum)
grad_bb = grad_bb * momentum + grad_bb_new * (1.0 - momentum)
# 最急降下法による値の更新
AA -= alpha * grad_AA
bb -= alpha * grad_bb
# printの代わりにsys.stdout.writeを使うとcarrige returnが使える
sys.stdout.write('\repoch:{}, step:{}, loss={:.6f}, acc={:.6f}'.format(epoch + 1, b + bs, loss, acc))
sys.stdout.flush()
sys.stdout.write('\n')
sys.stdout.flush()
###Output
epoch:1, step:60000, loss=0.615525, acc=0.843750
epoch:2, step:60000, loss=0.513534, acc=0.843750
epoch:3, step:60000, loss=0.460950, acc=0.906250
epoch:4, step:60000, loss=0.269180, acc=0.968750
epoch:5, step:60000, loss=0.650967, acc=0.875000
epoch:6, step:60000, loss=0.218641, acc=0.906250
###Markdown
モデルのテスト
###Code
test_images = load_images(test_image_file)
test_labels = load_labels(test_label_file)
test_onehot = to_onehot(test_labels)
num_data = len(images)
X = images.reshape((num_data, -1))
y = onehot.reshape((num_data, -1))
loss = 0.0
acc = 0.0
for b in range(0, num_data, batch_size):
bs = min(batch_size, num_data - b)
X_batch = X[indices[b:b+bs], :]
y_batch = y[indices[b:b+bs], :]
t = np.einsum('ij,bj->bi', AA, X_batch) + bb
log_y_pred = log_softmax(t)
losses = np.sum(-y_batch * log_y_pred, axis=-1, keepdims=True)
y_pred = np.exp(log_y_pred)
y_pred_id = np.argmax(y_pred, axis=-1)
y_real_id = np.argmax(y_batch, axis=-1)
acc += np.sum(y_pred_id == y_real_id)
loss += np.sum(losses)
loss /= num_data
acc /= num_data
print('Loss: {:.4f}'.format(loss))
print('Accuracy: {:.4f}'.format(acc))
###Output
Loss: 0.3474
Accuracy: 0.9038
|
docs/beta/notebooks/Project_MutationFuzzing.ipynb | ###Markdown
Project 1 - Mutation FuzzingMutation fuzzers are effective at testing and perform well for unstructured or for simple inputs formats. However, when dealing with complex structured inputs their random mutations are innefficient. Consider, for example, the following SVG file:``` ```A random mutation replacing `` for `=/sgv>` is perfectly possible, however it would result in an invalid SVG, the same would happen if we add a `"` to any attribute. When sequentially applying multiple random mutations, the probability of generating an input that is a valid SVG file significantly decreases.While fuzzers can run for days in a row to cover considerable behavior, the goal of this project is to utilize mutation fuzzing to cover as much code as possible during a specified number of generations. Our target is the [svglib](https://pypi.org/project/svglib/) SVG rendering library written in python. For an easier integration with the library we provide a wrapped function __parse_svg(string)__, which receives a string with the SVG content and invokes the parsing library. To ensure that all converted elements are correct, the wrapper function internally converts the parsed SVG into PDF and PNG formats. Finally, the wrapper function returns an _RLG Drawing_ object if the conversion was successfull or None if it wasn't.
###Code
import sys
import logging
import os
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF, renderPM
# Required to run svglib on Python3
xrange = range
logging.disable(logging.ERROR)
RUN_EVALUATION = True
DEBUG = True
COUNT = 0
def parse_svg(data):
if DEBUG:
global COUNT
if COUNT % 1000 == 0:
print(COUNT)
COUNT += 1
pdf_file = 'tmp.pdf'
png_file = 'tmp.png'
svg_file = 'tmp.svg'
try:
with open(svg_file, "w") as f:
f.write(data)
drawing = svg2rlg(svg_file)
assert(drawing is not None)
renderPDF.drawToFile(drawing, pdf_file)
#renderPM.drawToFile(drawing, png_file)
return drawing
finally:
if os.path.exists(svg_file):
os.remove(svg_file)
if os.path.exists(png_file):
os.remove(png_file)
if os.path.exists(pdf_file):
os.remove(pdf_file)
parse_svg("""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<path d="M17,30l19-12l43,54l-17,15zM14,84c12-20 46-61 61-72l13,19 c-17,10-50,50-60,64z" fill="#C30" stroke-linejoin="round" stroke-width="6" stroke="#C30"></path>
</svg>
""")
###Output
_____no_output_____
###Markdown
Auxiliary functionsThe SVG format has a tree structure. In order to aid the fuzzer's implementation we provide an auxiliary function to convert an SVG string representations into Python's [ElementTree](https://docs.python.org/2/library/xml.etree.elementtree.html) for easier manipulation.
###Code
import sys
from lxml import etree
def svg_as_tree(data):
"""Converts a String representation of an SVG into an ElementTree and returns its root
:param data: String representation of an SVG
:return: ElementTree https://docs.python.org/3/library/xml.etree.elementtree.html
"""
parser = etree.XMLParser(encoding='utf-8')
root = etree.fromstring(data.encode('utf-8'), parser=parser)
return root
###Output
_____no_output_____
###Markdown
The tree representation can be used to, for example, apply mutations on internal components of the nodes, as well as move, add or remove elements. The following code illustrates how to convert from a String into an [ElementTree](https://docs.python.org/2/library/xml.etree.elementtree.html).
###Code
svg_string = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<path d="M19,19h58v58h-58z" stroke="#000" fill="none" stroke-width="4"/>
<path d="M17,30l19-12l43,54l-17,15zM14,84c12-20 46-61 61-72l13,19 c-17,10-50,50-60,64z" fill="#C30" stroke-linejoin="round" stroke-width="6" stroke="#C30"/>
<cicle/>
</svg>
"""
root_node = svg_as_tree(svg_string)
print("%s - %s" % (root_node.tag, root_node.attrib))
###Output
_____no_output_____
###Markdown
After converting the String representation into a tree it is possible to iterate over the nodes
###Code
# Printing immediate child nodes:
for child in root_node:
print("%s - %s" % (child.tag, child.attrib))
###Output
_____no_output_____
###Markdown
As well are access and manipulate the node type (_tag_) and its attributes (_attrib_)
###Code
# Accessing and changing properties
first_child = root_node[0]
print("old value of stroke-width: %s" % first_child.attrib['stroke-width'])
first_child.attrib['stroke-width'] = "99"
print("new value of stroke-width: %s" % first_child.attrib['stroke-width'])
###Output
_____no_output_____
###Markdown
After the changes the tree can be converted back into a string to be used in _parse_svg()_ function.
###Code
new_string = etree.tostring(root_node)
print(new_string)
###Output
_____no_output_____
###Markdown
Fuzzer templateThe basic template from our fuzzer is based on the [MutationCoverageFuzzer](MutationFuzzer.ipynb) from the lecture.This template automatically loads a set of 10 SVG files as an initial seed.
###Code
from Coverage import Coverage
from MutationFuzzer import MutationCoverageFuzzer, FunctionCoverageRunner
class Project1MutationCoverageFuzzer(MutationCoverageFuzzer):
def __init__(self, min_mutations=2, max_mutations=10):
seed = self._get_initial_seed()
super().__init__(seed, min_mutations, max_mutations)
def _get_initial_seed(self):
"""Gets the initial seed for the fuzzer
:return: List of SVG in string format
"""
seed_dir = os.path.join(".", "data", "svg-full")
seed_files = list(filter(lambda f: ".svg" in f, os.listdir(seed_dir)))
seed = []
for f in seed_files:
with open(os.path.join(seed_dir, f)) as x:
s = ''.join(x.readlines()).strip()
seed.append(s)
print("Seed size: " + str(len(seed)) + " files")
return seed
###Output
_____no_output_____
###Markdown
Fuzzing the _svglib_To fuzz _svglib_ your fuzzer must execute it and inspect how much coverage it obtained with a specific input. With this goal we'll extend the [FunctionCoverageRunner](MutationFuzzer.ipynb) class from the lecture. The original class calculated coverage and was capable of handling exceptions, however, if the fuzzer triggered, for example, an infinite loop, it would not work. In this extension we add a configurable timeout for the command to ensure our library will always terminate.
###Code
from ExpectError import ExpectTimeout, ExpectError
class FunctionCoverageRunnerWithTimeout(FunctionCoverageRunner):
def __init__(self, function, timeout=1):
self._timeout = timeout
super().__init__(function)
def run(self, inp):
outcome = self.FAIL
result = None
self._coverage = []
with ExpectError(mute=True):
with ExpectTimeout(self._timeout, mute=True):
result = self.run_function(inp)
outcome = self.PASS
return result, outcome
parse_svg_runner = FunctionCoverageRunnerWithTimeout(parse_svg)
###Output
_____no_output_____
###Markdown
We also define our experiment as a set of 5 runs, with random seeds 2000-2004 with 10000 actions.
###Code
import datetime
import random
def run_experiment(fuzzer, start_seed=2000, end_seed=2005, trials=10000):
print("Started fuzzing at %s" % str(datetime.datetime.now()))
experiment_population = []
for seed in range(start_seed, end_seed):
print("Starting seed %d at %s" % (seed, str(datetime.datetime.now())))
random.seed(seed)
fuzzer.reset()
fuzzer.runs(parse_svg_runner, trials)
experiment_population.append(fuzzer.population)
print("Finished fuzzing at %s" % str(datetime.datetime.now()))
return experiment_population
###Output
_____no_output_____
###Markdown
We then initialize our fuzzer
###Code
mutation_fuzzer = Project1MutationCoverageFuzzer()
###Output
_____no_output_____
###Markdown
And execute it multiple times to test it. __Note:__ we're running this example with only 10 trials to demonstrate the functionality. The fuzzer should be executed for 10000 trials.
###Code
experiment_population = run_experiment(mutation_fuzzer, trials=10)
###Output
_____no_output_____
###Markdown
Obtaining the population coverageIn order to obtain the overal coverage achieved by the fuzzer's population we will adapt the [population_coverage](Coverage.ipynb) function from the lecture.The following code calculates the overall coverage from a fuzzer's population:
###Code
import matplotlib.pyplot as plt
def population_coverage(population, function):
cumulative_coverage = []
all_coverage = set()
for s in population:
with Coverage() as cov:
with ExpectError(mute=True):
with ExpectTimeout(1, mute=True):
function(s)
all_coverage |= cov.coverage()
cumulative_coverage.append(len(all_coverage))
return all_coverage, cumulative_coverage
###Output
_____no_output_____
###Markdown
Your codeNow extend the Project1MutationCoverageFuzzer class, implement your own custom mutations and fuzz _svglib_ to achieve a better coverage. Tips* You can develop any type of mutation as well as use random mutations.* The commands `with ExpectError(mute=True)` and `with ExpectTimeout(1, mute=True)` remove the error output. It may be useful to set `mute=False` for debugging.* Your fuzzer will be restarted (`reset()`) after each execution. * We recommend you to extend the class `Project1MutationCoverageFuzzer` as `class Project1MutationCoverageFuzzer(Project1MutationCoverageFuzzer): ...` to reause the implementations for the lecture.
###Code
class Project1MutationCoverageFuzzer(Project1MutationCoverageFuzzer):
# <Write your code here>
pass
###Output
_____no_output_____
###Markdown
EvaluationSince our experiment consists of a set of executions, we'll calculate the coverage of all populations, and return it's average as final result.
###Code
def evaluate(populations):
global COUNT
coverages = []
seen_statements = set()
for idx, population in enumerate(populations):
COUNT = 0
all_coverage, cumulative_coverage = population_coverage(
populations[idx], parse_svg)
seen_statements |= all_coverage
coverages.append(len(all_coverage))
plt.plot(cumulative_coverage)
plt.title('Coverage of parse_svg() with random inputs')
plt.xlabel('# of inputs')
plt.ylabel('lines covered')
print("Covered lines (run %d) %d" % (idx, len(all_coverage)))
print("Unique elements (run %d) %d" % (idx, len(cumulative_coverage)))
return tuple([sum(coverages) / len(coverages), len(seen_statements)])
print("Average coverage: %d - Total achieved coverage: %d" % evaluate(experiment_population))
###Output
_____no_output_____
###Markdown
Evaluation scheme* For the evaluation your fuzzer will be executed __five__ times with random seeds __2000-2004__ and __10000__ trials in each seed.* In order to be approved your fuzzer should achieve an average coverage of __4400__ LOC (lines of code). * Bonus points will be awarded for fuzzers which reach a total of more than __5500__ unique library statements throughout the experiment, as well as to fuzzers which reach an __exceptions__ from the library in any execution (One single bonus points will be awarded for exceptions, irrespective of the number of exceptions triggered). Examples include: ``` Exception ignored in: > Traceback (most recent call last): File "/etc/anaconda3/lib/python3.6/site-packages/PIL/Image.py", line 588, in __del__ def __del__(self): File "", line 5, in traceit File "", line 16, in check_time TimeoutError: ```* The grades will be based on the average coverage achieved by your fuzzer.* Students can be randomly selected to explain their code in order to demonstrate authorship.__The following code will be used to evaluate your fuzzer (Note: Your fuzzer must be executable by the following code)__
###Code
if RUN_EVALUATION:
print("Initializing evaluation")
parse_svg_runner = FunctionCoverageRunnerWithTimeout(parse_svg)
mutation_fuzzer = Project1MutationCoverageFuzzer()
print("Running experiment")
experiment_population = run_experiment(mutation_fuzzer, trials=10000)
if RUN_EVALUATION:
print("Computing results")
avg_statements, total_statements = evaluate(experiment_population)
print("Final result: Average coverage: %d - Total achieved coverage: %d" % (avg_statements, total_statements))
###Output
_____no_output_____
###Markdown
Project 1 - Mutation FuzzingMutation fuzzers are effective at testing and perform well for unstructured or for simple inputs formats. However, when dealing with complex structured inputs their random mutations are innefficient. Consider, for example, the following SVG file:``` ```A random mutation replacing `` for `=/sgv>` is perfectly possible, however it would result in an invalid SVG, the same would happen if we add a `"` to any attribute. When sequentially applying multiple random mutations, the probability of generating an input that is a valid SVG file significantly decreases.While fuzzers can run for days in a row to cover considerable behavior, the goal of this project is to utilize mutation fuzzing to cover as much code as possible during a specified number of generations. Our target is the [svglib](https://pypi.org/project/svglib/) SVG rendering library written in python. For an easier integration with the library we provide a wrapped function __parse_svg(string)__, which receives a string with the SVG content and invokes the parsing library. To ensure that all converted elements are correct, the wrapper function internally converts the parsed SVG into PDF and PNG formats. Finally, the wrapper function returns an _RLG Drawing_ object if the conversion was successfull or None if it wasn't.
###Code
import sys
import logging
import os
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF, renderPM
# Required to run svglib on Python3
xrange = range
logging.disable(logging.ERROR)
RUN_EVALUATION = True
DEBUG = True
COUNT = 0
def parse_svg(data):
if DEBUG:
global COUNT
if COUNT % 1000 == 0:
print(COUNT)
COUNT += 1
pdf_file = 'tmp.pdf'
png_file = 'tmp.png'
svg_file = 'tmp.svg'
try:
with open(svg_file, "w") as f:
f.write(data)
drawing = svg2rlg(svg_file)
assert(drawing is not None)
renderPDF.drawToFile(drawing, pdf_file)
#renderPM.drawToFile(drawing, png_file)
return drawing
finally:
if os.path.exists(svg_file):
os.remove(svg_file)
if os.path.exists(png_file):
os.remove(png_file)
if os.path.exists(pdf_file):
os.remove(pdf_file)
parse_svg("""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<path d="M17,30l19-12l43,54l-17,15zM14,84c12-20 46-61 61-72l13,19 c-17,10-50,50-60,64z" fill="#C30" stroke-linejoin="round" stroke-width="6" stroke="#C30"></path>
</svg>
""")
###Output
_____no_output_____
###Markdown
Auxiliary functionsThe SVG format has a tree structure. In order to aid the fuzzer's implementation we provide an auxiliary function to convert an SVG string representations into Python's [ElementTree](https://docs.python.org/2/library/xml.etree.elementtree.html) for easier manipulation.
###Code
import sys
from lxml import etree
def svg_as_tree(data):
"""Converts a String representation of an SVG into an ElementTree and returns its root
:param data: String representation of an SVG
:return: ElementTree https://docs.python.org/3/library/xml.etree.elementtree.html
"""
parser = etree.XMLParser(encoding='utf-8')
root = etree.fromstring(data.encode('utf-8'), parser=parser)
return root
###Output
_____no_output_____
###Markdown
The tree representation can be used to, for example, apply mutations on internal components of the nodes, as well as move, add or remove elements. The following code illustrates how to convert from a String into an [ElementTree](https://docs.python.org/2/library/xml.etree.elementtree.html).
###Code
svg_string = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<path d="M19,19h58v58h-58z" stroke="#000" fill="none" stroke-width="4"/>
<path d="M17,30l19-12l43,54l-17,15zM14,84c12-20 46-61 61-72l13,19 c-17,10-50,50-60,64z" fill="#C30" stroke-linejoin="round" stroke-width="6" stroke="#C30"/>
<cicle/>
</svg>
"""
root_node = svg_as_tree(svg_string)
print("%s - %s" % (root_node.tag, root_node.attrib))
###Output
_____no_output_____
###Markdown
After converting the String representation into a tree it is possible to iterate over the nodes
###Code
# Printing immediate child nodes:
for child in root_node:
print("%s - %s" % (child.tag, child.attrib))
###Output
_____no_output_____
###Markdown
As well are access and manipulate the node type (_tag_) and its attributes (_attrib_)
###Code
# Accessing and changing properties
first_child = root_node[0]
print("old value of stroke-width: %s" % first_child.attrib['stroke-width'])
first_child.attrib['stroke-width'] = "99"
print("new value of stroke-width: %s" % first_child.attrib['stroke-width'])
###Output
_____no_output_____
###Markdown
After the changes the tree can be converted back into a string to be used in _parse_svg()_ function.
###Code
new_string = etree.tostring(root_node)
print(new_string)
###Output
_____no_output_____
###Markdown
Fuzzer templateThe basic template from our fuzzer is based on the [MutationCoverageFuzzer](MutationFuzzer.ipynb) from the lecture.This template automatically loads a set of 10 SVG files as an initial seed.
###Code
from Coverage import Coverage
from MutationFuzzer import MutationCoverageFuzzer, FunctionCoverageRunner
class Project1MutationCoverageFuzzer(MutationCoverageFuzzer):
def __init__(self, min_mutations=2, max_mutations=10):
seed = self._get_initial_seed()
super().__init__(seed, min_mutations, max_mutations)
def _get_initial_seed(self):
"""Gets the initial seed for the fuzzer
:return: List of SVG in string format
"""
seed_dir = os.path.join(".", "data", "svg-full")
seed_files = list(filter(lambda f: ".svg" in f, os.listdir(seed_dir)))
seed = []
for f in seed_files:
with open(os.path.join(seed_dir, f)) as x:
s = ''.join(x.readlines()).strip()
seed.append(s)
print("Seed size: " + str(len(seed)) + " files")
return seed
###Output
_____no_output_____
###Markdown
Fuzzing the _svglib_To fuzz _svglib_ your fuzzer must execute it and inspect how much coverage it obtained with a specific input. With this goal we'll extend the [FunctionCoverageRunner](MutationFuzzer.ipynb) class from the lecture. The original class calculated coverage and was capable of handling exceptions, however, if the fuzzer triggered, for example, an infinite loop, it would not work. In this extension we add a configurable timeout for the command to ensure our library will always terminate.
###Code
from ExpectError import ExpectTimeout, ExpectError
class FunctionCoverageRunnerWithTimeout(FunctionCoverageRunner):
def __init__(self, function, timeout=1):
self._timeout = timeout
super().__init__(function)
def run(self, inp):
outcome = self.FAIL
result = None
self._coverage = []
with ExpectError(mute=True):
with ExpectTimeout(self._timeout, mute=True):
result = self.run_function(inp)
outcome = self.PASS
return result, outcome
parse_svg_runner = FunctionCoverageRunnerWithTimeout(parse_svg)
###Output
_____no_output_____
###Markdown
We also define our experiment as a set of 5 runs, with random seeds 2000-2004 with 10000 actions.
###Code
import datetime
import random
def run_experiment(fuzzer, start_seed=2000, end_seed=2005, trials=10000):
print("Started fuzzing at %s" % str(datetime.datetime.now()))
experiment_population = []
for seed in range(start_seed, end_seed):
print("Starting seed %d at %s" % (seed, str(datetime.datetime.now())))
random.seed(seed)
fuzzer.reset()
fuzzer.runs(parse_svg_runner, trials)
experiment_population.append(fuzzer.population)
print("Finished fuzzing at %s" % str(datetime.datetime.now()))
return experiment_population
###Output
_____no_output_____
###Markdown
We then initialize our fuzzer
###Code
mutation_fuzzer = Project1MutationCoverageFuzzer()
###Output
_____no_output_____
###Markdown
And execute it multiple times to test it. __Note:__ we're running this example with only 10 trials to demonstrate the functionality. The fuzzer should be executed for 10000 trials.
###Code
experiment_population = run_experiment(mutation_fuzzer, trials=10)
###Output
_____no_output_____
###Markdown
Obtaining the population coverageIn order to obtain the overal coverage achieved by the fuzzer's population we will adapt the [population_coverage](Coverage.ipynb) function from the lecture.The following code calculates the overall coverage from a fuzzer's population:
###Code
import matplotlib.pyplot as plt
def population_coverage(population, function):
cumulative_coverage = []
all_coverage = set()
for s in population:
with Coverage() as cov:
with ExpectError(mute=True):
with ExpectTimeout(1, mute=True):
function(s)
all_coverage |= cov.coverage()
cumulative_coverage.append(len(all_coverage))
return all_coverage, cumulative_coverage
###Output
_____no_output_____
###Markdown
Your codeNow extend the Project1MutationCoverageFuzzer class, implement your own custom mutations and fuzz _svglib_ to achieve a better coverage. Tips* You can develop any type of mutation as well as use random mutations.* The commands `with ExpectError(mute=True)` and `with ExpectTimeout(1, mute=True)` remove the error output. It may be useful to set `mute=False` for debugging.* Your fuzzer will be restarted (`reset()`) after each execution. * We recommend you to extend the class `Project1MutationCoverageFuzzer` as `class Project1MutationCoverageFuzzer(Project1MutationCoverageFuzzer): ...` to reause the implementations for the lecture.
###Code
class Project1MutationCoverageFuzzer(Project1MutationCoverageFuzzer):
# <Write your code here>
pass
###Output
_____no_output_____
###Markdown
EvaluationSince our experiment consists of a set of executions, we'll calculate the coverage of all populations, and return it's average as final result.
###Code
def evaluate(populations):
global COUNT
coverages = []
seen_statements = set()
for idx, population in enumerate(populations):
COUNT = 0
all_coverage, cumulative_coverage = population_coverage(
populations[idx], parse_svg)
seen_statements |= all_coverage
coverages.append(len(all_coverage))
plt.plot(cumulative_coverage)
plt.title('Coverage of parse_svg() with random inputs')
plt.xlabel('# of inputs')
plt.ylabel('lines covered')
print("Covered lines (run %d) %d" % (idx, len(all_coverage)))
print("Unique elements (run %d) %d" % (idx, len(cumulative_coverage)))
return tuple([sum(coverages) / len(coverages), len(seen_statements)])
print("Average coverage: %d - Total achieved coverage: %d" % evaluate(experiment_population))
###Output
_____no_output_____
###Markdown
Evaluation scheme* For the evaluation your fuzzer will be executed __five__ times with random seeds __2000-2004__ and __10000__ trials in each seed.* In order to be approved your fuzzer should achieve an average coverage of __4400__ LOC (lines of code). * Bonus points will be awarded for fuzzers which reach a total of more than __5500__ unique library statements throughout the experiment, as well as to fuzzers which reach an __exceptions__ from the library in any execution (One single bonus points will be awarded for exceptions, irrespective of the number of exceptions triggered). Examples include: ``` Exception ignored in: > Traceback (most recent call last): File "/etc/anaconda3/lib/python3.6/site-packages/PIL/Image.py", line 588, in __del__ def __del__(self): File "", line 5, in traceit File "", line 16, in check_time TimeoutError: ```* The grades will be based on the average coverage achieved by your fuzzer.* Students can be randomly selected to explain their code in order to demonstrate authorship.__The following code will be used to evaluate your fuzzer (Note: Your fuzzer must be executable by the following code)__
###Code
if RUN_EVALUATION:
print("Initializing evaluation")
parse_svg_runner = FunctionCoverageRunnerWithTimeout(parse_svg)
mutation_fuzzer = Project1MutationCoverageFuzzer()
print("Running experiment")
experiment_population = run_experiment(mutation_fuzzer, trials=10000)
if RUN_EVALUATION:
print("Computing results")
avg_statements, total_statements = evaluate(experiment_population)
print("Final result: Average coverage: %d - Total achieved coverage: %d" % (avg_statements, total_statements))
###Output
_____no_output_____ |
06Deep Learning/06Neural Networks Project - Gesture Recognition/Neural_Nets_Project_Starter_Code.ipynb | ###Markdown
Gesture RecognitionIn this group project, you are going to build a 3D Conv model that will be able to predict the 5 gestures correctly. Please import the following libraries to get started.
###Code
import scipy
scipy.__version__
import numpy as np
import os
from scipy.misc import imread, imresize
import datetime
import os
###Output
_____no_output_____
###Markdown
We set the random seed so that the results don't vary drastically.
###Code
np.random.seed(30)
import random as rn
rn.seed(30)
from keras import backend as K
import tensorflow as tf
tf.set_random_seed(30)
###Output
_____no_output_____
###Markdown
In this block, you read the folder names for training and validation. You also set the `batch_size` here. Note that you set the batch size in such a way that you are able to use the GPU in full capacity. You keep increasing the batch size until the machine throws an error.
###Code
train_doc = np.random.permutation(open('/notebooks/storage/Final_data/Collated_training/train.csv').readlines())
val_doc = np.random.permutation(open('/notebooks/storage/Final_data/Collated_training/val.csv').readlines())
batch_size = #experiment with the batch size
###Output
_____no_output_____
###Markdown
GeneratorThis is one of the most important part of the code. The overall structure of the generator has been given. In the generator, you are going to preprocess the images as you have images of 2 different dimensions as well as create a batch of video frames. You have to experiment with `img_idx`, `y`,`z` and normalization such that you get high accuracy.
###Code
def generator(source_path, folder_list, batch_size):
print( 'Source path = ', source_path, '; batch size =', batch_size)
img_idx = #create a list of image numbers you want to use for a particular video
while True:
t = np.random.permutation(folder_list)
num_batches = # calculate the number of batches
for batch in range(num_batches): # we iterate over the number of batches
batch_data = np.zeros((batch_size,x,y,z,3)) # x is the number of images you use for each video, (y,z) is the final size of the input images and 3 is the number of channels RGB
batch_labels = np.zeros((batch_size,5)) # batch_labels is the one hot representation of the output
for folder in range(batch_size): # iterate over the batch_size
imgs = os.listdir(source_path+'/'+ t[folder + (batch*batch_size)].split(';')[0]) # read all the images in the folder
for idx,item in enumerate(img_idx): # Iterate iver the frames/images of a folder to read them in
image = imread(source_path+'/'+ t[folder + (batch*batch_size)].strip().split(';')[0]+'/'+imgs[item]).astype(np.float32)
#crop the images and resize them. Note that the images are of 2 different shape
#and the conv3D will throw error if the inputs in a batch have different shapes
batch_data[folder,idx,:,:,0] = #normalise and feed in the image
batch_data[folder,idx,:,:,1] = #normalise and feed in the image
batch_data[folder,idx,:,:,2] = #normalise and feed in the image
batch_labels[folder, int(t[folder + (batch*batch_size)].strip().split(';')[2])] = 1
yield batch_data, batch_labels #you yield the batch_data and the batch_labels, remember what does yield do
# write the code for the remaining data points which are left after full batches
###Output
_____no_output_____
###Markdown
Note here that a video is represented above in the generator as (number of images, height, width, number of channels). Take this into consideration while creating the model architecture.
###Code
curr_dt_time = datetime.datetime.now()
train_path = '/notebooks/storage/Final_data/Collated_training/train'
val_path = '/notebooks/storage/Final_data/Collated_training/val'
num_train_sequences = len(train_doc)
print('# training sequences =', num_train_sequences)
num_val_sequences = len(val_doc)
print('# validation sequences =', num_val_sequences)
num_epochs = # choose the number of epochs
print ('# epochs =', num_epochs)
###Output
_____no_output_____
###Markdown
ModelHere you make the model using different functionalities that Keras provides. Remember to use `Conv3D` and `MaxPooling3D` and not `Conv2D` and `Maxpooling2D` for a 3D convolution model. You would want to use `TimeDistributed` while building a Conv2D + RNN model. Also remember that the last layer is the softmax. Design the network in such a way that the model is able to give good accuracy on the least number of parameters so that it can fit in the memory of the webcam.
###Code
from keras.models import Sequential, Model
from keras.layers import Dense, GRU, Flatten, TimeDistributed, Flatten, BatchNormalization, Activation
from keras.layers.convolutional import Conv3D, MaxPooling3D
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
from keras import optimizers
#write your model here
###Output
_____no_output_____
###Markdown
Now that you have written the model, the next step is to `compile` the model. When you print the `summary` of the model, you'll see the total number of parameters you have to train.
###Code
optimiser = #write your optimizer
model.compile(optimizer=optimiser, loss='categorical_crossentropy', metrics=['categorical_accuracy'])
print (model.summary())
###Output
_____no_output_____
###Markdown
Let us create the `train_generator` and the `val_generator` which will be used in `.fit_generator`.
###Code
train_generator = generator(train_path, train_doc, batch_size)
val_generator = generator(val_path, val_doc, batch_size)
model_name = 'model_init' + '_' + str(curr_dt_time).replace(' ','').replace(':','_') + '/'
if not os.path.exists(model_name):
os.mkdir(model_name)
filepath = model_name + 'model-{epoch:05d}-{loss:.5f}-{categorical_accuracy:.5f}-{val_loss:.5f}-{val_categorical_accuracy:.5f}.h5'
checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=False, save_weights_only=False, mode='auto', period=1)
LR = # write the REducelronplateau code here
callbacks_list = [checkpoint, LR]
###Output
_____no_output_____
###Markdown
The `steps_per_epoch` and `validation_steps` are used by `fit_generator` to decide the number of next() calls it need to make.
###Code
if (num_train_sequences%batch_size) == 0:
steps_per_epoch = int(num_train_sequences/batch_size)
else:
steps_per_epoch = (num_train_sequences//batch_size) + 1
if (num_val_sequences%batch_size) == 0:
validation_steps = int(num_val_sequences/batch_size)
else:
validation_steps = (num_val_sequences//batch_size) + 1
###Output
_____no_output_____
###Markdown
Let us now fit the model. This will start training the model and with the help of the checkpoints, you'll be able to save the model at the end of each epoch.
###Code
model.fit_generator(train_generator, steps_per_epoch=steps_per_epoch, epochs=num_epochs, verbose=1,
callbacks=callbacks_list, validation_data=val_generator,
validation_steps=validation_steps, class_weight=None, workers=1, initial_epoch=0)
###Output
_____no_output_____ |
examples/RedbackTutorial.ipynb | ###Markdown
Redback: an open source bayesian inference package for fitting electromagnetic transients. How redback can be useful to you.- Download data for supernovae, tidal disruption events, gamma-ray burst afterglows, kilonovae, prompt emission from different catalogs/telescopes; Swift, BATSE, Open access catalogs. Users can also provide their own data or use simulated data- Redback processes the data into a homogeneous transient object, plotting lightcurves and doing other processing.- The user can then fit one of the models implemented in redback. Or fit their own model. Models for several different types of electromagnetic transients are implemented and range from simple analytical models to numerical surrogates.- All models are implemented as functions and can be used to simulate populations, without needing to provide data. This way redback can be used simply as a tool to simulate realistic populations, no need to actually fit anything.- [Bilby](https://lscsoft.docs.ligo.org/bilby/index.html) under the hood. Can easily switch samplers/likelihoods etc. Over 15 samplers are implemented and the list continues to grow. - Fitting returns a homogenous result object, with functionality to plot lightcurves/walkers/corner and the posterior/evidence/credible interval etc. This way redback results can feed into hierarchical analysis of populations of transients or be used in reweighting. Online documentation- [Installation](https://redback.readthedocs.io/en/latest/)- [Examples](https://github.com/nikhil-sarin/redback/tree/master/examples)- [Documentation](https://redback.readthedocs.io/en/latest/) Contributing - Redback is currently in alpha with a paper in preparation. If you are interested in contributing please join the redback [slack](https://join.slack.com/t/slack-23u4492/shared_invite/zt-14y9q1qmo-VRmc8ZxHzB3u~dB3Wi6pjw) and get in touch with [me](mailto:[email protected]?subject=Contributing%20to%20redback). - All contributors at the alpha stage will be invited to be co-authors of the first paper.
###Code
import redback
import pandas as pd
from bilby.core.prior import PriorDict
import bilby
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:80% !important; }</style>"))
display(HTML("<style>.output { max-width:100% !important; }</style>"))
display(HTML("""<style>.output { display: flex; align-items: center;text-align: center;}</style>"""))
%pylab inline
###Output
_____no_output_____
###Markdown
Downloading data from different catalogs e.g., the open access catalogs
###Code
kne = 'at2017gfo'
data = redback.get_data.get_kilonova_data_from_open_transient_catalog_data(transient=kne)
data
###Output
The raw data file already exists.
The processed data file already exists. Returning.
###Markdown
The user is returned the data in a pandas dataframe. The data is also saved in a sensible way. There are two files; the raw data file and the processed data file where we do some basic processing and make it homogenous. Note that the data returned here is a simple pandas dataframe and can be manipulated in arbitrary ways. For example, let's say I just want to see the i band data
###Code
data[data['band']=='i']
###Output
_____no_output_____
###Markdown
Can similarly download data from LASAIR (ZTF/Vera Rubin broker), Afterglows from Swift, Prompt grb from Swift and BATSE.
###Code
GRB = '070809'
# Flux density, flux data
data = redback.get_data.get_bat_xrt_afterglow_data_from_swift(grb=GRB, data_mode="flux")
data
sne = "SN2011kl"
data = redback.get_data.get_supernova_data_from_open_transient_catalog_data(sne)
data
data = redback.get_data.get_lasair_data(transient="ZTF19aagqkrq", transient_type="afterglow")
data
###Output
The raw data file already exists.
The processed data file already exists. Returning.
###Markdown
Since this data is just a simple dataframe, you could play around with it yourself to create plots etc. However, we provide functionality to load this data into a 'transient' object. Providing methods for plotting and other functionality. There are 7 different types of transient objects implemented in redback, which all have unique functionality for the specific type of transient. There are two parent classes- Transient: For any type of generic transient- OpticalTransient: For any type of generic optical transient Five more targeted transient classes- SGRB- LGRB- Supernova - Kilonova- Tidal disruption event- Prompt These classes come with lots of functionality and lookup tables which provide metadata useful for further analysis, such as redshift, T90, start time, etc. They also allow other processing such as converting flux to luminosity. For each of the transients we have different data_modes which determines what data to fit, plot labels, type of likelihood to use etc. We note that the latter two can be changed by users if desired.- luminosity, flux, flux_density, magnitude, counts, time tagged events Creating a kilonova object for at2017gfo
###Code
kne = 'at2017gfo'
kilonova = redback.kilonova.Kilonova.from_open_access_catalogue(
name=kne, data_mode="flux_density", active_bands=np.array(["g", "i"]))
kilonova.plot_data(save=False, plot_others=False)
###Output
_____no_output_____
###Markdown
Here we created the kilonova transient object using the open access catalogue data, with the `data mode == 'flux_density'`. Here we have also specified `active_bands=np.array(['g', 'i')`, which sets the rest of the data to be inactive, i.e., not used in the fitting. All bands/frequencies are active by default. The function returns the axes so user can change the ylim etc from the default themselves as they would for any other matplotlib plot. Or pass it into the function as a keyword argument
###Code
kilonova = redback.kilonova.Kilonova.from_open_access_catalogue(
name=kne, data_mode="magnitude", active_bands=np.array(["g", "i", "r", "z"]))
ax = kilonova.plot_data(save=False, show=False, plot_others=True)
ax.set_ylim(25,16)
plt.show()
kilonova = redback.kilonova.Kilonova.from_open_access_catalogue(
name=kne, data_mode="magnitude", active_bands=np.array(["g", "i", "r", "z"]))
ax = kilonova.plot_data(save=False, show=False, plot_others=False, xlim_high=10)
###Output
_____no_output_____
###Markdown
Many other plotting aesthetic things can just be passed into the function. We also provide a simple plot_multiband method. Which will plot one band per panel.
###Code
fig, axes = plt.subplots(3, 2, sharex=True, sharey=True, figsize=(12, 8))
ax = kilonova.plot_multiband(figure=fig, axes=axes,
filters=["g", "r", "i", "z", "y", "J"], save=False)
###Output
_____no_output_____
###Markdown
Here we also passed in our own constructred figure and axes to get the exact look. If you dont pass these in redback will figure it out on its own. Again, the axes are returned so users can also tinker with the plot further. Or pass things as keyword arguments in the function. We can do the same thing with afterglows, supernovae, tde's etc etc
###Code
afterglow = redback.afterglow.SGRB.from_swift_grb(name=GRB, data_mode='flux',
truncate=True, truncate_method="prompt_time_error")
afterglow.analytical_flux_to_luminosity()
ax = afterglow.plot_data()
###Output
This GRB has no measured redshift, using default z = 0.75
###Markdown
We can also plot/fit data in time in MJD, for scenario's when you don't know the true burst start time. This is done via using `use_phase_model=True`. When we get to fitting, this flag will ensure we use the right data and also infer the start time of the transient.
###Code
supernova = redback.supernova.Supernova.from_open_access_catalogue(name=sne, data_mode='flux_density',
use_phase_model=True)
ax = supernova.plot_multiband(filters=["J", "H", "g", "i"])
###Output
_____no_output_____
###Markdown
Sometimes the user may have their own data that they simulated or was their own private data. All redback transient objects can be constructed by just passing in the relevant properties. Enabling the same functionality as above (and to use in fitting..)
###Code
data = pd.read_csv('example_data/grb_afterglow.csv')
data['band'] = 'x'
data['band'].iloc[data['frequency'] == 2.418000e+17] = 'X-ray'
data['band'].iloc[data['frequency'] == 3.000000e+09] = 'Radio 3 GHz'
data['band'].iloc[data['frequency'] == 6.000000e+09] = 'Radio 6 GHz'
data['band'].iloc[data['frequency'] == 5.090000e+14] = 'V'
data['band'].iloc[data['frequency'] == 3.730000e+14] = 'i'
time_d = data['time'].values
flux_density = data['flux'].values
frequency = data['frequency'].values
flux_density_err = data['flux_err'].values
bands = data['band'].values
data_mode = 'flux_density'
name = '170817A'
afterglow = redback.transient.Afterglow(
name=name, data_mode=data_mode, time=time_d,
flux_density=flux_density, flux_density_err=flux_density_err, frequency=frequency, bands=bands)
ax = afterglow.plot_data()
###Output
Meta data does not exist for this event.
###Markdown
Like all other plots users can change things like plot labels, limits etc etc either by passing in a keyword argument or by modifying the axes of the plot.
###Code
afterglow = redback.transient.Afterglow(
name=name, data_mode=data_mode, time=time_d,
flux_density=flux_density, flux_density_err=flux_density_err, frequency=frequency)
ax = afterglow.plot_multiband()
###Output
Meta data does not exist for this event.
###Markdown
We could also simulate the observations ourselves, then load each set of observations into a transient object and then do inference!! To simulate observations, we need a model. In redback we have already implemented a lot of different models, which can be combined or modified to create another model easily. These models range from phenomenological, to analytical, semi-analytical to numerical surrogates built with machine learning techniques. Implementing a new model is probably the easiest way to contribute to redback! Specifically, the models already included are Afterglow models:- Several structured jet models implemented in afterglowpy.- Tophat jet implemented in afterglowpy.- Cocoon- Kilonova afterglow- Surrogate built on top of jetfit.- Surrogate built on top of boxfit. Kilonova models- One/two/three component kilonova models- two_layer_stratified_kilonova- power_law_stratified_kilonova- kilonova heating rate- ejecta_relation_kilonova_model- Metzger 2017- Surrogates of several different numerical simulations- All kilonova models in gwemlightcurves Supernova models- Arnett- CSM- CSM + Ni- Basic magnetar powered- General magnetar powered- Supernova 1A- Supernova 1C- SNcosmo- magnetar + nickel- SLSN- exponential powerlaw Magnetar driven ejecta models- Metzger magnetar driven kilonova- Mergernova- Trapped magnetar- General magnetar driven kilonova Millisecond magnetar models- vacuum dipole magnetar- magnetar with variable braking index- evolving magnetar- magnetar with radiative losses- collapsing magnetar- piecewise magnetar Tidal disruption models- Simple analytic fallback- Surrogate from numerical simulation Phenomenological/fireball models/other exotica- Fast blue optical transients- Skew gaussian- Skew exponential - fred- fred_extended- Gaussian- 1-6 component piecewise power law- exponential_powerlaw We note that these models can output in flux_density or magnitude set by the keyword argument output_format or using the appropriate bolometric/flux function. Alongside these models we also include some general models which can many of the above models as a base_model- Homologous expansion- Thin shell- Extinction models- Phase models- Phase + extinction models- Gaussian process base model: Will be soon implemented. You can also make several modifications to all models using dependency injections or switches For a full up to date list of models implemented in redback, look at the [API](https://redback.readthedocs.io/en/latest/index.html) All models in redback are implemented as simple functions that do not require any other redback infrastructure. They can be used to simulate populations, get a sense of the impact of different parameters, or for debugging.
###Code
from redback.constants import day_to_s
from redback.model_library import all_models_dict
model = 'arnett_bolometric'
function = all_models_dict[model]
time = np.logspace(2, 8, 100)/day_to_s
bolometric_luminosity = function(time, f_nickel=0.2,
mej=30, vej=10000, kappa=2, kappa_gamma=1e2)
plt.loglog(time, bolometric_luminosity)
plt.xlabel('Time [days]')
plt.ylabel(r'$L_{\rm bol}$')
###Output
_____no_output_____
###Markdown
Every function is documented, describing what the inputs are; their units etc etc. For some models we have also implemented a simple way to get a link to the paper describing it which provides further details. 
###Code
print(function.citation)
###Output
https://ui.adsabs.harvard.edu/abs/1982ApJ...253..785A/abstract
###Markdown
We can also simulate an entire population by creating a population prior (what distribution each of the parameters for the entire population are drawn from) and simulate lightcurves for all of them. This does not capture realistic survey features e.g., cadence but that can be easily incorporated. Redback uses bilby for priors and there are plenty to choose from.Analytical priors-------------------------- Beta- Categorical- Cauchy- ChiSquared- Cosine- DeltaFunction- Exponential- FermiDirac- Gamma- Gaussian- HalfGaussian- LogGaussian- LogUniform- Logistic- Lorentzian- PowerLaw- Sine- StudentT- SymmetricLogUniform- TruncatedGaussian- UniformInterpolated or from file-------------------------Users can also create a prior from a grid of values i.e., an interpolated_prior.See documentation [here](https://lscsoft.docs.ligo.org/bilby/api/bilby.core.prior.interpolated.Interped.htmlbilby.core.prior.interpolated.Interped). Every function has a default prior which can be loaded via
###Code
priors = redback.priors.get_priors(model=model)
priors
###Output
_____no_output_____
###Markdown
This prior object is essentially a dictionary of the different priors describing the shape, range, latex labels and units of each of the parameters. You can overwrite any of the priors as you would a standard python dictionary
###Code
priors['f_nickel'] = 0.5
###Output
_____no_output_____
###Markdown
We can sample randomly from the prior to create fake lightcurves
###Code
samples = priors.sample(100)
samples = pd.DataFrame(samples)
samples
###Output
_____no_output_____
###Markdown
We can place complex constraints on our prior to mimic a realistic survey. Say for example I wanted to create a population where none of the population was dimmer than 24th mag at peak in the r mag and that the peak was less than 50 days.
###Code
def brightness_constraint(parameters):
"""
Ensure the Supernova is not dimmer than 24th Mag at peak and that the peak is at less than 50 days.
"""
converted_parameters = parameters.copy()
converted_parameters = pd.DataFrame(converted_parameters)
kwargs = {}
kwargs['frequency'] = redback.utils.bands_to_frequency('r')
kwargs['output_format'] = 'magnitude'
tdays = np.logspace(2, 7, 50)/day_to_s
mags = np.zeros(len(converted_parameters))
peak_t = np.zeros(len(converted_parameters))
for x in range(len(mags)):
mag = function(tdays, **converted_parameters.iloc[x], **kwargs)
mags[x] = np.min(mag)
peak_t[x] = tdays[np.argmax(mag)]
converted_parameters['peak_constraint'] = 24 - mags
converted_parameters['peak_time'] = 50 - peak_t
return converted_parameters
model = 'arnett'
function = all_models_dict[model]
priors = PriorDict(conversion_function=brightness_constraint)
priors['peak_constraint'] = bilby.core.prior.Constraint(0, 10)
priors['peak_time'] = bilby.core.prior.Constraint(0, 10)
priors.update(redback.priors.get_priors(model))
priors['redshift'] = 0.5
population_samples = pd.DataFrame(priors.sample(50))
###Output
_____no_output_____
###Markdown
We can now go through and create r band lightcurves for all of them. We can also similarly create light curves for any other filter. You can also use your own model as the 'engine'.
###Code
for x in range(len(population_samples)):
tdays = np.logspace(2, 7, 50)/day_to_s
kwargs = {}
kwargs['frequency'] = redback.utils.bands_to_frequency('r')
kwargs['output_format'] = 'magnitude'
mags = function(tdays, **population_samples.iloc[x], **kwargs)
plt.semilogx(tdays, mags, 'C0o', c='red')
plt.gca().invert_yaxis()
plt.xlabel('Time [days]')
plt.ylabel('Magnitude')
plt.xlim(1e-3,40)
plt.ylim(35, 16)
###Output
_____no_output_____
###Markdown
With stuff about data/priors out of the way. Let's now turn to the primary purpose of redback: fitting. Redback workflow for fitting- Download the data from a public catalog, or provide your own data. Or simulate it.- Load the data into a homogenous transient object, which does the necessary processing and provides simple way to plot data.- Specify a model (either already implemented in redback or their own function).- Write a prior or use the default priors. - every model has default priors already implemented - place constraints on the prior if necessary. These could be constraints related to the region the model is physical/something about the observation/non detections (this is one way but there are others), or where a numerical surrogate is trained on etc. - Specify a sampler and sampler settings as in bilby- Fit model!- The fit returns a homogenous result object, which can be used for further diagnostics, and provides a simple way to plot the fit. The examples provide more detailed complicated examples of fitting different transients. Here in the interest of both time and reduce complexity; I'll show a really simple/fast example.
###Code
# first specify some basic sampler settings, model name, transient name etc etc
model = 'evolving_magnetar'
GRB = '070809'
# number of live points. Lower is faster but worse. Higher is slower but more reliable.
nlive = 500
sampler = 'nestle'
#download the data
data = redback.get_data.get_bat_xrt_afterglow_data_from_swift(grb=GRB, data_mode="flux")
# create the afterglow object;
# truncate the data using the prompt_time_error method to get rid of
# any erronous BAT data points not belonging to the transient.
afterglow = redback.afterglow.SGRB.from_swift_grb(name=GRB, data_mode='flux',
truncate=True, truncate_method="prompt_time_error")
# convert flux data to luminosity using an analytical approximation.
# We could also use a numerical method utilising CIAO/Sherpa and the spectrum.
afterglow.analytical_flux_to_luminosity()
# load the default priors for the model
priors = redback.priors.get_priors(model=model)
result = redback.fit_model(model=model, sampler=sampler, nlive=nlive, transient=afterglow,
prior=priors, sample='rslice', resume=True)
###Output
You are downloading BAT and XRT data, you will need to truncate the data for some models.
The raw data file already exists. Returning.
The processed data file already exists. Returning.
This GRB has no measured redshift, using default z = 0.75
###Markdown
The fitting will print out a bunch of things which are helpful diagnostics and indicate how things are processing, what settings are used and when things will finish. Most samplers have checkpointing so if for some reason your computer crashes/supercomputer goes down; progress is not lost. The fitting returns a result object which has a lot of different attributes and methods allowing further diagnostics. A dataframe of the posterior values
###Code
result.posterior
###Output
_____no_output_____
###Markdown
Other metadata/methods
###Code
print(result.log_evidence)
print(result.log_evidence_err)
print(result.bayesian_model_dimensionality)
print(result.covariance_matrix)
print(result.information_gain)
print(result.max_autocorrelation_time)
print(result.transient)
print(result.transient_type)
print(result.occam_factor(result.priors))
###Output
341.4049521126413
0.1569401395404265
5.332259505346883
[[ 3.77608615e+27 -4.85316474e+13 -8.12376950e+08 2.42308125e+12
-1.21373390e+11 -8.20115760e+11 -9.55496925e+12 6.05234874e+57]
[-4.85316474e+13 4.36597365e+00 2.18957537e-04 -9.84469764e-02
5.90934315e-02 3.40676202e-02 6.97126854e-01 -4.72740715e+43]
[-8.12376950e+08 2.18957537e-04 7.13818561e-06 5.22664033e-03
1.07915077e-05 2.25651424e-04 -2.17977677e-03 4.36696955e+42]
[ 2.42308125e+12 -9.84469764e-02 5.22664033e-03 4.10986833e+00
6.65932888e-02 7.90132496e-02 -1.44701469e+00 3.81991879e+45]
[-1.21373390e+11 5.90934315e-02 1.07915077e-05 6.65932888e-02
8.02862695e+00 -3.23181630e-02 1.10807489e+00 1.98916313e+44]
[-8.20115760e+11 3.40676202e-02 2.25651424e-04 7.90132496e-02
-3.23181630e-02 5.35439041e-02 2.88556759e-02 -1.45540497e+44]
[-9.55496925e+12 6.97126854e-01 -2.17977677e-03 -1.44701469e+00
1.10807489e+00 2.88556759e-02 7.56376177e+02 -2.07322763e+45]
[ 6.05234874e+57 -4.72740715e+43 4.36696955e+42 3.81991879e+45
1.98916313e+44 -1.45540497e+44 -2.07322763e+45 5.18408768e+90]]
12.315103699484268
None
<redback.transient.afterglow.SGRB object at 0x7fd466346ca0>
sgrb
2.918842967871632e-21
###Markdown
Plotting methods
###Code
result.plot_corner(parameters=['p0', 'muinf', 'mu0', 'alpha_1', 'tm'], save=False, priors=True)
plt.show()
result.plot_lightcurve(random_models=100)
###Output
_____no_output_____
###Markdown
Method to plot multiband lightcurve; 1 band/frequency on each panel with fit going through them.`result.plot_multiband_lightcurve` Method to plot the transient data; i.e., same thing as the transient object plot_data and plot_multiband.`result.plot_data``result.plot_multiband` Method to plot the CDF and PDF of all parameters/log_likelihood and log_prior`result.plot_marginals` Method to plot the walkers if using an MCMC sampler `result.plot_walkers` Other result features- Reweighting to a different prior/model.- Changing formats; creating an arviz result object.- Making pp plots for a population- Hierarchical inference/recycling functionality.
###Code
redback.utils.calc_one_dimensional_median_and_error_bar(result.posterior['alpha_1'],
quantiles=(0.16,0.84), fmt='.2f').string
###Output
_____no_output_____
###Markdown
You can also load a result file from different analyses enabling the same functionality as above.
###Code
path = 'GRBData/afterglow/luminosity/evolving_magnetar/GRB070809_result.json'
my_result = redback.result.read_in_result(path)
###Output
_____no_output_____ |
Nutanix Interview/4. candies.ipynb | ###Markdown
Alice is a kindergarten teacher. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her performance in the class. Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to minimize the total number of candies she must buy.**Example** arr = [4,6,4,5,6,2]She gives the students candy in the following minimal amounts: [1,2,1,2,3,1]. She must buy a minimum of 10 candies.**Function Description**Complete the candies function in the editor below.candies has the following parameter(s): int n: the number of children in the class int arr[n]: the ratings of each student**Returns** int: the minimum number of candies Alice must buy
###Code
def get_minimum_candies(candy, ratings, k):
if k == 0:
return 0
for i in range(1, k):
c = candy[i]
left = ratings[i - 1]
mid = ratings[i]
right = ratings[i + 1]
if left < mid <= right:
c = candy[i - 1] + 1
elif left < mid and mid > right:
c = candy[i - 1] + 1
elif left > mid:
j = i
while i > 0 and ratings[j - 1] > ratings[j]:
candy[j - 1] = max(candy[j - 1], candy[j] + 1)
j -= 1
elif left == mid or mid == right:
c = 1
candy[i] = c
return candy
if __name__ == '__main__':
n = int(input())
ratings = []
candy = [1 for j in range(0, n + 1)]
for x in range(0, n):
rating = int(input())
ratings.append(rating)
ratings.append(0)
print(sum(get_minimum_candies(candy, ratings, n)) - 1)
###Output
_____no_output_____ |
demos/image-classification/02-infer.ipynb | ###Markdown
Create and Test a Model-Serving Nuclio FunctionThis notebook demonstrates how to write an inference server, test it, and turn it into an auto-scaling Nuclio serverless function.- [Initialize Nuclio Emulation, Environment Variables, and Configuration](image-class-infer-init-func)- [Create and Load the Model and Set Up the Function Handler](image-class-infer-create-n-load-model-n-set-up-func-handler)- [Trigger the Function](image-class-infer-func-trigger)- [Prepare to Deploy the Function](image-class-infer-func-deploy-prepare)- [Deploy the Function](image-class-infer-func-deploy)- [Test the Function](image-class-infer-func-test) Initialize Nuclio Emulation, Environment Variables, and Configuration> **Note:** Use ` nuclio: ignore` for sections that dont need to be copied to the function.
###Code
# nuclio: ignore
import nuclio
import random
import matplotlib.pyplot as plt
%%nuclio env
IMAGE_WIDTH = 128
IMAGE_HEIGHT = 128
version = 1.0
%nuclio env -c MODEL_PATH=/model/
%nuclio env -l MODEL_PATH=./model/
%%nuclio cmd -c
pip install git+https://github.com/fchollet/keras
pip install tensorflow
pip install numpy
pip install requests
pip install pillow
%%nuclio config
spec.build.baseImage = "python:3.6-jessie"
%nuclio mount /model ~/image-classification/cats_dogs/model
###Output
mounting volume path /model as ~/image-classification/cats_dogs/model
###Markdown
Create and Load the Model and Set Up the Function Handler
###Code
import numpy as np
from tensorflow import keras
from keras.models import load_model
from keras.preprocessing import image
from keras.preprocessing.image import load_img
import json
import requests
import os
from os import environ, path
from tempfile import mktemp
model_file = environ['MODEL_PATH'] + 'cats_dogs.hd5'
prediction_map_file = environ['MODEL_PATH'] + 'prediction_classes_map.json'
# Set image parameters
IMAGE_WIDTH = int(environ['IMAGE_WIDTH'])
IMAGE_HEIGHT = int(environ['IMAGE_HEIGHT'])
# load model
def init_context(context):
context.model = load_model(model_file)
with open(prediction_map_file, 'r') as f:
context.prediction_map = json.load(f)
def download_file(context, url, target_path):
with requests.get(url, stream=True) as response:
response.raise_for_status()
with open(target_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
context.logger.info_with('Downloaded file',url=url)
def handler(context, event):
tmp_file = mktemp()
image_url = event.body.decode('utf-8').strip()
download_file(context, image_url, tmp_file)
img = load_img(tmp_file, target_size=(IMAGE_WIDTH, IMAGE_HEIGHT))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
predicted_probability = context.model.predict_proba(images, batch_size=10)
predicted_class = list(zip(predicted_probability, map(lambda x: '1' if x >= 0.5 else '0', predicted_probability)))
actual_class = [(context.prediction_map[x[1]],x[0][0]) for x in predicted_class]
os.remove(tmp_file)
result = {'class':actual_class[0][0], 'dog-probability':float(actual_class[0][1])}
return json.dumps(result)
###Output
_____no_output_____
###Markdown
Trigger the Function
###Code
# nuclio: ignore
init_context(context)
# nuclio: ignore
# Select a sample for the test.
# Set both the local path for the test and the URL for downloading the sample from AWS S3.
DATA_LOCATION = "./cats_and_dogs_filtered/"
sample = random.choice(os.listdir(DATA_LOCATION+"/cats_n_dogs"))
image_local = DATA_LOCATION + "cats_n_dogs/"+sample # Temporary location for downloading the file
image_url = 'https://s3.amazonaws.com/iguazio-sample-data/images/catanddog/' + sample
# Show the image
img = load_img(image_local, target_size=(IMAGE_WIDTH, IMAGE_HEIGHT))
plt.imshow(img)
event = nuclio.Event(body=bytes(image_url, 'utf-8'))
output = handler(context, event)
print(output)
%nuclio show
###Output
%nuclio: notebook exported to /tmp/tmpzj2aeznv/infer.yaml
Code:
# Generated by nuclio.export.NuclioExporter on 2019-03-25 11:51
import numpy as np
from tensorflow import keras
from keras.models import load_model
from keras.preprocessing import image
from keras.preprocessing.image import load_img
import json
import requests
import os
from os import environ, path
from tempfile import mktemp
model_file = environ['MODEL_PATH'] + 'cats_dogs.hd5'
prediction_map_file = environ['MODEL_PATH'] + 'prediction_classes_map.json'
IMAGE_WIDTH = int(environ['IMAGE_WIDTH'])
IMAGE_HEIGHT = int(environ['IMAGE_HEIGHT'])
def init_context(context):
context.model = load_model(model_file)
with open(prediction_map_file, 'r') as f:
context.prediction_map = json.load(f)
def download_file(context, url, target_path):
with requests.get(url, stream=True) as response:
response.raise_for_status()
with open(target_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
context.logger.info_with('Downloaded file',url=url)
def handler(context, event):
tmp_file = mktemp()
image_url = event.body.decode('utf-8').strip()
download_file(context, image_url, tmp_file)
img = load_img(tmp_file, target_size=(IMAGE_WIDTH, IMAGE_HEIGHT))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
predicted_probability = context.model.predict_proba(images, batch_size=10)
predicted_class = list(zip(predicted_probability, map(lambda x: '1' if x >= 0.5 else '0', predicted_probability)))
actual_class = [(context.prediction_map[x[1]],x[0][0]) for x in predicted_class]
os.remove(tmp_file)
result = {'class':actual_class[0][0], 'dog-probability':float(actual_class[0][1])}
return json.dumps(result)
Config:
apiVersion: nuclio.io/v1
kind: Function
metadata:
name: infer
spec:
build:
baseImage: python:3.6-jessie
commands:
- pip install git+https://github.com/fchollet/keras
- pip install tensorflow
- pip install numpy
- pip install requests
- pip install pillow
noBaseImagesPull: true
env:
- name: IMAGE_WIDTH
value: '128'
- name: IMAGE_HEIGHT
value: '128'
- name: version
value: '1.0'
- name: MODEL_PATH
value: /model/
handler: handler:handler
runtime: python:3.6
volumes:
- volume:
flexVolume:
driver: v3io/fuse
options:
accessKey: ad348937-7359-48e8-8f68-8014c66f2d2c
container: users
subPath: /iguazio/image-classification/cats_dogs/model
name: fs
volumeMount:
mountPath: /model
name: fs
###Markdown
Prepare to Deploy the FunctionBefore you deploy the function, open a Jupyter terminal and run the following command:`pip install --upgrade nuclio-jupyter` Deploy the FunctionRun the following command to deploy the function:
###Code
%nuclio deploy -n cats-dogs -p ai -c
###Output
_____no_output_____
###Markdown
Test the Function
###Code
# Run a test with the new function. Replace the "function URL:port" with the actual URL and port number.
# To get the function's URL, in the platform dashboard navigate to the function page -
# Functions> ai > cats-dogs - and select the Status tab.
!curl -X POST -d "https://s3.amazonaws.com/iguazio-sample-data/images/catanddog/cat.123.jpg" <function URL:port>
###Output
_____no_output_____
###Markdown
Create and Test a Model-Serving Nuclio FunctionThis notebook demonstrates how to write an inference server, test it, and turn it into an auto-scaling Nuclio serverless function.- [Initialize Nuclio Emulation, Environment Variables, and Configuration](image-class-infer-init-func)- [Create and Load the Model and Set Up the Function Handler](image-class-infer-create-n-load-model-n-set-up-func-handler)- [Trigger the Function](image-class-infer-func-trigger)- [Prepare to Deploy the Function](image-class-infer-func-deploy-prepare)- [Deploy the Function](image-class-infer-func-deploy)- [Test the Function](image-class-infer-func-test) Initialize Nuclio Emulation, Environment Variables, and Configuration> **Note:** Use ` nuclio: ignore` for sections that dont need to be copied to the function.
###Code
# nuclio: ignore
import nuclio
import random
import matplotlib.pyplot as plt
import os
# DB Config
%nuclio env %v3io
# Function Config
%nuclio env -c MODEL_PATH=/model/
%nuclio env -l MODEL_PATH=./model/
%nuclio env MODEL_FILE = cats_dogs.hd5
%nuclio env CLASSES_MAP = prediction_classes_map.json
%nuclio env version = 1.0
# Input Config
%nuclio env IMAGE_WIDTH = 128
%nuclio env IMAGE_HEIGHT = 128
# TF silence deprecated warning
%nuclio env TF_CPP_MIN_LOG_LEVEL = 3
%%nuclio cmd -c
pip install git+https://github.com/fchollet/keras
pip install tensorflow
pip install numpy
pip install requests
pip install pillow
%%nuclio config
spec.build.baseImage = "python:3.6-jessie"
%nuclio mount /model ~/demos/image-classification/model
###Output
mounting volume path /model as ~/demos/image-classification/model
###Markdown
Create and Load the Model and Set Up the Function Handler
###Code
import numpy as np
from tensorflow import keras
from keras.models import load_model
from keras.preprocessing import image
from keras.preprocessing.image import load_img
import json
import requests
import os
from os import environ, path
from tempfile import mktemp
model_file = os.path.join(environ['MODEL_PATH'], environ['MODEL_FILE'])
prediction_map_file = os.path.join(environ['MODEL_PATH'], environ['CLASSES_MAP'])
# Set image parameters
IMAGE_WIDTH = int(environ['IMAGE_WIDTH'])
IMAGE_HEIGHT = int(environ['IMAGE_HEIGHT'])
# load model
def init_context(context):
context.model = load_model(model_file)
with open(prediction_map_file, 'r') as f:
context.prediction_map = json.load(f)
def download_file(context, url, target_path):
with requests.get(url, stream=True) as response:
response.raise_for_status()
with open(target_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
context.logger.info_with('Downloaded file',url=url)
def handler(context, event):
tmp_file = mktemp()
image_url = event.body.decode('utf-8').strip()
download_file(context, image_url, tmp_file)
img = load_img(tmp_file, target_size=(IMAGE_WIDTH, IMAGE_HEIGHT))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
predicted_probability = context.model.predict_proba(images, batch_size=10)
predicted_class = list(zip(predicted_probability, map(lambda x: '1' if x >= 0.5 else '0', predicted_probability)))
actual_class = [(context.prediction_map[x[1]],x[0][0]) for x in predicted_class]
os.remove(tmp_file)
result = {'class':actual_class[0][0], 'dog-probability':float(actual_class[0][1])}
return json.dumps(result)
###Output
_____no_output_____
###Markdown
Trigger the Function
###Code
# nuclio: ignore
init_context(context)
# nuclio: ignore
# Select a sample for the test.
# Set both the local path for the test and the URL for downloading the sample from AWS S3.
DATA_LOCATION = "./cats_and_dogs_filtered/"
sample = random.choice(os.listdir(DATA_LOCATION+"/cats_n_dogs"))
image_local = DATA_LOCATION + "cats_n_dogs/"+sample # Temporary location for downloading the file
image_url = 'https://s3.amazonaws.com/iguazio-sample-data/images/catanddog/' + sample
# Show the image
img = load_img(image_local, target_size=(IMAGE_WIDTH, IMAGE_HEIGHT))
plt.imshow(img)
event = nuclio.Event(body=bytes(image_url, 'utf-8'))
output = handler(context, event)
print(output)
%nuclio show
###Output
%nuclio: notebook 02-infer exported
Config:
apiVersion: nuclio.io/v1
kind: Function
metadata:
annotations:
nuclio.io/generated_by: function generated at 18-09-2019 by iguazio from /User/demos/image-classification/02-infer.ipynb
labels: {}
name: 02-infer
spec:
build:
baseImage: python:3.6-jessie
commands:
- pip install git+https://github.com/fchollet/keras
- pip install tensorflow
- pip install numpy
- pip install requests
- pip install pillow
functionSourceCode: IyBHZW5lcmF0ZWQgYnkgbnVjbGlvLmV4cG9ydC5OdWNsaW9FeHBvcnRlciBvbiAyMDE5LTA5LTE4IDEwOjQ0CgoKCgoKCgppbXBvcnQgbnVtcHkgYXMgbnAgCmZyb20gdGVuc29yZmxvdyBpbXBvcnQga2VyYXMKZnJvbSBrZXJhcy5tb2RlbHMgaW1wb3J0IGxvYWRfbW9kZWwKZnJvbSBrZXJhcy5wcmVwcm9jZXNzaW5nIGltcG9ydCBpbWFnZQpmcm9tIGtlcmFzLnByZXByb2Nlc3NpbmcuaW1hZ2UgaW1wb3J0IGxvYWRfaW1nCmltcG9ydCBqc29uCmltcG9ydCByZXF1ZXN0cwoKaW1wb3J0IG9zCmZyb20gb3MgaW1wb3J0IGVudmlyb24sIHBhdGgKZnJvbSB0ZW1wZmlsZSBpbXBvcnQgbWt0ZW1wCgptb2RlbF9maWxlID0gb3MucGF0aC5qb2luKGVudmlyb25bJ01PREVMX1BBVEgnXSwgZW52aXJvblsnTU9ERUxfRklMRSddKQpwcmVkaWN0aW9uX21hcF9maWxlID0gb3MucGF0aC5qb2luKGVudmlyb25bJ01PREVMX1BBVEgnXSwgZW52aXJvblsnQ0xBU1NFU19NQVAnXSkKCklNQUdFX1dJRFRIID0gaW50KGVudmlyb25bJ0lNQUdFX1dJRFRIJ10pCklNQUdFX0hFSUdIVCA9IGludChlbnZpcm9uWydJTUFHRV9IRUlHSFQnXSkKCmRlZiBpbml0X2NvbnRleHQoY29udGV4dCk6IAogICAgY29udGV4dC5tb2RlbCA9IGxvYWRfbW9kZWwobW9kZWxfZmlsZSkKICAgIHdpdGggb3BlbihwcmVkaWN0aW9uX21hcF9maWxlLCAncicpIGFzIGY6CiAgICAgICAgY29udGV4dC5wcmVkaWN0aW9uX21hcCA9IGpzb24ubG9hZChmKQoKZGVmIGRvd25sb2FkX2ZpbGUoY29udGV4dCwgdXJsLCB0YXJnZXRfcGF0aCk6CiAgICB3aXRoIHJlcXVlc3RzLmdldCh1cmwsIHN0cmVhbT1UcnVlKSBhcyByZXNwb25zZToKICAgICAgICByZXNwb25zZS5yYWlzZV9mb3Jfc3RhdHVzKCkKICAgICAgICB3aXRoIG9wZW4odGFyZ2V0X3BhdGgsICd3YicpIGFzIGY6CiAgICAgICAgICAgIGZvciBjaHVuayBpbiByZXNwb25zZS5pdGVyX2NvbnRlbnQoY2h1bmtfc2l6ZT04MTkyKToKICAgICAgICAgICAgICAgIGlmIGNodW5rOgogICAgICAgICAgICAgICAgICAgIGYud3JpdGUoY2h1bmspCgogICAgY29udGV4dC5sb2dnZXIuaW5mb193aXRoKCdEb3dubG9hZGVkIGZpbGUnLHVybD11cmwpCgpkZWYgaGFuZGxlcihjb250ZXh0LCBldmVudCk6CiAgICB0bXBfZmlsZSA9IG1rdGVtcCgpCiAgICBpbWFnZV91cmwgPSBldmVudC5ib2R5LmRlY29kZSgndXRmLTgnKS5zdHJpcCgpCiAgICBkb3dubG9hZF9maWxlKGNvbnRleHQsIGltYWdlX3VybCwgdG1wX2ZpbGUpCiAgICAKICAgIGltZyA9IGxvYWRfaW1nKHRtcF9maWxlLCB0YXJnZXRfc2l6ZT0oSU1BR0VfV0lEVEgsIElNQUdFX0hFSUdIVCkpCiAgICB4ID0gaW1hZ2UuaW1nX3RvX2FycmF5KGltZykKICAgIHggPSBucC5leHBhbmRfZGltcyh4LCBheGlzPTApCgogICAgaW1hZ2VzID0gbnAudnN0YWNrKFt4XSkKICAgIHByZWRpY3RlZF9wcm9iYWJpbGl0eSA9IGNvbnRleHQubW9kZWwucHJlZGljdF9wcm9iYShpbWFnZXMsIGJhdGNoX3NpemU9MTApCiAgICBwcmVkaWN0ZWRfY2xhc3MgPSBsaXN0KHppcChwcmVkaWN0ZWRfcHJvYmFiaWxpdHksIG1hcChsYW1iZGEgeDogJzEnIGlmIHggPj0gMC41IGVsc2UgJzAnLCBwcmVkaWN0ZWRfcHJvYmFiaWxpdHkpKSkKICAgIGFjdHVhbF9jbGFzcyA9IFsoY29udGV4dC5wcmVkaWN0aW9uX21hcFt4WzFdXSx4WzBdWzBdKSBmb3IgeCBpbiBwcmVkaWN0ZWRfY2xhc3NdICAgCiAgICBvcy5yZW1vdmUodG1wX2ZpbGUpCiAgICByZXN1bHQgPSB7J2NsYXNzJzphY3R1YWxfY2xhc3NbMF1bMF0sICdkb2ctcHJvYmFiaWxpdHknOmZsb2F0KGFjdHVhbF9jbGFzc1swXVsxXSl9CiAgICByZXR1cm4ganNvbi5kdW1wcyhyZXN1bHQpCgo=
noBaseImagesPull: true
env:
- name: V3IO_FRAMESD
value: framesd.default-tenant.svc:8080
- name: V3IO_USERNAME
value: iguazio
- name: V3IO_ACCESS_KEY
value: bd182781-6b24-4899-b2b7-a84608931aeb
- name: V3IO_API
value: v3io-webapi.default-tenant.svc:8081
- name: MODEL_PATH
value: /model/
- name: MODEL_FILE
value: cats_dogs.hd5
- name: CLASSES_MAP
value: prediction_classes_map.json
- name: version
value: '1.0'
- name: IMAGE_WIDTH
value: '128'
- name: IMAGE_HEIGHT
value: '128'
- name: TF_CPP_MIN_LOG_LEVEL
value: '3'
handler: 02-infer:handler
runtime: python:3.6
volumes:
- volume:
flexVolume:
driver: v3io/fuse
options:
accessKey: bd182781-6b24-4899-b2b7-a84608931aeb
container: users
subPath: /iguazio/demos/image-classification/model
name: fs
volumeMount:
mountPath: /model
name: fs
Code:
# Generated by nuclio.export.NuclioExporter on 2019-09-18 10:44
import numpy as np
from tensorflow import keras
from keras.models import load_model
from keras.preprocessing import image
from keras.preprocessing.image import load_img
import json
import requests
import os
from os import environ, path
from tempfile import mktemp
model_file = os.path.join(environ['MODEL_PATH'], environ['MODEL_FILE'])
prediction_map_file = os.path.join(environ['MODEL_PATH'], environ['CLASSES_MAP'])
IMAGE_WIDTH = int(environ['IMAGE_WIDTH'])
IMAGE_HEIGHT = int(environ['IMAGE_HEIGHT'])
def init_context(context):
context.model = load_model(model_file)
with open(prediction_map_file, 'r') as f:
context.prediction_map = json.load(f)
def download_file(context, url, target_path):
with requests.get(url, stream=True) as response:
response.raise_for_status()
with open(target_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
context.logger.info_with('Downloaded file',url=url)
def handler(context, event):
tmp_file = mktemp()
image_url = event.body.decode('utf-8').strip()
download_file(context, image_url, tmp_file)
img = load_img(tmp_file, target_size=(IMAGE_WIDTH, IMAGE_HEIGHT))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
predicted_probability = context.model.predict_proba(images, batch_size=10)
predicted_class = list(zip(predicted_probability, map(lambda x: '1' if x >= 0.5 else '0', predicted_probability)))
actual_class = [(context.prediction_map[x[1]],x[0][0]) for x in predicted_class]
os.remove(tmp_file)
result = {'class':actual_class[0][0], 'dog-probability':float(actual_class[0][1])}
return json.dumps(result)
###Markdown
Prepare to Deploy the FunctionBefore you deploy the function, open a Jupyter terminal and run the following command:`pip install --upgrade nuclio-jupyter` Deploy the FunctionRun the following command to deploy the function:
###Code
%nuclio deploy -n cats-dogs -p ai -c
###Output
[nuclio.deploy] 2019-09-18 10:45:19,498 (info) Building processor image
[nuclio.deploy] 2019-09-18 10:45:26,663 (info) Pushing image
[nuclio.deploy] 2019-09-18 10:45:26,665 (info) Build complete
[nuclio.deploy] 2019-09-18 10:45:36,884 (info) Function deploy complete
[nuclio.deploy] 2019-09-18 10:45:36,899 done updating cats-dogs, function address: 18.219.68.129:32141
%nuclio: function deployed
###Markdown
Test the Function
###Code
# nuclio: ignore
# Run a test with the new function. Replace the "function URL:port" with the actual URL and port number.
# To get the function's URL, in the platform dashboard navigate to the function page -
# Functions> ai > cats-dogs - and select the Status tab.
!curl -X POST -d "https://s3.amazonaws.com/iguazio-sample-data/images/catanddog/cat.123.jpg" <function URL:port>
###Output
{"class": "dog", "dog-probability": 0.6951420307159424}
###Markdown
Create and Test a Model-Serving Nuclio FunctionThis notebook demonstrates how to write an inference server, test it, and turn it into an auto-scaling Nuclio serverless function.- [Initialize Nuclio Emulation, Environment Variables, and Configuration](image-class-infer-init-func)- [Create and Load the Model and Set Up the Function Handler](image-class-infer-create-n-load-model-n-set-up-func-handler)- [Trigger the Function](image-class-infer-func-trigger)- [Prepare to Deploy the Function](image-class-infer-func-deploy-prepare)- [Deploy the Function](image-class-infer-func-deploy)- [Test the Function](image-class-infer-func-test) Initialize Nuclio Emulation, Environment Variables, and Configuration> **Note:** Use ` nuclio: ignore` for sections that dont need to be copied to the function.
###Code
# nuclio: ignore
import nuclio
import random
import matplotlib.pyplot as plt
%%nuclio env
IMAGE_WIDTH = 128
IMAGE_HEIGHT = 128
version = 1.0
%nuclio env -c MODEL_PATH=/model/
%nuclio env -l MODEL_PATH=./model/
%%nuclio cmd -c
pip install git+https://github.com/fchollet/keras
pip install tensorflow
pip install numpy
pip install requests
pip install pillow
%%nuclio config
spec.build.baseImage = "python:3.6-jessie"
%nuclio mount /model ~/demos/image-classification/cats_dogs/model
###Output
mounting volume path /model as ~/image-classification/cats_dogs/model
###Markdown
Create and Load the Model and Set Up the Function Handler
###Code
import numpy as np
from tensorflow import keras
from keras.models import load_model
from keras.preprocessing import image
from keras.preprocessing.image import load_img
import json
import requests
import os
from os import environ, path
from tempfile import mktemp
model_file = environ['MODEL_PATH'] + 'cats_dogs.hd5'
prediction_map_file = environ['MODEL_PATH'] + 'prediction_classes_map.json'
# Set image parameters
IMAGE_WIDTH = int(environ['IMAGE_WIDTH'])
IMAGE_HEIGHT = int(environ['IMAGE_HEIGHT'])
# load model
def init_context(context):
context.model = load_model(model_file)
with open(prediction_map_file, 'r') as f:
context.prediction_map = json.load(f)
def download_file(context, url, target_path):
with requests.get(url, stream=True) as response:
response.raise_for_status()
with open(target_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
context.logger.info_with('Downloaded file',url=url)
def handler(context, event):
tmp_file = mktemp()
image_url = event.body.decode('utf-8').strip()
download_file(context, image_url, tmp_file)
img = load_img(tmp_file, target_size=(IMAGE_WIDTH, IMAGE_HEIGHT))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
predicted_probability = context.model.predict_proba(images, batch_size=10)
predicted_class = list(zip(predicted_probability, map(lambda x: '1' if x >= 0.5 else '0', predicted_probability)))
actual_class = [(context.prediction_map[x[1]],x[0][0]) for x in predicted_class]
os.remove(tmp_file)
result = {'class':actual_class[0][0], 'dog-probability':float(actual_class[0][1])}
return json.dumps(result)
###Output
_____no_output_____
###Markdown
Trigger the Function
###Code
# nuclio: ignore
init_context(context)
# nuclio: ignore
# Select a sample for the test.
# Set both the local path for the test and the URL for downloading the sample from AWS S3.
DATA_LOCATION = "./cats_and_dogs_filtered/"
sample = random.choice(os.listdir(DATA_LOCATION+"/cats_n_dogs"))
image_local = DATA_LOCATION + "cats_n_dogs/"+sample # Temporary location for downloading the file
image_url = 'https://s3.amazonaws.com/iguazio-sample-data/images/catanddog/' + sample
# Show the image
img = load_img(image_local, target_size=(IMAGE_WIDTH, IMAGE_HEIGHT))
plt.imshow(img)
event = nuclio.Event(body=bytes(image_url, 'utf-8'))
output = handler(context, event)
print(output)
%nuclio show
###Output
%nuclio: notebook exported to /tmp/tmpzj2aeznv/infer.yaml
Code:
# Generated by nuclio.export.NuclioExporter on 2019-03-25 11:51
import numpy as np
from tensorflow import keras
from keras.models import load_model
from keras.preprocessing import image
from keras.preprocessing.image import load_img
import json
import requests
import os
from os import environ, path
from tempfile import mktemp
model_file = environ['MODEL_PATH'] + 'cats_dogs.hd5'
prediction_map_file = environ['MODEL_PATH'] + 'prediction_classes_map.json'
IMAGE_WIDTH = int(environ['IMAGE_WIDTH'])
IMAGE_HEIGHT = int(environ['IMAGE_HEIGHT'])
def init_context(context):
context.model = load_model(model_file)
with open(prediction_map_file, 'r') as f:
context.prediction_map = json.load(f)
def download_file(context, url, target_path):
with requests.get(url, stream=True) as response:
response.raise_for_status()
with open(target_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
context.logger.info_with('Downloaded file',url=url)
def handler(context, event):
tmp_file = mktemp()
image_url = event.body.decode('utf-8').strip()
download_file(context, image_url, tmp_file)
img = load_img(tmp_file, target_size=(IMAGE_WIDTH, IMAGE_HEIGHT))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
predicted_probability = context.model.predict_proba(images, batch_size=10)
predicted_class = list(zip(predicted_probability, map(lambda x: '1' if x >= 0.5 else '0', predicted_probability)))
actual_class = [(context.prediction_map[x[1]],x[0][0]) for x in predicted_class]
os.remove(tmp_file)
result = {'class':actual_class[0][0], 'dog-probability':float(actual_class[0][1])}
return json.dumps(result)
Config:
apiVersion: nuclio.io/v1
kind: Function
metadata:
name: infer
spec:
build:
baseImage: python:3.6-jessie
commands:
- pip install git+https://github.com/fchollet/keras
- pip install tensorflow
- pip install numpy
- pip install requests
- pip install pillow
noBaseImagesPull: true
env:
- name: IMAGE_WIDTH
value: '128'
- name: IMAGE_HEIGHT
value: '128'
- name: version
value: '1.0'
- name: MODEL_PATH
value: /model/
handler: handler:handler
runtime: python:3.6
volumes:
- volume:
flexVolume:
driver: v3io/fuse
options:
accessKey: ad348937-7359-48e8-8f68-8014c66f2d2c
container: users
subPath: /iguazio/image-classification/cats_dogs/model
name: fs
volumeMount:
mountPath: /model
name: fs
###Markdown
Prepare to Deploy the FunctionBefore you deploy the function, open a Jupyter terminal and run the following command:`pip install --upgrade nuclio-jupyter` Deploy the FunctionRun the following command to deploy the function:
###Code
%nuclio deploy -n cats-dogs -p ai -c
###Output
_____no_output_____
###Markdown
Test the Function
###Code
# Run a test with the new function. Replace the "function URL:port" with the actual URL and port number.
# To get the function's URL, in the platform dashboard navigate to the function page -
# Functions> ai > cats-dogs - and select the Status tab.
!curl -X POST -d "https://s3.amazonaws.com/iguazio-sample-data/images/catanddog/cat.123.jpg" <function URL:port>
###Output
_____no_output_____ |
01_getting_started.ipynb | ###Markdown
Getting StartedThis notebook is inspired to the Stable Baselines3 tutorial available at [https://github.com/araffin/rl-tutorial-jnrr19](https://github.com/araffin/rl-tutorial-jnrr19). IntroductionIn this notebook, we will learn how to use **Open AI Gym** environments and the basics of **Stable Baselines3**: how to instance an RL algorithm, train and evaluate it. LinksOpen AI Gym Github: [https://github.com/openai/gym](https://github.com/openai/gym)Open AI Gym Documentation: [https://www.gymlibrary.ml](https://www.gymlibrary.ml)Stable Baselines 3 Github:[https://github.com/DLR-RM/stable-baselines3](https://github.com/DLR-RM/stable-baselines3)Stable Baseline 3 Documentation: [https://stable-baselines3.readthedocs.io/en/master/](https://stable-baselines3.readthedocs.io/en/master/) Install Dependencies and Stable Baselines3 Using Pip
###Code
!apt-get install ffmpeg freeglut3-dev xvfb # For visualization
!pip install stable-baselines3[extra]
import stable_baselines3
stable_baselines3.__version__
###Output
_____no_output_____
###Markdown
Video RecordingIn Google Colab it is not possible to render the Gym environments, so we need to record a video and then reproduce it. Here are the helper functions.
###Code
# Set up fake display; otherwise rendering will fail
import os
import base64
from pathlib import Path
from IPython import display as ipythondisplay
from stable_baselines3.common.vec_env import VecVideoRecorder, DummyVecEnv
os.system("Xvfb :1 -screen 0 1024x768x24 &")
os.environ['DISPLAY'] = ':1'
def show_videos(video_path='', prefix=''):
"""
Taken from https://github.com/eleurent/highway-env
:param video_path: (str) Path to the folder containing videos
:param prefix: (str) Filter the video, showing only the only starting with this prefix
"""
html = []
for mp4 in Path(video_path).glob("{}*.mp4".format(prefix)):
video_b64 = base64.b64encode(mp4.read_bytes())
html.append('''<video alt="{}" autoplay
loop controls style="height: 400px;">
<source src="data:video/mp4;base64,{}" type="video/mp4" />
</video>'''.format(mp4, video_b64.decode('ascii')))
ipythondisplay.display(ipythondisplay.HTML(data="<br>".join(html)))
def record_video(env_id, model, video_length=500, prefix='', video_folder='videos/'):
"""
:param env_id: (str)
:param model: (RL model)
:param video_length: (int)
:param prefix: (str)
:param video_folder: (str)
"""
eval_env = DummyVecEnv([lambda: gym.make(env_id)])
# Start the video at step=0 and record 500 steps
eval_env = VecVideoRecorder(eval_env, video_folder=video_folder,
record_video_trigger=lambda step: step == 0, video_length=video_length,
name_prefix=prefix)
obs = eval_env.reset()
for _ in range(video_length):
action, _ = model.predict(obs[0])
obs, _, _, _ = eval_env.step([action])
# Close the video recorder
eval_env.close()
def render(env_id, policy, video_length=500, prefix='', video_folder='videos/'):
record_video(env_id, policy, video_length, prefix, video_folder)
show_videos(video_folder, prefix)
###Output
_____no_output_____
###Markdown
PlottingA helper function to plot the learning curves.
###Code
import matplotlib.pyplot as plt
def plot_results(results):
plt.figure()
for k in results.keys():
data = np.load(results[k] + '/evaluations.npz')
ts = data['timesteps']
res = data['results']
_mean, _std = res.mean(axis=1), res.std(axis=1)
plt.plot(ts, _mean, label=k)
plt.fill_between(ts, _mean-_std, _mean+_std, alpha=.2)
plt.xlabel('Timesteps')
plt.ylabel('Average return')
plt.legend(loc='lower right')
plt.show()
###Output
_____no_output_____
###Markdown
Initializing EnvironmentsInitializing environments in Gym and is done as follows. We can find a list of available environment [here](https://gym.openai.com/envs/classic_control).
###Code
import gym
env = gym.make('CartPole-v1')
###Output
_____no_output_____
###Markdown
"A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The system is controlled by applying a force of +1 or -1 to the cart. The pendulum starts upright, and the goal is to prevent it from falling over. A reward of +1 is provided for every timestep that the pole remains upright. "Cartpole Environment Decription: [https://gym.openai.com/envs/CartPole-v1/](https://gym.openai.com/envs/CartPole-v1/)Cartpole Source Code: [https://github.com/openai/gym/blob/master/gym/envs/classic_control/cartpole.py](https://github.com/openai/gym/blob/master/gym/envs/classic_control/cartpole.py) Interacting with the EnvironmentWe run an instance of `CartPole-v1` environment for 30 timesteps, showing the information returned by the environment.
###Code
state = env.reset() # resets the environment in the initial state
print("Initial state: ", state)
for _ in range(30):
action = env.action_space.sample() # sample a random action
state, reward, done, _ = env.step(action) # execute the action in the environment
print("State:", state,
"Action:", action,
"Reward:", reward,
"Done:", done)
env.close()
###Output
_____no_output_____
###Markdown
A Gym environment provides to the user mainly four methods:* `reset()`: resets the environment to its initial state $S_0 \sim d_0$ and returns the observation corresponding to the initial state.* `step(action)`: takes an action $A_t$ as an input and executes the action in current state $S_t$ of the environment. This method returns a tuple of four values: * `observation` (object): an environment-specific object representation of your observation of the environment after the action is executed. It corresponds to the observation of the next state $S_{t+1} \sim p(\cdot|S_t,A_t)$ * `reward` (float): immediate reward $R_{t+1} = r(S_t,A_t)$ obtained by executing action $A_t$ in state $S_t$ * `done`(boolean): whether the reached next state $S_{t+1}$ is a terminal state. * `info` (dict): additional information useful for debugging and environment-specific. * `render(method='human')`: allows visualizing the agent in action. Note that graphical interface does not work on Google Colab, so we cannot use it directly (we will need a workaround).* `seed()`: sets the seed for this environment’s random number generator. Observation and Action Spaces* `observation_space`: this attribute provides the format of valid observations $\mathcal{S}$. It is of datatype `Space` provided by Gym. For example, if the observation space is of type `Box` and the shape of the object is `(4,)`, this denotes a valid observation will be an array of 4 numbers.* `action_space`: this attribute provides the format of valid actions $\mathcal{A}$. It is of datatype `Space` provided by Gym. For example, if the action space is of type `Discrete` and gives the value `Discrete(2)`, this means there are two valid discrete actions: 0 and 1.
###Code
print(env.observation_space)
print(env.action_space)
print(env.observation_space.high)
print(env.observation_space.low)
###Output
_____no_output_____
###Markdown
`Spaces` types available in Gym:* `Box`: an $n$-dimensional compact space (i.e., a compact subset of $\mathbb{R}^n$). The bounds of the space are contained in the `high` and `low` attributes.* `Discrete`: a discrete space made of $n$ elements, where $\{0,1,\dots,n-1\}$ are the possible values.Other `Spaces` types can be used: `Dict`, `Tuple`, `MultiBinary`, `MultiDiscrete`.
###Code
import numpy as np
from gym.spaces import Box, Discrete
observation_space = Box(low=-1.0, high=2.0, shape=(3,), dtype=np.float32)
print(observation_space.sample())
observation_space = Discrete(4)
print(observation_space.sample())
###Output
_____no_output_____
###Markdown
Details on the Cartpole Environment From [https://github.com/openai/gym/blob/master/gym/envs/classic_control/cartpole.py](https://github.com/openai/gym/blob/master/gym/envs/classic_control/cartpole.py)A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The pendulum starts upright, and the goal is to prevent it from falling over by increasing and reducing the cart's velocity. Action SpaceThe action space is `action` in $\{0,1\}$, where `action` is used to push the cart with a fixed amount of force: | Num | Action | |-----|------------------------| | 0 | Push cart to the left | | 1 | Push cart to the right | Note: The amount the velocity is reduced or increased is not fixed as it depends on the angle the pole is pointing. This is because the center of gravity of the pole increases the amount of energy needed to move the cart underneath it. Observation SpaceThe observation is a `ndarray` with shape `(4,)` where the elements correspond to the following: | Num | Observation | Min | Max | |-----|-----------------------|----------------------|--------------------| | 0 | Cart Position | -4.8* | 4.8* | | 1 | Cart Velocity | -Inf | Inf | | 2 | Pole Angle | ~ -0.418 rad (-24°)**| ~ 0.418 rad (24°)** | | 3 | Pole Angular Velocity | -Inf | Inf |**Note:** above denotes the ranges of possible observations for each element, but in two cases this range exceeds the range of possible values in an un-terminated episode:- `*`: the cart x-position can be observed between `(-4.8, 4.8)`, but an episode terminates if the cart leaves the `(-2.4, 2.4)` range.- `**`: Similarly, the pole angle can be observed between `(-.418, .418)` radians or precisely **±24°**, but an episode is terminated if the pole angle is outside the `(-.2095, .2095)` range or precisely **±12°** RewardsReward is 1 for every step taken, including the termination step. Starting StateAll observations are assigned a uniform random value between (-0.05, 0.05) Episode TerminationThe episode terminates of one of the following occurs:1. Pole Angle is more than ±12°2. Cart Position is more than ±2.4 (center of the cart reaches the edge of the display)3. Episode length is greater than 500 Evaluation of some Simple PoliciesWe now evaluate some policies on the cartpole.* **Uniform Policy**: uniformly random policy$$\pi(a|s) = \mathrm{Uni}(\{0,1\})$$* **Reactive Policy**: simple deterministic policy that selects the action based on the pole angle$$\pi(s) = \begin{cases} 0 & \text{if Pole Angle } \le 0 \\ 1 & \text{otherwise} \end{cases}$$
###Code
class UniformPolicy:
def predict(self, obs):
return np.random.randint(0, 2), obs # return the observation to comply with stable-baselines3
class ReactivePolicy:
def predict(self, obs):
if obs[2] <= 0:
return 0, obs
else:
return 1, obs
###Output
_____no_output_____
###Markdown
Let us create a function to evaluate the agent's performance.
###Code
def evaluate(env, policy, gamma=1., num_episodes=100):
"""
Evaluate a RL agent
:param env: (Env object) the Gym environment
:param policy: (BasePolicy object) the policy in stable_baselines3
:param gamma: (float) the discount factor
:param num_episodes: (int) number of episodes to evaluate it
:return: (float) Mean reward for the last num_episodes
"""
all_episode_rewards = []
for i in range(num_episodes): # iterate over the episodes
episode_rewards = []
done = False
discounter = 1.
obs = env.reset()
while not done: # iterate over the steps until termination
action, _ = policy.predict(obs)
obs, reward, done, info = env.step(action)
episode_rewards.append(reward * discounter) # compute discounted reward
discounter *= gamma
all_episode_rewards.append(sum(episode_rewards))
mean_episode_reward = np.mean(all_episode_rewards)
std_episode_reward = np.std(all_episode_rewards) / np.sqrt(num_episodes - 1)
print("Mean reward:", mean_episode_reward,
"Std reward:", std_episode_reward,
"Num episodes:", num_episodes)
return mean_episode_reward, std_episode_reward
###Output
_____no_output_____
###Markdown
Let us test the uniform policy.
###Code
uniform_policy = UniformPolicy()
uniform_policy_mean, uniform_policy_std = evaluate(env, uniform_policy)
render('CartPole-v1', uniform_policy, prefix='cartpole-uniform_policy')
###Output
_____no_output_____
###Markdown
Let us test the reactive policy.
###Code
reactive_policy = ReactivePolicy()
reactive_policy_mean, reactive_policy_std = evaluate(env, reactive_policy)
render('CartPole-v1', reactive_policy, prefix='cartpole-reactive_policy')
###Output
_____no_output_____
###Markdown
PPO TrainingWe now use Stable Baselines3 to train some simple algorithms. We start by using [Proximal Policy Optimization](https://stable-baselines3.readthedocs.io/en/master/modules/ppo.html).We select the [MlpPolicy](https://stable-baselines3.readthedocs.io/en/master/modules/ppo.htmlppo-policies) because the state of the CartPole environment is a feature vector (not images for instance). The type of action to use (discrete/continuous) will be automatically deduced from the environment action space.We consider two network architectures:* Linear policy* Two hidden layers of 32 neurons each
###Code
from stable_baselines3 import PPO
# Instantiate the algorithm with 32x32 NN approximator for both actor and critic
ppo_mlp = PPO("MlpPolicy", env, verbose=1,
learning_rate=0.01,
policy_kwargs=dict(net_arch = [dict(pi=[32, 32], vf=[32, 32])]))
print(ppo_mlp.policy)
# Instantiate the algorithm with linear approximator for both actor and critic
ppo_linear = PPO("MlpPolicy", env, verbose=1,
learning_rate=0.01,
policy_kwargs=dict(net_arch = [dict(pi=[], vf=[])]))
print(ppo_linear.policy)
###Output
_____no_output_____
###Markdown
Let us now train the algorithms. In order to keep track of the performance during learning, we can log the evaluations.
###Code
# Separate evaluation env
eval_env = gym.make('CartPole-v1')
# Train the agent for 50000 steps
ppo_mlp.learn(total_timesteps=50000, eval_freq=2048, eval_env=eval_env,
eval_log_path='./logs/cartpole/ppo_mlp', log_interval=4)
ppo_linear.learn(total_timesteps=50000, eval_freq=2048, eval_env=eval_env,
eval_log_path='./logs/cartpole/ppo_linear', log_interval=4)
###Output
_____no_output_____
###Markdown
Let us plot the learning curves.
###Code
results = {'PPO-MLP': './logs/cartpole/ppo_mlp',
'PPO-LINEAR': './logs/cartpole/ppo_linear',}
plot_results(results)
# Evaluate the trained models
ppo_mlp_mean, ppo_mlp_std = evaluate(env, ppo_mlp)
render('CartPole-v1', ppo_mlp, prefix='ppo_mlp')
ppo_linear_mean, ppo_linear_std = evaluate(env, ppo_linear)
render('CartPole-v1', ppo_linear, prefix='ppo_linear')
###Output
_____no_output_____
###Markdown
Let us have a look at the weights learned by PPO with the linear policy. Since actions are discrete, the policy model is **softmax**:$$\pi_{\boldsymbol{\theta}}(a|\mathbf{s}) \propto \exp \left( \mathbf{s}^T \boldsymbol{\theta}(a) + b(a) \right)$$
###Code
print(ppo_linear.policy.action_net.weight)
print(ppo_linear.policy.action_net.bias)
###Output
_____no_output_____
###Markdown
DQN Training Let us now try [DQN](https://stable-baselines3.readthedocs.io/en/master/modules/dqn.html) with an MlpPolicy as well.
###Code
from stable_baselines3 import DQN
from torch import nn
# Instantiate the algorithm with 32x32 NN approximator
dqn_mlp = DQN("MlpPolicy", env, verbose=1,
learning_starts=3000,
policy_kwargs=dict(net_arch = [32, 32], activation_fn=nn.Tanh))
print(dqn_mlp.policy)
# Train the agent for 50000 steps
dqn_mlp.learn(total_timesteps=50000, eval_freq=2048, eval_env=eval_env,
eval_log_path='./logs/cartpole/dqn_mlp', log_interval=100)
# Evaluate the trained models
dqn_mlp_mean, dqn_mlp_std = evaluate(env, dqn_mlp)
render('CartPole-v1', dqn_mlp, prefix='dqn_mlp')
###Output
_____no_output_____
###Markdown
Let us now plot the final results.
###Code
#Plot the training curves
results['DQN'] = './logs/cartpole/dqn_mlp'
plot_results(results)
#Plot the results
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
algs = ['Random', 'Reactive', 'PPO MLP', 'PPO Linear', 'DQN']
means = [uniform_policy_mean, reactive_policy_mean, ppo_mlp_mean, ppo_linear_mean, dqn_mlp_mean]
errors = [uniform_policy_std, reactive_policy_std, ppo_mlp_std, ppo_linear_std, dqn_mlp_std]
ax.bar(algs, means, yerr=errors, align='center', alpha=0.5, ecolor='black', capsize=10)
plt.show()
###Output
_____no_output_____
###Markdown
Expressions Let's start with some basic expressions
###Code
17
-2 + 15
-2 - 1
-2 - -1
4 / 2
1 / 2
1 % 2
15 % 2
1 / 2.0
type(1)
type(1/2)
1/2.0 + 1/4.0
2.1 + 5.3
2 + 2 * 2
(2 + 2) * 2 # overriding precedence
###Output
_____no_output_____
###Markdown
See more about precedence here: https://docs.python.org/3/reference/expressions.htmloperator-precedence
###Code
3 < 4 # conditional expression
3 == 4
3 == 3
3 = 3 # ignore the *details* of the error for now
3 > 4
3 >= 3
2 <= 1
###Output
_____no_output_____
###Markdown
Other types of expressions
###Code
'abc'
"xyz"
"""This is called a multi-line string.
It can, obviously, span multiple lines! """
"ab" + "cd"
type("ab")
"a-" * 3
True
False
True and True
True and False
False and True
False and False
True or True
True or False
False or True
False or False
True or False and False or False
(True or False) and (False or False)
###Output
_____no_output_____
###Markdown
Call Expressions
###Code
max(7, 9)
max(2+25, 9)
pow(3, 2)
max( min(1, -2) , min( pow(3, 5) , -4) )
a = [(4, 'a'), (3, 'b', 5), ('c', 5, 7)]
type(a[2][0])
type(1/2)
###Output
_____no_output_____ |
Regression/Multi-variate LASSO regression with CV.ipynb | ###Markdown
Multi-variate Rregression Metamodel with DOE based on random sampling* Input variable space should be constructed using random sampling, not classical factorial DOE* Linear fit is often inadequate but higher-order polynomial fits often leads to overfitting i.e. learns spurious, flawed relationships between input and output* R-square fit can often be misleding measure in case of high-dimensional regression* Metamodel can be constructed by selectively discovering features (or their combination) which matter and shrinking other high-order terms towards zero LASSO: Least Absolute Shrinkage and Selection Operator$$ {\displaystyle \min _{\beta _{0},\beta }\left\{{\frac {1}{N}}\sum _{i=1}^{N}(y_{i}-\beta _{0}-x_{i}^{T}\beta )^{2}\right\}{\text{ subject to }}\sum _{j=1}^{p}|\beta _{j}|\leq t.} $$ Import libraries
###Code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
###Output
_____no_output_____
###Markdown
Generate random (equivalent to Latin Hypercube sampling done in Optislang) feature vectors
###Code
X=np.array(10*np.random.randn(37,5))
df=pd.DataFrame(X,columns=['Feature'+str(l) for l in range(1,6)])
df.head()
###Output
_____no_output_____
###Markdown
Plot the random distributions of input features
###Code
for i in df.columns:
df.hist(i,bins=5,xlabelsize=15,ylabelsize=15,figsize=(8,6))
###Output
_____no_output_____
###Markdown
Generate the output variable by analytic function + Gaussian noise (our goal will be to *'learn'* this function) Let's construst the ground truth or originating function as follows: $$ y=f(x_1,x_2,x_3,x_4,x_5)= 5x_1^2+13x_2+0.1x_1x_3^2+2x_4x_5+0.1x_5^3+0.8x_1x_4x_5+\psi(x)\ :\ \psi(x) = {\displaystyle f(x\;|\;\mu ,\sigma ^{2})={\frac {1}{\sqrt {2\pi \sigma ^{2}}}}\;e^{-{\frac {(x-\mu )^{2}}{2\sigma ^{2}}}}}$$
###Code
df['y']=5*df['Feature1']**2+13*df['Feature2']+0.1*df['Feature3']**2*df['Feature1'] \
+2*df['Feature4']*df['Feature5']+0.1*df['Feature5']**3+0.8*df['Feature1']*df['Feature4']*df['Feature5'] \
+30*np.random.normal(loc=5,scale=2)
df.head()
###Output
_____no_output_____
###Markdown
Plot single-variable scatterplots
###Code
for i in df.columns:
df.plot.scatter(i,'y', edgecolors=(0,0,0),s=50,c='g',grid=True)
###Output
_____no_output_____
###Markdown
Standard linear regression
###Code
from sklearn.linear_model import LinearRegression
linear_model = LinearRegression(normalize=True)
X_linear=df.drop('y',axis=1)
y_linear=df['y']
linear_model.fit(X_linear,y_linear)
y_pred_linear = linear_model.predict(X_linear)
###Output
_____no_output_____
###Markdown
R-square of simple linear fit is very bad, coefficients have no meaning i.e. we did not 'learn' the function
###Code
RMSE_linear = np.sqrt(np.sum(np.square(y_pred_linear-y_linear)))
print("Root-mean-square error of linear model:",RMSE_linear)
coeff_linear = pd.DataFrame(linear_model.coef_,index=df.drop('y',axis=1).columns, columns=['Linear model coefficients'])
coeff_linear
print ("R2 value of linear model:",linear_model.score(X_linear,y_linear))
plt.figure(figsize=(12,8))
plt.xlabel("Predicted value with linear fit",fontsize=20)
plt.ylabel("Actual y-values",fontsize=20)
plt.grid(1)
plt.scatter(y_pred_linear,y_linear,edgecolors=(0,0,0),lw=2,s=80)
plt.plot(y_pred_linear,y_pred_linear, 'k--', lw=2)
###Output
_____no_output_____
###Markdown
Create polynomial features
###Code
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(3,include_bias=False)
X_poly = poly.fit_transform(X)
X_poly_feature_name = poly.get_feature_names(['Feature'+str(l) for l in range(1,6)])
print(X_poly_feature_name)
print(len(X_poly_feature_name))
df_poly = pd.DataFrame(X_poly, columns=X_poly_feature_name)
df_poly.head()
df_poly['y']=df['y']
df_poly.head()
X_train=df_poly.drop('y',axis=1)
y_train=df_poly['y']
###Output
_____no_output_____
###Markdown
Polynomial model without regularization and cross-validation
###Code
poly = LinearRegression(normalize=True)
model_poly=poly.fit(X_train,y_train)
y_poly = poly.predict(X_train)
RMSE_poly=np.sqrt(np.sum(np.square(y_poly-y_train)))
print("Root-mean-square error of simple polynomial model:",RMSE_poly)
coeff_poly = pd.DataFrame(model_poly.coef_,index=df_poly.drop('y',axis=1).columns,
columns=['Coefficients polynomial model'])
coeff_poly
###Output
_____no_output_____
###Markdown
R-square value of the simple polynomial model is perfect but the model is flawed as shown above i.e. it learned wrong coefficients and overfitted the to the data
###Code
print ("R2 value of simple polynomial model:",model_poly.score(X_train,y_train))
###Output
R2 value of simple polynomial model: 1.0
###Markdown
Metamodel (Optislang style :) - polynomial model with cross-validation and LASSO regularization** This is an advanced machine learning method which prevents over-fitting by penalizing high-valued coefficients i.e. keep them bounded **
###Code
from sklearn.linear_model import LassoCV
model1 = LassoCV(cv=10,verbose=0,normalize=True,eps=0.001,n_alphas=100, tol=0.0001,max_iter=5000)
model1.fit(X_train,y_train)
y_pred1 = np.array(model1.predict(X_train))
RMSE_1=np.sqrt(np.sum(np.square(y_pred1-y_train)))
print("Root-mean-square error of Metamodel:",RMSE_1)
coeff1 = pd.DataFrame(model1.coef_,index=df_poly.drop('y',axis=1).columns, columns=['Coefficients Metamodel'])
coeff1
model1.score(X_train,y_train)
model1.alpha_
###Output
_____no_output_____
###Markdown
Recall that the ground truth or originating function is as follows: $$ y=f(x_1,x_2,x_3,x_4,x_5)= 5x_1^2+13x_2+0.1x_1x_3^2+2x_4x_5+0.1x_5^3+0.8x_1x_4x_5+\psi(x) $$ Printing only the non-zero coefficients of the *metamodel*
###Code
coeff1[coeff1['Coefficients Metamodel']!=0]
plt.figure(figsize=(12,8))
plt.xlabel("Predicted value with Metamodel",fontsize=20)
plt.ylabel("Actual y-values",fontsize=20)
plt.grid(1)
plt.scatter(y_pred1,y_train,edgecolors=(0,0,0),lw=2,s=80)
plt.plot(y_pred1,y_pred1, 'k--', lw=2)
# Display results
m_log_alphas = -np.log10(model1.alphas_)
plt.figure()
ymin, ymax = 2300, 3800
plt.plot(m_log_alphas, model1.mse_path_, ':')
plt.plot(m_log_alphas, model1.mse_path_.mean(axis=-1), 'k',
label='Average across the folds', linewidth=2)
plt.axvline(-np.log10(model1.alpha_), linestyle='--', color='k',
label='alpha: CV estimate')
plt.legend()
plt.xlabel('-log(alpha)')
plt.ylabel('Mean square error')
plt.axis('tight')
###Output
_____no_output_____
###Markdown
| Name | Description | Date| :- |-------------: | :-:|Reza Hashemi| Multi-variate LASSO regression with CV. | On 12th of July 2019 Multi-variate Rregression Metamodel with DOE based on random sampling* Input variable space should be constructed using random sampling, not classical factorial DOE* Linear fit is often inadequate but higher-order polynomial fits often leads to overfitting i.e. learns spurious, flawed relationships between input and output* R-square fit can often be misleding measure in case of high-dimensional regression* Metamodel can be constructed by selectively discovering features (or their combination) which matter and shrinking other high-order terms towards zero LASSO: Least Absolute Shrinkage and Selection Operator$$ {\displaystyle \min _{\beta _{0},\beta }\left\{{\frac {1}{N}}\sum _{i=1}^{N}(y_{i}-\beta _{0}-x_{i}^{T}\beta )^{2}\right\}{\text{ subject to }}\sum _{j=1}^{p}|\beta _{j}|\leq t.} $$ Import libraries
###Code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
###Output
_____no_output_____
###Markdown
Generate random (equivalent to Latin Hypercube sampling done in Optislang) feature vectors
###Code
X=np.array(10*np.random.randn(37,5))
df=pd.DataFrame(X,columns=['Feature'+str(l) for l in range(1,6)])
df.head()
###Output
_____no_output_____
###Markdown
Plot the random distributions of input features
###Code
for i in df.columns:
df.hist(i,bins=5,xlabelsize=15,ylabelsize=15,figsize=(8,6))
###Output
_____no_output_____
###Markdown
Generate the output variable by analytic function + Gaussian noise (our goal will be to *'learn'* this function) Let's construst the ground truth or originating function as follows: $$ y=f(x_1,x_2,x_3,x_4,x_5)= 5x_1^2+13x_2+0.1x_1x_3^2+2x_4x_5+0.1x_5^3+0.8x_1x_4x_5+\psi(x)\ :\ \psi(x) = {\displaystyle f(x\;|\;\mu ,\sigma ^{2})={\frac {1}{\sqrt {2\pi \sigma ^{2}}}}\;e^{-{\frac {(x-\mu )^{2}}{2\sigma ^{2}}}}}$$
###Code
df['y']=5*df['Feature1']**2+13*df['Feature2']+0.1*df['Feature3']**2*df['Feature1'] \
+2*df['Feature4']*df['Feature5']+0.1*df['Feature5']**3+0.8*df['Feature1']*df['Feature4']*df['Feature5'] \
+30*np.random.normal(loc=5,scale=2)
df.head()
###Output
_____no_output_____
###Markdown
Plot single-variable scatterplots
###Code
for i in df.columns:
df.plot.scatter(i,'y', edgecolors=(0,0,0),s=50,c='g',grid=True)
###Output
_____no_output_____
###Markdown
Standard linear regression
###Code
from sklearn.linear_model import LinearRegression
linear_model = LinearRegression(normalize=True)
X_linear=df.drop('y',axis=1)
y_linear=df['y']
linear_model.fit(X_linear,y_linear)
y_pred_linear = linear_model.predict(X_linear)
###Output
_____no_output_____
###Markdown
R-square of simple linear fit is very bad, coefficients have no meaning i.e. we did not 'learn' the function
###Code
RMSE_linear = np.sqrt(np.sum(np.square(y_pred_linear-y_linear)))
print("Root-mean-square error of linear model:",RMSE_linear)
coeff_linear = pd.DataFrame(linear_model.coef_,index=df.drop('y',axis=1).columns, columns=['Linear model coefficients'])
coeff_linear
print ("R2 value of linear model:",linear_model.score(X_linear,y_linear))
plt.figure(figsize=(12,8))
plt.xlabel("Predicted value with linear fit",fontsize=20)
plt.ylabel("Actual y-values",fontsize=20)
plt.grid(1)
plt.scatter(y_pred_linear,y_linear,edgecolors=(0,0,0),lw=2,s=80)
plt.plot(y_pred_linear,y_pred_linear, 'k--', lw=2)
###Output
_____no_output_____
###Markdown
Create polynomial features
###Code
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(3,include_bias=False)
X_poly = poly.fit_transform(X)
X_poly_feature_name = poly.get_feature_names(['Feature'+str(l) for l in range(1,6)])
print(X_poly_feature_name)
print(len(X_poly_feature_name))
df_poly = pd.DataFrame(X_poly, columns=X_poly_feature_name)
df_poly.head()
df_poly['y']=df['y']
df_poly.head()
X_train=df_poly.drop('y',axis=1)
y_train=df_poly['y']
###Output
_____no_output_____
###Markdown
Polynomial model without regularization and cross-validation
###Code
poly = LinearRegression(normalize=True)
model_poly=poly.fit(X_train,y_train)
y_poly = poly.predict(X_train)
RMSE_poly=np.sqrt(np.sum(np.square(y_poly-y_train)))
print("Root-mean-square error of simple polynomial model:",RMSE_poly)
coeff_poly = pd.DataFrame(model_poly.coef_,index=df_poly.drop('y',axis=1).columns,
columns=['Coefficients polynomial model'])
coeff_poly
###Output
_____no_output_____
###Markdown
R-square value of the simple polynomial model is perfect but the model is flawed as shown above i.e. it learned wrong coefficients and overfitted the to the data
###Code
print ("R2 value of simple polynomial model:",model_poly.score(X_train,y_train))
###Output
R2 value of simple polynomial model: 1.0
###Markdown
Metamodel (Optislang style :) - polynomial model with cross-validation and LASSO regularization** This is an advanced machine learning method which prevents over-fitting by penalizing high-valued coefficients i.e. keep them bounded **
###Code
from sklearn.linear_model import LassoCV
model1 = LassoCV(cv=10,verbose=0,normalize=True,eps=0.001,n_alphas=100, tol=0.0001,max_iter=5000)
model1.fit(X_train,y_train)
y_pred1 = np.array(model1.predict(X_train))
RMSE_1=np.sqrt(np.sum(np.square(y_pred1-y_train)))
print("Root-mean-square error of Metamodel:",RMSE_1)
coeff1 = pd.DataFrame(model1.coef_,index=df_poly.drop('y',axis=1).columns, columns=['Coefficients Metamodel'])
coeff1
model1.score(X_train,y_train)
model1.alpha_
###Output
_____no_output_____
###Markdown
Recall that the ground truth or originating function is as follows: $$ y=f(x_1,x_2,x_3,x_4,x_5)= 5x_1^2+13x_2+0.1x_1x_3^2+2x_4x_5+0.1x_5^3+0.8x_1x_4x_5+\psi(x) $$ Printing only the non-zero coefficients of the *metamodel*
###Code
coeff1[coeff1['Coefficients Metamodel']!=0]
plt.figure(figsize=(12,8))
plt.xlabel("Predicted value with Metamodel",fontsize=20)
plt.ylabel("Actual y-values",fontsize=20)
plt.grid(1)
plt.scatter(y_pred1,y_train,edgecolors=(0,0,0),lw=2,s=80)
plt.plot(y_pred1,y_pred1, 'k--', lw=2)
# Display results
m_log_alphas = -np.log10(model1.alphas_)
plt.figure()
ymin, ymax = 2300, 3800
plt.plot(m_log_alphas, model1.mse_path_, ':')
plt.plot(m_log_alphas, model1.mse_path_.mean(axis=-1), 'k',
label='Average across the folds', linewidth=2)
plt.axvline(-np.log10(model1.alpha_), linestyle='--', color='k',
label='alpha: CV estimate')
plt.legend()
plt.xlabel('-log(alpha)')
plt.ylabel('Mean square error')
plt.axis('tight')
###Output
_____no_output_____ |
examples/in_depth/Containers.ipynb | ###Markdown
Helper function for demo
###Code
from pytorch_adapt.utils.common_functions import get_lr
def print_optimizers_slim(optimizers):
for k, v in optimizers.items():
print(
f"{k}: {v.__class__.__name__} with lr={get_lr(v)} weight_decay={v.param_groups[0]['weight_decay']}"
)
print("")
###Output
_____no_output_____
###Markdown
Containers Initialization
###Code
import torch
from pytorch_adapt.containers import LRSchedulers, Models, Optimizers
device = torch.device("cuda")
G = torch.nn.Linear(1000, 100)
C = torch.nn.Linear(100, 10)
D = torch.nn.Linear(100, 1)
models = Models({"G": G, "C": C, "D": D})
optimizers = Optimizers((torch.optim.Adam, {"lr": 0.456, "weight_decay": 0.123}))
schedulers = LRSchedulers((torch.optim.lr_scheduler.ExponentialLR, {"gamma": 0.99}))
###Output
_____no_output_____
###Markdown
Create with
###Code
optimizers.create_with(models)
schedulers.create_with(optimizers)
print(models)
print_optimizers_slim(optimizers)
print(schedulers)
###Output
_____no_output_____
###Markdown
Merge
###Code
more_models = Models({"X": torch.nn.Linear(20, 1)})
models.merge(more_models)
optimizers = Optimizers((torch.optim.Adam, {"lr": 0.456}))
special_opt = Optimizers(
(torch.optim.SGD, {"lr": 1, "weight_decay": 1e-5}), keys=["G", "X"]
)
optimizers.merge(special_opt)
optimizers.create_with(models)
print(models)
print_optimizers_slim(optimizers)
###Output
_____no_output_____
###Markdown
Delete keys
###Code
from pytorch_adapt.containers import DeleteKey
opt1 = Optimizers((torch.optim.SGD, {"lr": 0.01, "momentum": 0.9}))
opt2 = Optimizers((DeleteKey, {}), keys=["G", "D"])
opt1.merge(opt2)
opt1.create_with(models)
print_optimizers_slim(opt1)
###Output
_____no_output_____
###Markdown
Model Container Functions
###Code
models.train()
for k, v in models.items():
print(k, "training", v.training)
models.eval()
for k, v in models.items():
print(k, "training", v.training)
models.zero_grad()
models.to(device)
for k, v in models.items():
print(k, "device", v.weight.device)
###Output
_____no_output_____
###Markdown
Optimizer Container Functions
###Code
data = torch.randn(32, 1000).to(device)
models.to(device)
for keys in [None, ["C"]]:
logits = C(G(data))
loss = torch.sum(logits)
# zero gradients, compute gradients, update weights
if keys is None:
optimizers.zero_back_step(loss)
# only apply zero_back_step to specific optimizers
else:
optimizers.zero_back_step(loss, keys=keys)
###Output
_____no_output_____
###Markdown
Optimizer LR Multiplier
###Code
optimizers = Optimizers(
(torch.optim.Adam, {"lr": 0.1}), multipliers={"G": 50, "C": 0.5}
)
optimizers.create_with(models)
print_optimizers_slim(optimizers)
###Output
_____no_output_____
###Markdown
LR Scheduler Functions
###Code
schedulers = LRSchedulers(
(torch.optim.lr_scheduler.ExponentialLR, {"gamma": 0.99}),
scheduler_types={"per_step": ["G", "C"], "per_epoch": ["D", "X"]},
)
schedulers.create_with(optimizers)
# step lr schedulers by type
schedulers.step("per_step")
schedulers.step("per_epoch")
# get lr schedulers by type
per_step = schedulers.filter_by_scheduler_type("per_step")
per_epoch = schedulers.filter_by_scheduler_type("per_epoch")
###Output
_____no_output_____
###Markdown
Helper function for demo
###Code
from pytorch_adapt.utils.common_functions import get_lr
def print_optimizers_slim(optimizers):
for k, v in optimizers.items():
print(
f"{k}: {v.__class__.__name__} with lr={get_lr(v)} weight_decay={v.param_groups[0]['weight_decay']}"
)
print("")
###Output
_____no_output_____
###Markdown
Containers Initialization
###Code
import torch
from pytorch_adapt.containers import LRSchedulers, Models, Optimizers
device = torch.device("cuda")
G = torch.nn.Linear(1000, 100)
C = torch.nn.Linear(100, 10)
D = torch.nn.Linear(100, 1)
models = Models({"G": G, "C": C, "D": D})
optimizers = Optimizers((torch.optim.Adam, {"lr": 0.456, "weight_decay": 0.123}))
schedulers = LRSchedulers((torch.optim.lr_scheduler.ExponentialLR, {"gamma": 0.99}))
###Output
_____no_output_____
###Markdown
Create with
###Code
optimizers.create_with(models)
schedulers.create_with(optimizers)
print(models)
print_optimizers_slim(optimizers)
print(schedulers)
###Output
G: Linear(in_features=1000, out_features=100, bias=True)
C: Linear(in_features=100, out_features=10, bias=True)
D: Linear(in_features=100, out_features=1, bias=True)
G: Adam with lr=0.456 weight_decay=0.123
C: Adam with lr=0.456 weight_decay=0.123
D: Adam with lr=0.456 weight_decay=0.123
G: <torch.optim.lr_scheduler.ExponentialLR object at 0x7fecdace11d0>
C: <torch.optim.lr_scheduler.ExponentialLR object at 0x7febc76b3bd0>
D: <torch.optim.lr_scheduler.ExponentialLR object at 0x7febc76b3cd0>
###Markdown
Merge
###Code
more_models = Models({"X": torch.nn.Linear(20, 1)})
models.merge(more_models)
optimizers = Optimizers((torch.optim.Adam, {"lr": 0.456}))
special_opt = Optimizers(
(torch.optim.SGD, {"lr": 1, "weight_decay": 1e-5}), keys=["G", "X"]
)
optimizers.merge(special_opt)
optimizers.create_with(models)
print(models)
print_optimizers_slim(optimizers)
###Output
G: Linear(in_features=1000, out_features=100, bias=True)
C: Linear(in_features=100, out_features=10, bias=True)
D: Linear(in_features=100, out_features=1, bias=True)
X: Linear(in_features=20, out_features=1, bias=True)
G: SGD with lr=1 weight_decay=1e-05
C: Adam with lr=0.456 weight_decay=0
D: Adam with lr=0.456 weight_decay=0
X: SGD with lr=1 weight_decay=1e-05
###Markdown
Delete keys
###Code
from pytorch_adapt.containers import DeleteKey
opt1 = Optimizers((torch.optim.SGD, {"lr": 0.01, "momentum": 0.9}))
opt2 = Optimizers((DeleteKey, {}), keys=["G", "D"])
opt1.merge(opt2)
opt1.create_with(models)
print_optimizers_slim(opt1)
###Output
C: SGD with lr=0.01 weight_decay=0
X: SGD with lr=0.01 weight_decay=0
###Markdown
Model Container Functions
###Code
models.train()
for k, v in models.items():
print(k, "training", v.training)
models.eval()
for k, v in models.items():
print(k, "training", v.training)
models.zero_grad()
models.to(device)
for k, v in models.items():
print(k, "device", v.weight.device)
###Output
G training True
C training True
D training True
X training True
G training False
C training False
D training False
X training False
G device cuda:0
C device cuda:0
D device cuda:0
X device cuda:0
###Markdown
Optimizer Container Functions
###Code
data = torch.randn(32, 1000).to(device)
models.to(device)
for keys in [None, ["C"]]:
logits = C(G(data))
loss = torch.sum(logits)
# zero gradients, compute gradients, update weights
if keys is None:
optimizers.zero_back_step(loss)
# only apply zero_back_step to specific optimizers
else:
optimizers.zero_back_step(loss, keys=keys)
###Output
_____no_output_____
###Markdown
Optimizer LR Multiplier
###Code
optimizers = Optimizers(
(torch.optim.Adam, {"lr": 0.1}), multipliers={"G": 50, "C": 0.5}
)
optimizers.create_with(models)
print_optimizers_slim(optimizers)
###Output
G: Adam with lr=5.0 weight_decay=0
C: Adam with lr=0.05 weight_decay=0
D: Adam with lr=0.1 weight_decay=0
X: Adam with lr=0.1 weight_decay=0
###Markdown
LR Scheduler Functions
###Code
schedulers = LRSchedulers(
(torch.optim.lr_scheduler.ExponentialLR, {"gamma": 0.99}),
scheduler_types={"per_step": ["G", "C"], "per_epoch": ["D", "X"]},
)
schedulers.create_with(optimizers)
# step lr schedulers by type
schedulers.step("per_step")
schedulers.step("per_epoch")
# get lr schedulers by type
per_step = schedulers.filter_by_scheduler_type("per_step")
per_epoch = schedulers.filter_by_scheduler_type("per_epoch")
###Output
_____no_output_____ |
data_management/importers/sulross_to_json.ipynb | ###Markdown
Creating CCT json database for Sul Ross Need to install ExifTool: - Follow instruction at https://www.sno.phy.queensu.ca/~phil/exiftool/install.htmlUnix (wget download the tar on the [home page](https://www.sno.phy.queensu.ca/~phil/exiftool/Image-ExifTool-11.44.tar.gz), test and install)- Install its Python wrapper (git clone the repo following instructions on https://smarnach.github.io/pyexiftool/ and inside the directory do `python setup.py install`)
###Code
import os
from datetime import datetime
import json
from collections import defaultdict
from tqdm import tqdm
import exiftool
import path_utils # ai4eutils
###Output
_____no_output_____
###Markdown
List image IDsGet the list of image_id in folders `Summer2018` and `Presidio001`
###Code
data_dir = '/home/beaver/cameratraps/mnt/sulross' # container mount point
image_dirs = os.listdir(data_dir)
image_dirs
image_paths = []
for image_dir in image_dirs:
image_dir = os.path.join(data_dir, image_dir)
if os.path.isdir(image_dir):
print(image_dir)
for image_path in tqdm(path_utils.recursive_file_list(image_dir, bConvertSlashes=False)):
if path_utils.is_image_file(image_path):
image_paths.append(os.path.join(image_dir, image_path))
image_paths = sorted(image_paths)
len(image_paths)
image_paths[:3]
# exclude the test folders - these are subsets of the other two folders Presidio001 and Summer2018
image_ids = []
for i in image_paths:
image_id = i.split('/home/beaver/cameratraps/mnt/sulross/')[1]
if not image_id.startswith('test'):
image_ids.append(image_id)
len(image_ids)
image_ids[:3]
len(image_ids)
with open('/home/beaver/cameratraps/data/sulross/20190522_image_ids.json', 'w') as f:
json.dump(image_ids, f, indent=1)
meta = {}
for i in range (0, 100):
meta[i] = '1'
len(meta)
###Output
_____no_output_____
###Markdown
Extract labels from EXIF dataUsed `sulross_get_exif.py` to save the field with the species information from the images. This is saved in `20190522_metadata.json`.
###Code
image_id_to_metadata = json.load(open('/Users/siyuyang/Source/temp_data/CameraTrap/engagements/SulRoss/20190522/20190522_metadata.json'))
len(image_id_to_metadata)
image_id_to_species = {}
no_species = []
for image_id, metadata in image_id_to_metadata.items():
species_present = False
for m in metadata:
parts = m.split('|')
if not species_present and len(parts) == 2 and parts[0] == 'Species':
s = parts[1]
if s == 'None':
s = ''
image_id_to_species[image_id] = s
species_present = True
if not species_present:
no_species.append((image_id, metadata))
image_id_to_species[image_id] = ''
len(image_id_to_species)
len(no_species) # number of images without EXIF field that says "Species|" - assume empty...
# Most empty images are denoted by "Species|None"
no_species[100]
###Output
_____no_output_____
###Markdown
Spot checked that these are empty of animals.
###Code
all_species = set(image_id_to_species.values())
len(all_species)
all_species
name_change = {
'Popcupine': 'Porcupine',
'Blacktailed jackrabbit': 'Black-tailed Jackrabbit',
'': 'empty'
}
# lower-case all species names; get rid of the leading _ in some of them like _Skunk
###Output
_____no_output_____
###Markdown
Image IDs are `Presidio001/Cam016/Presidio001__Cam016__2018-03-05__11-43-58(11).JPG`, and the part `Presidio001/Cam016/Presidio001__Cam016__2018-03-05__11-43-` is a sequence ID.
###Code
def get_info_from_image_name(image_id):
image_name = image_id.split('.')[0]
frame_num = int(image_name.split('(')[-1].split(')')[0])
seq_id_parts = image_name.split('-')
seq_id = '-'.join(seq_id_parts[:-1])
parts = image_id.split('/')
# want '2019-05-19 08:57:43'
dt = parts[-1].split('.')[0].split('(')[0].split('__')
date = dt[2]
time = dt[3]
dt = '{} {}'.format(date, ':'.join(time.split('-')))
# location is folder_name+camera_id
location = '{}+{}'.format(parts[0], parts[1])
return seq_id, frame_num, dt, location
image_id = 'Presidio001/Cam016/Presidio001__Cam016__2018-03-05__11-43-58(11).JPG'
get_info_from_image_name(image_id)
image_id = 'Summer2018/D15/Summer2018__D15__2018-06-23__03-56-24(1).JPG'
get_info_from_image_name(image_id)
images = []
seq_id_to_num_frames = defaultdict(int)
species_count = defaultdict(int)
for image_id, species in tqdm(image_id_to_species.items()):
if species in name_change:
species = name_change[species]
if species.startswith('_'):
species = species.split('_')[1]
species = species.lower()
species_count[species] += 1
seq_id, frame_num, dt, location = get_info_from_image_name(image_id)
seq_id_to_num_frames[seq_id] += 1
images.append({
'id': image_id.split('.')[0],
'file_name': image_id,
'datetime': dt,
'seq_id': seq_id,
'frame_num': frame_num,
'location': location,
'species': species
})
images[1000]
species_count
len(species_count)
category_map = {
'empty': 0
}
species = list(species_count.keys())
i = 1
for s in species:
if s != 'empty':
category_map[s] = i
i += 1
category_map
len(category_map)
final_images = []
annotations = []
for image in images:
# each image only has one species label in this dataset, so use image_id as annotation_id
annotations.append({
'id': image['id'] + '_anno',
'image_id': image['id'],
'category_id': category_map[image['species']]
})
image['seq_num_frames'] = seq_id_to_num_frames[image['seq_id']]
# frame_num starts at 1
if image['frame_num'] > image['seq_num_frames']:
print(image)
final_images.append(image)
###Output
_____no_output_____
###Markdown
Only one image had frame_num > seq_num_frames...
###Code
len(final_images)
len(annotations)
final_images[1000]
annotations[1000]
for image in final_images:
del image['species']
final_images[1000]
categories = []
for name, i in category_map.items():
categories.append({
'id': i,
'name': name
})
len(categories)
db = {
'info': {
'version': '20190530',
'description': 'Sul Ross University data, from folders Presidio001 and Summer2018.',
'contributor': 'Patricia Harveson, Sul Ross University. Database created by Siyu Yang',
'year': 2019,
'date_created': str(datetime.today())
},
'images': final_images,
'categories': categories,
'annotations': annotations
}
with open('/Users/siyuyang/Source/temp_data/CameraTrap/engagements/SulRoss/20190522/Database/sulross_20190530.json', 'w') as f:
json.dump(db, f, indent=1)
###Output
_____no_output_____ |
src/triage/component/audition/Audition_Tutorial.ipynb | ###Markdown
Setting up the Auditioner instance Currently you need to specify the set of `model_group_ids` and `train_end_times` you want to use manually, so here we're reading a few sets out of the database.Additionally, you need to specify a name for the best distance table when creating the Auditioner and should ensure it doesn't already exist.For simplicity, we'll just look at precision@50_abs here. Pre-Audition PreAudition provids some higher level functions to obtain `model_group_ids` and `train_end_times`. For example, `get_model_groups_from_experiment()` and `get_train_end_times()`.
###Code
from triage.component.audition.pre_audition import PreAudition
pre_aud = PreAudition(conn)
# select model groups by experiment hash id
# model_groups = pre_aud.get_model_groups_from_experiment('f111bf3nc75n1104b37nd6fdn7b83d14')
# select model groups by label
model_groups = pre_aud.get_model_groups_from_label('final_ruling_code_1_4_5_states_klaus_fix_nulls_more_trees')
end_times = pre_aud.get_train_end_times(after='2012-01-01')
print(len(model_groups))
end_times
###Output
4072
###Markdown
Or you can write your own query to get the set of `model_group_ids` and `train_end_times`.
###Code
sel = """
SELECT DISTINCT(model_group_id)
FROM results.model_groups
WHERE model_config->>'label_definition'='final_ruling_code_1_4_5_states_klaus_fix_nulls_more_trees'
"""
model_groups = pre_aud.get_model_groups(sel)
print(len(model_groups))
sel = """
SELECT DISTINCT train_end_time
FROM results.models
WHERE model_group_id IN ({})
AND EXTRACT(DAY FROM train_end_time) IN (1)
AND train_end_time >= '2012-01-01'
;
""".format(', '.join(map(str, model_groups)))
end_times = pre_aud.get_train_end_times(query=sel)
end_times
###Output
_____no_output_____
###Markdown
Auditioner Auditioner is the main API to do the rules selection and model groups selection. It filters model groups using a two-step process. - Broad thresholds to filter out truly bad models - A selection rule grid to find the best model groups over time for each of a variety of methods For those model gorups which don't have full train_end_time periods, they will be pruned as well.
###Code
from triage.component.audition import Auditioner
aud = Auditioner(
db_engine = conn,
model_group_ids = model_groups,
train_end_times = end_times,
initial_metric_filters = [{'metric': 'precision@', 'parameter': '50_abs', 'max_from_best': 1.0, 'threshold_value': 0.0}],
models_table = 'models',
distance_table = 'kr_test_dist'
)
###Output
_____no_output_____
###Markdown
How to use Auditioner Plotting the best distance metric and groups over time This is done with the `plot_model_groups` method and may take a minute to generate. What it does is to get rid of really bad model groups wrt the metric of interest. A model group is discarded if: - It’s never close to the “best” model (define close to best) or - If it’s metric is below a certain number (define min threshold) at least once
###Code
aud.plot_model_groups()
###Output
/Users/Eddie/Documents/DSSG/triage/venv/lib/python3.5/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: The Vega10 colormap was deprecated in version 2.0. Use tab10 instead.
warnings.warn(message, mplDeprecation, stacklevel=1)
###Markdown
With our first default setting, we don't filter out models because `max_from_best`=`1.0` and `threshold_value`=`0.0` are the loosest criteria.- The frist graph shows us the fraction of models worse than the best model by distance wrt the metric of interest.- The second graph shows us the performance of a model group over time. The dashed line is the best case at that time period.
###Code
ids = aud.thresholded_model_group_ids
len(ids)
###Output
_____no_output_____
###Markdown
Applying thresholds to weed out bad models Here we use the `set_one_metric_filter` to apply a simple filter in order to eliminate poorly performing ones. The model groups will be plotted again after updating the filters.
###Code
aud.set_one_metric_filter(
metric='precision@',
parameter='50_abs',
max_from_best=0.5,
threshold_value=0.0)
###Output
/Users/Eddie/Documents/DSSG/triage/venv/lib/python3.5/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: The Vega10 colormap was deprecated in version 2.0. Use tab10 instead.
warnings.warn(message, mplDeprecation, stacklevel=1)
###Markdown
Apply a round of filtering, starting with no `threshold_value` and a fairly wide margin on `max_from_best`
###Code
# how many model groups are left after the first round of filtering?
len(aud.thresholded_model_group_ids)
###Output
_____no_output_____
###Markdown
If that didn't thin things out too much, so let's get a bit more agressive with both parameters.If we want to have multiple filters, then use `update_metric_filters` to apply a set of filters to the model groups we're considering in order to eliminate poorly performing ones. The model groups will be plotted again after updating the filters.
###Code
aud.update_metric_filters([{
'metric': 'precision@',
'parameter': '50_abs',
'max_from_best': 0.5,
'threshold_value': 0.12
}])
len(aud.thresholded_model_group_ids)
###Output
/Users/Eddie/Documents/DSSG/triage/venv/lib/python3.5/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: The Vega10 colormap was deprecated in version 2.0. Use tab10 instead.
warnings.warn(message, mplDeprecation, stacklevel=1)
###Markdown
Applying selection rules and calculating regrets for the narrowed set of models The goal of audition is to narrow a very large number of model groups to a small number of best candidates, ideally making use of the full time series of information. There are several ways one could consider doing so, using over-time averages of the metrics of interest, weighted averages to balance between metrics, the distance from best metrics, and balancing metric average values and stability.Audition formalizes this idea through "selection rules" that take in the data up to a given point in time, apply some rule to choose a model group, and evaluate the performance of that chosen model in the subsequent time window, the regret. You can register, evaluate, and update selection rules associated with the Auditioner object as shown below.Audition will run similations of different model group selection rules to show users and let users asses which rule(s) is the best for their needs. Next, Audition will output numbers of best model in current time period for each model. Rules Maker We need to create a selection rule grid which will be passed to `aud.register_selection_rule_grid()` to run the simulations. The selection rule grid is only recognized as a list of dictionaries of all the parameters. One can create this giant grid by hands, but Audition also provides some helper functions to create the grid easily.
###Code
from triage.component.audition.rules_maker import SimpleRuleMaker, RandomGroupRuleMaker, create_selection_grid
Rule1 = SimpleRuleMaker()
Rule1.add_rule_best_current_value(metric='precision@', parameter='50_abs', n=3)
Rule1.add_rule_best_average_value(metric='precision@', parameter='50_abs', n=3)
Rule1.add_rule_lowest_metric_variance(metric='precision@', parameter='50_abs', n=3)
Rule1.add_rule_most_frequent_best_dist(metric='precision@', parameter='50_abs', dist_from_best_case=[0.05], n=3)
Rule2 = RandomGroupRuleMaker(n=1)
seln_rules = create_selection_grid(Rule1, Rule2)
seln_rules
###Output
_____no_output_____
###Markdown
Or we can create this grid from scratch which will give us the same output.
###Code
seln_rules = [{
'shared_parameters': [
{'metric': 'precision@', 'parameter': '50_abs'},
],
'selection_rules': [
{'name': 'best_current_value', 'n': 3},
{'name': 'best_average_value', 'n': 3},
{'name': 'lowest_metric_variance', 'n': 3},
{'name': 'most_frequent_best_dist', 'dist_from_best_case': [0.05], 'n': 3}
]
},
{
'shared_parameters': [{}],
'selection_rules': [{'name': 'random_model_group', 'n': 1}]
}]
###Output
_____no_output_____
###Markdown
Another example of the selection rules
###Code
# seln_rules = [{
# 'shared_parameters': [
# {'metric': 'precision@', 'parameter': '200_abs'},
# ],
# 'selection_rules': [
# {'name': 'best_current_value', 'n': 1},
# {'name': 'best_average_value', 'n': 1},
# {'name': 'most_frequent_best_dist', 'dist_from_best_case': [0.01, 0.05, 0.1, 0.15]}
# ]
# },
# {
# 'shared_parameters': [
# {'metric': 'precision@', 'parameter': '200_abs'}
# ],
# 'selection_rules': [
# {'name': 'best_avg_recency_weight', 'curr_weight': [1.5, 2.0, 5.0], 'decay_type': ['linear']}
# ]
# },
# {
# 'shared_parameters': [{}],
# 'selection_rules': [{'name': 'random_model_group'}]
# }]
###Output
_____no_output_____
###Markdown
Register rules and run the simulations Register the rules to Audition and it will run the simulations of `regret` and `metric_next_time` for every time period with all the rules and parameters combinations.
###Code
aud.register_selection_rule_grid(seln_rules, plot=True)
###Output
/Users/Eddie/Documents/DSSG/triage/venv/lib/python3.5/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: The Vega10 colormap was deprecated in version 2.0. Use tab10 instead.
warnings.warn(message, mplDeprecation, stacklevel=1)
###Markdown
We can pull the `results_for_rule` out which is a DataFrame of simulation data.
###Code
aud.results_for_rule['precision@50_abs'].head()
###Output
_____no_output_____
###Markdown
Finally, when you have a selection rule grid you're happy with, the selection_rule_model_group_ids parameter of the Auditioner will give you the model groups chosen by the selection rules in the grid when applied to the most recent end time for use in application:
###Code
aud.selection_rule_model_group_ids
###Output
_____no_output_____
###Markdown
Setting up the Auditioner instance When using audition, we'll need a few parameters:- A name for the "best distance" database table that will store the results of the auditioning process.- The metric and parameter for our evaluations, such as precision@1000_absAdditionally, you need to specify the set of `model_group_ids` and `train_end_times` you want to use manually, but `PreAudition` provides some tools for grabbing these from the database in some typical use cases.
###Code
best_dist_table = 'aud_best_dist' # if you're looking at multiple experiments side-by-side, change this for each one
metric = 'precision@'
parameter = '1000_abs'
###Output
_____no_output_____
###Markdown
Pre-Audition `PreAudition` provides some higher level functions to obtain `model_group_ids` and `train_end_times`. For example, `get_model_groups_from_experiment()` and `get_train_end_times()` (note that this will return the `train_end_times` associated with the set of model groups returned by one of the `get_model_groups` methods, so those should be run first)Note that the `baseline_model_types` parameter in the constructor is optional and can be used to identify model groups as baselines rather than candidates for model selection
###Code
pre_aud = PreAudition(
conn,
baseline_model_types=['sklearn.dummy.DummyClassifier'] # optional, requires a list
)
# select model groups by experiment hash id
model_groups = pre_aud.get_model_groups_from_experiment('a1316f404aecc9df9e3c5264b32770f8')
# Alternatively, you can select model groups by label definition using:
# model_groups = pre_aud.get_model_groups_from_label('final_ruling_code_1_4_5_states_klaus_fix_nulls_more_trees')
# Note that this will find train_end_times associated with the model groups defined above
# The "after" parameter is optional
end_times = pre_aud.get_train_end_times(after='2011-01-01')
###Output
_____no_output_____
###Markdown
`get_model_groups_from_experiment()` returns a dictionary with keys `model_groups` and `baseline_model_groups`. How many of each did we get?
###Code
# Number of non-baseline model groups:
print(len(model_groups['model_groups']))
# Number of baseline model groups:
print(len(model_groups['baseline_model_groups']))
###Output
1
###Markdown
`get_train_end_times()` returns a list of `train_end_times`:
###Code
end_times
###Output
_____no_output_____
###Markdown
Alternatively, you can write your own query to get the sets of `model_group_ids`, `baseline_model_group_ids`, and `train_end_times`.For instance, for model groups:```pythonsel = """SELECT DISTINCT(model_group_id)FROM results.model_groupsWHERE model_config->>'label_definition'='final_ruling_code_1_4_5_states_klaus_fix_nulls_more_trees' AND model_type NOT IN ('sklearn.dummy.DummyClassifier')"""model_groups = pre_aud.get_model_groups(sel)```And for baseline model groups:```pythonsel = """SELECT DISTINCT(model_group_id)FROM results.model_groupsWHERE model_config->>'label_definition'='final_ruling_code_1_4_5_states_klaus_fix_nulls_more_trees' AND model_type IN ('sklearn.dummy.DummyClassifier')"""baseline_model_groups = pre_aud.get_model_groups(sel)```And for train_end_times:```pythonsel = """SELECT DISTINCT train_end_timeFROM results.modelsWHERE model_group_id IN ({}) AND EXTRACT(DAY FROM train_end_time) IN (1) AND train_end_time >= '2010-01-01';""".format(', '.join(map(str, model_groups+baseline_model_groups)))end_times = pre_aud.get_train_end_times(query=sel)``` Auditioner Auditioner is the main API to do the rules selection and model groups selection. It filters model groups using a two-step process. - Broad thresholds to filter out truly bad models - A selection rule grid to find the best model groups over time for each of a variety of methods Note that model groups that don't have full train_end_time periods will be excluded from the analysis, so it's important to **ensure that all model groups have been completed across all train/test splits**When we set up our auditioner object, we need to give it a database connection, the model groups to consider (and optionally baseline model groups), train_end_times, and tell it how we're going to filter the models. Note that the `initial_metric_filters` parameter specified below tells `Auditioner` what metric and parameter we'll be using and starts off without any initial filtering constraints (which is what you'll typically want):
###Code
aud = Auditioner(
db_engine = conn,
model_group_ids = model_groups['model_groups'],
train_end_times = end_times,
initial_metric_filters = [{'metric': metric, 'parameter': parameter, 'max_from_best': 1.0, 'threshold_value': 0.0}],
distance_table = best_dist_table,
baseline_model_group_ids = model_groups['baseline_model_groups'] # optional
)
###Output
_____no_output_____
###Markdown
How to use Auditioner Plotting the best distance metric and groups over time This is done with the `plot_model_groups` method and may take a minute to generate. What it does is to get rid of really bad model groups wrt the metric of interest. A model group is discarded if: - It’s never close to the “best” model (define close to best) or - If it’s metric is below a certain number (define min threshold) at least once
###Code
aud.plot_model_groups()
###Output
_____no_output_____
###Markdown
With our first default setting, we don't filter out models because `max_from_best`=`1.0` and `threshold_value`=`0.0` are the loosest criteria.- The frist graph shows us the fraction of models worse than the best model by distance wrt the metric of interest.- The second graph shows us the performance of a model group over time. The dashed line is the best case at that time period.
###Code
ids = aud.thresholded_model_group_ids
len(ids)
###Output
_____no_output_____
###Markdown
Applying thresholds to weed out bad models Here we use the `set_one_metric_filter` to apply a simple filter in order to eliminate poorly performing ones. The model groups will be plotted again after updating the filters.Here's how these filters work:- In order to meet the `max_from_best` filter, a model group must have *at least one result* under that threshold- In order to meet the `threshold_value` filter, a model group must have *all results* perform above that threshold
###Code
aud.set_one_metric_filter(
metric=metric,
parameter=parameter,
max_from_best=0.2,
threshold_value=0.0)
###Output
_____no_output_____
###Markdown
Apply a round of filtering, starting with no `threshold_value` and a fairly wide margin on `max_from_best`
###Code
# how many model groups are left after the first round of filtering?
len(aud.thresholded_model_group_ids)
###Output
_____no_output_____
###Markdown
That didn't thin things out too much, so let's get a bit more agressive with both parameters.If we want to have multiple filters, then use `update_metric_filters` to apply a set of filters to the model groups we're considering in order to eliminate poorly performing ones. The model groups will be plotted again after updating the filters.
###Code
# let's try some more agressive filtering:
aud.update_metric_filters([{
'metric': metric,
'parameter': parameter,
'max_from_best': 0.17,
'threshold_value': 0.2
}])
###Output
_____no_output_____
###Markdown
That certainly thinned out our candidate models a lot more! In practice, you may need to iterate a few times to find a good set of filter parameters for your specific project.Note that the `DummyClassifier` model group doesn't meet our filters, but we'll still see it on the audition graphs because we've identified it as a baseline model group (however it won't be included as a candidate for our model selection results)
###Code
# how many model groups are left after the latest round of filtering?
len(aud.thresholded_model_group_ids)
###Output
_____no_output_____
###Markdown
Note that `aud` is storing the state of the most recent filtering performed, so `aud.thresholded_model_group_ids` will always give you the set of model groups that meet the current filtering parameters. These filters will also apply as a starting point for the selection rules below: Applying selection rules and calculating regrets for the narrowed set of models The goal of audition is to narrow a very large number of model groups to a small number of best candidates, ideally making use of the full time series of information. There are several ways one could consider doing so, using over-time averages of the metrics of interest, weighted averages to balance between metrics, the distance from best metrics, and balancing metric average values and stability.Audition formalizes this idea through "selection rules" that take in the data up to a given point in time, apply some rule to choose a model group, and evaluate the performance of that chosen model in the subsequent time window, the regret. You can register, evaluate, and update selection rules associated with the Auditioner object as shown below.Audition will run similations of different model group selection rules to show users and let users asses which rule(s) is the best for their needs. Next, Audition will output numbers of best model in current time period for each model. Rules Maker We need to create a selection rule grid which will be passed to `aud.register_selection_rule_grid()` to run the simulations. The selection rule grid is only recognized as a list of dictionaries of all the parameters. One can create this giant grid by hands, but Audition also provides some helper functions to create the grid easily. Note that in these selection rule definitions the parameter `n` specifies how many of the best-performing models (according to that selection strategy) to return when we ask for the current best model groups.
###Code
Rule1 = SimpleRuleMaker()
# if we only care about performance on the most recent test set
Rule1.add_rule_best_current_value(metric=metric, parameter=parameter, n=3)
# if we care about the average performance across all test sets
Rule1.add_rule_best_average_value(metric=metric, parameter=parameter, n=3)
# If we care about performance across all test sets, but think recent performance is more important
Rule1.add_rule_best_avg_recency_weight(metric=metric, parameter=parameter,
curr_weight=[1.5, 2.0, 5.0], decay_type=["linear"], n=3)
# If we only care about stability (regardless of performance)
Rule1.add_rule_lowest_metric_variance(metric=metric, parameter=parameter, n=3)
# If we care about how frequently the model is within a given distance from the best-performing one
Rule1.add_rule_most_frequent_best_dist(metric=metric, parameter=parameter, dist_from_best_case=[0.05], n=3)
# As a comparison point, we could also just choose a model group at random
Rule2 = RandomGroupRuleMaker(n=1)
seln_rules = create_selection_grid(Rule1, Rule2)
seln_rules
###Output
_____no_output_____
###Markdown
Alternatively, we can create specify our selection rule grid from scratch directly, such as:```pythonseln_rules = [{ 'shared_parameters': [ {'metric': 'precision@', 'parameter': '200_abs'}, ], 'selection_rules': [ {'name': 'best_current_value', 'n': 3}, {'name': 'best_average_value', 'n': 3}, {'name': 'most_frequent_best_dist', 'dist_from_best_case': [0.01, 0.05, 0.1, 0.15], 'n': 3} ] }, { 'shared_parameters': [ {'metric': 'precision@', 'parameter': '200_abs'} ], 'selection_rules': [ {'name': 'best_avg_recency_weight', 'curr_weight': [1.5, 2.0, 5.0], 'decay_type': ['linear']} ] }, { 'shared_parameters': [{}], 'selection_rules': [{'name': 'random_model_group'}] }]``` Register rules and run the simulations Register the rules to Audition and it will run the simulations of `regret` and `metric_next_time` for every time period with all the rules and parameters combinations.
###Code
aud.register_selection_rule_grid(seln_rules, plot=True)
###Output
_____no_output_____
###Markdown
We can pull the `results_for_rule` out which is a DataFrame of simulation data.
###Code
aud.results_for_rule[metric+parameter].head()
###Output
_____no_output_____
###Markdown
Finally, when you have a selection rule grid you're happy with, the selection_rule_model_group_ids parameter of the Auditioner will give you the model groups chosen by the selection rules in the grid when applied to the most recent end time for use in application:
###Code
aud.selection_rule_model_group_ids
###Output
_____no_output_____ |
sec9_pool.ipynb | ###Markdown
Future类,task的容器,提供了submit,done,cancel等方法。 Work_Iterm类,真正执行任务的单元。
###Code
from concurrent.futures import ThreadPoolExecutor, wait, as_completed
import time
# concurrent.futures 线程池模块
def do(sec, name):
time.sleep(sec)
print('{}:{} sec done!'.format(name, sec))
return sec
def doone(one):
time.sleep(one)
print('{} sec done!'.format(one))
return one
executor = ThreadPoolExecutor(max_workers=2)
task = executor.submit(do, 1, 't0')
task1 = executor.submit(do, 1.5, 't1')
task2 = executor.submit(do, 2, 't2')
task2.cancel() # 取消任务,task2没有被执行,pool中worker为2。
# running正在执行的、completed执行完的不能cancel
print(task.done()) # 判断是否完成
print(task.result(timeout=None)) # 取返回值,阻塞主线程
args = [[1, 't0'], [1.5, 't1'], [2, 't2']]
all_task = [executor.submit(do, *arg) for arg in args] # 出现错误不会被抛出
# wait(all_task, return_when='FIRST_COMPLETED') # 等待,阻塞主线程
# print('main')
for future in as_completed(all_task): # 得到已经完成的task,as_completed 是生成器 yield
res = future.result()
print(res, 'success.')
# one_args = [0.5, 1, 1.5]
# for future in executor.map(do, one_args):
# # 直接得到task返回值
# print(future, 'success')
with ThreadPoolExecutor(3) as executor:
task = executor.submit(do, 1, 't0')
task1 = executor.submit(do, 1.5, 't1')
task2 = executor.submit(do, 2, 't2')
###Output
t0:1 sec done!
t1:1.5 sec done!
t2:2 sec done!
|
notebook/2-1-beautifulsoup-basic.ipynb | ###Markdown
Basic usage of beautifulsoup**First we still need to open a [page](https://mofanpy.com/static/scraping/basic-structure.html), then we can apply beautifulsoup on this page's html.**
###Code
from bs4 import BeautifulSoup
from urllib.request import urlopen
# if has Chinese, apply decode()
html = urlopen("https://mofanpy.com/static/scraping/basic-structure.html").read().decode('utf-8')
print(html)
###Output
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<title>Scraping tutorial 1 | 莫烦Python</title>
<link rel="icon" href="https://mofanpy.com/static/img/description/tab_icon.png">
</head>
<body>
<h1>爬虫测试1</h1>
<p>
这是一个在 <a href="https://mofanpy.com/">莫烦Python</a>
<a href="https://mofanpy.com/tutorials/scraping">爬虫教程</a> 中的简单测试.
</p>
</body>
</html>
###Markdown
**Parsing this html using a method called lxml, create a soup object. You can simply "h1" or "p" to call the heading 1 and paragraph tag from soup.**
###Code
soup = BeautifulSoup(html, features='lxml')
print(soup.h1)
print('\n', soup.p)
###Output
<h1>爬虫测试1</h1>
<p>
这是一个在 <a href="https://mofanpy.com/">莫烦Python</a>
<a href="https://mofanpy.com/tutorials/scraping">爬虫教程</a> 中的简单测试.
</p>
###Markdown
**Or using some helpful functions to find tags. Access the attribute of found tags using a key just like what you do in a python dictionary.**
###Code
all_href = soup.find_all('a')
all_href = [l['href'] for l in all_href]
print('\n', all_href)
###Output
['https://mofanpy.com/', 'https://mofanpy.com/tutorials/scraping']
###Markdown
Basic usage of beautifulsoup**First we still need to open a [page](https://morvanzhou.github.io/static/scraping/basic-structure.html), then we can apply beautifulsoup on this page's html.**
###Code
from bs4 import BeautifulSoup
from urllib.request import urlopen
# if has Chinese, apply decode()
html = urlopen("https://morvanzhou.github.io/static/scraping/basic-structure.html").read().decode('utf-8')
print(html)
###Output
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<title>Scraping tutorial 1 | 莫烦Python</title>
<link rel="icon" href="https://morvanzhou.github.io/static/img/description/tab_icon.png">
</head>
<body>
<h1>爬虫测试1</h1>
<p>
这是一个在 <a href="https://morvanzhou.github.io/">莫烦Python</a>
<a href="https://morvanzhou.github.io/tutorials/scraping">爬虫教程</a> 中的简单测试.
</p>
</body>
</html>
###Markdown
**Parsing this html using a method called lxml, create a soup object. You can simply "h1" or "p" to call the heading 1 and paragraph tag from soup.**
###Code
soup = BeautifulSoup(html, features='lxml')
print(soup.h1)
print('\n', soup.p)
###Output
<h1>爬虫测试1</h1>
<p>
这是一个在 <a href="https://morvanzhou.github.io/">莫烦Python</a>
<a href="https://morvanzhou.github.io/tutorials/scraping">爬虫教程</a> 中的简单测试.
</p>
###Markdown
**Or using some helpful functions to find tags. Access the attribute of found tags using a key just like what you do in a python dictionary.**
###Code
all_href = soup.find_all('a')
all_href = [l['href'] for l in all_href]
print('\n', all_href)
###Output
['https://morvanzhou.github.io/', 'https://morvanzhou.github.io/tutorials/scraping']
|
04_odds_ratio.ipynb | ###Markdown
Calculating Odds Ratio> API details.
###Code
#hide
%load_ext autoreload
%autoreload 2
#hide
from nbdev.showdoc import *
from nbdev import *
from corradin_ovp_utils.catalog import test_data_catalog, conf_test_data_catalog
from fastcore.test import ExceptionExpected
#export
import pandas as pd
from typing import Any, Dict, List, Optional, Literal, Union
from dataclasses import dataclass
from fastcore.basics import basic_repr
from pydantic import BaseModel
from itertools import product
from ast import literal_eval
import numpy as np
geno_each_sample = test_data_catalog.load("geno_each_sample")
case_geno_each_sample = test_data_catalog.load("case_geno_each_sample")
control_geno_each_sample = test_data_catalog.load("control_geno_each_sample")
sample_file = test_data_catalog.load("sample_file")
all_geno_df = test_data_catalog.load("all_geno_df")
geno_each_sample
geno_each_sample.columns
###Output
_____no_output_____
###Markdown
---
###Code
#export
@dataclass
class RsidComboInfo():
df: pd.DataFrame
rsid_list: List[str]
NA_val: str
__repr__ = basic_repr("rsid_list,NA_val")
#TODO: Query does not work when rsid is a number, need to find a way around that
def query(self, **rsid_dict):
if not all([rsid in self.rsid_list for rsid in rsid_dict.keys()]):
raise ValueError("Some Rsid are not in the dataframe")
filtered_df = self.df.copy()
for rsid, geno in rsid_dict.items():
filtered_df = filtered_df.query(f"{rsid} == '{geno}'")
return filtered_df
def get_all_genos(self, rsid:str):
return self.df[rsid].unique()
@property
def total_samples_with_NA(self):
return self.df.unique_samples_count.sum()
@property
def num_samples_NA(self):
return self.df.loc[(self.df[self.rsid_list] == self.NA_val).any(axis=1)].unique_samples_count.sum()
@property
def total_samples_no_NA(self):
return self.total_samples_with_NA - self.num_samples_NA
def get_geno_combination_df(geno_each_sample_df: pd.DataFrame, rsid_list:List[str], NA_val="NA", as_df= False):
#geno_each_sample_df[["rs77948203", "rs1014626", "rs1004237"]].reset_index().groupby(["rs77948203", "rs1014626", "rs1004237"])["sample_id"].unique().reset_index()
geno_combination_df = geno_each_sample_df[rsid_list].fillna(NA_val).reset_index().groupby(rsid_list)["sample_id"].agg(**{"unique_samples_id":"unique", "unique_samples_count": "nunique"}).reset_index()
if as_df:
return geno_combination_df
else:
info_obj = RsidComboInfo(df= geno_combination_df, rsid_list = rsid_list, NA_val= NA_val)
return info_obj
test_rsid_info_obj = get_geno_combination_df(geno_each_sample,["rs77948203"])
test_rsid_info_obj
test_rsid_info_obj.df
assert test_rsid_info_obj.df.equals(geno_each_sample["rs77948203"].fillna("NA").reset_index().groupby("rs77948203")["sample_id"].agg(**{"unique_samples_id":"unique", "unique_samples_count": "nunique"}).reset_index())
assert test_rsid_info_obj.rsid_list == ['rs77948203']
###Output
_____no_output_____
###Markdown
---
###Code
get_geno_combination_df(geno_each_sample,["rs77948203"]).query(rs77948203='AA')
get_geno_combination_df(geno_each_sample,["rs77948203", "rs1014626"]).df
get_geno_combination_df(geno_each_sample,["rs77948203", "rs1014626"]).get_all_genos("rs1014626")
###Output
_____no_output_____
###Markdown
You can query multiple genotypes by passing in keyword arguments or a dictionary
###Code
query_result_1 = get_geno_combination_df(geno_each_sample,["rs77948203", "rs1014626"]).query(rs77948203= 'AG', rs1014626= 'TT')
query_result_1
query_result_2 = get_geno_combination_df(geno_each_sample,["rs77948203", "rs1014626"]).query(**{"rs77948203": 'AG', "rs1014626": 'TT'})
query_result_2
assert query_result_1.equals(query_result_2)
###Output
_____no_output_____
###Markdown
Querying an unknown rsid will lead to an error
###Code
with ExceptionExpected(ex=ValueError, regex = "Some Rsid are not in the dataframe"):test_rsid_info_obj.query(rs7794820='AA') #missing the last digit of rsid
get_geno_combination_df(geno_each_sample,["rs77948203"]).query(rs77948203='NA').empty
###Output
_____no_output_____
###Markdown
You can choose to return a simple dataframe, or an object that has enhanced capabilities
###Code
get_geno_combination_df(geno_each_sample,["rs1014626"]).df
get_geno_combination_df(geno_each_sample,["rs1014626"], as_df = True)
assert get_geno_combination_df(geno_each_sample,["rs1014626"]).df.equals(get_geno_combination_df(geno_each_sample,["rs1014626"], as_df = True))
###Output
_____no_output_____
###Markdown
---
###Code
test_geno_combination_df = get_geno_combination_df(geno_each_sample,["rs77948203", "rs1014626"])
test_geno_combination_df.df
test_geno_combination_df.num_samples_NA
NA_samples_df = test_geno_combination_df.df.loc[(test_geno_combination_df.df[["rs77948203", "rs1014626"]] == "NA").any(axis=1)]
NA_samples_df
test_geno_combination_df.total_samples_with_NA
test_eq(test_geno_combination_df.num_samples_NA, NA_samples_df["unique_samples_count"].sum())
test_eq(test_geno_combination_df.num_samples_NA, 11)
test_eq(test_geno_combination_df.total_samples_with_NA, 14947)
test_eq(test_geno_combination_df.total_samples_no_NA, 14936)
get_geno_combination_df(geno_each_sample,["rs77948203", "rs1014626", "rs134490"])
###Output
_____no_output_____
###Markdown
---
###Code
sample_file_full_df = sample_file.load_all_files()
sample_file_full_df
geno_each_sample
case_geno_each_sample
test = get_geno_combination_df(case_geno_each_sample,["rs9610458", "rs134490"])
test
test.df
all_geno_df
#export
class CaseControlOddsRatio(BaseModel):
case: RsidComboInfo
control: RsidComboInfo
geno_df: pd.DataFrame
# def __init__(self, *, case_df, control_df, geno_df):
@property
def snp_cols(self):
case_snp_cols = self.case.df.columns.difference(['unique_samples_id', 'unique_samples_count'])
control_snp_cols = self.control.df.columns.difference(['unique_samples_id', 'unique_samples_count'])
assert set(case_snp_cols) == set(control_snp_cols)
snp_cols_sorted = sorted(list(set(case_snp_cols)))
return snp_cols_sorted
@property
def possible_genotypes_single(self):
return self.geno_df[["AA", "AB", "BB"]]
@property
def possible_genotypes_combo(self):
geno_combo_df = pd.DataFrame(product(*[self.possible_genotypes_single.loc[rsid].tolist()
for rsid in self.possible_genotypes_single.index]), columns = self.possible_genotypes_single.index)
return geno_combo_df
@property
def case_total_no_NA(self):
return self.case.total_samples_no_NA
@property
def case_total_with_NA(self):
return self.case.total_samples_with_NA
@property
def control_total_no_NA(self):
return self.control.total_samples_no_NA
@property
def control_total_with_NA(self):
return self.control.total_samples_with_NA
def calculate_odds_ratio(self, query_geno_dict: Dict[str, str], ndigits = 5):
try:
geno_case = self.case.query(**query_geno_dict).unique_samples_count.item()
# except ValueError:
# print(self.case.query(**query_geno_dict).unique_samples_count)
#try:
geno_control = self.control.query(**query_geno_dict).unique_samples_count.item()
# except ValueError:
# print(self.control.query(**query_geno_dict).unique_samples_count)
odds_ratio = odds_ratio_calculator(geno_case= geno_case,
geno_control=geno_control,
case_total_no_NA = self.case_total_no_NA,
control_total_no_NA = self.control_total_no_NA)
odds_ratio_rounded = round(odds_ratio, ndigits = ndigits)
except ValueError:
return np.nan
return odds_ratio_rounded
@property
def odds_ratios_df(self):
odds_ratio = [self.calculate_odds_ratio(query_dict) for query_dict in self.possible_genotypes_combo.to_dict(orient="records")]
odds_ratio_df = self.possible_genotypes_combo.assign(odds_ratio = odds_ratio)
return odds_ratio_df
class Config:
arbitrary_types_allowed = True
def odds_ratio_calculator(geno_case, geno_control, case_total_no_NA, control_total_no_NA):
"""
calculates odds ratio using formula specified by type of pipeline
"""
try:
# if self.odds_ratio_type == 1:
case_odds = geno_case / (case_total_no_NA - geno_case)
control_odds = geno_control / (control_total_no_NA - geno_control)
# else:
# case_odds = case / case_total
# control_odds = control / control_total
odds_ratio = case_odds / control_odds
# if odds_ratio == 0:
# odds_ratio = "NA"
return odds_ratio
except ZeroDivisionError:
return "NA"
test_case_control_odds_ratio_single = CaseControlOddsRatio(case = get_geno_combination_df(case_geno_each_sample, ["rs9610458"]),
control = get_geno_combination_df(control_geno_each_sample, ["rs9610458"]),
geno_df = all_geno_df.loc[["rs9610458"]])
test_case_control_odds_ratio_single
test_case_control_odds_ratio_single.possible_genotypes_combo.to_dict(orient="records")
test_eq(test_case_control_odds_ratio_single.case.total_samples_no_NA, 9385)
test_eq(test_case_control_odds_ratio_single.control.total_samples_no_NA, 5076)
test_eq(test_case_control_odds_ratio_single.calculate_odds_ratio({"rs9610458": "CC"}), 0.93426)
test_eq(test_case_control_odds_ratio_single.odds_ratios_df["odds_ratio"].tolist(), [0.93426, 0.93578, 1.14175])
test_case_control_odds_ratio = CaseControlOddsRatio(case = get_geno_combination_df(case_geno_each_sample, ["rs9610458", "rs134490"]),
control = get_geno_combination_df(control_geno_each_sample, ["rs9610458", "rs134490"]),
geno_df = all_geno_df.loc[["rs9610458", "rs134490"]])
test_case_control_odds_ratio.possible_genotypes_single
assert test_case_control_odds_ratio.possible_genotypes_single.equals(pd.DataFrame.from_dict({"rs9610458": ["CC", "CT", "TT"],
"rs134490": ["CC", "CT", "TT"]},
orient = "index", columns = ["AA", "AB", "BB"]).rename_axis("id_col"))
assert test_case_control_odds_ratio.geno_df.loc[test_case_control_odds_ratio.snp_cols].equals(pd.DataFrame.from_dict({"rs134490": ["C", "T", "CC", "CT", "TT"],
"rs9610458": ["C", "T", "CC", "CT", "TT"]},
orient = "index",
columns = ["alleleA", "alleleB", "AA", "AB", "BB"]).rename_axis("id_col"))
test_case_control_odds_ratio.case.df
test_case_control_odds_ratio.odds_ratios_df
test_eq(test_case_control_odds_ratio.case.total_samples_no_NA, 8048)
test_eq(test_case_control_odds_ratio.control.total_samples_no_NA, 4439)
test_eq(test_case_control_odds_ratio.odds_ratios_df["odds_ratio"].tolist(), [1.001, 1.00885, 0.92318, 1.07029, 0.86588, 0.98498, 1.05632, 1.06943, 1.15646])
test_eq(test_case_control_odds_ratio.case.query(rs9610458="CC", rs134490="CC").unique_samples_count.item(), 49)
#export
def odds_ratio_df_single_combined(*,case_geno_each_sample:pd.DataFrame, control_geno_each_sample:pd.DataFrame, all_geno_df:pd.DataFrame, single_rsid:str, combo_rsid_list:List[str]):
""" `combo_rsid_list` has to contain `single_rsid`
"""
assert single_rsid in combo_rsid_list
test_case_control_odds_ratio_single = CaseControlOddsRatio(case = get_geno_combination_df(case_geno_each_sample, [single_rsid]),
control = get_geno_combination_df(control_geno_each_sample, [single_rsid]),
geno_df = all_geno_df.loc[[single_rsid]])
test_case_control_odds_ratio_combo = CaseControlOddsRatio(case = get_geno_combination_df(case_geno_each_sample, combo_rsid_list),
control = get_geno_combination_df(control_geno_each_sample, combo_rsid_list),
geno_df = all_geno_df.loc[combo_rsid_list])
odds_ratio_df_combined = test_case_control_odds_ratio_combo.odds_ratios_df.merge(test_case_control_odds_ratio_single.odds_ratios_df, on = single_rsid, suffixes = ["_combo", "_single"])
#odds_ratio_df_combined = odds_ratio_df_combined.reset_index(drop=True)
odds_ratio_df_combined = odds_ratio_df_combined.merge(test_case_control_odds_ratio_combo.case.df, on = combo_rsid_list, how = "left")
odds_ratio_df_combined = odds_ratio_df_combined.merge(test_case_control_odds_ratio_combo.control.df, on = combo_rsid_list, how = "left", suffixes = ["_case", "_control"])
odds_ratio_df_combined["case_total_no_NA"] = test_case_control_odds_ratio_combo.case_total_no_NA
odds_ratio_df_combined["case_total_with_NA"] = test_case_control_odds_ratio_combo.case_total_with_NA
odds_ratio_df_combined["control_total_no_NA"] = test_case_control_odds_ratio_combo.control_total_no_NA
odds_ratio_df_combined["control_total_with_NA"] = test_case_control_odds_ratio_combo.control_total_with_NA
return odds_ratio_df_combined
odds_ratio_df_single_combined(case_geno_each_sample = case_geno_each_sample,
control_geno_each_sample = control_geno_each_sample,
single_rsid = "rs9610458",
all_geno_df = all_geno_df,
combo_rsid_list = ["rs9610458", "rs77948203"])
###Output
_____no_output_____
###Markdown
---
###Code
odds_ratio_df_rs9610458_rs77948203 = test_data_catalog.load("odds_ratio_df_rs9610458_rs77948203")
odds_ratio_df_rs9610458_rs77948203
#export
def reconstruct_genetic_info(summary_df, rsid_list:List[str], exclude_NA=True):
#TODO: handle the case where no sample ids are provided
summary_df_copy = summary_df.copy()
if exclude_NA:
summary_df_copy = summary_df_copy.loc[summary_df_copy.notna().all(axis=1),:]
case_geno_each_sample_reconstructed = summary_df_copy.loc[:, rsid_list + ["unique_samples_id_case"]].explode("unique_samples_id_case")
case_geno_each_sample_reconstructed = case_geno_each_sample_reconstructed.set_index("unique_samples_id_case")
case_geno_each_sample_reconstructed.index.name = "sample_id"
control_geno_each_sample_reconstructed = summary_df_copy.loc[:, rsid_list + ["unique_samples_id_control"]].explode("unique_samples_id_control")
control_geno_each_sample_reconstructed = control_geno_each_sample_reconstructed.set_index("unique_samples_id_control")
control_geno_each_sample_reconstructed.index.name = "sample_id"
return {"case_geno_each_sample": case_geno_each_sample_reconstructed, "control_geno_each_sample": control_geno_each_sample_reconstructed}
test_data_catalog.reload().load("odds_ratio_df_rs134490_rs1004237")
reconstruct_genetic_info(odds_ratio_df_rs9610458_rs77948203, rsid_list = ["rs9610458", "rs77948203"])
test_df_reconstructed = odds_ratio_df_single_combined(**reconstruct_genetic_info(odds_ratio_df_rs9610458_rs77948203,
rsid_list = ["rs9610458", "rs77948203"]),
single_rsid = "rs9610458",
all_geno_df = all_geno_df,
combo_rsid_list = ["rs9610458", "rs77948203"])
test_df_reconstructed
odds_ratio_df_rs9610458_rs77948203
#the reconstructed df doesn't have NA
test_df_reconstructed.drop(columns=["case_total_with_NA", "control_total_with_NA"]).equals(odds_ratio_df_rs9610458_rs77948203.drop(columns=["case_total_with_NA", "control_total_with_NA"]))
###Output
_____no_output_____
###Markdown
module name here> API details.
###Code
#hide
from nbdev.showdoc import *
import numpy as np
from corradin_ovp_utils.catalog import test_data_catalog, conf_test_data_catalog
from fastcore.test import ExceptionExpected
#export
import pandas as pd
from typing import Any, Dict, List, Optional, Literal, Union
from dataclasses import dataclass
geno_each_sample = test_data_catalog.load("geno_each_sample")
geno_each_sample
#export
@dataclass
class RsidComboInfo():
df: pd.DataFrame
rsid_list: List[str]
NA_val: str
def query(self, **rsid_dict):
if not all([rsid in self.rsid_list for rsid in rsid_dict.keys()]):
raise ValueError("Some Rsid are not in the dataframe")
filtered_df = self.df.copy()
for rsid, geno in rsid_dict.items():
filtered_df = filtered_df.query(f"{rsid} == '{geno}'")
return filtered_df
def get_all_genos(self, rsid:str):
return self.df[rsid].unique()
@property
def total_samples_with_NA(self):
return self.df.unique_samples_count.sum()
@property
def num_samples_NA(self):
return self.df.loc[(self.df[self.rsid_list] == self.NA_val).any(axis=1)].unique_samples_count.sum()
@property
def total_samples_no_NA(self):
return self.total_samples_with_NA - self.num_samples_NA
def __repr__(self):
return f"{self.__class__}(rsid_list = {self.rsid_list}, NA_val = '{self.NA_val}')"
def get_geno_combination_df(geno_each_sample_df: pd.DataFrame, rsid_list:List[str], NA_val="NA", as_df= False):
#geno_each_sample_df[["rs77948203", "rs1014626", "rs1004237"]].reset_index().groupby(["rs77948203", "rs1014626", "rs1004237"])["sample_id"].unique().reset_index()
geno_combination_df = geno_each_sample_df[rsid_list].fillna(NA_val).reset_index().groupby(rsid_list)["sample_id"].agg(**{"unique_samples_id":"unique", "unique_samples_count": "nunique"}).reset_index()
if as_df:
return geno_combination_df
else:
info_obj = RsidComboInfo(df= geno_combination_df, rsid_list = rsid_list, NA_val= NA_val)
return info_obj
test_rsid_info_obj = get_geno_combination_df(geno_each_sample,["rs77948203"])
test_rsid_info_obj
test_rsid_info_obj.df
assert test_rsid_info_obj.df.equals(geno_each_sample["rs77948203"].fillna("NA").reset_index().groupby("rs77948203")["sample_id"].agg(**{"unique_samples_id":"unique", "unique_samples_count": "nunique"}).reset_index())
assert test_rsid_info_obj.rsid_list == ['rs77948203']
###Output
/Users/ahoang/Documents/Learning/nbdev_tutorial_2nd_try/.venv/lib/python3.8/site-packages/ipykernel/ipkernel.py:283: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.
and should_run_async(code)
###Markdown
---
###Code
get_geno_combination_df(geno_each_sample,["rs77948203"]).query(rs77948203='AA')
get_geno_combination_df(geno_each_sample,["rs77948203", "rs1014626"]).df
###Output
_____no_output_____
###Markdown
You can query multiple genotypes by passing in keyword arguments or a dictionary
###Code
query_result_1 = get_geno_combination_df(geno_each_sample,["rs77948203", "rs1014626"]).query(rs77948203= 'AG', rs1014626= 'TT')
query_result_1
query_result_2 = get_geno_combination_df(geno_each_sample,["rs77948203", "rs1014626"]).query(**{"rs77948203": 'AG', "rs1014626": 'TT'})
query_result_2
assert query_result_1.equals(query_result_2)
###Output
/Users/ahoang/Documents/Learning/nbdev_tutorial_2nd_try/.venv/lib/python3.8/site-packages/ipykernel/ipkernel.py:283: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.
and should_run_async(code)
###Markdown
Querying an unknown rsid will lead to an error
###Code
with ExceptionExpected(ex=ValueError, regex = "Some Rsid are not in the dataframe"):test_rsid_info_obj.query(rs7794820='AA') #missing the last digit of rsid
get_geno_combination_df(geno_each_sample,["rs77948203"]).query(rs77948203='NA').empty
###Output
/Users/ahoang/Documents/Learning/nbdev_tutorial_2nd_try/.venv/lib/python3.8/site-packages/ipykernel/ipkernel.py:283: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.
and should_run_async(code)
###Markdown
You can choose to return a simple dataframe, or an object that has enhanced capabilities
###Code
get_geno_combination_df(geno_each_sample,["rs1014626"]).df
get_geno_combination_df(geno_each_sample,["rs1014626"], as_df = True)
assert get_geno_combination_df(geno_each_sample,["rs1014626"]).df.equals(get_geno_combination_df(geno_each_sample,["rs1014626"], as_df = True))
test_geno_combination_df = get_geno_combination_df(geno_each_sample,["rs77948203", "rs1014626"])
test_geno_combination_df.df
test_geno_combination_df.num_samples_NA
NA_samples_df = test_geno_combination_df.df.loc[(test_geno_combination_df.df[["rs77948203", "rs1014626"]] == "NA").any(axis=1)]
NA_samples_df
assert test_geno_combination_df.num_samples_NA == NA_samples_df["unique_samples_count"].sum() == 9
assert test_geno_combination_df.total_samples_with_NA == 9772
assert test_geno_combination_df.total_samples_no_NA == 9763
get_geno_combination_df(geno_each_sample,["rs77948203", "rs1014626", "rs134490"])
###Output
/Users/ahoang/Documents/Learning/nbdev_tutorial_2nd_try/.venv/lib/python3.8/site-packages/ipykernel/ipkernel.py:283: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.
and should_run_async(code)
|
end-to-end-Machine-Learning/signal/notebooks/notebook-02-statistical_test.ipynb | ###Markdown
Chosen models
###Code
SENSORA = 'HOS_mlp'
SENSORV_union = 'HOS_mlp'
SENSORV_appended = 'HOS_mlp'
SENSORC_union = 'FOURIER_mlp'
SENSORC_appended = 'FOURIER_mlp'
experiments = ['SENSORA/appended', 'SENSORV/union', 'SENSORV/appended', 'SENSORC/union', 'SENSORC/appended']
metrics = ['acc', 'fpr_weighted', 'fnr_weighted']
def get_results_filename(model_name='HOS_mlp'):
results_names = []
for m in metrics:
results_names.append(model_name + '_' + m + '.pkl')
return results_names
get_results_filename()
###Output
_____no_output_____
###Markdown
Load results Axial flux sensor
###Code
results_folder = join('..', 'results', experiments[0], 'pkl')
fnames = get_results_filename(model_name=SENSORA)
print('Loading experiment: {}'.format(results_folder))
print('fnames: {}'.format(fnames))
SENSORA_APPENDED_ACC = joblib.load(join(results_folder, fnames[0]))
SENSORA_APPENDED_FPR = joblib.load(join(results_folder, fnames[1]))
SENSORA_APPENDED_FNR = joblib.load(join(results_folder, fnames[2]))
###Output
Loading experiment: ../results/SENSORA/appended/pkl
fnames: ['HOS_mlp_acc.pkl', 'HOS_mlp_fpr_weighted.pkl', 'HOS_mlp_fnr_weighted.pkl']
###Markdown
Vibration sensor
###Code
results_folder = join('..', 'results', experiments[1], 'pkl')
fnames = get_results_filename(model_name=SENSORV_union)
print('Loading experiment: {}'.format(results_folder))
print('fnames: {}'.format(fnames))
SENSORV_UNION_ACC = joblib.load(join(results_folder, fnames[0]))
SENSORV_UNION_FPR = joblib.load(join(results_folder, fnames[1]))
SENSORV_UNION_FNR = joblib.load(join(results_folder, fnames[2]))
results_folder = join('..', 'results', experiments[2], 'pkl')
fnames = get_results_filename(model_name=SENSORV_appended)
print('Loading experiment: {}'.format(results_folder))
print('fnames: {}'.format(fnames))
SENSORV_APPENDED_ACC = joblib.load(join(results_folder, fnames[0]))
SENSORV_APPENDED_FPR = joblib.load(join(results_folder, fnames[1]))
SENSORV_APPENDED_FNR = joblib.load(join(results_folder, fnames[2]))
###Output
Loading experiment: ../results/SENSORV/union/pkl
fnames: ['HOS_mlp_acc.pkl', 'HOS_mlp_fpr_weighted.pkl', 'HOS_mlp_fnr_weighted.pkl']
Loading experiment: ../results/SENSORV/appended/pkl
fnames: ['HOS_mlp_acc.pkl', 'HOS_mlp_fpr_weighted.pkl', 'HOS_mlp_fnr_weighted.pkl']
###Markdown
Current sensor
###Code
results_folder = join('..', 'results', experiments[3], 'pkl')
fnames = get_results_filename(model_name=SENSORC_union)
print('Loading experiment: {}'.format(results_folder))
print('fnames: {}'.format(fnames))
SENSORC_UNION_ACC = joblib.load(join(results_folder, fnames[0]))
SENSORC_UNION_FPR = joblib.load(join(results_folder, fnames[1]))
SENSORC_UNION_FNR = joblib.load(join(results_folder, fnames[2]))
results_folder = join('..', 'results', experiments[4], 'pkl')
fnames = get_results_filename(model_name=SENSORC_appended)
print('Loading experiment: {}'.format(results_folder))
print('fnames: {}'.format(fnames))
SENSORC_APPENDED_ACC = joblib.load(join(results_folder, fnames[0]))
SENSORC_APPENDED_FPR = joblib.load(join(results_folder, fnames[1]))
SENSORC_APPENDED_FNR = joblib.load(join(results_folder, fnames[2]))
###Output
Loading experiment: ../results/SENSORC/union/pkl
fnames: ['FOURIER_mlp_acc.pkl', 'FOURIER_mlp_fpr_weighted.pkl', 'FOURIER_mlp_fnr_weighted.pkl']
Loading experiment: ../results/SENSORC/appended/pkl
fnames: ['FOURIER_mlp_acc.pkl', 'FOURIER_mlp_fpr_weighted.pkl', 'FOURIER_mlp_fnr_weighted.pkl']
###Markdown
Build the DataFrame
###Code
df = pd.DataFrame(index=experiments, columns=metrics)
df
df = pd.DataFrame(index=experiments, columns=metrics)
df.loc['SENSORA/appended']['acc'] = SENSORA_APPENDED_ACC
df.loc['SENSORA/appended']['fpr_weighted'] = SENSORA_APPENDED_FPR
df.loc['SENSORA/appended']['fnr_weighted'] = SENSORA_APPENDED_FNR
df.loc['SENSORV/union']['acc'] = SENSORV_UNION_ACC
df.loc['SENSORV/union']['fpr_weighted'] = SENSORV_UNION_FPR
df.loc['SENSORV/union']['fnr_weighted'] = SENSORV_UNION_FNR
df.loc['SENSORV/appended']['acc'] = SENSORV_APPENDED_ACC
df.loc['SENSORV/appended']['fpr_weighted'] = SENSORV_APPENDED_FPR
df.loc['SENSORV/appended']['fnr_weighted'] = SENSORV_APPENDED_FNR
df.loc['SENSORC/union']['acc'] = SENSORC_UNION_ACC
df.loc['SENSORC/union']['fpr_weighted'] = SENSORC_UNION_FPR
df.loc['SENSORC/union']['fnr_weighted'] = SENSORC_UNION_FNR
df.loc['SENSORC/appended']['acc'] = SENSORC_APPENDED_ACC
df.loc['SENSORC/appended']['fpr_weighted'] = SENSORC_APPENDED_FPR
df.loc['SENSORC/appended']['fnr_weighted'] = SENSORC_APPENDED_FNR
df.head()
###Output
_____no_output_____
###Markdown
Employ one way ANOVA and ad-hoc paired Tukey HSD test
###Code
from scipy import stats
import statsmodels.api as sm
from statsmodels.formula.api import ols
def anova_and_tukey(df, metric='acc'):
def get_df_metric(df, metric='acc'):
return pd.DataFrame.from_items(zip(df[metric].index, df[metric].values))
new_df = get_df_metric(df, metric)
fvalue, pvalue =stats.f_oneway(new_df['SENSORA/appended'], new_df['SENSORV/union'], new_df['SENSORV/appended'],
new_df['SENSORC/union'], new_df['SENSORC/appended'])
# reshape the d dataframe suitable for statsmodels package
d_melt = pd.melt(new_df.reset_index(), id_vars=['index'], value_vars=experiments)
# replace column names
d_melt.columns = ['index', 'sensor', 'value']
# Ordinary Least Squares (OLS) model
model = ols('value ~ C(sensor)', data=d_melt).fit()
anova_table = sm.stats.anova_lm(model, typ=2)
from statsmodels.stats.multicomp import pairwise_tukeyhsd
from statsmodels.sandbox.stats.multicomp import TukeyHSDResults
from statsmodels.stats.libqsturng import psturng
# perform multiple pairwise comparison (Tukey HSD)
m_comp = pairwise_tukeyhsd(endog=d_melt['value'], groups=d_melt['sensor'], alpha=0.05)
pvalues = psturng(np.abs(m_comp.meandiffs / m_comp.std_pairs), len(m_comp.groupsunique), m_comp.df_total)
return anova_table, m_comp, pvalues
###Output
/home/navar/anaconda3/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88
return f(*args, **kwds)
###Markdown
For ACC
###Code
anova_acc, m, pvalues = anova_and_tukey(df, 'acc')
anova_acc
m.summary()
pvalues
###Output
_____no_output_____
###Markdown
For FPR-W and FNR-W
###Code
anova_fpr, m, pvalues = anova_and_tukey(df, 'fpr_weighted')
anova_fpr
m.summary()
pvalues
anova_fnr, m, pvalues = anova_and_tukey(df, 'fnr_weighted')
anova_fnr
m.summary()
pvalues
m.plot_simultaneous()
###Output
_____no_output_____
###Markdown
Employ the paired Hypohesis test of Kolmogorov-Smirnov
###Code
h_table_acc = pd.DataFrame(index=experiments, columns=experiments)
h_table_fpr = pd.DataFrame(index=experiments, columns=experiments)
h_table_fnr = pd.DataFrame(index=experiments, columns=experiments)
from scipy import stats
def ks_test_groups(df, htable, metric):
max_idx = df.shape[0]
for e in range(0, max_idx):
idx = 0
exp1 = df.iloc[e]
for e2 in range(0, max_idx):
exp2 = df.iloc[e2]
# print("E1: {}".format(exp1.name))
# print("E2: {}".format(exp2.name))
# print('=======')
g = df.loc[exp1.name][metric]
f = df.loc[exp2.name][metric]
htable.loc[exp1.name][exp2.name] = stats.ks_2samp(g, f).pvalue
return htable
###Output
_____no_output_____
###Markdown
For ACC
###Code
r = ks_test_groups(df, htable=h_table_acc, metric='acc')
r
###Output
_____no_output_____
###Markdown
For FPR
###Code
r = ks_test_groups(df, htable=h_table_fpr, metric='fpr_weighted')
r
###Output
_____no_output_____
###Markdown
For FNR
###Code
r = ks_test_groups(df, htable=h_table_fnr, metric='fnr_weighted')
r
###Output
_____no_output_____ |
Traffic_Sign_Classifier_norm_128_augment-brightness.ipynb | ###Markdown
Self-Driving Car Engineer Nanodegree Deep Learning Project: Build a Traffic Sign Recognition ClassifierIn this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary. > **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission. In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) that can be used to guide the writing process. Completing the code template and writeup template will cover all of the [rubric points](https://review.udacity.com/!/rubrics/481/view) for this project.The [rubric](https://review.udacity.com/!/rubrics/481/view) contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode. --- Step 0: Load The Data
###Code
import matplotlib.pyplot as plt
import random
import numpy as np
import random
import cv2
import tensorflow as tf
from PIL import Image, ImageEnhance
# Visualizations will be shown in the notebook.
%matplotlib inline
# Load pickled data
import pickle
# TODO: Fill this in based on where you saved the training and testing data
training_file = '../data/train.p'
validation_file= '../data/valid.p'
testing_file = '../data/test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
# Load name of id
with open("signnames.csv", "r") as f:
signnames = f.read()
id_to_name = { int(line.split(",")[0]):line.split(",")[1] for line in signnames.split("\n")[1:] if len(line) > 0}
print("\nLoad data file completed.")
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
print("Image X_train.shape : {}".format(X_train.shape))
print("Image X_valid.shape : {}".format(X_valid.shape))
print("Image X_test.shape : {}".format(X_test.shape))
print("Labels y_train.shape: {}".format(y_train.shape))
print("Labels y_valid.shape: {}".format(y_valid.shape))
print("Labels y_test.shape : {}".format(y_test.shape))
print ('y_test[:10]=', y_test[:10])
print()
print("signnames.csv content:")
for i in range(len(id_to_name)):
print ("%d, %s" %( i, id_to_name[i]))
################# show an example image ###########
index = 7794
X_img = X_train[index]
plt.figure(figsize=(2,2))
plt.imshow(X_img)
img_title = 'y label=' + str(y_train[index]) + ', ' + id_to_name[y_train[index]]
plt.title(img_title)
print()
print("X_img.shape: ", X_img.shape)
print('X_img[:1, :5, :]=\n', X_img[:1, :5, :])
###Output
Image X_train.shape : (34799, 32, 32, 3)
Image X_valid.shape : (4410, 32, 32, 3)
Image X_test.shape : (12630, 32, 32, 3)
Labels y_train.shape: (34799,)
Labels y_valid.shape: (4410,)
Labels y_test.shape : (12630,)
y_test[:10]= [16 1 38 33 11 38 18 12 25 35]
signnames.csv content:
0, Speed limit (20km/h)
1, Speed limit (30km/h)
2, Speed limit (50km/h)
3, Speed limit (60km/h)
4, Speed limit (70km/h)
5, Speed limit (80km/h)
6, End of speed limit (80km/h)
7, Speed limit (100km/h)
8, Speed limit (120km/h)
9, No passing
10, No passing for vehicles over 3.5 metric tons
11, Right-of-way at the next intersection
12, Priority road
13, Yield
14, Stop
15, No vehicles
16, Vehicles over 3.5 metric tons prohibited
17, No entry
18, General caution
19, Dangerous curve to the left
20, Dangerous curve to the right
21, Double curve
22, Bumpy road
23, Slippery road
24, Road narrows on the right
25, Road work
26, Traffic signals
27, Pedestrians
28, Children crossing
29, Bicycles crossing
30, Beware of ice/snow
31, Wild animals crossing
32, End of all speed and passing limits
33, Turn right ahead
34, Turn left ahead
35, Ahead only
36, Go straight or right
37, Go straight or left
38, Keep right
39, Keep left
40, Roundabout mandatory
41, End of no passing
42, End of no passing by vehicles over 3.5 metric tons
X_img.shape: (32, 32, 3)
X_img[:1, :5, :]=
[[[255 254 186]
[171 166 126]
[165 165 96]
[255 248 210]
[201 153 128]]]
###Markdown
--- Step 1: Dataset Summary & ExplorationThe pickled data is a dictionary with 4 key/value pairs:- `'features'` is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).- `'labels'` is a 1D array containing the label/class id of the traffic sign. The file `signnames.csv` contains id -> name mappings for each id.- `'sizes'` is a list containing tuples, (width, height) representing the original width and height the image.- `'coords'` is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. **THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES**Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the [pandas shape method](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html) might be useful for calculating some of the summary results. Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas
###Code
### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = len(X_train)
# TODO: Number of validation examples
n_validation = len(X_valid)
# TODO: Number of testing examples.
n_test = len(X_test)
# TODO: What's the shape of an traffic sign image?
image_shape = X_train[0].shape
# TODO: How many unique classes/labels there are in the dataset.
#n_classes = 43 #see signnames.csv
#n_classes = len(np.unique(y_train))
n_classes = len(set(y_train))
print("Number of training examples =", n_train)
print("Number of validation examples =", n_validation)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
###Output
Number of training examples = 34799
Number of validation examples = 4410
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43
###Markdown
Include an exploratory visualization of the dataset Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc. The [Matplotlib](http://matplotlib.org/) [examples](http://matplotlib.org/examples/index.html) and [gallery](http://matplotlib.org/gallery.html) pages are a great resource for doing visualizations in Python.**NOTE:** It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?
###Code
# Visualizations will be shown in the notebook.
%matplotlib inline
# generate set of random random numbers (12) between 0 and max of data
indices = random.sample(range(n_train), 12) #random.randint(0, len(X_train))
#show the training images
print('Training images:', indices)
plt.figure(figsize=(15,15))
for i in range(len(indices)):
image = X_train[indices[i]]
plt.subplot(1, 12, i+1)
plt.title(y_train[indices[i]])
plt.imshow(image)
plt.show()
#show the validation images
print('Validation images:', indices)
indices = random.sample(range(n_validation), 12)
plt.figure(figsize=(15,15))
for i in range(len(indices)):
image = X_valid[indices[i]]
plt.subplot(1,12,i+1)
plt.title(y_valid[indices[i]])
plt.imshow(image)
plt.show()
# histogram of label frequency
hist, bins = np.histogram(y_train, bins=n_classes)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()
###Output
_____no_output_____
###Markdown
---- Step 2: Design and Test a Model ArchitectureDesign and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the [German Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset).The LeNet-5 implementation shown in the [classroom](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play! With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission. There are various aspects to consider when thinking about this problem:- Neural network architecture (is the network over or underfitting?)- Play around preprocessing techniques (normalization, rgb to grayscale, etc)- Number of examples per label (some have more than others).- Generate fake data.Here is an example of a [published baseline model on this problem](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf). It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
###Code
### Define your architecture here.
### Feel free to use as many code cells as needed.
from sklearn.utils import shuffle
X_train, y_train = shuffle(X_train, y_train)
print("Shuffle (X_train, y_train)")
print("X_train.shape=", X_train.shape)
print("y_train.shape=", y_train.shape)
X_train_gen, y_train_gen = X_train, y_train
print("X_train_gen.shape=", X_train_gen.shape)
print("y_train_gen.shape=", y_train_gen.shape)
###Output
Shuffle (X_train, y_train)
X_train.shape= (34799, 32, 32, 3)
y_train.shape= (34799,)
X_train_gen.shape= (34799, 32, 32, 3)
y_train_gen.shape= (34799,)
###Markdown
Pre-process the Data Set (normalization, grayscale, etc.) Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, `(pixel - 128)/ 128` is a quick way to approximately normalize the data and can be used in this project. Other pre-processing steps are optional. You can try different techniques to see if it improves performance. Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
###Code
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
def normalizeMeanStd(img):
img = img - np.mean(img)
img = img / np.std(img)
return img
def normalize128(image):
#img = (image - 128)/128 equal img = image/128 - 1
img = np.divide(image, 128)
image = np.subtract(img,1)
return image
X_train_norm = normalize128(X_train[:,])
X_valid_norm = normalize128(X_valid[:,])
X_test_original = X_test
X_test_norm = normalize128(X_test[:,])
print("Image X_train_norm.shape : {}".format(X_train_norm.shape))
print("Image X_valid_norm.shape : {}".format(X_valid_norm.shape))
print("Image X_test_norm.shape : {}".format(X_test_norm.shape))
import cv2
def augment_brightness_camera_images(image):
image1 = cv2.cvtColor(image,cv2.COLOR_RGB2HSV)
random_bright = .25+np.random.uniform()
#print(random_bright)
image1[:,:,2] = image1[:,:,2]*random_bright
image1 = cv2.cvtColor(image1,cv2.COLOR_HSV2RGB)
return image1
for i in range(len(X_train_gen)):
X_train_gen[i] = augment_brightness_camera_images(X_train_gen[i])
X_train_gen_norm = normalize128(X_train_gen[:,])
print ("Before concatenate:")
print ('X_train_norm.shape=', X_train_norm.shape)
print ('X_train_gen_norm.shape=', X_train_gen_norm.shape)
print ('y_train.shape=', y_train.shape)
print ('y_train_gen.shape=', y_train_gen.shape)
X_train_norm = np.concatenate((X_train_norm, X_train_gen_norm), axis=0)
y_train = np.concatenate((y_train, y_train_gen), axis=0)
print("After pre-processed the data set:")
print("Image X_train_norm.shape : {}".format(X_train_norm.shape))
print("Image X_valid_norm.shape : {}".format(X_valid_norm.shape))
print("Image X_test_norm.shape : {}".format(X_test_norm.shape))
print("Labels y_train.shape: {}".format(y_train.shape))
print("Labels y_valid.shape: {}".format(y_valid.shape))
print("Labels y_test.shape : {}".format(y_test.shape))
################## Show normalized Train set samples #######################
img_num = 12
# generate set of random random numbers (12) between 0 and max of data
indices = random.sample(range(n_train), img_num) #random.randint(0, len(X_train))
#show the training images
print('Training gray images[:,:,0]: indices ', indices)
plt.figure(figsize=(15,15))
for i in range(len(indices)):
plt.subplot(1, img_num, i+1)
plt.title(y_train[indices[i]])
plt.imshow(X_train_norm[indices[i]][:,:,0], cmap='gray')
plt.show()
print('Training gray images[:,:,1]: indices ', indices)
plt.figure(figsize=(15,15))
for i in range(len(indices)):
plt.subplot(1, img_num, i+1)
plt.title(y_train[indices[i]])
plt.imshow(X_train_norm[indices[i]][:,:,1], cmap='gray')
plt.show()
print('Training gray images[:,:,2]: indices ', indices)
plt.figure(figsize=(15,15))
for i in range(len(indices)):
plt.subplot(1, img_num, i+1)
plt.title(y_train[indices[i]])
plt.imshow(X_train_norm[indices[i]][:,:,2], cmap='gray')
plt.show()
#########################################
###Output
Training gray images[:,:,0]: indices [23513, 15457, 4383, 7142, 30292, 7510, 9831, 14922, 32831, 25928, 14372, 17462]
###Markdown
Model Architecture SOLUTION: Implement LeNet-5Implement the [LeNet-5](http://yann.lecun.com/exdb/lenet/) neural network architecture.This is the only cell you need to edit. InputThe LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since Traffic Sign images are RGB, C is 3 in this case. Architecture**Layer 1: Convolutional.** The output shape should be 28x28x6.**Activation.** Your choice of activation function.**Pooling.** The output shape should be 14x14x6.**Layer 2: Convolutional.** The output shape should be 10x10x16.**Activation.** Your choice of activation function.**Pooling.** The output shape should be 5x5x16.**Flatten.** Flatten the output shape of the final pooling layer such that it's 1D instead of 3D. The easiest way to do is by using `tf.contrib.layers.flatten`, which is already imported for you.**Layer 3: Fully Connected.** This should have 120 outputs.**Activation.** Your choice of activation function.**Layer 4: Fully Connected.** This should have 84 outputs.**Activation.** Your choice of activation function.**Layer 5: Fully Connected (Logits).** This should have 43 outputs. OutputReturn the result of the 2nd fully connected layer.
###Code
img_channel = X_train_norm.shape[3]
print ('img_channel=', img_channel)
EPOCHS = 50
BATCH_SIZE = 128
rate = 0.001
save_modle_dir = './lenet_norm_128_augment-bright/'
from tensorflow.contrib.layers import flatten
def LeNet(x):
# Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
mu = 0
sigma = 0.1
# SOLUTION: Layer 1: Convolutional. Input = 32x32ximg_channel. Output = 28x28x6.
conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, img_channel, 6), mean = mu, stddev = sigma))
conv1_b = tf.Variable(tf.zeros(6))
conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b
# SOLUTION: Activation.
conv1 = tf.nn.relu(conv1)
# SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.
conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))
conv2_b = tf.Variable(tf.zeros(16))
conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b
# SOLUTION: Activation.
conv2 = tf.nn.relu(conv2)
# SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.
conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# SOLUTION: Flatten. Input = 5x5x16. Output = 400.
fc0 = flatten(conv2)
# SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.
fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))
fc1_b = tf.Variable(tf.zeros(120))
fc1 = tf.matmul(fc0, fc1_W) + fc1_b
# SOLUTION: Activation.
fc1 = tf.nn.relu(fc1)
# SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
fc2_W = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))
fc2_b = tf.Variable(tf.zeros(84))
fc2 = tf.matmul(fc1, fc2_W) + fc2_b
# SOLUTION: Activation.
fc2 = tf.nn.relu(fc2)
# SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 43.
fc3_W = tf.Variable(tf.truncated_normal(shape=(84, 43), mean = mu, stddev = sigma))
fc3_b = tf.Variable(tf.zeros(43))
logits = tf.matmul(fc2, fc3_W) + fc3_b
return logits
###Output
_____no_output_____
###Markdown
Features and LabelsTrain LeNet to classify German Traffic Sign data.`x` is a placeholder for a batch of input images.`y` is a placeholder for a batch of output labels.
###Code
x = tf.placeholder(tf.float32, (None, 32, 32, img_channel))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, 43)
print ('x=', x)
print ('y=', y)
print ('one_hot_y=', one_hot_y)
###Output
x= Tensor("Placeholder:0", shape=(?, 32, 32, 3), dtype=float32)
y= Tensor("Placeholder_1:0", dtype=int32)
one_hot_y= Tensor("one_hot:0", dtype=float32)
###Markdown
Train, Validate and Test the ModelA validation set can be used to assess how well the model is performing. A low accuracy on the training and validationsets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
###Code
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
logits = LeNet(x)
print ('logits.shape=', logits.shape)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
#training_operation = tf.train.AdamOptimizer(learning_rate = rate).minimize(loss_operation)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
###Output
logits.shape= (?, 43)
###Markdown
Model EvaluationEvaluate how well the loss and accuracy of the model for a given dataset.
###Code
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})
total_accuracy += (accuracy * len(batch_x))
#print ('evaluate.logits.shape=', logits.shape)
return total_accuracy / num_examples
###Output
_____no_output_____
###Markdown
Train the ModelRun the training data through the training pipeline to train the model.Before each epoch, shuffle the training set.After each epoch, measure the loss and accuracy of the validation set.Save the model after training."""Training...EPOCH 1 ...Validation Accuracy = 0.816EPOCH 2 ...Validation Accuracy = 0.876EPOCH 3 ...Validation Accuracy = 0.887......EPOCH 48 ...Validation Accuracy = 0.956EPOCH 49 ...Validation Accuracy = 0.956EPOCH 50 ...Validation Accuracy = 0.956Model saved"""
###Code
print ('EPOCHS=', EPOCHS)
print ('learning_rate=', rate)
print ('BATCH_SIZE=', BATCH_SIZE)
print ('X_train normalize samples=', X_train_norm.shape)
print ('Image channels=', img_channel)
print ('batchs=', len(X_train)//BATCH_SIZE)
print ('save_modle_dir=', save_modle_dir)
print ()
print ("Start taining at 15:33 ")
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
num_examples = len(X_train_norm)
print("Training...")
print()
for i in range(EPOCHS):
X_train_norm, y_train = shuffle(X_train_norm, y_train)
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH_SIZE
batch_x, batch_y = X_train_norm[offset:end], y_train[offset:end]
#loss = sess.run(loss_operation, feed_dict={x: batch_x, y: batch_y})
sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})
#if (offset%(BATCH_SIZE*50) == 0):
# print('Epoch {:>2}, Batch {:>3} '.format(i+1,(offset//BATCH_SIZE)))
validation_accuracy = evaluate(X_valid_norm, y_valid)
print("EPOCH {} ...".format(i+1))
print("Validation Accuracy = {:.3f}".format(validation_accuracy))
saver.save(sess, save_modle_dir)
print("Model saved")
###Output
Training...
EPOCH 1 ...
Validation Accuracy = 0.826
EPOCH 2 ...
Validation Accuracy = 0.892
EPOCH 3 ...
Validation Accuracy = 0.904
EPOCH 4 ...
Validation Accuracy = 0.907
EPOCH 5 ...
Validation Accuracy = 0.916
EPOCH 6 ...
Validation Accuracy = 0.912
EPOCH 7 ...
Validation Accuracy = 0.922
EPOCH 8 ...
Validation Accuracy = 0.918
EPOCH 9 ...
Validation Accuracy = 0.927
EPOCH 10 ...
Validation Accuracy = 0.919
EPOCH 11 ...
Validation Accuracy = 0.914
EPOCH 12 ...
Validation Accuracy = 0.928
EPOCH 13 ...
Validation Accuracy = 0.924
EPOCH 14 ...
Validation Accuracy = 0.917
EPOCH 15 ...
Validation Accuracy = 0.922
EPOCH 16 ...
Validation Accuracy = 0.923
EPOCH 17 ...
Validation Accuracy = 0.937
EPOCH 18 ...
Validation Accuracy = 0.922
EPOCH 19 ...
Validation Accuracy = 0.933
EPOCH 20 ...
Validation Accuracy = 0.931
EPOCH 21 ...
Validation Accuracy = 0.940
EPOCH 22 ...
Validation Accuracy = 0.933
EPOCH 23 ...
Validation Accuracy = 0.936
EPOCH 24 ...
Validation Accuracy = 0.930
EPOCH 25 ...
Validation Accuracy = 0.932
EPOCH 26 ...
Validation Accuracy = 0.936
EPOCH 27 ...
Validation Accuracy = 0.938
EPOCH 28 ...
Validation Accuracy = 0.928
EPOCH 29 ...
Validation Accuracy = 0.937
EPOCH 30 ...
Validation Accuracy = 0.942
EPOCH 31 ...
Validation Accuracy = 0.935
EPOCH 32 ...
Validation Accuracy = 0.947
EPOCH 33 ...
Validation Accuracy = 0.947
EPOCH 34 ...
Validation Accuracy = 0.946
EPOCH 35 ...
Validation Accuracy = 0.947
EPOCH 36 ...
Validation Accuracy = 0.934
EPOCH 37 ...
Validation Accuracy = 0.943
EPOCH 38 ...
Validation Accuracy = 0.936
EPOCH 39 ...
Validation Accuracy = 0.941
EPOCH 40 ...
Validation Accuracy = 0.946
EPOCH 41 ...
Validation Accuracy = 0.941
EPOCH 42 ...
Validation Accuracy = 0.938
EPOCH 43 ...
Validation Accuracy = 0.941
EPOCH 44 ...
Validation Accuracy = 0.932
EPOCH 45 ...
Validation Accuracy = 0.939
EPOCH 46 ...
Validation Accuracy = 0.940
EPOCH 47 ...
Validation Accuracy = 0.948
EPOCH 48 ...
Validation Accuracy = 0.938
EPOCH 49 ...
Validation Accuracy = 0.942
EPOCH 50 ...
Validation Accuracy = 0.935
Model saved
###Markdown
Evaluate the ModelOnce you are completely satisfied with your model, evaluate the performance of the model on the test set.Be sure to only do this once!If you were to measure the performance of your trained model on the test set, then improve your model, and then measure the performance of your model on the test set again, that would invalidate your test results. You wouldn't get a true measure of how well your model would perform against real data.You do not need to modify this section.
###Code
with tf.Session() as sess:
saver.restore(sess, save_modle_dir)
test_accuracy = evaluate(X_test_norm, y_test)
print("Test Accuracy = {:.3f}".format(test_accuracy))
###Output
INFO:tensorflow:Restoring parameters from ./lenet_norm_128_augment-bright/
Test Accuracy = 0.923
###Markdown
Random select test images for Evaluate the Model
###Code
import random
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
img_num = 20
indices = np.random.randint(0, len(X_test_norm), size=img_num)
print ('Test images indices=',indices)
X_test_norm_input = np.array(X_test_norm[indices])
print ('X_test_norm_input.shape=', X_test_norm_input.shape)
print ('X_test_norm_input[0].shape=', X_test_norm_input[:1].shape)
print()
y_test_input = y_test[indices]
print ('y_test_input.shape=', y_test_input.shape, y_test_input)
print('Test images:')
plt.figure(figsize=(15,15))
for i in range(len(indices)):
image = X_test[indices[i]]
plt.subplot(1, img_num, i+1)
plt.title(y_test[indices[i]])
plt.imshow(image)
plt.show()
with tf.Session() as sess:
saver.restore(sess, save_modle_dir)
print ("\n X_test_norm_input.shape=", type(X_test_norm_input), X_test_norm_input.shape)#, inputX)
output = sess.run(logits, feed_dict={x: X_test_norm_input})
predicts = sess.run(tf.argmax(output, 1))
print("labels :", y_test_input)
print("predict:", predicts )
predict_num = np.sum(np.equal(y_test_input, predicts))
print("%d images predict right!" %( predict_num))
print('Accuracy is {}%'.format((predict_num)/len(y_test_input) *100), 'on the test images.')
###Output
INFO:tensorflow:Restoring parameters from ./lenet_norm_128_augment-bright/
X_test_norm_input.shape= <class 'numpy.ndarray'> (20, 32, 32, 3)
labels : [ 2 3 18 8 17 10 38 9 6 5 5 14 2 2 32 41 14 35 3 38]
predict: [ 2 3 18 8 17 10 38 9 6 5 5 14 2 2 32 9 14 35 3 38]
19 images predict right!
Accuracy is 95.0% on the test images.
###Markdown
--- Step 3: Test a Model on New ImagesTo give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.You may find `signnames.csv` useful as it contains mappings from the class id (integer) to the actual sign name. Load and Output the New Test Images
###Code
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import os
directory = "./test_images/"
images_filenames = os.listdir(directory)
images_filenames.sort()
print ('images_filenames.len=', len(images_filenames), images_filenames)
test_new_images = []
for i, file in enumerate(images_filenames):
#print ('%d: %s' % (i, directory + file))
# It appears that the first file in the directory is some kind of navigation link ... in linux OS
if (file[0] != '.'):
#print ('%d: %s' % (i, directory + file))
img = plt.imread(directory + file)
test_new_images.append(img)
# number of new images
print("Number of new images: ", len(test_new_images))
print("test_new_images[0].shape=", test_new_images[0].shape)
plt.figure(figsize=(15, 15))
for i in range(len(test_new_images)):
plt.subplot(1, 10, i+1)
plt.imshow(test_new_images[i])
plt.show()
###Output
images_filenames.len= 11 ['.ipynb_checkpoints', 'children.jpg', 'construction.jpg', 'keep right.jpg', 'pedestrian.jpg', 'prioritty.jpg', 'right of way.jpg', 'right.jpg', 'stop.jpg', 'thirty_miles.jpg', 'warning.jpg']
Number of new images: 10
test_new_images[0].shape= (319, 389, 3)
###Markdown
Pre-process the new imagesFirst the images are converted to gray image and then resized to 32x32
###Code
test_new_images_gray=[]
for i, image in enumerate(test_new_images):
img = cv2.resize(image,(32,32))
if (img_channel == 1):
img = to_gray(img)
img = hist_equalize(img)
img = normalize_image(img)
else:
img = normalize128(img)
test_new_images_gray.append(img)
print("After normalize...test_new_images_gray[0].shape=", test_new_images_gray[0].shape)
"""
plt.figure(figsize=(15, 15))
for i in range(len(test_new_images_gray)):
plt.subplot(1, 10, i+1)
plt.imshow(test_new_images_gray[i],cmap='gray')
plt.show()
"""
#Convert the images list to np array
test_new_images_processed = np.asarray(test_new_images_gray)
# add the channel/depth dimension to each new image
if (img_channel == 1):
test_new_images_processed = test_new_images_processed[...,None]
print('After channel is added, test_new_images_processed.shape: ',test_new_images_processed.shape)
# labels of the new images
test_new_labels = np.array([28,25,38,27,12,11,33,14,1,18])
print ("len(test_new_labels)=", test_new_labels.shape, test_new_labels)
###Output
After normalize...test_new_images_gray[0].shape= (32, 32, 3)
After channel is added, test_new_images_processed.shape: (10, 32, 32, 3)
len(test_new_labels)= (10,) [28 25 38 27 12 11 33 14 1 18]
###Markdown
Predict the Sign Type for Each Image
###Code
############# The simplest way to predict the test images #################
with tf.Session() as sess:
saver.restore(sess, save_modle_dir)
print ("test_new_images_processed.shape=", type(test_new_images_processed), test_new_images_processed.shape)#, inputX)
#output = sess.run(logits, feed_dict={x: X_input[:2]})
output = sess.run(logits, feed_dict={x: test_new_images_processed})
#print ('Output=', output)
predict_index = sess.run(tf.argmax(output, 1))
print("y lables :", test_new_labels)
print("predicts :", predict_index )
predict_num = np.sum(np.equal(test_new_labels, predict_index))
print("%d images predict right!" %( predict_num))
print('Accuracy is {}%'.format((predict_num)/len(test_new_labels) *100), 'on the test images.')
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
def get_predictions(img_data, label_data):
''' Takes input image data and corresponding label data
and computes prediction
Returns list of predictions
'''
print('Prediction started ...')
predictions = []
with tf.Session() as sess:
saver.restore(sess, save_modle_dir) # restore the session already saved
for i in range(len(img_data)):
# get prediction for each image (consider a single image as a batch)
batch_x, batch_y = [img_data[i]], [label_data[i]]
prediction = sess.run(accuracy_operation, feed_dict={x:batch_x, y:batch_y})
predictions.append(prediction)
return predictions
# get the predictions for the new test images
predicts = get_predictions(test_new_images_processed, test_new_labels)
#predicts = get_predictions(X_test_norm, y_test)
print('Test image | prediction ')
print('--------------------------')
print('length of test:',len(predicts))
print('----Test completed -----')
for i in range(len(predicts)):
print(' image_{} | {:.1f}'.format(i+1, predicts[i]))
###Output
Prediction started ...
INFO:tensorflow:Restoring parameters from ./lenet_norm_128_augment-bright/
Test image | prediction
--------------------------
length of test: 10
----Test completed -----
image_1 | 0.0
image_2 | 1.0
image_3 | 1.0
image_4 | 0.0
image_5 | 1.0
image_6 | 1.0
image_7 | 1.0
image_8 | 1.0
image_9 | 1.0
image_10 | 1.0
###Markdown
Analyze Performance
###Code
### Calculate the accuracy for these 10 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
test_accuracy = np.sum(predicts)*100/len(predicts)
print('Accuracy is {}%'.format(test_accuracy), 'on the test images.')
###Output
Accuracy is 80.0% on the test images.
###Markdown
Output Top 5 Softmax Probabilities For Each Image Found on the Web For each of the new images, print out the model's softmax probabilities to show the **certainty** of the model's predictions (limit the output to the top 5 probabilities for each image). [`tf.nn.top_k`](https://www.tensorflow.org/versions/r0.12/api_docs/python/nn.htmltop_k) could prove helpful here. The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.`tf.nn.top_k` will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. `tf.nn.top_k` is used to choose the three classes with the highest probability:``` (5, 6) arraya = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497, 0.12789202], [ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401, 0.15899337], [ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 , 0.23892179], [ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 , 0.16505091], [ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137, 0.09155967]])```Running it through `sess.run(tf.nn.top_k(tf.constant(a), k=3))` produces:```TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202], [ 0.28086119, 0.27569815, 0.18063401], [ 0.26076848, 0.23892179, 0.23664738], [ 0.29198961, 0.26234032, 0.16505091], [ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5], [0, 1, 4], [0, 5, 1], [1, 3, 5], [1, 4, 3]], dtype=int32))```Looking just at the first row we get `[ 0.34763842, 0.24879643, 0.12789202]`, you can confirm these are the 3 largest probabilities in `a`. You'll also notice `[3, 0, 5]` are the corresponding indices.
###Code
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
top_k = 5
probabilities=[]
with tf.Session() as sess:
saver.restore(sess, save_modle_dir) # restore the session already saved
for i in range(len(test_new_images_processed)):
softmax = tf.nn.softmax(logits)
top_five = tf.nn.top_k(softmax, k = top_k)
# get prediction for each image (consider a single image as a batch)
batch_x = [test_new_images_processed[i]]
probability = sess.run(top_five, feed_dict={x:batch_x})
probabilities.append(probability)
idx = 0
for prob in probabilities:
labels = prob.indices
probs = prob.values
print((idx+1),'True sign: label', test_new_labels[idx], '-', id_to_name[test_new_labels[idx]])
#print(' ---------')
for i in range(len(labels[0])):
print(' Predict. sign {}:'.format(i+1), '{:.2f} % '.format(probs[0][i]*100), '{}-'.format(labels[0][i]),
'{}'.format(id_to_name[labels[0][i]]))
if test_new_labels[idx] !=labels[0][0]:
print(' --------------------------------')
print(' INCORRECT classification')
idx += 1
print('-------------------------------------')
##############
###Output
INFO:tensorflow:Restoring parameters from ./lenet_norm_128_augment-bright/
1 True sign: label 28 - Children crossing
Predict. sign 1: 100.00 % 22- Bumpy road
Predict. sign 2: 0.00 % 31- Wild animals crossing
Predict. sign 3: 0.00 % 26- Traffic signals
Predict. sign 4: 0.00 % 23- Slippery road
Predict. sign 5: 0.00 % 18- General caution
--------------------------------
INCORRECT classification
-------------------------------------
2 True sign: label 25 - Road work
Predict. sign 1: 100.00 % 25- Road work
Predict. sign 2: 0.00 % 18- General caution
Predict. sign 3: 0.00 % 22- Bumpy road
Predict. sign 4: 0.00 % 24- Road narrows on the right
Predict. sign 5: 0.00 % 11- Right-of-way at the next intersection
-------------------------------------
3 True sign: label 38 - Keep right
Predict. sign 1: 99.53 % 38- Keep right
Predict. sign 2: 0.47 % 13- Yield
Predict. sign 3: 0.00 % 39- Keep left
Predict. sign 4: 0.00 % 2- Speed limit (50km/h)
Predict. sign 5: 0.00 % 0- Speed limit (20km/h)
-------------------------------------
4 True sign: label 27 - Pedestrians
Predict. sign 1: 83.93 % 22- Bumpy road
Predict. sign 2: 15.98 % 11- Right-of-way at the next intersection
Predict. sign 3: 0.09 % 18- General caution
Predict. sign 4: 0.00 % 27- Pedestrians
Predict. sign 5: 0.00 % 26- Traffic signals
--------------------------------
INCORRECT classification
-------------------------------------
5 True sign: label 12 - Priority road
Predict. sign 1: 100.00 % 12- Priority road
Predict. sign 2: 0.00 % 0- Speed limit (20km/h)
Predict. sign 3: 0.00 % 1- Speed limit (30km/h)
Predict. sign 4: 0.00 % 2- Speed limit (50km/h)
Predict. sign 5: 0.00 % 3- Speed limit (60km/h)
-------------------------------------
6 True sign: label 11 - Right-of-way at the next intersection
Predict. sign 1: 100.00 % 11- Right-of-way at the next intersection
Predict. sign 2: 0.00 % 22- Bumpy road
Predict. sign 3: 0.00 % 23- Slippery road
Predict. sign 4: 0.00 % 18- General caution
Predict. sign 5: 0.00 % 27- Pedestrians
-------------------------------------
7 True sign: label 33 - Turn right ahead
Predict. sign 1: 100.00 % 33- Turn right ahead
Predict. sign 2: 0.00 % 35- Ahead only
Predict. sign 3: 0.00 % 37- Go straight or left
Predict. sign 4: 0.00 % 12- Priority road
Predict. sign 5: 0.00 % 39- Keep left
-------------------------------------
8 True sign: label 14 - Stop
Predict. sign 1: 100.00 % 14- Stop
Predict. sign 2: 0.00 % 5- Speed limit (80km/h)
Predict. sign 3: 0.00 % 1- Speed limit (30km/h)
Predict. sign 4: 0.00 % 29- Bicycles crossing
Predict. sign 5: 0.00 % 0- Speed limit (20km/h)
-------------------------------------
9 True sign: label 1 - Speed limit (30km/h)
Predict. sign 1: 100.00 % 1- Speed limit (30km/h)
Predict. sign 2: 0.00 % 2- Speed limit (50km/h)
Predict. sign 3: 0.00 % 0- Speed limit (20km/h)
Predict. sign 4: 0.00 % 3- Speed limit (60km/h)
Predict. sign 5: 0.00 % 4- Speed limit (70km/h)
-------------------------------------
10 True sign: label 18 - General caution
Predict. sign 1: 100.00 % 18- General caution
Predict. sign 2: 0.00 % 28- Children crossing
Predict. sign 3: 0.00 % 26- Traffic signals
Predict. sign 4: 0.00 % 39- Keep left
Predict. sign 5: 0.00 % 37- Go straight or left
-------------------------------------
###Markdown
Project WriteupOnce you have completed the code implementation, document your results in a project writeup using this [template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) as a guide. The writeup can be in a markdown or pdf file. > **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission. --- Step 4 (Optional): Visualize the Neural Network's State with Test Images This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol. Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the [LeNet lab's](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.For an example of what feature map outputs look like, check out NVIDIA's results in their paper [End-to-End Deep Learning for Self-Driving Cars](https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/) in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image. Your output should look something like this (above)
###Code
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.
# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry
def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
# Here make sure to preprocess your image_input in a way your network expects
# with size, normalization, ect if needed
# image_input =
# Note: x should be the same name as your network's tensorflow data placeholder variable
# If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
featuremaps = activation.shape[3]
plt.figure(plt_num, figsize=(15,15))
for featuremap in range(featuremaps):
plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
if activation_min != -1 & activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
elif activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
elif activation_min !=-1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
else:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
###Output
_____no_output_____ |
DeepLearningAlgos/DeepLearningUdacity/5_word2vec.ipynb | ###Markdown
Deep Learning=============Assignment 5------------The goal of this assignment is to train a Word2Vec skip-gram model over [Text8](http://mattmahoney.net/dc/textdata) data.
###Code
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
%matplotlib inline
from __future__ import print_function
import collections
import math
import numpy as np
import os
import random
import tensorflow as tf
import zipfile
from matplotlib import pylab
from six.moves import range
from six.moves.urllib.request import urlretrieve
from sklearn.manifold import TSNE
###Output
_____no_output_____
###Markdown
Download the data from the source website if necessary.
###Code
url = 'http://mattmahoney.net/dc/'
def maybe_download(filename, expected_bytes):
"""Download a file if not present, and make sure it's the right size."""
if not os.path.exists(filename):
filename, _ = urlretrieve(url + filename, filename)
statinfo = os.stat(filename)
if statinfo.st_size == expected_bytes:
print('Found and verified %s' % filename)
else:
print(statinfo.st_size)
raise Exception(
'Failed to verify ' + filename + '. Can you get to it with a browser?')
return filename
filename = maybe_download('text8.zip', 31344016)
###Output
Found and verified text8.zip
###Markdown
Read the data into a string.
###Code
filename = 'text8.zip'
def read_data(filename):
"""Extract the first file enclosed in a zip file as a list of words"""
with zipfile.ZipFile(filename) as f:
data = tf.compat.as_str(f.read(f.namelist()[0])).split()
return data
words = read_data(filename)
print('Data size %d' % len(words))
###Output
Data size 17005207
###Markdown
Build the dictionary and replace rare words with UNK token.
###Code
vocabulary_size = 50000
def build_dataset(words):
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
if word in dictionary:
index = dictionary[word]
else:
index = 0 # dictionary['UNK']
unk_count = unk_count + 1
data.append(index)
count[0][1] = unk_count
reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
return data, count, dictionary, reverse_dictionary
data, count, dictionary, reverse_dictionary = build_dataset(words)
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10])
del words # Hint to reduce memory.
###Output
Most common words (+UNK) [['UNK', 418391], ('the', 1061396), ('of', 593677), ('and', 416629), ('one', 411764)]
Sample data [5239, 3082, 12, 6, 195, 2, 3135, 46, 59, 156]
###Markdown
Function to generate a training batch for the skip-gram model.
###Code
data_index = 0
def generate_batch(batch_size, num_skips, skip_window):
global data_index
assert batch_size % num_skips == 0
assert num_skips <= 2 * skip_window
batch = np.ndarray(shape=(batch_size), dtype=np.int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
span = 2 * skip_window + 1 # [ skip_window target skip_window ]
buffer = collections.deque(maxlen=span) #a word sequence
for _ in range(span):
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
#print(buffer)
for i in range(batch_size // num_skips):
target = skip_window # target label at the center of the buffer
targets_to_avoid = [ skip_window ]
#print('target => {0}'.format(target))
for j in range(num_skips):
while target in targets_to_avoid:
target = random.randint(0, span - 1) #WHILE until target not in targer_to_avoid
targets_to_avoid.append(target)
#print('targets_to_avoid => {0}'.format(targets_to_avoid))
batch[i * num_skips + j] = buffer[skip_window]
labels[i * num_skips + j, 0] = buffer[target]
buffer.append(data[data_index]) # move the window, renew the buffer
data_index = (data_index + 1) % len(data)
#print('target => {0}'.format(target))
#print('targets_to_avoid => {0}'.format(targets_to_avoid))
#print(buffer)
#following 3 lines change Skip-gram to CBOW delete them to change back
#temp = batch
#batch = labels.reshape(batch_size)
#labels = temp.reshape(batch_size,1)
return batch, labels
print('data:', [reverse_dictionary[di] for di in data[:8]])
for num_skips, skip_window in [(2, 1), (4, 2)]:
data_index = 0
batch, labels = generate_batch(batch_size=8, num_skips=num_skips, skip_window=skip_window)
print('\nwith num_skips = %d and skip_window = %d:' % (num_skips, skip_window))
print(' batch:', [reverse_dictionary[bi] for bi in batch])
print(' labels:', [reverse_dictionary[li] for li in labels.reshape(8)])
###Output
data: ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'first']
with num_skips = 2 and skip_window = 1:
batch: ['originated', 'originated', 'as', 'as', 'a', 'a', 'term', 'term']
labels: ['anarchism', 'as', 'a', 'originated', 'term', 'as', 'a', 'of']
with num_skips = 4 and skip_window = 2:
batch: ['as', 'as', 'as', 'as', 'a', 'a', 'a', 'a']
labels: ['anarchism', 'originated', 'term', 'a', 'originated', 'term', 'of', 'as']
###Markdown
Train a skip-gram model.
###Code
batch_size = 300
embedding_size = 128 # Dimension of the embedding vector.
skip_window = 15 # How many words to consider left and right.
num_skips = 30 # How many times to reuse an input to generate a label.
# We pick a random validation set to sample nearest neighbors. here we limit the
# validation samples to the words that have a low numeric ID, which by
# construction are also the most frequent.
valid_size = 16 # Random set of words to evaluate similarity on.
valid_window = 100 # Only pick dev samples in the head of the distribution.
valid_examples = np.array(random.sample(range(valid_window), valid_size))
num_sampled = 64 # Number of negative examples to sample.
graph = tf.Graph()
with graph.as_default(), tf.device('/cpu:0'):
# Input data.
train_dataset = tf.placeholder(tf.int32, shape=[batch_size])
train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
# Variables.
embeddings = tf.Variable(
tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
softmax_weights = tf.Variable(
tf.truncated_normal([vocabulary_size, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)))
softmax_biases = tf.Variable(tf.zeros([vocabulary_size]))
# Model.
# Look up embeddings for inputs.
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
# Compute the softmax loss, using a sample of the negative labels each time.
loss = tf.reduce_mean(
tf.nn.sampled_softmax_loss(softmax_weights, softmax_biases, embed,
train_labels, num_sampled, vocabulary_size))
# Optimizer.
# Note: The optimizer will optimize the softmax_weights AND the embeddings.
# This is because the embeddings are defined as a variable quantity and the
# optimizer's `minimize` method will by default modify all variable quantities
# that contribute to the tensor it is passed.
# See docs on `tf.train.Optimizer.minimize()` for more details.
optimizer = tf.train.AdagradOptimizer(1.0).minimize(loss)
# Compute the similarity between minibatch examples and all embeddings.
# We use the cosine distance:
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
valid_embeddings = tf.nn.embedding_lookup(
normalized_embeddings, valid_dataset)
similarity = tf.matmul(valid_embeddings, tf.transpose(normalized_embeddings))
num_steps = 100001
with tf.Session(graph=graph) as session:
tf.initialize_all_variables().run()
print('Initialized')
average_loss = 0
for step in range(num_steps):
batch_data, batch_labels = generate_batch(
batch_size, num_skips, skip_window)
feed_dict = {train_dataset : batch_data, train_labels : batch_labels}
_, l = session.run([optimizer, loss], feed_dict=feed_dict)
average_loss += l
if step % 2000 == 0:
if step > 0:
average_loss = average_loss / 2000
# The average loss is an estimate of the loss over the last 2000 batches.
print('Average loss at step %d: %f' % (step, average_loss))
average_loss = 0
# note that this is expensive (~20% slowdown if computed every 500 steps)
if step % 10000 == 0:
sim = similarity.eval()
for i in range(valid_size):
valid_word = reverse_dictionary[valid_examples[i]]
top_k = 8 # number of nearest neighbors
nearest = (-sim[i, :]).argsort()[1:top_k+1]
log = 'Nearest to %s:' % valid_word
for k in range(top_k):
close_word = reverse_dictionary[nearest[k]]
log = '%s %s,' % (log, close_word)
print(log)
final_embeddings = normalized_embeddings.eval()
num_points = 600
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
two_d_embeddings = tsne.fit_transform(final_embeddings[1:num_points+1, :])
def plot(embeddings, labels):
assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
pylab.figure(figsize=(30,30)) # in inches
for i, label in enumerate(labels):
x, y = embeddings[i,:]
pylab.scatter(x, y)
pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',
ha='right', va='bottom')
pylab.show()
words = [reverse_dictionary[i] for i in range(1, num_points+1)]
plot(two_d_embeddings, words)
###Output
_____no_output_____ |
src/.ipynb_checkpoints/Extract_Patches_Own_data-checkpoint.ipynb | ###Markdown
Extract Image&Label Patches For Training and TestThis notebook is to extract Image&Label patches from original images and labels.The only thing you need to do, is to set up the `img_dir`, `ann_dir` and `out_dir`.Note: Please Run `Gen_BDist_Map.ipynb` at first.
###Code
import glob
import os
from shutil import copyfile
import scipy.io as sio
import cv2
import numpy as np
import itertools
import matplotlib.pyplot as plt
from tqdm import tqdm
from misc.patch_extractor import PatchExtractor
from misc.utils import rm_n_mkdir
from config import Config
def bounding_box(img):
rows = np.any(img, axis=1)
cols = np.any(img, axis=0)
rmin, rmax = np.where(rows)[0][[0, -1]]
cmin, cmax = np.where(cols)[0][[0, -1]]
# due to python indexing, need to add 1 to max
# else accessing will be 1px in the box, not out
rmax += 1
cmax += 1
return [rmin, rmax, cmin, cmax]
def draw_contours(mask, ann_inst, line_thickness=1):
overlay = np.copy((mask).astype(np.uint8))
label_map = ann_inst
instances_list = list(np.unique(label_map)) # get list of instances
instances_list.remove(0) # remove background
contours = []
for inst_id in instances_list:
instance_map = np.array(
ann_inst == inst_id, np.uint8) # get single object
y1, y2, x1, x2 = bounding_box(instance_map)
y1 = y1 - 2 if y1 - 2 >= 0 else y1
x1 = x1 - 2 if x1 - 2 >= 0 else x1
x2 = x2 + 2 if x2 + 2 <= ann_inst.shape[1] - 1 else x2
y2 = y2 + 2 if y2 + 2 <= ann_inst.shape[0] - 1 else y2
inst_map_crop = instance_map[y1:y2, x1:x2]
contours_crop = cv2.findContours(
inst_map_crop, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
index_correction = np.asarray([[[[x1, y1]]]])
for i in range(len(contours_crop[0])):
contours.append(
list(np.asarray(contours_crop[0][i].astype('int32')) + index_correction))
contours = list(itertools.chain(*contours))
cv2.drawContours(overlay, np.asarray(contours), -1, 2, line_thickness)
return overlay
cfg = Config()
img_ext = '.png'
label_ext = '.mat'
extract_type = 'mirror' # 'valid' for fcn8 segnet etc.
# 'mirror' for u-net etc.
# check the patch_extractor.py 'main' to see the different
# orignal size (win size) - input size - output size (step size)
# 512x512 - 256x256 - 256x256 fcn8, dcan, segnet
# 536x536 - 268x268 - 84x84 unet, dist
# 540x540 - 270x270 - 80x80 xy, hover
# 504x504 - 252x252 - 252x252 micronetcd tr
step_size = [256, 256] # should match self.train_mask_shape (config.py)
win_size = [512, 512] # should be at least twice time larger than
# self.train_base_shape (config.py) to reduce
# the padding effect during augmentation
xtractor = PatchExtractor(win_size, step_size)
### Paths to data - these need to be modified according to where the original data is stored
img_ext = '.png'
img_dir = '/home1/gzy/NucleiSegmentation/High_CCRCC/Test/Images/'
ann_dir = '/home1/gzy/NucleiSegmentation/High_CCRCC/Test/Labels/'
####
out_dir = "/home1/gzy/NucleiSegmentation/High_CCRCC/Test/%dx%d_%dx%d_dist" % \
(win_size[0], win_size[1], step_size[0], step_size[1])
file_list = glob.glob('%s/*%s' % (img_dir, img_ext))
file_list.sort()
rm_n_mkdir(out_dir)
for filename in tqdm(file_list):
filename = os.path.basename(filename)
basename = filename.split('.')[0]
#print(filename)
img = cv2.imread(img_dir + basename + img_ext)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
labels = sio.loadmat(ann_dir + basename + '.mat')
ann_inst = labels['instance_map']
ann_type = labels['class_map']
ann_marker = labels['marker_map']*255
ann = np.dstack([ann_inst, ann_type, ann_marker])
ann = ann.astype('int32')
img = np.concatenate([img, ann], axis=-1)
sub_patches = xtractor.extract(img, extract_type)
for idx, patch in enumerate(sub_patches):
np.save("{0}/{1}_{2:03d}.npy".format(out_dir, basename, idx), patch)
###Output
100%|██████████| 200/200 [00:57<00:00, 3.49it/s]
|
sqlite3/python_sqlite3.ipynb | ###Markdown
SQLite3 A DB-API for SQLite database SQLite is a C based library that provides a light-weighted disk based database that doesn't require a seperate server process that allow access to database. It's built-in library in python, The sqlite3 module was written by Gerhard Häring. It provides a SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.It's possible to create our prototypes with SQLite3 as our base db and later we can port to larger db's like PostgreSQl/Oracle. Connection API
###Code
#To use the module, you must first create a Connection object that
# represents the database. Here the data will be stored in the example.db file:
import sqlite3
con = sqlite3.connect('expl.db')
# You can also give (:memory:) to create in-ram db
###Output
_____no_output_____
###Markdown
Once you created connection, next step is to create cursor object where we can call its execute method to perform SQL commands. Here , Cursor is like a physical work-area or row pointing our table inside database. So that when we execute any command it will retrieve data row wise.
###Code
cur = con.cursor()
# Create table
cur.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
# Insert a row of data
cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
# Save (commit) the changes
con.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
# con.close()
###Output
_____no_output_____
###Markdown
The Data which we have saved in the memory or in the file is persistant and it can be available any time when you retrieve them.
###Code
for row in cur.execute('SELECT * FROM stocks ORDER BY price'):
print(row)
# Basic db api for creating and retrieving data
connection = sqlite3.connect(":memory:")
cursr = connection.cursor()
cursr.execute("create table lang (name, first_appeared)")
# This is the qmark style:
cursr.execute("insert into lang values (?, ?)", ("C", 1972))
# The qmark style used with executemany():
lang_list = [
("Fortran", 1957),
("Python", 1991),
("Go", 2009),
]
cursr.executemany("insert into lang values (?, ?)", lang_list)
# And this is the named style:
cursr.execute("select * from lang where first_appeared=:year", {"year": 1972})
print(cursr.fetchone())
print(cursr.fetchall())
connection.close()
###Output
('C', 1972)
[]
###Markdown
SQL and Python Types***The following Python types can thus be sent to SQLite| Python | SQLite3 ||-----|--------|| None | NULL || int | INTEGER || float | REAL || str | TEXT || bytes | BLOB |*** SQLite3 System much extensible, as we can even store additional python types using adaption , and let sqlite to convert using convertors. As described before, SQLite supports only a limited set of types natively. To use other Python types with SQLite, you must adapt them to one of the sqlite3 module’s supported types for SQLite: one of NoneType, int, float, str, bytes.There are two ways to enable the sqlite3 module to adapt a custom Python type to one of the supported ones.
###Code
# Letting your object adapt itself
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __conform__(self, protocol):
if protocol is sqlite3.PrepareProtocol:
return "%f;%f" % (self.x, self.y)
con = sqlite3.connect(":memory:")
cur = con.cursor()
p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print(cur.fetchone()[0])
con.close()
# Registering an adapter callable
# The other possibility is to create a function that converts the type to the
# string representation and register the function with register_adapter().
class Pnt:
def __init__(self, x, y):
self.x, self.y = x, y
def adapt_point(point):
return "%f;%f" % (point.x, point.y)
sqlite3.register_adapter(Pnt, adapt_point)
con = sqlite3.connect(":memory:")
cur = con.cursor()
p = Pnt(4.0, -3.2)
cur.execute("select ?", (p,))
print(cur.fetchone()[0])
con.close()
###Output
4.000000;-3.200000
###Markdown
Some Shortcut Methods
###Code
#Using the nonstandard execute(), executemany() and executescript() methods of the
# Connection object, your code can be written more concisely because you don’t have to
# create the (often superfluous) Cursor objects explicitly. Instead,
# the Cursor objects are created implicitly and these shortcut methods return the cursor objects.
langs = [
("C++", 1985),
("Objective-C", 1984),
]
con = sqlite3.connect(":memory:")
# Create the table
con.execute("create table lang(name, first_appeared)")
# Fill the table
con.executemany("insert into lang(name, first_appeared) values (?, ?)", langs)
# Print the table contents
for row in con.execute("select name, first_appeared from lang"):
print(row)
print("I just deleted", con.execute("delete from lang").rowcount, "rows")
# close is not a shortcut method and it's not called automatically,
# so the connection object should be closed manually
con.close()
# Accessing columns by names
con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select 'John' as name, 42 as age")
for row in cur:
assert row[0] == row["name"]
assert row["name"] == row["nAmE"]
assert row[1] == row["age"]
assert row[1] == row["AgE"]
con.close()
###Output
_____no_output_____
###Markdown
CRUD OPERATIONS
###Code
# creating,read,update, delete table in database
#connect to sqlite db
conn = sqlite3.connect(":memory:")
#create a cursor obj
cur = conn.cursor()
# drop query
cur.execute("DROP TABLE IF EXISTS STUDENT")
# create query
query = '''CREATE TABLE STUDENT(
ID INT PRIMARY KEY NOT NULL,
NAME CHAR(20) NOT NULL,
ROLL CHAR(20),
ADDRESS CHAR(50),
CLASS CHAR(20)
)'''
cur.execute(query)
conn.commit()
#static insertion
conn.execute("INSERT INTO STUDENT (ID,NAME,ROLL,ADDRESS,CLASS) "
"VALUES (1, 'John', '001', 'Bangalore', '10th')")
conn.execute("INSERT INTO STUDENT (ID,NAME,ROLL,ADDRESS,CLASS) "
"VALUES (2, 'Naren', '002', 'Hyd', '12th')")
conn.commit()
# param/args insert
query = ('INSERT INTO STUDENT (ID,NAME,ROLL,ADDRESS,CLASS) '
'VALUES (:ID, :NAME, :ROLL, :ADDRESS, :CLASS);')
params = {
'ID': 3,
'NAME': 'Jax',
'ROLL': '003',
'ADDRESS': 'Delhi',
'CLASS': '9th'
}
conn.execute(query, params)
conn.commit()
cur.execute('SELECT * FROM STUDENT')
print(cur.fetchall())
cur.execute("UPDATE STUDENT set ROLL = 005 where ID = 1")
cur.execute('SELECT * FROM STUDENT')
print(cur.fetchall())
conn.close()
###Output
[(1, 'John', '001', 'Bangalore', '10th'), (2, 'Naren', '002', 'Hyd', '12th'), (3, 'Jax', '003', 'Delhi', '9th')]
[(1, 'John', '5', 'Bangalore', '10th'), (2, 'Naren', '002', 'Hyd', '12th'), (3, 'Jax', '003', 'Delhi', '9th')]
|
[03 - Results]/dos results ver 4/models/iter-2/fft_r11-i2.ipynb | ###Markdown
Module Imports for Data Fetiching and Visualization
###Code
import time
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
###Output
_____no_output_____
###Markdown
Module Imports for Data Processing
###Code
from sklearn import preprocessing
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
import pickle
###Output
_____no_output_____
###Markdown
Importing Dataset from GitHub Train Data
###Code
df1 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-15-m-1-r11.csv?token=AKVFSOH4TC4IY3N4CSRVFYK63JDDO')
df2 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-15-m-11-r11.csv?token=AKVFSOBY5KWVYP7MVPVLSKS63JDDQ')
df3 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-4-m-1-r11.csv?token=AKVFSOBOPZXRIHTY75257K263JDDW')
df4 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-4-m-11-r11.csv?token=AKVFSOBNHAMMTIEDLLG2S3263JDD4')
df5 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-6-m-1-r11.csv?token=AKVFSOGJEWMJIC34XUWDJNC63JDD6')
df6 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-6-m-11-r11.csv?token=AKVFSOGFKJBHUH2ZJR6X7T263JDEG')
df7 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-9-m-1-r11.csv?token=AKVFSOB3MTPMSXHBLAMI76S63JDEI')
df8 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-9-m-11-r11.csv?token=AKVFSOCLQ3I32KFGCMKCY5K63JDEO')
df9 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-normal-n-0-15-r11.csv?token=AKVFSOCYILXP5XA4GGQEKYC63JDES')
df10 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-normal-n-0-4-r11.csv?token=AKVFSOE54EDO56EYFZTHU5K63JDEY')
df11 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-normal-n-0-6-r11.csv?token=AKVFSOFOZ3U36V47XBCSAQ263JDE4')
df12 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-normal-n-0-9-r11.csv?token=AKVFSOBWYIQ5T5PELBMMN7S63JDFA')
print(df1.shape)
print(df2.shape)
print(df3.shape)
print(df4.shape)
print(df5.shape)
print(df6.shape)
print(df7.shape)
print(df8.shape)
print(df9.shape)
print(df10.shape)
print(df11.shape)
print(df12.shape)
df = df1.append(df2, ignore_index=True,sort=False)
df = df.append(df3, ignore_index=True,sort=False)
df = df.append(df4, ignore_index=True,sort=False)
df = df.append(df5, ignore_index=True,sort=False)
df = df.append(df6, ignore_index=True,sort=False)
df = df.append(df7, ignore_index=True,sort=False)
df = df.append(df8, ignore_index=True,sort=False)
df = df.append(df9, ignore_index=True,sort=False)
df = df.append(df10, ignore_index=True,sort=False)
df = df.append(df11, ignore_index=True,sort=False)
df = df.append(df12, ignore_index=True,sort=False)
df = df.sort_values('timestamp')
df.to_csv('fft-r11-train.csv',index=False)
df = pd.read_csv('fft-r11-train.csv')
df
df.shape
###Output
_____no_output_____
###Markdown
Test Data
###Code
df13 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-15-m-12-r11.csv?token=AKVFSODFX632MJC3CW5FU7S63JEEK')
df14 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-15-m-7-r11.csv?token=AKVFSOGYGNPHWB42VH7Q2GK63JEEQ')
df15 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-4-m-12-r11.csv?token=AKVFSOFZ6KJEJ26DEU6UFHS63JEES')
df16 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-4-m-7-r11.csv?token=AKVFSOER2UFUJ5R5M2LN2B263JEEW')
df17 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-6-m-12-r11.csv?token=AKVFSOB57H6WKTXOY4DPBX263JEE2')
df18 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-6-m-7-r11.csv?token=AKVFSOCLQ35HXGV32FCHFJ263JEE6')
df19 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-9-m-12-r11.csv?token=AKVFSOCTWJFN5PAITIQQD7S63JEFE')
df20 = pd.read_csv('https://raw.githubusercontent.com/chamikasudusinghe/nocml/master/dos%20results%20ver%204/router-dataset/r11/2-fft-malicious-n-0-9-m-7-r11.csv?token=AKVFSOHI6JNCK4OP4LHGZOS63JEFI')
print(df13.shape)
print(df14.shape)
print(df15.shape)
print(df16.shape)
print(df17.shape)
print(df18.shape)
print(df19.shape)
print(df20.shape)
df5
###Output
_____no_output_____
###Markdown
Processing
###Code
df.isnull().sum()
df = df.drop(columns=['timestamp','src_ni','src_router','dst_ni','dst_router'])
df.corr()
plt.figure(figsize=(25,25))
sns.heatmap(df.corr(), annot = True)
plt.show()
def find_correlation(data, threshold=0.9):
corr_mat = data.corr()
corr_mat.loc[:, :] = np.tril(corr_mat, k=-1)
already_in = set()
result = []
for col in corr_mat:
perfect_corr = corr_mat[col][abs(corr_mat[col])> threshold].index.tolist()
if perfect_corr and col not in already_in:
already_in.update(set(perfect_corr))
perfect_corr.append(col)
result.append(perfect_corr)
select_nested = [f[1:] for f in result]
select_flat = [i for j in select_nested for i in j]
return select_flat
columns_to_drop = find_correlation(df.drop(columns=['target']))
columns_to_drop
#df = df.drop(columns=[''])
plt.figure(figsize=(21,21))
sns.heatmap(df.corr(), annot = True)
plt.show()
plt.figure(figsize=(25,25))
sns.heatmap(df.corr())
plt.show()
###Output
_____no_output_____
###Markdown
Processing Dataset for Training
###Code
train_X = df.drop(columns=['target'])
train_Y = df['target']
#standardization
x = train_X.values
min_max_scaler = preprocessing.MinMaxScaler()
columns = train_X.columns
x_scaled = min_max_scaler.fit_transform(x)
train_X = pd.DataFrame(x_scaled)
train_X.columns = columns
train_X
train_X[train_X.duplicated()].shape
test_X = df13.drop(columns=['target','timestamp','src_ni','src_router','dst_ni','dst_router'])
test_Y = df13['target']
x = test_X.values
min_max_scaler = preprocessing.MinMaxScaler()
columns = test_X.columns
x_scaled = min_max_scaler.fit_transform(x)
test_X = pd.DataFrame(x_scaled)
test_X.columns = columns
print(test_X[test_X.duplicated()].shape)
test_X
test_X1 = df14.drop(columns=['target','timestamp','src_ni','src_router','dst_ni','dst_router'])
test_Y1 = df14['target']
x = test_X1.values
min_max_scaler = preprocessing.MinMaxScaler()
columns = test_X1.columns
x_scaled = min_max_scaler.fit_transform(x)
test_X1 = pd.DataFrame(x_scaled)
test_X1.columns = columns
print(test_X1[test_X1.duplicated()].shape)
test_X2 = df15.drop(columns=['target','timestamp','src_ni','src_router','dst_ni','dst_router'])
test_Y2 = df15['target']
x = test_X2.values
min_max_scaler = preprocessing.MinMaxScaler()
columns = test_X2.columns
x_scaled = min_max_scaler.fit_transform(x)
test_X2 = pd.DataFrame(x_scaled)
test_X2.columns = columns
print(test_X2[test_X2.duplicated()].shape)
test_X3 = df16.drop(columns=['target','timestamp','src_ni','src_router','dst_ni','dst_router'])
test_Y3 = df16['target']
x = test_X3.values
min_max_scaler = preprocessing.MinMaxScaler()
columns = test_X3.columns
x_scaled = min_max_scaler.fit_transform(x)
test_X3 = pd.DataFrame(x_scaled)
test_X3.columns = columns
print(test_X3[test_X3.duplicated()].shape)
test_X4 = df17.drop(columns=['target','timestamp','src_ni','src_router','dst_ni','dst_router'])
test_Y4 = df17['target']
x = test_X4.values
min_max_scaler = preprocessing.MinMaxScaler()
columns = test_X4.columns
x_scaled = min_max_scaler.fit_transform(x)
test_X4 = pd.DataFrame(x_scaled)
test_X4.columns = columns
print(test_X4[test_X4.duplicated()].shape)
test_X5 = df18.drop(columns=['target','timestamp','src_ni','src_router','dst_ni','dst_router'])
test_Y5 = df18['target']
x = test_X5.values
min_max_scaler = preprocessing.MinMaxScaler()
columns = test_X5.columns
x_scaled = min_max_scaler.fit_transform(x)
test_X5 = pd.DataFrame(x_scaled)
test_X5.columns = columns
print(test_X5[test_X5.duplicated()].shape)
test_X6 = df19.drop(columns=['target','timestamp','src_ni','src_router','dst_ni','dst_router'])
test_Y6 = df19['target']
x = test_X6.values
min_max_scaler = preprocessing.MinMaxScaler()
columns = test_X6.columns
x_scaled = min_max_scaler.fit_transform(x)
test_X6 = pd.DataFrame(x_scaled)
test_X6.columns = columns
print(test_X6[test_X6.duplicated()].shape)
test_X7 = df20.drop(columns=['target','timestamp','src_ni','src_router','dst_ni','dst_router'])
test_Y7 = df20['target']
x = test_X7.values
min_max_scaler = preprocessing.MinMaxScaler()
columns = test_X7.columns
x_scaled = min_max_scaler.fit_transform(x)
test_X7 = pd.DataFrame(x_scaled)
test_X7.columns = columns
print(test_X7[test_X7.duplicated()].shape)
###Output
(0, 20)
###Markdown
Machine Learning Models Module Imports for Data Processing and Report Generation in Machine Learning Models
###Code
from sklearn.model_selection import train_test_split
import statsmodels.api as sm
from sklearn import metrics
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_squared_error
###Output
_____no_output_____
###Markdown
Labels1. 0 - malicious2. 1 - good
###Code
train_Y = df['target']
train_Y.value_counts()
###Output
_____no_output_____
###Markdown
Training and Validation Splitting of the Dataset
###Code
seed = 5
np.random.seed(seed)
X_train, X_test, y_train, y_test = train_test_split(train_X, train_Y, test_size=0.2, random_state=seed, shuffle=True)
###Output
_____no_output_____
###Markdown
Feature Selection
###Code
#SelectKBest for feature selection
bf = SelectKBest(score_func=chi2, k=17)
fit = bf.fit(X_train,y_train)
dfscores = pd.DataFrame(fit.scores_)
dfcolumns = pd.DataFrame(columns)
featureScores = pd.concat([dfcolumns,dfscores],axis=1)
featureScores.columns = ['Specs','Score']
print(featureScores.nlargest(17,'Score'))
featureScores.plot(kind='barh')
###Output
Specs Score
14 max_packet_count 8254.788949
15 packet_count_index 7321.281341
7 traversal_id 7141.018767
13 packet_count_incr 4130.778659
12 packet_count_decr 4124.012761
16 port_index 3307.790578
17 traversal_index 2215.237974
8 hop_count 709.065206
9 current_hop 585.280367
10 hop_percentage 291.276957
1 inport 104.950536
11 enqueue_time 55.596235
0 outport 29.488180
6 vc 13.217211
2 cache_coherence_type 5.236659
18 cache_coherence_vnet_index 3.462115
4 flit_type 0.598208
###Markdown
Decision Tree Classifier
###Code
#decisiontreee
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
dt = DecisionTreeClassifier(max_depth=20,max_features=20,random_state = 42)
dt.fit(X_train,y_train)
pickle.dump(dt, open("dt-r11.pickle.dat", 'wb'))
y_pred_dt= dt.predict(X_test)
dt_score_train = dt.score(X_train,y_train)
print("Train Prediction Score",dt_score_train*100)
dt_score_test = accuracy_score(y_test,y_pred_dt)
print("Test Prediction Score",dt_score_test*100)
y_pred_dt_test= dt.predict(test_X)
dt_score_test = accuracy_score(test_Y,y_pred_dt_test)
print("Test Prediction Score",dt_score_test*100)
y_pred_dt_test= dt.predict(test_X1)
dt_score_test = accuracy_score(test_Y1,y_pred_dt_test)
print("Test Prediction Score",dt_score_test*100)
y_pred_dt_test= dt.predict(test_X2)
dt_score_test = accuracy_score(test_Y2,y_pred_dt_test)
print("Test Prediction Score",dt_score_test*100)
y_pred_dt_test= dt.predict(test_X3)
dt_score_test = accuracy_score(test_Y3,y_pred_dt_test)
print("Test Prediction Score",dt_score_test*100)
y_pred_dt_test= dt.predict(test_X4)
dt_score_test = accuracy_score(test_Y4,y_pred_dt_test)
print("Test Prediction Score",dt_score_test*100)
y_pred_dt_test= dt.predict(test_X5)
dt_score_test = accuracy_score(test_Y5,y_pred_dt_test)
print("Test Prediction Score",dt_score_test*100)
y_pred_dt_test= dt.predict(test_X6)
dt_score_test = accuracy_score(test_Y6,y_pred_dt_test)
print("Test Prediction Score",dt_score_test*100)
y_pred_dt_test= dt.predict(test_X7)
dt_score_test = accuracy_score(test_Y7,y_pred_dt_test)
print("Test Prediction Score",dt_score_test*100)
feat_importances = pd.Series(dt.feature_importances_, index=columns)
feat_importances.plot(kind='barh')
cm = confusion_matrix(y_test, y_pred_dt)
class_label = ["Anomalous", "Normal"]
df_cm = pd.DataFrame(cm, index=class_label,columns=class_label)
sns.heatmap(df_cm, annot=True, fmt='d')
plt.title("Confusion Matrix")
plt.xlabel("Predicted Label")
plt.ylabel("True Label")
plt.show()
print(classification_report(y_test,y_pred_dt))
dt_roc_auc = roc_auc_score(y_test, y_pred_dt)
fpr, tpr, thresholds = roc_curve(y_test, dt.predict_proba(X_test)[:,1])
plt.figure()
plt.plot(fpr, tpr, label='DTree (area = %0.2f)' % dt_roc_auc)
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.savefig('DT_ROC')
plt.show()
###Output
_____no_output_____
###Markdown
XGB Classifier
###Code
from xgboost import XGBClassifier
from xgboost import plot_importance
xgbc = XGBClassifier(max_depth=20,min_child_weight=1,n_estimators=500,random_state=42,learning_rate=0.2)
xgbc.fit(X_train,y_train)
pickle.dump(xgbc, open("xgbc-r11.pickle.dat", 'wb'))
y_pred_xgbc= xgbc.predict(X_test)
xgbc_score_train = xgbc.score(X_train,y_train)
print("Train Prediction Score",xgbc_score_train*100)
xgbc_score_test = accuracy_score(y_test,y_pred_xgbc)
print("Test Prediction Score",xgbc_score_test*100)
y_pred_xgbc_test= xgbc.predict(test_X)
xgbc_score_test = accuracy_score(test_Y,y_pred_xgbc_test)
print("Test Prediction Score",xgbc_score_test*100)
y_pred_xgbc_test= xgbc.predict(test_X1)
xgbc_score_test = accuracy_score(test_Y1,y_pred_xgbc_test)
print("Test Prediction Score",xgbc_score_test*100)
y_pred_xgbc_test= xgbc.predict(test_X2)
xgbc_score_test = accuracy_score(test_Y2,y_pred_xgbc_test)
print("Test Prediction Score",xgbc_score_test*100)
y_pred_xgbc_test= xgbc.predict(test_X3)
xgbc_score_test = accuracy_score(test_Y3,y_pred_xgbc_test)
print("Test Prediction Score",xgbc_score_test*100)
y_pred_xgbc_test= xgbc.predict(test_X4)
xgbc_score_test = accuracy_score(test_Y4,y_pred_xgbc_test)
print("Test Prediction Score",xgbc_score_test*100)
y_pred_xgbc_test= xgbc.predict(test_X5)
xgbc_score_test = accuracy_score(test_Y5,y_pred_xgbc_test)
print("Test Prediction Score",xgbc_score_test*100)
y_pred_xgbc_test= xgbc.predict(test_X6)
xgbc_score_test = accuracy_score(test_Y6,y_pred_xgbc_test)
print("Test Prediction Score",xgbc_score_test*100)
y_pred_xgbc_test= xgbc.predict(test_X7)
xgbc_score_test = accuracy_score(test_Y7,y_pred_xgbc_test)
print("Test Prediction Score",xgbc_score_test*100)
plot_importance(xgbc)
plt.show()
cm = confusion_matrix(y_test, y_pred_xgbc)
class_label = ["Anomalous", "Normal"]
df_cm = pd.DataFrame(cm, index=class_label,columns=class_label)
sns.heatmap(df_cm, annot=True, fmt='d')
plt.title("Confusion Matrix")
plt.xlabel("Predicted Label")
plt.ylabel("True Label")
plt.show()
print(classification_report(y_test,y_pred_xgbc))
xgb_roc_auc = roc_auc_score(y_test, y_pred_xgbc)
fpr, tpr, thresholds = roc_curve(y_test, xgbc.predict_proba(X_test)[:,1])
plt.figure()
plt.plot(fpr, tpr, label='XGBoost (area = %0.2f)' % xgb_roc_auc)
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.savefig('XGB_ROC')
plt.show()
###Output
_____no_output_____ |
06_Stats/Wind_Stats/Exercises_with_solutions.ipynb | ###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Wind StatisticsCheck out [Wind Statistics Exercises Video Tutorial](https://youtu.be/2x3WsWiNV18) to watch a data scientist go through the exercises Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind StatisticsCheck out [Wind Statistics Exercises Video Tutorial](https://youtu.be/2x3WsWiNV18) to watch a data scientist go through the exercises Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.fillna(0).values.flatten().mean()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind StatisticsCheck out [Wind Statistics Exercises Video Tutorial](https://youtu.be/2x3WsWiNV18) to watch a data scientist go through the exercises Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind StatisticsCheck out [Wind Statistics Exercises Video Tutorial](https://youtu.be/2x3WsWiNV18) to watch a data scientist go through the exercises Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_table(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
# number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
# OR
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.fillna(0).values.flatten().mean()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
//anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py:4291: RuntimeWarning: Invalid value encountered in percentile
interpolation=interpolation)
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_table(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
# number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
# OR
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.fillna(0).values.flatten().mean()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
//anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py:4291: RuntimeWarning: Invalid value encountered in percentile
interpolation=interpolation)
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.fillna(0).values.flatten().mean()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
from datetime import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind StatisticsCheck out [Wind Statistics Exercises Video Tutorial](https://youtu.be/2x3WsWiNV18) to watch a data scientist go through the exercises Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Wind StatisticsCheck out [Wind Statistics Exercises Video Tutorial](https://youtu.be/2x3WsWiNV18) to watch a data scientist go through the exercises Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/murali0861/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/murali0861/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_table(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
# number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
# OR
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.fillna(0).values.flatten().mean()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
//anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py:4291: RuntimeWarning: Invalid value encountered in percentile
interpolation=interpolation)
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_table(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
# number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
# OR
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.fillna(0).values.flatten().mean()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
//anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py:4291: RuntimeWarning: Invalid value encountered in percentile
interpolation=interpolation)
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('m')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_table(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
# number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
# OR
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.fillna(0).values.flatten().mean()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind StatisticsCheck out [Wind Statistics Exercises Video Tutorial](https://youtu.be/2x3WsWiNV18) to watch a data scientist go through the exercises Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind StatisticsCheck out [Wind Statistics Exercises Video Tutorial](https://youtu.be/2x3WsWiNV18) to watch a data scientist go through the exercises Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind StatisticsCheck out [Wind Statistics Exercises Video Tutorial](https://youtu.be/2x3WsWiNV18) to watch a data scientist go through the exercises Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
data.info()
###Output
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 6574 entries, 1961-01-01 to 1978-12-31
Data columns (total 12 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 RPT 6568 non-null float64
1 VAL 6571 non-null float64
2 ROS 6572 non-null float64
3 KIL 6569 non-null float64
4 SHA 6572 non-null float64
5 BIR 6574 non-null float64
6 DUB 6571 non-null float64
7 CLA 6572 non-null float64
8 MUL 6571 non-null float64
9 CLO 6573 non-null float64
10 BEL 6574 non-null float64
11 MAL 6570 non-null float64
dtypes: float64(12)
memory usage: 667.7 KB
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
type(data.index)
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_table(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
/Users/andylei/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:3: FutureWarning: read_table is deprecated, use read_csv instead.
This is separate from the ipykernel package so we can avoid doing imports until
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
# number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
# OR
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.fillna(0).values.flatten().mean()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
data.index
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind StatisticsCheck out [Wind Statistics Exercises Video Tutorial](https://youtu.be/2x3WsWiNV18) to watch a data scientist go through the exercises Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_csv(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
#number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
#or
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_table(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
# number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
# OR
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.fillna(0).values.flatten().mean()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
//anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py:4291: RuntimeWarning: Invalid value encountered in percentile
interpolation=interpolation)
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_table(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
# number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
# OR
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.fillna(0).values.flatten().mean()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
//anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py:4291: RuntimeWarning: Invalid value encountered in percentile
interpolation=interpolation)
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Wind Statistics Introduction:The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exerciseeasier, in particular for the bonus question.You should be able to perform all of these operations without usinga for loop or other looping construct.1. The data in 'wind.data' has the following format:
###Code
"""
Yr Mo Dy RPT VAL ROS KIL SHA BIR DUB CLA MUL CLO BEL MAL
61 1 1 15.04 14.96 13.17 9.29 NaN 9.87 13.67 10.25 10.83 12.58 18.50 15.04
61 1 2 14.71 NaN 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83
61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 NaN 8.50 7.67 12.75 12.71
"""
###Output
_____no_output_____
###Markdown
The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. More information about the dataset go [here](wind.desc). Step 1. Import the necessary libraries
###Code
import pandas as pd
import datetime
###Output
_____no_output_____
###Markdown
Step 2. Import the dataset from this [address](https://github.com/guipsamora/pandas_exercises/blob/master/06_Stats/Wind_Stats/wind.data) Step 3. Assign it to a variable called data and replace the first 3 columns by a proper datetime index.
###Code
# parse_dates gets 0, 1, 2 columns and parses them as the index
data_url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data'
data = pd.read_table(data_url, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
###Output
_____no_output_____
###Markdown
Step 4. Year 2061? Do we really have data from this year? Create a function to fix it and apply it.
###Code
# The problem is that the dates are 2061 and so on...
# function that uses datetime
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
# apply the function fix_century on the column and replace the values to the right ones
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
# data.info()
data.head()
###Output
_____no_output_____
###Markdown
Step 5. Set the right dates as the index. Pay attention at the data type, it should be datetime64[ns].
###Code
# transform Yr_Mo_Dy it to date type datetime64
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
# set 'Yr_Mo_Dy' as the index
data = data.set_index('Yr_Mo_Dy')
data.head()
# data.info()
###Output
_____no_output_____
###Markdown
Step 6. Compute how many values are missing for each location over the entire record. They should be ignored in all calculations below.
###Code
# "Number of non-missing values for each location: "
data.isnull().sum()
###Output
_____no_output_____
###Markdown
Step 7. Compute how many non-missing values there are in total.
###Code
# number of columns minus the number of missing values for each location
data.shape[0] - data.isnull().sum()
# OR
data.notnull().sum()
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.fillna(0).values.flatten().mean()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
//anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py:4291: RuntimeWarning: Invalid value encountered in percentile
interpolation=interpolation)
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____
###Markdown
Step 8. Calculate the mean windspeeds of the windspeeds over all the locations and all the times. A single number for the entire dataset.
###Code
data.sum().sum() / data.notna().sum().sum()
###Output
_____no_output_____
###Markdown
Step 9. Create a DataFrame called loc_stats and calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days A different set of numbers for each location.
###Code
data.describe(percentiles=[])
###Output
_____no_output_____
###Markdown
Step 10. Create a DataFrame called day_stats and calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day. A different set of numbers for each day.
###Code
# create the dataframe
day_stats = pd.DataFrame()
# this time we determine axis equals to one so it gets each row.
day_stats['min'] = data.min(axis = 1) # min
day_stats['max'] = data.max(axis = 1) # max
day_stats['mean'] = data.mean(axis = 1) # mean
day_stats['std'] = data.std(axis = 1) # standard deviations
day_stats.head()
###Output
_____no_output_____
###Markdown
Step 11. Find the average windspeed in January for each location. Treat January 1961 and January 1962 both as January.
###Code
data.loc[data.index.month == 1].mean()
###Output
_____no_output_____
###Markdown
Step 12. Downsample the record to a yearly frequency for each location.
###Code
data.groupby(data.index.to_period('A')).mean()
###Output
_____no_output_____
###Markdown
Step 13. Downsample the record to a monthly frequency for each location.
###Code
data.groupby(data.index.to_period('M')).mean()
###Output
_____no_output_____
###Markdown
Step 14. Downsample the record to a weekly frequency for each location.
###Code
data.groupby(data.index.to_period('W')).mean()
###Output
_____no_output_____
###Markdown
Step 15. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 2 1961) for the first 52 weeks.
###Code
# resample data to 'W' week and use the functions
weekly = data.resample('W').agg(['min','max','mean','std'])
# slice it for the first 52 weeks and locations
weekly.loc[weekly.index[1:53], "RPT":"MAL"] .head(10)
###Output
_____no_output_____ |
site/en-snapshot/probability/examples/Bayesian_Gaussian_Mixture_Model.ipynb | ###Markdown
Copyright 2018 The TensorFlow Probability Authors.Licensed under the Apache License, Version 2.0 (the "License");
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
###Output
_____no_output_____
###Markdown
Bayesian Gaussian Mixture Model and Hamiltonian MCMC View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook In this colab we'll explore sampling from the posterior of a Bayesian Gaussian Mixture Model (BGMM) using only TensorFlow Probability primitives. Model For $k\in\{1,\ldots, K\}$ mixture components each of dimension $D$, we'd like to model $i\in\{1,\ldots,N\}$ iid samples using the following Bayesian Gaussian Mixture Model:$$\begin{align*}\theta &\sim \text{Dirichlet}(\text{concentration}=\alpha_0)\\\mu_k &\sim \text{Normal}(\text{loc}=\mu_{0k}, \text{scale}=I_D)\\T_k &\sim \text{Wishart}(\text{df}=5, \text{scale}=I_D)\\Z_i &\sim \text{Categorical}(\text{probs}=\theta)\\Y_i &\sim \text{Normal}(\text{loc}=\mu_{z_i}, \text{scale}=T_{z_i}^{-1/2})\\\end{align*}$$ Note, the `scale` arguments all have `cholesky` semantics. We use this convention because it is that of TF Distributions (which itself uses this convention in part because it is computationally advantageous). Our goal is to generate samples from the posterior:$$p\left(\theta, \{\mu_k, T_k\}_{k=1}^K \Big| \{y_i\}_{i=1}^N, \alpha_0, \{\mu_{ok}\}_{k=1}^K\right)$$Notice that $\{Z_i\}_{i=1}^N$ is not present--we're interested in only those random variables which don't scale with $N$. (And luckily there's a TF distribution which handles marginalizing out $Z_i$.)It is not possible to directly sample from this distribution owing to a computationally intractable normalization term.[Metropolis-Hastings algorithms](https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm) are technique for for sampling from intractable-to-normalize distributions.TensorFlow Probability offers a number of MCMC options, including several based on Metropolis-Hastings. In this notebook, we'll use [Hamiltonian Monte Carlo](https://en.wikipedia.org/wiki/Hamiltonian_Monte_Carlo) (`tfp.mcmc.HamiltonianMonteCarlo`). HMC is often a good choice because it can converge rapidly, samples the state space jointly (as opposed to coordinatewise), and leverages one of TF's virtues: automatic differentiation. That said, sampling from a BGMM posterior might actually be better done by other approaches, e.g., [Gibb's sampling](https://en.wikipedia.org/wiki/Gibbs_sampling).
###Code
%matplotlib inline
import functools
import matplotlib.pyplot as plt; plt.style.use('ggplot')
import numpy as np
import seaborn as sns; sns.set_context('notebook')
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices) > 0:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
###Output
_____no_output_____
###Markdown
Before actually building the model, we'll need to define a new type of distribution. From the model specification above, its clear we're parameterizing the MVN with an inverse covariance matrix, i.e., [precision matrix](https://en.wikipedia.org/wiki/Precision_(statistics%29). To accomplish this in TF, we'll need to roll out our `Bijector`. This `Bijector` will use the forward transformation:- `Y = tf.linalg.triangular_solve((tf.linalg.matrix_transpose(chol_precision_tril), X, adjoint=True) + loc`.And the `log_prob` calculation is just the inverse, i.e.:- `X = tf.linalg.matmul(chol_precision_tril, X - loc, adjoint_a=True)`.Since all we need for HMC is `log_prob`, this means we avoid ever calling `tf.linalg.triangular_solve` (as would be the case for `tfd.MultivariateNormalTriL`). This is advantageous since `tf.linalg.matmul` is usually faster owing to better cache locality.
###Code
class MVNCholPrecisionTriL(tfd.TransformedDistribution):
"""MVN from loc and (Cholesky) precision matrix."""
def __init__(self, loc, chol_precision_tril, name=None):
super(MVNCholPrecisionTriL, self).__init__(
distribution=tfd.Independent(tfd.Normal(tf.zeros_like(loc),
scale=tf.ones_like(loc)),
reinterpreted_batch_ndims=1),
bijector=tfb.Chain([
tfb.Shift(shift=loc),
tfb.Invert(tfb.ScaleMatvecTriL(scale_tril=chol_precision_tril,
adjoint=True)),
]),
name=name)
###Output
_____no_output_____
###Markdown
The `tfd.Independent` distribution turns independent draws of one distribution, into a multivariate distribution with statistically independent coordinates. In terms of computing `log_prob`, this "meta-distribution" manifests as a simple sum over the event dimension(s).Also notice that we took the `adjoint` ("transpose") of the scale matrix. This is because if precision is inverse covariance, i.e., $P=C^{-1}$ and if $C=AA^\top$, then $P=BB^{\top}$ where $B=A^{-\top}$. Since this distribution is kind of tricky, let's quickly verify that our `MVNCholPrecisionTriL` works as we think it should.
###Code
def compute_sample_stats(d, seed=42, n=int(1e6)):
x = d.sample(n, seed=seed)
sample_mean = tf.reduce_mean(x, axis=0, keepdims=True)
s = x - sample_mean
sample_cov = tf.linalg.matmul(s, s, adjoint_a=True) / tf.cast(n, s.dtype)
sample_scale = tf.linalg.cholesky(sample_cov)
sample_mean = sample_mean[0]
return [
sample_mean,
sample_cov,
sample_scale,
]
dtype = np.float32
true_loc = np.array([1., -1.], dtype=dtype)
true_chol_precision = np.array([[1., 0.],
[2., 8.]],
dtype=dtype)
true_precision = np.matmul(true_chol_precision, true_chol_precision.T)
true_cov = np.linalg.inv(true_precision)
d = MVNCholPrecisionTriL(
loc=true_loc,
chol_precision_tril=true_chol_precision)
[sample_mean, sample_cov, sample_scale] = [
t.numpy() for t in compute_sample_stats(d)]
print('true mean:', true_loc)
print('sample mean:', sample_mean)
print('true cov:\n', true_cov)
print('sample cov:\n', sample_cov)
###Output
true mean: [ 1. -1.]
sample mean: [ 1.0002806 -1.000105 ]
true cov:
[[ 1.0625 -0.03125 ]
[-0.03125 0.015625]]
sample cov:
[[ 1.0641273 -0.03126175]
[-0.03126175 0.01559312]]
###Markdown
Since the sample mean and covariance are close to the true mean and covariance, it seems like the distribution is correctly implemented. Now, we'll use `MVNCholPrecisionTriL` `tfp.distributions.JointDistributionNamed` to specify the BGMM model. For the observational model, we'll use `tfd.MixtureSameFamily` to automatically integrate out the $\{Z_i\}_{i=1}^N$ draws.
###Code
dtype = np.float64
dims = 2
components = 3
num_samples = 1000
bgmm = tfd.JointDistributionNamed(dict(
mix_probs=tfd.Dirichlet(
concentration=np.ones(components, dtype) / 10.),
loc=tfd.Independent(
tfd.Normal(
loc=np.stack([
-np.ones(dims, dtype),
np.zeros(dims, dtype),
np.ones(dims, dtype),
]),
scale=tf.ones([components, dims], dtype)),
reinterpreted_batch_ndims=2),
precision=tfd.Independent(
tfd.WishartTriL(
df=5,
scale_tril=np.stack([np.eye(dims, dtype=dtype)]*components),
input_output_cholesky=True),
reinterpreted_batch_ndims=1),
s=lambda mix_probs, loc, precision: tfd.Sample(tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(probs=mix_probs),
components_distribution=MVNCholPrecisionTriL(
loc=loc,
chol_precision_tril=precision)),
sample_shape=num_samples)
))
def joint_log_prob(observations, mix_probs, loc, chol_precision):
"""BGMM with priors: loc=Normal, precision=Inverse-Wishart, mix=Dirichlet.
Args:
observations: `[n, d]`-shaped `Tensor` representing Bayesian Gaussian
Mixture model draws. Each sample is a length-`d` vector.
mix_probs: `[K]`-shaped `Tensor` representing random draw from
`Dirichlet` prior.
loc: `[K, d]`-shaped `Tensor` representing the location parameter of the
`K` components.
chol_precision: `[K, d, d]`-shaped `Tensor` representing `K` lower
triangular `cholesky(Precision)` matrices, each being sampled from
a Wishart distribution.
Returns:
log_prob: `Tensor` representing joint log-density over all inputs.
"""
return bgmm.log_prob(
mix_probs=mix_probs, loc=loc, precision=chol_precision, s=observations)
###Output
_____no_output_____
###Markdown
Generate "Training" Data For this demo, we'll sample some random data.
###Code
true_loc = np.array([[-2., -2],
[0, 0],
[2, 2]], dtype)
random = np.random.RandomState(seed=43)
true_hidden_component = random.randint(0, components, num_samples)
observations = (true_loc[true_hidden_component] +
random.randn(num_samples, dims).astype(dtype))
###Output
_____no_output_____
###Markdown
Bayesian Inference using HMC Now that we've used TFD to specify our model and obtained some observed data, we have all the necessary pieces to run HMC.To do this, we'll use a [partial application](https://en.wikipedia.org/wiki/Partial_application) to "pin down" the things we don't want to sample. In this case that means we need only pin down `observations`. (The hyper-parameters are already baked in to the prior distributions and not part of the `joint_log_prob` function signature.)
###Code
unnormalized_posterior_log_prob = functools.partial(joint_log_prob, observations)
initial_state = [
tf.fill([components],
value=np.array(1. / components, dtype),
name='mix_probs'),
tf.constant(np.array([[-2., -2],
[0, 0],
[2, 2]], dtype),
name='loc'),
tf.linalg.eye(dims, batch_shape=[components], dtype=dtype, name='chol_precision'),
]
###Output
_____no_output_____
###Markdown
Unconstrained Representation Hamiltonian Monte Carlo (HMC) requires the target log-probability function be differentiable with respect to its arguments. Furthermore, HMC can exhibit dramatically higher statistical efficiency if the state-space is unconstrained.This means we'll have to work out two main issues when sampling from the BGMM posterior:1. $\theta$ represents a discrete probability vector, i.e., must be such that $\sum_{k=1}^K \theta_k = 1$ and $\theta_k>0$.2. $T_k$ represents an inverse covariance matrix, i.e., must be such that $T_k \succ 0$, i.e., is [positive definite](https://en.wikipedia.org/wiki/Positive-definite_matrix). To address this requirement we'll need to:1. transform the constrained variables to an unconstrained space2. run the MCMC in unconstrained space3. transform the unconstrained variables back to the constrained space.As with `MVNCholPrecisionTriL`, we'll use [`Bijector`s](https://www.tensorflow.org/api_docs/python/tf/distributions/bijectors/Bijector) to transform random variables to unconstrained space.- The [`Dirichlet`](https://en.wikipedia.org/wiki/Dirichlet_distribution) is transformed to unconstrained space via the [softmax function](https://en.wikipedia.org/wiki/Softmax_function).- Our precision random variable is a distribution over postive semidefinite matrices. To unconstrain these we'll use the `FillTriangular` and `TransformDiagonal` bijectors. These convert vectors to lower-triangular matrices and ensure the diagonal is positive. The former is useful because it enables sampling only $d(d+1)/2$ floats rather than $d^2$.
###Code
unconstraining_bijectors = [
tfb.SoftmaxCentered(),
tfb.Identity(),
tfb.Chain([
tfb.TransformDiagonal(tfb.Softplus()),
tfb.FillTriangular(),
])]
@tf.function(autograph=False)
def sample():
return tfp.mcmc.sample_chain(
num_results=2000,
num_burnin_steps=500,
current_state=initial_state,
kernel=tfp.mcmc.SimpleStepSizeAdaptation(
tfp.mcmc.TransformedTransitionKernel(
inner_kernel=tfp.mcmc.HamiltonianMonteCarlo(
target_log_prob_fn=unnormalized_posterior_log_prob,
step_size=0.065,
num_leapfrog_steps=5),
bijector=unconstraining_bijectors),
num_adaptation_steps=400),
trace_fn=lambda _, pkr: pkr.inner_results.inner_results.is_accepted)
[mix_probs, loc, chol_precision], is_accepted = sample()
###Output
_____no_output_____
###Markdown
We'll now execute the chain and print the posterior means.
###Code
acceptance_rate = tf.reduce_mean(tf.cast(is_accepted, dtype=tf.float32)).numpy()
mean_mix_probs = tf.reduce_mean(mix_probs, axis=0).numpy()
mean_loc = tf.reduce_mean(loc, axis=0).numpy()
mean_chol_precision = tf.reduce_mean(chol_precision, axis=0).numpy()
precision = tf.linalg.matmul(chol_precision, chol_precision, transpose_b=True)
print('acceptance_rate:', acceptance_rate)
print('avg mix probs:', mean_mix_probs)
print('avg loc:\n', mean_loc)
print('avg chol(precision):\n', mean_chol_precision)
loc_ = loc.numpy()
ax = sns.kdeplot(loc_[:,0,0], loc_[:,0,1], shade=True, shade_lowest=False)
ax = sns.kdeplot(loc_[:,1,0], loc_[:,1,1], shade=True, shade_lowest=False)
ax = sns.kdeplot(loc_[:,2,0], loc_[:,2,1], shade=True, shade_lowest=False)
plt.title('KDE of loc draws');
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Probability Authors.Licensed under the Apache License, Version 2.0 (the "License");
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
###Output
_____no_output_____
###Markdown
Bayesian Gaussian Mixture Model and Hamiltonian MCMC View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook In this colab we'll explore sampling from the posterior of a Bayesian Gaussian Mixture Model (BGMM) using only TensorFlow Probability primitives. Model For $k\in\{1,\ldots, K\}$ mixture components each of dimension $D$, we'd like to model $i\in\{1,\ldots,N\}$ iid samples using the following Bayesian Gaussian Mixture Model:$$\begin{align*}\theta &\sim \text{Dirichlet}(\text{concentration}=\alpha_0)\\\mu_k &\sim \text{Normal}(\text{loc}=\mu_{0k}, \text{scale}=I_D)\\T_k &\sim \text{Wishart}(\text{df}=5, \text{scale}=I_D)\\Z_i &\sim \text{Categorical}(\text{probs}=\theta)\\Y_i &\sim \text{Normal}(\text{loc}=\mu_{z_i}, \text{scale}=T_{z_i}^{-1/2})\\\end{align*}$$ Note, the `scale` arguments all have `cholesky` semantics. We use this convention because it is that of TF Distributions (which itself uses this convention in part because it is computationally advantageous). Our goal is to generate samples from the posterior:$$p\left(\theta, \{\mu_k, T_k\}_{k=1}^K \Big| \{y_i\}_{i=1}^N, \alpha_0, \{\mu_{ok}\}_{k=1}^K\right)$$Notice that $\{Z_i\}_{i=1}^N$ is not present--we're interested in only those random variables which don't scale with $N$. (And luckily there's a TF distribution which handles marginalizing out $Z_i$.)It is not possible to directly sample from this distribution owing to a computationally intractable normalization term.[Metropolis-Hastings algorithms](https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm) are technique for for sampling from intractable-to-normalize distributions.TensorFlow Probability offers a number of MCMC options, including several based on Metropolis-Hastings. In this notebook, we'll use [Hamiltonian Monte Carlo](https://en.wikipedia.org/wiki/Hamiltonian_Monte_Carlo) (`tfp.mcmc.HamiltonianMonteCarlo`). HMC is often a good choice because it can converge rapidly, samples the state space jointly (as opposed to coordinatewise), and leverages one of TF's virtues: automatic differentiation. That said, sampling from a BGMM posterior might actually be better done by other approaches, e.g., [Gibb's sampling](https://en.wikipedia.org/wiki/Gibbs_sampling).
###Code
%matplotlib inline
import functools
import matplotlib.pyplot as plt; plt.style.use('ggplot')
import numpy as np
import seaborn as sns; sns.set_context('notebook')
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices) > 0:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
###Output
_____no_output_____
###Markdown
Before actually building the model, we'll need to define a new type of distribution. From the model specification above, its clear we're parameterizing the MVN with an inverse covariance matrix, i.e., [precision matrix](https://en.wikipedia.org/wiki/Precision_(statistics%29). To accomplish this in TF, we'll need to roll out our `Bijector`. This `Bijector` will use the forward transformation:- `Y = tf.linalg.triangular_solve((tf.linalg.matrix_transpose(chol_precision_tril), X, adjoint=True) + loc`.And the `log_prob` calculation is just the inverse, i.e.:- `X = tf.linalg.matmul(chol_precision_tril, X - loc, adjoint_a=True)`.Since all we need for HMC is `log_prob`, this means we avoid ever calling `tf.linalg.triangular_solve` (as would be the case for `tfd.MultivariateNormalTriL`). This is advantageous since `tf.linalg.matmul` is usually faster owing to better cache locality.
###Code
class MVNCholPrecisionTriL(tfd.TransformedDistribution):
"""MVN from loc and (Cholesky) precision matrix."""
def __init__(self, loc, chol_precision_tril, name=None):
super(MVNCholPrecisionTriL, self).__init__(
distribution=tfd.Independent(tfd.Normal(tf.zeros_like(loc),
scale=tf.ones_like(loc)),
reinterpreted_batch_ndims=1),
bijector=tfb.Chain([
tfb.Affine(shift=loc),
tfb.Invert(tfb.Affine(scale_tril=chol_precision_tril,
adjoint=True)),
]),
name=name)
###Output
_____no_output_____
###Markdown
The `tfd.Independent` distribution turns independent draws of one distribution, into a multivariate distribution with statistically independent coordinates. In terms of computing `log_prob`, this "meta-distribution" manifests as a simple sum over the event dimension(s).Also notice that we took the `adjoint` ("transpose") of the scale matrix. This is because if precision is inverse covariance, i.e., $P=C^{-1}$ and if $C=AA^\top$, then $P=BB^{\top}$ where $B=A^{-\top}$. Since this distribution is kind of tricky, let's quickly verify that our `MVNCholPrecisionTriL` works as we think it should.
###Code
def compute_sample_stats(d, seed=42, n=int(1e6)):
x = d.sample(n, seed=seed)
sample_mean = tf.reduce_mean(x, axis=0, keepdims=True)
s = x - sample_mean
sample_cov = tf.linalg.matmul(s, s, adjoint_a=True) / tf.cast(n, s.dtype)
sample_scale = tf.linalg.cholesky(sample_cov)
sample_mean = sample_mean[0]
return [
sample_mean,
sample_cov,
sample_scale,
]
dtype = np.float32
true_loc = np.array([1., -1.], dtype=dtype)
true_chol_precision = np.array([[1., 0.],
[2., 8.]],
dtype=dtype)
true_precision = np.matmul(true_chol_precision, true_chol_precision.T)
true_cov = np.linalg.inv(true_precision)
d = MVNCholPrecisionTriL(
loc=true_loc,
chol_precision_tril=true_chol_precision)
[sample_mean, sample_cov, sample_scale] = [
t.numpy() for t in compute_sample_stats(d)]
print('true mean:', true_loc)
print('sample mean:', sample_mean)
print('true cov:\n', true_cov)
print('sample cov:\n', sample_cov)
###Output
true mean: [ 1. -1.]
sample mean: [ 1.0002806 -1.000105 ]
true cov:
[[ 1.0625 -0.03125 ]
[-0.03125 0.015625]]
sample cov:
[[ 1.0641273 -0.03126175]
[-0.03126175 0.01559312]]
###Markdown
Since the sample mean and covariance are close to the true mean and covariance, it seems like the distribution is correctly implemented. Now, we'll use `MVNCholPrecisionTriL` `tfp.distributions.JointDistributionNamed` to specify the BGMM model. For the observational model, we'll use `tfd.MixtureSameFamily` to automatically integrate out the $\{Z_i\}_{i=1}^N$ draws.
###Code
dtype = np.float64
dims = 2
components = 3
num_samples = 1000
bgmm = tfd.JointDistributionNamed(dict(
mix_probs=tfd.Dirichlet(
concentration=np.ones(components, dtype) / 10.),
loc=tfd.Independent(
tfd.Normal(
loc=np.stack([
-np.ones(dims, dtype),
np.zeros(dims, dtype),
np.ones(dims, dtype),
]),
scale=tf.ones([components, dims], dtype)),
reinterpreted_batch_ndims=2),
precision=tfd.Independent(
tfd.WishartTriL(
df=5,
scale_tril=np.stack([np.eye(dims, dtype=dtype)]*components),
input_output_cholesky=True),
reinterpreted_batch_ndims=1),
s=lambda mix_probs, loc, precision: tfd.Sample(tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(probs=mix_probs),
components_distribution=MVNCholPrecisionTriL(
loc=loc,
chol_precision_tril=precision)),
sample_shape=num_samples)
))
def joint_log_prob(observations, mix_probs, loc, chol_precision):
"""BGMM with priors: loc=Normal, precision=Inverse-Wishart, mix=Dirichlet.
Args:
observations: `[n, d]`-shaped `Tensor` representing Bayesian Gaussian
Mixture model draws. Each sample is a length-`d` vector.
mix_probs: `[K]`-shaped `Tensor` representing random draw from
`Dirichlet` prior.
loc: `[K, d]`-shaped `Tensor` representing the location parameter of the
`K` components.
chol_precision: `[K, d, d]`-shaped `Tensor` representing `K` lower
triangular `cholesky(Precision)` matrices, each being sampled from
a Wishart distribution.
Returns:
log_prob: `Tensor` representing joint log-density over all inputs.
"""
return bgmm.log_prob(
mix_probs=mix_probs, loc=loc, precision=chol_precision, s=observations)
###Output
_____no_output_____
###Markdown
Generate "Training" Data For this demo, we'll sample some random data.
###Code
true_loc = np.array([[-2., -2],
[0, 0],
[2, 2]], dtype)
random = np.random.RandomState(seed=43)
true_hidden_component = random.randint(0, components, num_samples)
observations = (true_loc[true_hidden_component] +
random.randn(num_samples, dims).astype(dtype))
###Output
_____no_output_____
###Markdown
Bayesian Inference using HMC Now that we've used TFD to specify our model and obtained some observed data, we have all the necessary pieces to run HMC.To do this, we'll use a [partial application](https://en.wikipedia.org/wiki/Partial_application) to "pin down" the things we don't want to sample. In this case that means we need only pin down `observations`. (The hyper-parameters are already baked in to the prior distributions and not part of the `joint_log_prob` function signature.)
###Code
unnormalized_posterior_log_prob = functools.partial(joint_log_prob, observations)
initial_state = [
tf.fill([components],
value=np.array(1. / components, dtype),
name='mix_probs'),
tf.constant(np.array([[-2., -2],
[0, 0],
[2, 2]], dtype),
name='loc'),
tf.linalg.eye(dims, batch_shape=[components], dtype=dtype, name='chol_precision'),
]
###Output
_____no_output_____
###Markdown
Unconstrained Representation Hamiltonian Monte Carlo (HMC) requires the target log-probability function be differentiable with respect to its arguments. Furthermore, HMC can exhibit dramatically higher statistical efficiency if the state-space is unconstrained.This means we'll have to work out two main issues when sampling from the BGMM posterior:1. $\theta$ represents a discrete probability vector, i.e., must be such that $\sum_{k=1}^K \theta_k = 1$ and $\theta_k>0$.2. $T_k$ represents an inverse covariance matrix, i.e., must be such that $T_k \succ 0$, i.e., is [positive definite](https://en.wikipedia.org/wiki/Positive-definite_matrix). To address this requirement we'll need to:1. transform the constrained variables to an unconstrained space2. run the MCMC in unconstrained space3. transform the unconstrained variables back to the constrained space.As with `MVNCholPrecisionTriL`, we'll use [`Bijector`s](https://www.tensorflow.org/api_docs/python/tf/distributions/bijectors/Bijector) to transform random variables to unconstrained space.- The [`Dirichlet`](https://en.wikipedia.org/wiki/Dirichlet_distribution) is transformed to unconstrained space via the [softmax function](https://en.wikipedia.org/wiki/Softmax_function).- Our precision random variable is a distribution over postive semidefinite matrices. To unconstrain these we'll use the `FillTriangular` and `TransformDiagonal` bijectors. These convert vectors to lower-triangular matrices and ensure the diagonal is positive. The former is useful because it enables sampling only $d(d+1)/2$ floats rather than $d^2$.
###Code
unconstraining_bijectors = [
tfb.SoftmaxCentered(),
tfb.Identity(),
tfb.Chain([
tfb.TransformDiagonal(tfb.Softplus()),
tfb.FillTriangular(),
])]
@tf.function(autograph=False)
def sample():
return tfp.mcmc.sample_chain(
num_results=2000,
num_burnin_steps=500,
current_state=initial_state,
kernel=tfp.mcmc.SimpleStepSizeAdaptation(
tfp.mcmc.TransformedTransitionKernel(
inner_kernel=tfp.mcmc.HamiltonianMonteCarlo(
target_log_prob_fn=unnormalized_posterior_log_prob,
step_size=0.065,
num_leapfrog_steps=5),
bijector=unconstraining_bijectors),
num_adaptation_steps=400),
trace_fn=lambda _, pkr: pkr.inner_results.inner_results.is_accepted)
[mix_probs, loc, chol_precision], is_accepted = sample()
###Output
_____no_output_____
###Markdown
We'll now execute the chain and print the posterior means.
###Code
acceptance_rate = tf.reduce_mean(tf.cast(is_accepted, dtype=tf.float32)).numpy()
mean_mix_probs = tf.reduce_mean(mix_probs, axis=0).numpy()
mean_loc = tf.reduce_mean(loc, axis=0).numpy()
mean_chol_precision = tf.reduce_mean(chol_precision, axis=0).numpy()
precision = tf.linalg.matmul(chol_precision, chol_precision, transpose_b=True)
print('acceptance_rate:', acceptance_rate)
print('avg mix probs:', mean_mix_probs)
print('avg loc:\n', mean_loc)
print('avg chol(precision):\n', mean_chol_precision)
loc_ = loc.numpy()
ax = sns.kdeplot(loc_[:,0,0], loc_[:,0,1], shade=True, shade_lowest=False)
ax = sns.kdeplot(loc_[:,1,0], loc_[:,1,1], shade=True, shade_lowest=False)
ax = sns.kdeplot(loc_[:,2,0], loc_[:,2,1], shade=True, shade_lowest=False)
plt.title('KDE of loc draws');
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Probability Authors.Licensed under the Apache License, Version 2.0 (the "License");
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
###Output
_____no_output_____
###Markdown
Bayesian Gaussian Mixture Model and Hamiltonian MCMC View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook In this colab we'll explore sampling from the posterior of a Bayesian Gaussian Mixture Model (BGMM) using only TensorFlow Probability primitives. Model For $k\in\{1,\ldots, K\}$ mixture components each of dimension $D$, we'd like to model $i\in\{1,\ldots,N\}$ iid samples using the following Bayesian Gaussian Mixture Model:$$\begin{align*}\theta &\sim \text{Dirichlet}(\text{concentration}=\alpha_0)\\\mu_k &\sim \text{Normal}(\text{loc}=\mu_{0k}, \text{scale}=I_D)\\T_k &\sim \text{Wishart}(\text{df}=5, \text{scale}=I_D)\\Z_i &\sim \text{Categorical}(\text{probs}=\theta)\\Y_i &\sim \text{Normal}(\text{loc}=\mu_{z_i}, \text{scale}=T_{z_i}^{-1/2})\\\end{align*}$$ Note, the `scale` arguments all have `cholesky` semantics. We use this convention because it is that of TF Distributions (which itself uses this convention in part because it is computationally advantageous). Our goal is to generate samples from the posterior:$$p\left(\theta, \{\mu_k, T_k\}_{k=1}^K \Big| \{y_i\}_{i=1}^N, \alpha_0, \{\mu_{ok}\}_{k=1}^K\right)$$Notice that $\{Z_i\}_{i=1}^N$ is not present--we're interested in only those random variables which don't scale with $N$. (And luckily there's a TF distribution which handles marginalizing out $Z_i$.)It is not possible to directly sample from this distribution owing to a computationally intractable normalization term.[Metropolis-Hastings algorithms](https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm) are technique for for sampling from intractable-to-normalize distributions.TensorFlow Probability offers a number of MCMC options, including several based on Metropolis-Hastings. In this notebook, we'll use [Hamiltonian Monte Carlo](https://en.wikipedia.org/wiki/Hamiltonian_Monte_Carlo) (`tfp.mcmc.HamiltonianMonteCarlo`). HMC is often a good choice because it can converge rapidly, samples the state space jointly (as opposed to coordinatewise), and leverages one of TF's virtues: automatic differentiation. That said, sampling from a BGMM posterior might actually be better done by other approaches, e.g., [Gibb's sampling](https://en.wikipedia.org/wiki/Gibbs_sampling).
###Code
%matplotlib inline
import functools
import matplotlib.pyplot as plt; plt.style.use('ggplot')
import numpy as np
import seaborn as sns; sns.set_context('notebook')
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices) > 0:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
###Output
_____no_output_____
###Markdown
Before actually building the model, we'll need to define a new type of distribution. From the model specification above, its clear we're parameterizing the MVN with an inverse covariance matrix, i.e., [precision matrix](https://en.wikipedia.org/wiki/Precision_(statistics%29). To accomplish this in TF, we'll need to roll out our `Bijector`. This `Bijector` will use the forward transformation:- `Y = tf.linalg.triangular_solve((tf.linalg.matrix_transpose(chol_precision_tril), X, adjoint=True) + loc`.And the `log_prob` calculation is just the inverse, i.e.:- `X = tf.linalg.matmul(chol_precision_tril, X - loc, adjoint_a=True)`.Since all we need for HMC is `log_prob`, this means we avoid ever calling `tf.linalg.triangular_solve` (as would be the case for `tfd.MultivariateNormalTriL`). This is advantageous since `tf.linalg.matmul` is usually faster owing to better cache locality.
###Code
class MVNCholPrecisionTriL(tfd.TransformedDistribution):
"""MVN from loc and (Cholesky) precision matrix."""
def __init__(self, loc, chol_precision_tril, name=None):
super(MVNCholPrecisionTriL, self).__init__(
distribution=tfd.Independent(tfd.Normal(tf.zeros_like(loc),
scale=tf.ones_like(loc)),
reinterpreted_batch_ndims=1),
bijector=tfb.Chain([
tfb.Shift(shift=loc),
tfb.Invert(tfb.ScaleMatvecTriL(scale_tril=chol_precision_tril,
adjoint=True)),
]),
name=name)
###Output
_____no_output_____
###Markdown
The `tfd.Independent` distribution turns independent draws of one distribution, into a multivariate distribution with statistically independent coordinates. In terms of computing `log_prob`, this "meta-distribution" manifests as a simple sum over the event dimension(s).Also notice that we took the `adjoint` ("transpose") of the scale matrix. This is because if precision is inverse covariance, i.e., $P=C^{-1}$ and if $C=AA^\top$, then $P=BB^{\top}$ where $B=A^{-\top}$. Since this distribution is kind of tricky, let's quickly verify that our `MVNCholPrecisionTriL` works as we think it should.
###Code
def compute_sample_stats(d, seed=42, n=int(1e6)):
x = d.sample(n, seed=seed)
sample_mean = tf.reduce_mean(x, axis=0, keepdims=True)
s = x - sample_mean
sample_cov = tf.linalg.matmul(s, s, adjoint_a=True) / tf.cast(n, s.dtype)
sample_scale = tf.linalg.cholesky(sample_cov)
sample_mean = sample_mean[0]
return [
sample_mean,
sample_cov,
sample_scale,
]
dtype = np.float32
true_loc = np.array([1., -1.], dtype=dtype)
true_chol_precision = np.array([[1., 0.],
[2., 8.]],
dtype=dtype)
true_precision = np.matmul(true_chol_precision, true_chol_precision.T)
true_cov = np.linalg.inv(true_precision)
d = MVNCholPrecisionTriL(
loc=true_loc,
chol_precision_tril=true_chol_precision)
[sample_mean, sample_cov, sample_scale] = [
t.numpy() for t in compute_sample_stats(d)]
print('true mean:', true_loc)
print('sample mean:', sample_mean)
print('true cov:\n', true_cov)
print('sample cov:\n', sample_cov)
###Output
true mean: [ 1. -1.]
sample mean: [ 1.0002806 -1.000105 ]
true cov:
[[ 1.0625 -0.03125 ]
[-0.03125 0.015625]]
sample cov:
[[ 1.0641273 -0.03126175]
[-0.03126175 0.01559312]]
###Markdown
Since the sample mean and covariance are close to the true mean and covariance, it seems like the distribution is correctly implemented. Now, we'll use `MVNCholPrecisionTriL` `tfp.distributions.JointDistributionNamed` to specify the BGMM model. For the observational model, we'll use `tfd.MixtureSameFamily` to automatically integrate out the $\{Z_i\}_{i=1}^N$ draws.
###Code
dtype = np.float64
dims = 2
components = 3
num_samples = 1000
bgmm = tfd.JointDistributionNamed(dict(
mix_probs=tfd.Dirichlet(
concentration=np.ones(components, dtype) / 10.),
loc=tfd.Independent(
tfd.Normal(
loc=np.stack([
-np.ones(dims, dtype),
np.zeros(dims, dtype),
np.ones(dims, dtype),
]),
scale=tf.ones([components, dims], dtype)),
reinterpreted_batch_ndims=2),
precision=tfd.Independent(
tfd.WishartTriL(
df=5,
scale_tril=np.stack([np.eye(dims, dtype=dtype)]*components),
input_output_cholesky=True),
reinterpreted_batch_ndims=1),
s=lambda mix_probs, loc, precision: tfd.Sample(tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(probs=mix_probs),
components_distribution=MVNCholPrecisionTriL(
loc=loc,
chol_precision_tril=precision)),
sample_shape=num_samples)
))
def joint_log_prob(observations, mix_probs, loc, chol_precision):
"""BGMM with priors: loc=Normal, precision=Inverse-Wishart, mix=Dirichlet.
Args:
observations: `[n, d]`-shaped `Tensor` representing Bayesian Gaussian
Mixture model draws. Each sample is a length-`d` vector.
mix_probs: `[K]`-shaped `Tensor` representing random draw from
`Dirichlet` prior.
loc: `[K, d]`-shaped `Tensor` representing the location parameter of the
`K` components.
chol_precision: `[K, d, d]`-shaped `Tensor` representing `K` lower
triangular `cholesky(Precision)` matrices, each being sampled from
a Wishart distribution.
Returns:
log_prob: `Tensor` representing joint log-density over all inputs.
"""
return bgmm.log_prob(
mix_probs=mix_probs, loc=loc, precision=chol_precision, s=observations)
###Output
_____no_output_____
###Markdown
Generate "Training" Data For this demo, we'll sample some random data.
###Code
true_loc = np.array([[-2., -2],
[0, 0],
[2, 2]], dtype)
random = np.random.RandomState(seed=43)
true_hidden_component = random.randint(0, components, num_samples)
observations = (true_loc[true_hidden_component] +
random.randn(num_samples, dims).astype(dtype))
###Output
_____no_output_____
###Markdown
Bayesian Inference using HMC Now that we've used TFD to specify our model and obtained some observed data, we have all the necessary pieces to run HMC.To do this, we'll use a [partial application](https://en.wikipedia.org/wiki/Partial_application) to "pin down" the things we don't want to sample. In this case that means we need only pin down `observations`. (The hyper-parameters are already baked in to the prior distributions and not part of the `joint_log_prob` function signature.)
###Code
unnormalized_posterior_log_prob = functools.partial(joint_log_prob, observations)
initial_state = [
tf.fill([components],
value=np.array(1. / components, dtype),
name='mix_probs'),
tf.constant(np.array([[-2., -2],
[0, 0],
[2, 2]], dtype),
name='loc'),
tf.linalg.eye(dims, batch_shape=[components], dtype=dtype, name='chol_precision'),
]
###Output
_____no_output_____
###Markdown
Unconstrained Representation Hamiltonian Monte Carlo (HMC) requires the target log-probability function be differentiable with respect to its arguments. Furthermore, HMC can exhibit dramatically higher statistical efficiency if the state-space is unconstrained.This means we'll have to work out two main issues when sampling from the BGMM posterior:1. $\theta$ represents a discrete probability vector, i.e., must be such that $\sum_{k=1}^K \theta_k = 1$ and $\theta_k>0$.2. $T_k$ represents an inverse covariance matrix, i.e., must be such that $T_k \succ 0$, i.e., is [positive definite](https://en.wikipedia.org/wiki/Positive-definite_matrix). To address this requirement we'll need to:1. transform the constrained variables to an unconstrained space2. run the MCMC in unconstrained space3. transform the unconstrained variables back to the constrained space.As with `MVNCholPrecisionTriL`, we'll use [`Bijector`s](https://www.tensorflow.org/api_docs/python/tf/distributions/bijectors/Bijector) to transform random variables to unconstrained space.- The [`Dirichlet`](https://en.wikipedia.org/wiki/Dirichlet_distribution) is transformed to unconstrained space via the [softmax function](https://en.wikipedia.org/wiki/Softmax_function).- Our precision random variable is a distribution over postive semidefinite matrices. To unconstrain these we'll use the `FillTriangular` and `TransformDiagonal` bijectors. These convert vectors to lower-triangular matrices and ensure the diagonal is positive. The former is useful because it enables sampling only $d(d+1)/2$ floats rather than $d^2$.
###Code
unconstraining_bijectors = [
tfb.SoftmaxCentered(),
tfb.Identity(),
tfb.Chain([
tfb.TransformDiagonal(tfb.Softplus()),
tfb.FillTriangular(),
])]
@tf.function(autograph=False)
def sample():
return tfp.mcmc.sample_chain(
num_results=2000,
num_burnin_steps=500,
current_state=initial_state,
kernel=tfp.mcmc.SimpleStepSizeAdaptation(
tfp.mcmc.TransformedTransitionKernel(
inner_kernel=tfp.mcmc.HamiltonianMonteCarlo(
target_log_prob_fn=unnormalized_posterior_log_prob,
step_size=0.065,
num_leapfrog_steps=5),
bijector=unconstraining_bijectors),
num_adaptation_steps=400),
trace_fn=lambda _, pkr: pkr.inner_results.inner_results.is_accepted)
[mix_probs, loc, chol_precision], is_accepted = sample()
###Output
_____no_output_____
###Markdown
We'll now execute the chain and print the posterior means.
###Code
acceptance_rate = tf.reduce_mean(tf.cast(is_accepted, dtype=tf.float32)).numpy()
mean_mix_probs = tf.reduce_mean(mix_probs, axis=0).numpy()
mean_loc = tf.reduce_mean(loc, axis=0).numpy()
mean_chol_precision = tf.reduce_mean(chol_precision, axis=0).numpy()
precision = tf.linalg.matmul(chol_precision, chol_precision, transpose_b=True)
print('acceptance_rate:', acceptance_rate)
print('avg mix probs:', mean_mix_probs)
print('avg loc:\n', mean_loc)
print('avg chol(precision):\n', mean_chol_precision)
loc_ = loc.numpy()
ax = sns.kdeplot(loc_[:,0,0], loc_[:,0,1], shade=True, shade_lowest=False)
ax = sns.kdeplot(loc_[:,1,0], loc_[:,1,1], shade=True, shade_lowest=False)
ax = sns.kdeplot(loc_[:,2,0], loc_[:,2,1], shade=True, shade_lowest=False)
plt.title('KDE of loc draws');
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Probability Authors.Licensed under the Apache License, Version 2.0 (the "License");
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
###Output
_____no_output_____
###Markdown
Bayesian Gaussian Mixture Model and Hamiltonian MCMC View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook In this colab we'll explore sampling from the posterior of a Bayesian Gaussian Mixture Model (BGMM) using only TensorFlow Probability primitives. Model For $k\in\{1,\ldots, K\}$ mixture components each of dimension $D$, we'd like to model $i\in\{1,\ldots,N\}$ iid samples using the following Bayesian Gaussian Mixture Model:$$\begin{align*}\theta &\sim \text{Dirichlet}(\text{concentration}=\alpha_0)\\\mu_k &\sim \text{Normal}(\text{loc}=\mu_{0k}, \text{scale}=I_D)\\T_k &\sim \text{Wishart}(\text{df}=5, \text{scale}=I_D)\\Z_i &\sim \text{Categorical}(\text{probs}=\theta)\\Y_i &\sim \text{Normal}(\text{loc}=\mu_{z_i}, \text{scale}=T_{z_i}^{-1/2})\\\end{align*}$$ Note, the `scale` arguments all have `cholesky` semantics. We use this convention because it is that of TF Distributions (which itself uses this convention in part because it is computationally advantageous). Our goal is to generate samples from the posterior:$$p\left(\theta, \{\mu_k, T_k\}_{k=1}^K \Big| \{y_i\}_{i=1}^N, \alpha_0, \{\mu_{ok}\}_{k=1}^K\right)$$Notice that $\{Z_i\}_{i=1}^N$ is not present--we're interested in only those random variables which don't scale with $N$. (And luckily there's a TF distribution which handles marginalizing out $Z_i$.)It is not possible to directly sample from this distribution owing to a computationally intractable normalization term.[Metropolis-Hastings algorithms](https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm) are technique for for sampling from intractable-to-normalize distributions.TensorFlow Probability offers a number of MCMC options, including several based on Metropolis-Hastings. In this notebook, we'll use [Hamiltonian Monte Carlo](https://en.wikipedia.org/wiki/Hamiltonian_Monte_Carlo) (`tfp.mcmc.HamiltonianMonteCarlo`). HMC is often a good choice because it can converge rapidly, samples the state space jointly (as opposed to coordinatewise), and leverages one of TF's virtues: automatic differentiation. That said, sampling from a BGMM posterior might actually be better done by other approaches, e.g., [Gibb's sampling](https://en.wikipedia.org/wiki/Gibbs_sampling).
###Code
%matplotlib inline
import functools
import matplotlib.pyplot as plt; plt.style.use('ggplot')
import numpy as np
import seaborn as sns; sns.set_context('notebook')
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices) > 0:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
###Output
_____no_output_____
###Markdown
Before actually building the model, we'll need to define a new type of distribution. From the model specification above, its clear we're parameterizing the MVN with an inverse covariance matrix, i.e., [precision matrix](https://en.wikipedia.org/wiki/Precision_(statistics%29). To accomplish this in TF, we'll need to roll out our `Bijector`. This `Bijector` will use the forward transformation:- `Y = tf.linalg.triangular_solve((tf.linalg.matrix_transpose(chol_precision_tril), X, adjoint=True) + loc`.And the `log_prob` calculation is just the inverse, i.e.:- `X = tf.linalg.matmul(chol_precision_tril, X - loc, adjoint_a=True)`.Since all we need for HMC is `log_prob`, this means we avoid ever calling `tf.linalg.triangular_solve` (as would be the case for `tfd.MultivariateNormalTriL`). This is advantageous since `tf.linalg.matmul` is usually faster owing to better cache locality.
###Code
class MVNCholPrecisionTriL(tfd.TransformedDistribution):
"""MVN from loc and (Cholesky) precision matrix."""
def __init__(self, loc, chol_precision_tril, name=None):
super(MVNCholPrecisionTriL, self).__init__(
distribution=tfd.Independent(tfd.Normal(tf.zeros_like(loc),
scale=tf.ones_like(loc)),
reinterpreted_batch_ndims=1),
bijector=tfb.Chain([
tfb.Affine(shift=loc),
tfb.Invert(tfb.Affine(scale_tril=chol_precision_tril,
adjoint=True)),
]),
name=name)
###Output
_____no_output_____
###Markdown
The `tfd.Independent` distribution turns independent draws of one distribution, into a multivariate distribution with statistically independent coordinates. In terms of computing `log_prob`, this "meta-distribution" manifests as a simple sum over the event dimension(s).Also notice that we took the `adjoint` ("transpose") of the scale matrix. This is because if precision is inverse covariance, i.e., $P=C^{-1}$ and if $C=AA^\top$, then $P=BB^{\top}$ where $B=A^{-\top}$. Since this distribution is kind of tricky, let's quickly verify that our `MVNCholPrecisionTriL` works as we think it should.
###Code
def compute_sample_stats(d, seed=42, n=int(1e6)):
x = d.sample(n, seed=seed)
sample_mean = tf.reduce_mean(x, axis=0, keepdims=True)
s = x - sample_mean
sample_cov = tf.linalg.matmul(s, s, adjoint_a=True) / tf.cast(n, s.dtype)
sample_scale = tf.linalg.cholesky(sample_cov)
sample_mean = sample_mean[0]
return [
sample_mean,
sample_cov,
sample_scale,
]
dtype = np.float32
true_loc = np.array([1., -1.], dtype=dtype)
true_chol_precision = np.array([[1., 0.],
[2., 8.]],
dtype=dtype)
true_precision = np.matmul(true_chol_precision, true_chol_precision.T)
true_cov = np.linalg.inv(true_precision)
d = MVNCholPrecisionTriL(
loc=true_loc,
chol_precision_tril=true_chol_precision)
[sample_mean, sample_cov, sample_scale] = [
t.numpy() for t in compute_sample_stats(d)]
print('true mean:', true_loc)
print('sample mean:', sample_mean)
print('true cov:\n', true_cov)
print('sample cov:\n', sample_cov)
###Output
true mean: [ 1. -1.]
sample mean: [ 1.0002806 -1.000105 ]
true cov:
[[ 1.0625 -0.03125 ]
[-0.03125 0.015625]]
sample cov:
[[ 1.0641273 -0.03126175]
[-0.03126175 0.01559312]]
###Markdown
Since the sample mean and covariance are close to the true mean and covariance, it seems like the distribution is correctly implemented. Now, we'll use `MVNCholPrecisionTriL` `tfp.distributions.JointDistributionNamed` to specify the BGMM model. For the observational model, we'll use `tfd.MixtureSameFamily` to automatically integrate out the $\{Z_i\}_{i=1}^N$ draws.
###Code
dtype = np.float64
dims = 2
components = 3
num_samples = 1000
bgmm = tfd.JointDistributionNamed(dict(
mix_probs=tfd.Dirichlet(
concentration=np.ones(components, dtype) / 10.),
loc=tfd.Independent(
tfd.Normal(
loc=np.stack([
-np.ones(dims, dtype),
np.zeros(dims, dtype),
np.ones(dims, dtype),
]),
scale=tf.ones([components, dims], dtype)),
reinterpreted_batch_ndims=2),
precision=tfd.Independent(
tfd.WishartTriL(
df=5,
scale_tril=np.stack([np.eye(dims, dtype=dtype)]*components),
input_output_cholesky=True),
reinterpreted_batch_ndims=1),
s=lambda mix_probs, loc, precision: tfd.Sample(tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(probs=mix_probs),
components_distribution=MVNCholPrecisionTriL(
loc=loc,
chol_precision_tril=precision)),
sample_shape=num_samples)
))
def joint_log_prob(observations, mix_probs, loc, chol_precision):
"""BGMM with priors: loc=Normal, precision=Inverse-Wishart, mix=Dirichlet.
Args:
observations: `[n, d]`-shaped `Tensor` representing Bayesian Gaussian
Mixture model draws. Each sample is a length-`d` vector.
mix_probs: `[K]`-shaped `Tensor` representing random draw from
`Dirichlet` prior.
loc: `[K, d]`-shaped `Tensor` representing the location parameter of the
`K` components.
chol_precision: `[K, d, d]`-shaped `Tensor` representing `K` lower
triangular `cholesky(Precision)` matrices, each being sampled from
a Wishart distribution.
Returns:
log_prob: `Tensor` representing joint log-density over all inputs.
"""
return bgmm.log_prob(
mix_probs=mix_probs, loc=loc, precision=chol_precision, s=observations)
###Output
_____no_output_____
###Markdown
Generate "Training" Data For this demo, we'll sample some random data.
###Code
true_loc = np.array([[-2., -2],
[0, 0],
[2, 2]], dtype)
random = np.random.RandomState(seed=43)
true_hidden_component = random.randint(0, components, num_samples)
observations = (true_loc[true_hidden_component] +
random.randn(num_samples, dims).astype(dtype))
###Output
_____no_output_____
###Markdown
Bayesian Inference using HMC Now that we've used TFD to specify our model and obtained some observed data, we have all the necessary pieces to run HMC.To do this, we'll use a [partial application](https://en.wikipedia.org/wiki/Partial_application) to "pin down" the things we don't want to sample. In this case that means we need only pin down `observations`. (The hyper-parameters are already baked in to the prior distributions and not part of the `joint_log_prob` function signature.)
###Code
unnormalized_posterior_log_prob = functools.partial(joint_log_prob, observations)
initial_state = [
tf.fill([components],
value=np.array(1. / components, dtype),
name='mix_probs'),
tf.constant(np.array([[-2., -2],
[0, 0],
[2, 2]], dtype),
name='loc'),
tf.linalg.eye(dims, batch_shape=[components], dtype=dtype, name='chol_precision'),
]
###Output
_____no_output_____
###Markdown
Unconstrained Representation Hamiltonian Monte Carlo (HMC) requires the target log-probability function be differentiable with respect to its arguments. Furthermore, HMC can exhibit dramatically higher statistical efficiency if the state-space is unconstrained.This means we'll have to work out two main issues when sampling from the BGMM posterior:1. $\theta$ represents a discrete probability vector, i.e., must be such that $\sum_{k=1}^K \theta_k = 1$ and $\theta_k>0$.2. $T_k$ represents an inverse covariance matrix, i.e., must be such that $T_k \succ 0$, i.e., is [positive definite](https://en.wikipedia.org/wiki/Positive-definite_matrix). To address this requirement we'll need to:1. transform the constrained variables to an unconstrained space2. run the MCMC in unconstrained space3. transform the unconstrained variables back to the constrained space.As with `MVNCholPrecisionTriL`, we'll use [`Bijector`s](https://www.tensorflow.org/api_docs/python/tf/distributions/bijectors/Bijector) to transform random variables to unconstrained space.- The [`Dirichlet`](https://en.wikipedia.org/wiki/Dirichlet_distribution) is transformed to unconstrained space via the [softmax function](https://en.wikipedia.org/wiki/Softmax_function).- Our precision random variable is a distribution over postive semidefinite matrices. To unconstrain these we'll use the `FillTriangular` and `TransformDiagonal` bijectors. These convert vectors to lower-triangular matrices and ensure the diagonal is positive. The former is useful because it enables sampling only $d(d+1)/2$ floats rather than $d^2$.
###Code
unconstraining_bijectors = [
tfb.SoftmaxCentered(),
tfb.Identity(),
tfb.Chain([
tfb.TransformDiagonal(tfb.Softplus()),
tfb.FillTriangular(),
])]
@tf.function(autograph=False)
def sample():
return tfp.mcmc.sample_chain(
num_results=2000,
num_burnin_steps=500,
current_state=initial_state,
kernel=tfp.mcmc.SimpleStepSizeAdaptation(
tfp.mcmc.TransformedTransitionKernel(
inner_kernel=tfp.mcmc.HamiltonianMonteCarlo(
target_log_prob_fn=unnormalized_posterior_log_prob,
step_size=0.065,
num_leapfrog_steps=5),
bijector=unconstraining_bijectors),
num_adaptation_steps=400),
trace_fn=lambda _, pkr: pkr.inner_results.inner_results.is_accepted)
[mix_probs, loc, chol_precision], is_accepted = sample()
###Output
_____no_output_____
###Markdown
We'll now execute the chain and print the posterior means.
###Code
acceptance_rate = tf.reduce_mean(tf.cast(is_accepted, dtype=tf.float32)).numpy()
mean_mix_probs = tf.reduce_mean(mix_probs, axis=0).numpy()
mean_loc = tf.reduce_mean(loc, axis=0).numpy()
mean_chol_precision = tf.reduce_mean(chol_precision, axis=0).numpy()
precision = tf.linalg.matmul(chol_precision, chol_precision, transpose_b=True)
print('acceptance_rate:', acceptance_rate)
print('avg mix probs:', mean_mix_probs)
print('avg loc:\n', mean_loc)
print('avg chol(precision):\n', mean_chol_precision)
loc_ = loc.numpy()
ax = sns.kdeplot(loc_[:,0,0], loc_[:,0,1], shade=True, shade_lowest=False)
ax = sns.kdeplot(loc_[:,1,0], loc_[:,1,1], shade=True, shade_lowest=False)
ax = sns.kdeplot(loc_[:,2,0], loc_[:,2,1], shade=True, shade_lowest=False)
plt.title('KDE of loc draws');
###Output
_____no_output_____ |
Google Cloud Platform/Cloud Vision/Google_Cloud_Vision_API_Boosting_ads.ipynb | ###Markdown
**Introduction to Google Cloud Vision:**----------In the next post, I will show a usage approach to the Google Cloud vision API.In the following example we will be using tables which contain supermetrics information and are stored in our SQL database.Within the database we will have the unique URLs of each ad and we will use these URLs to analyze the context of the image stored in each one of them.
###Code
!pip install webcolors google-cloud-vision
###Output
_____no_output_____
###Markdown
After installing the necessary additional libraries or packages, we need to import them.
###Code
import os, io
from google.cloud import vision
import pandas as pd
from pandas import DataFrame
import webcolors
from PIL import Image as pilmage
import requests
from io import BytesIO
import json
import re
import ast
###Output
_____no_output_____
###Markdown
**Functions:**----------------------Cloud Vision will return information from the RGB color guide of our images when we request the color, therefore, we generate a function to classify the colors according to their closest primary color and obtain the name of the color and not its RGB code.
###Code
#funtion to get the color
def closest_colour(requested_colour):
min_colours = {}
for key, name in webcolors.CSS3_HEX_TO_NAMES.items():
r_c, g_c, b_c = webcolors.hex_to_rgb(key)
rd = (r_c - requested_colour[0]) ** 2
gd = (g_c - requested_colour[1]) ** 2
bd = (b_c - requested_colour[2]) ** 2
min_colours[(rd + gd + bd)] = name
return min_colours[min(min_colours.keys())]
def get_colour_name(requested_colour):
try:
closest_name = actual_name = webcolors.rgb_to_name(requested_colour)
except ValueError:
closest_name = closest_colour(requested_colour)
actual_name = None
return actual_name, closest_name
#funtions to get the color
#we are in a Google machine, we load our credentials in JSON format in our environment.
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'credentials.json'
client = vision.ImageAnnotatorClient()
image = vision.Image()
#We create an empty dataframe and generate a query to our databases in bigqguery.
colors_dataframe = pd.DataFrame({'url': [], 'pixel_fraction':[], 'score':[], 'reed':[], 'gree':[], 'blue':[]})
query_url = """
SELECT
source,
ad_id,
image_asset_url as url
FROM `main_url_dh`
where source = 'Facebook ads' and image_asset_url != '0'
group by 1,2,3
UNION ALL
SELECT
source,
ad_id,
promoted_tweet_card_image_url as url
FROM `main_url_dh`
where source = 'Twitter ads' and promoted_tweet_card_image_url != '0'
group by 1,2,3
"""
dataframe = pd.read_gbq(query_url)
dataframe_dupli = dataframe.drop_duplicates(subset = ['url']).copy()
dataframe_dupli.reset_index(inplace = True)
#We certify that there are no duplicate records in our dataframe
dataframe_dupli.url.shape
#Our jsons, which are a response from Cloud Vision, contain a particular format, which we need to adjust before we can process them in our dataframe,
#for this we create a function according to the type of information that we request from Cloud Vision.
def construction_of_json(string, model):
if model == 'colors':
b = string.replace('[', '').replace(']', '}').replace('color {\n', 'color:{').replace('\n}', '},')\
.replace('\nscore', 'score').replace('\npixel_fraction', ',pixel_fraction')\
.replace(' ', '-').replace('\n', '').replace(',-color', '}, color').replace('color:', '{"color":')\
.replace('red', '"red"').replace('green', '"green"').replace('blue', '"blue"').replace('score', '"score"').replace('pixel_fraction', '"pixel_fraction"')\
.replace('-', '').replace(',', ';').replace(';"',',"').replace('0"', '0,"').replace(';', ',').replace('},', '}').replace('} {', '},{').replace('}"', '},"')
elif model == 'topics':
b = string.replace('[', '').replace(']', '}').replace(',','},').replace('/m/', '').replace(' ', '')\
.replace('mid', '"mid"').replace('description', '"description"').replace('topicality', '"topicality"').replace('score', '"score"').replace('\n', ',').replace(',}', '}')\
.replace('"mid"', '{"mid"')
return ast.literal_eval(b)
#In the same way, we use our previous functions applied to our dataframes, to obtain the color, topic and url data.
def color_measurement(dataframe):
dataframe['tuple_colors'] = dataframe[['red', 'green', 'blue']].apply(tuple, axis = 1)
dataframe['colors'] = dataframe.tuple_colors.apply(lambda x: get_colour_name(x))
dataframe[['type', 'color']] = pd.DataFrame(dataframe['colors'].tolist(), index = dataframe.index)
print(dataframe.columns)
dataframe.sort_values(['url', 'pixel_fraction'], ascending= [True, False], inplace = True)
dataframe['section'] = dataframe.groupby('url').cumcount()
dataframe.reset_index(inplace = True, drop = True)
return dataframe[(dataframe.section>=0) & (dataframe.section<=2)].reset_index(drop = True)
def topic_measurement(dataframe):
dataframe.sort_values(['url', 'topicality'], ascending= [True, False], inplace = True)
dataframe['section'] = dataframe.groupby('url').cumcount()
return dataframe[(dataframe.section>=0) & (dataframe.section<=2)].reset_index(drop = True)
def text_measurement(dataframe):
dataframe['description'] = dataframe['description'].str.lower()
dataframe['description'] = dataframe['description'].map(lambda x: re.sub(r'\n', ' ', x))
return dataframe
#Some URLs contain images in compressed formats that are not compatible with cloud vision. We create a function for those images.
def transform_image_is_not_image(response, url, models):
img = pilmage.open(BytesIO(response.content))
path = '/content/temporal_file.jpg'
if 'RGBA' in str(img.mode):
print(' ', url, 'type' + str(img.mode))
img = img.convert('RGB')
img.save(path)
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
if models == 'colors':
response = client.image_properties(image = image).image_properties_annotation
dominant_colors = response.dominant_colors
dictionary = construction_of_json(string = str(dominant_colors.colors), model = models)
dataframe_colors = pd.concat([DataFrame(list(DataFrame(dictionary)['color'])), DataFrame(dictionary)[['score', 'pixel_fraction']]], axis = 1)
if models == 'topics':
res_lebes = client.label_detection(image=image)
labels = res_lebes.label_annotations
dictionary = construction_of_json(string = str(labels), model = models)
dataframe_colors = DataFrame.from_dict(dictionary)
if models == 'texts':
response = client.text_detection(image = image)
texts = response.text_annotations
if len(list(texts)) == 0:
dataframe_colors = DataFrame({'locale': ['no_text'], 'description':['no_text']})
else:
dataframe_colors = DataFrame({'description': [texts[0].description], 'locale': [texts[0].locale]})
dataframe_colors['url'] = url
os.remove(path)
return dataframe_colors.reset_index(drop = True)
###Output
_____no_output_____
###Markdown
Then we create our three main functions, which will consume all of our previous functions. They will perform the extraction of text, color and topics from our images, receiving the dataframe and URL.
###Code
def image_extraction_texts_function(data, image):
empty = DataFrame()
for url in list(data):
image.source.image_uri = url
response = client.text_detection(image = image)
texts = response.text_annotations
if len(list(texts)) == 0:
response = requests.get(url)
print('El URL: ', url, 'tiene una respuesta: ', response)
if '404' not in str(response):
if '.vmap' not in str(url):
empty = empty.append(transform_image_is_not_image(response, url, 'texts'))
else:
empty = empty.append(DataFrame({'url': [url], 'locale': ['error'], 'description':['error']}))
else:
empty = empty.append(DataFrame({'url': [url], 'locale': ['error'], 'description':['error']}))
elif '.jpg' not in str(url):
response = requests.get(url)
print('El URL: ', url, 'tiene una respuesta: ', response)
empty = empty.append(transform_image_is_not_image(response, url, 'texts'))
else:
dataframe_colors = DataFrame({'description': [texts[0].description], 'locale': [texts[0].locale]})
dataframe_colors['url'] = url
empty = empty.append(dataframe_colors)
frame = text_measurement(empty)
return empty, frame
def image_extraction_topics_function(data, image):
empty = DataFrame()
for url in list(data):
image.source.image_uri = url
res_lebes = client.label_detection(image=image)
labels = res_lebes.label_annotations
if len(list(labels)) == 0:
response = requests.get(url)
print('El URL: ', url, 'tiene una respuesta: ', response)
if '404' not in str(response):
if '.vmap' not in str(url):
empty = empty.append(transform_image_is_not_image(response, url, 'topics'))
else:
empty = empty.append(DataFrame({'url': [url], 'mid': [url], 'description':['video'], 'topicality':[0.0], 'score':[0]}))
else:
empty = empty.append(DataFrame({'url': [url], 'mid': [url], 'description':['error'], 'topicality':[0.0], 'score':[0]}))
elif '.jpg' not in str(url):
response = requests.get(url)
print('El URL: ', url, 'tiene una respuesta: ', response)
empty = empty.append(transform_image_is_not_image(response, url, 'topics'))
else:
dictionary = construction_of_json(str(labels), 'topics')
dataframe_colors = DataFrame.from_dict(dictionary)
dataframe_colors['url'] = url
empty = empty.append(dataframe_colors)
frame = topic_measurement(empty)
return empty, frame
def image_extraction_colors_function(data, image):
empty = DataFrame()
for url in list(data):
image.source.image_uri = url
response = client.image_properties(image = image).image_properties_annotation
dominant_colors = response.dominant_colors
if len(list(dominant_colors.colors)) == 0:
response = requests.get(url)
print('El URL: ', url, 'tiene una respuesta: ', response)
if '404' not in str(response):
if '.vmap' not in str(url):
empty = empty.append(transform_image_is_not_image(response, url, 'colors'))
else:
pass
else:
empty = empty.append(DataFrame({'url': [url], 'pixel_fraction':[132], 'score':[132], 'red':[132], 'green':[132], 'blue':[132]}))
elif '.jpg' not in str(url):
response = requests.get(url)
print('El URL: ', url, 'tiene una respuesta: ', response)
empty = empty.append(transform_image_is_not_image(response, url, 'colors'))
else:
dictionary = construction_of_json(str(dominant_colors.colors), 'colors')
dataframe_colors = pd.concat([DataFrame(list(DataFrame(dictionary)['color'])), DataFrame(dictionary)[['score', 'pixel_fraction']]], axis = 1)
dataframe_colors['url'] = url
empty = empty.append(dataframe_colors)
frame = color_measurement(empty)
return empty, frame
###Output
_____no_output_____
###Markdown
Later we will have to join all the dataframes that we have created, having as primary key our "URL" which will be the only and common element among all the dataframes that we have generated.
###Code
def merge_frames(first_frame, dataframes, model):
if model == 'colors':
middle_frame = pd.merge(
pd.merge(
pd.merge(first_frame,
dataframes[dataframes.section == 0][['url','color', 'tuple_colors', 'pixel_fraction']].rename(columns = {'color': 'main_color', 'tuple_colors': 'main_color_id',
'pixel_fraction': 'main_pixel_fraction'}),
how = 'left', on = 'url'),
dataframes[dataframes.section == 1][['url','color', 'tuple_colors', 'pixel_fraction']].rename(columns = {'color': 'second_color', 'tuple_colors': 'second_color_id',
'pixel_fraction': 'second_pixel_fraction'}),
how = 'left', on = 'url'),
dataframes[dataframes.section == 2][['url','color', 'tuple_colors', 'pixel_fraction']].rename(columns = {'color': 'third_color', 'tuple_colors': 'third_color_id',
'pixel_fraction': 'third_pixel_fraction'}),
how = 'left', on = 'url')
middle_frame['total_pixel_fraction'] = middle_frame.main_pixel_fraction + middle_frame.second_pixel_fraction + middle_frame.third_pixel_fraction
return middle_frame
elif model == 'topics':
last_frame = pd.merge(
pd.merge(
pd.merge(
first_frame,
dataframes[(dataframes.section == 0)][['url', 'description', 'topicality']].rename(columns = {'description': 'main_topic', 'topicality': 'main_topicality'}),
on = 'url', how = 'left'
),
dataframes[(dataframes.section == 1)][['url', 'description', 'topicality']].rename(columns = {'description': 'second_topic', 'topicality': 'second_topicality'}),
on = 'url', how = 'left'
),
dataframes[(dataframes.section == 2)][['url', 'description', 'topicality']].rename(columns = {'description': 'third_topic', 'topicality': 'third_topicality'}),
on = 'url', how = 'left'
)
last_frame['accurancy_topic_score'] = (last_frame.main_topicality + last_frame.second_topicality + last_frame.third_topicality) / 3
last_frame['tuple_topic'] = last_frame[['main_topic', 'second_topic', 'third_topic']].apply(tuple, axis = 1)
return last_frame
###Output
_____no_output_____
###Markdown
We run our processes and finally send all our synthesized data to bigquery.
###Code
complete_extraction_colors, image_metadata_colors = image_extraction_colors_function(dataframe_dupli.url, image)
complete_extraction_topics, image_metadata_topics = image_extraction_topics_function(dataframe_dupli.url, image)
complete_extraction_texts, image_metadata_text = image_extraction_texts_function(dataframe_dupli.url, image)
semi_last_frame = pd.merge(merge_frames(first_frame = dataframe_dupli[['url', 'source', 'ad_id']], dataframes = image_metadata_colors, model = 'colors'),
merge_frames(first_frame = dataframe_dupli[['url', 'source', 'ad_id']], dataframes = image_metadata_topics, model = 'topics'),
on = ['url', 'source', 'ad_id'],
how = 'left')
final_frame = pd.merge(semi_last_frame, image_metadata_text, on = 'url', how = 'left')
final_frame.to_gbq(destination_table = 'clients_table.main_categorical_values',
project_id = 'omg-latam-prd-adh-datahouse-cl',
if_exists = 'replace')
###Output
_____no_output_____ |
v1-uvod/sc-2018-siit-v1-cv-basics.ipynb | ###Markdown
Soft Computing Vežba 1 - Digitalna slika, computer vision, OpenCV OpenCVOpen source biblioteka namenjena oblasti računarske vizije (eng. computer vision). Dokumentacija dostupna ovde. matplotlibPlotting biblioteka za programski jezik Python i njegov numerički paket NumPy. Dokumentacija dostupna ovde. Učitavanje slikeOpenCV metoda za učitavanje slike sa diska je imread(path_to_image), koja kao parametar prima putanju do slike na disku. Učitana slika img je zapravo NumPy matrica, čije dimenzije zavise od same prirode slike. Ako je slika u boji, onda je img trodimenzionalna matrica, čije su prve dve dimenzije visina i širina slike, a treća dimenzija je veličine 3, zato što ona predstavlja boju (RGB, po jedan segment za svaku osnonvu boju).
###Code
import numpy as np
import cv2 # OpenCV biblioteka
import matplotlib
import matplotlib.pyplot as plt
# iscrtavanje slika i plotova unutar samog browsera
%matplotlib inline
# prikaz vecih slika
matplotlib.rcParams['figure.figsize'] = 16,12
img = cv2.imread('images/girl.jpg') # ucitavanje slike sa diska
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # konvertovanje iz BGR u RGB model boja (OpenCV ucita sliku kao BGR)
plt.imshow(img) # prikazivanje slike
###Output
_____no_output_____
###Markdown
Prikazivanje dimenzija slike
###Code
print(img.shape) # shape je property Numpy array-a za prikaz dimenzija
###Output
_____no_output_____
###Markdown
Obratiti pažnju da slika u boji ima 3 komponente za svaki piksel na slici - R (red), G (green) i B (blue).
###Code
img
###Output
_____no_output_____
###Markdown
Primetite da je svaki element matrice **uint8** (unsigned 8-bit integer), odnosno celobroja vrednost u interval [0, 255].
###Code
img.dtype
###Output
_____no_output_____
###Markdown
Osnovne operacije pomoću NumpyPredstavljanje slike kao Numpy array je vrlo korisna stvar, jer omogućava jednostavnu manipulaciju i izvršavanje osnovih operacija nad slikom. Isecanje (crop)
###Code
img_crop = img[100:200, 300:600] # prva koordinata je po visini (formalno red), druga po širini (formalo kolona)
plt.imshow(img_crop)
###Output
_____no_output_____
###Markdown
Okretanje (flip)
###Code
img_flip_h = img[:, ::-1] # prva koordinata ostaje ista, a kolone se uzimaju unazad
plt.imshow(img_flip_h)
img_flip_v = img[::-1, :] # druga koordinata ostaje ista, a redovi se uzimaju unazad
plt.imshow(img_flip_v)
img_flip_c = img[:, :, ::-1] # možemo i izmeniti redosled boja (RGB->BGR), samo je pitanje koliko to ima smisla
plt.imshow(img_flip_c)
###Output
_____no_output_____
###Markdown
Invertovanje
###Code
img_inv = 255 - img # ako su pikeli u intervalu [0,255] ovo je ok, a ako su u intervalu [0.,1.] onda bi bilo 1. - img
plt.imshow(img_inv)
###Output
_____no_output_____
###Markdown
Konvertovanje iz RGB u "grayscale"Konvertovanjem iz RGB modela u nijanse sivih (grayscale) se gubi informacija o boji piksela na slici, ali sama slika postaje mnogo lakša za dalju obradu.Ovo se može uraditi na više načina:1. **Srednja vrednost** RGB komponenti - najjednostavnija varijanta $$ G = \frac{R+G+B}{3} $$2. **Metod osvetljenosti** - srednja vrednost najjače i najslabije boje $$ G = \frac{max(R,G,B) + min(R,G,B)}{2} $$3. **Metod perceptivne osvetljenosti** - težinska srednja vrednost koja uzima u obzir ljudsku percepciju (npr. najviše smo osetljivi na zelenu boju, pa to treba uzeti u obzir)$$ G = 0.21*R + 0.72*G + 0.07*B $$
###Code
# implementacija metode perceptivne osvetljenosti
def my_rgb2gray(img_rgb):
img_gray = np.ndarray((img_rgb.shape[0], img_rgb.shape[1])) # zauzimanje memorije za sliku (nema trece dimenzije)
img_gray = 0.21*img_rgb[:, :, 0] + 0.77*img_rgb[:, :, 1] + 0.07*img_rgb[:, :, 2]
img_gray = img_gray.astype('uint8') # u prethodnom koraku smo mnozili sa float, pa sada moramo da vratimo u [0,255] opseg
return img_gray
img_gray = my_rgb2gray(img)
plt.imshow(img_gray, 'gray') # kada se prikazuje slika koja nije RGB, obavezno je staviti 'gray' kao drugi parametar
###Output
_____no_output_____
###Markdown
Ipak je najbolje se držati implementacije u **OpenCV** biblioteci :).
###Code
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img_gray.shape
plt.imshow(img_gray, 'gray')
img_gray
###Output
_____no_output_____
###Markdown
Binarna slikaSlika čiji pikseli imaju samo dve moguće vrednosti: crno i belo. U zavisnosti da li interval realan (float32) ili celobrojan (uint8), ove vrednosti mogu biti {0,1} ili {0,255}.U binarnoj slici često izdvajamo ono što nam je bitno (**foreground**), od ono što nam je nebitno (**background**). Formalnije, ovaj postupak izdvajanja bitnog od nebitnog na slici nazivamo **segmentacija**.Najčešći način dobijanja binarne slike je korišćenje nekog praga (**threshold**), pa ako je vrednost piksela veća od zadatog praga taj piksel dobija vrednost 1, u suprotnom 0. Postoji više tipova threshold-ovanja:1. Globalni threshold - isti prag se primenjuje na sve piksele2. Lokalni threshold - različiti pragovi za različite delove slike3. Adaptivni threshold - prag se ne određuje ručno (ne zadaje ga čovek), već kroz neki postupak. Može biti i globalni i lokalni. Globalni thresholdKako izdvojiti npr. samo lice?
###Code
img_tr = img_gray > 127 # svi piskeli koji su veci od 127 ce dobiti vrednost True, tj. 1, i obrnuto
plt.imshow(img_tr, 'gray')
###Output
_____no_output_____
###Markdown
OpenCV ima metodu threshold koja kao prvi parametar prima sliku koja se binarizuje, kao drugi parametar prima prag binarizacije, treći parametar je vrednost rezultujućeg piksela ako je veći od praga (255=belo), poslednji parametar je tip thresholda (u ovo slučaju je binarizacija).
###Code
ret, image_bin = cv2.threshold(img_gray, 100, 255, cv2.THRESH_BINARY) # ret je vrednost praga, image_bin je binarna slika
print(ret)
plt.imshow(image_bin, 'gray')
###Output
_____no_output_____
###Markdown
Otsu thresholdOtsu metoda se koristi za automatsko pronalaženje praga za threshold na slici.
###Code
ret, image_bin = cv2.threshold(img_gray, 0, 255, cv2.THRESH_OTSU) # ret je izracunata vrednost praga, image_bin je binarna slika
print("Otsu's threshold: " + str(ret))
plt.imshow(image_bin, 'gray')
###Output
_____no_output_____
###Markdown
Adaptivni thresholdU nekim slučajevima primena globalnog praga za threshold ne daje dobre rezultate. Dobar primer su slike na kojima se menja osvetljenje, gde globalni threshold praktično uništi deo slike koji je previše osvetljen ili zatamnjen.Adaptivni threshold je drugačiji pristup, gde se za svaki piksel na slici izračunava zaseban prag, na osnovu njemu okolnnih piksela. Primer
###Code
image_ada = cv2.imread('images/sonnet.png')
image_ada = cv2.cvtColor(image_ada, cv2.COLOR_BGR2GRAY)
plt.imshow(image_ada, 'gray')
ret, image_ada_bin = cv2.threshold(image_ada, 100, 255, cv2.THRESH_BINARY)
plt.imshow(image_ada_bin, 'gray')
###Output
_____no_output_____
###Markdown
Loši rezultati su dobijeni upotrebom globalnog thresholda.Poboljšavamo rezultate korišćenjem adaptivnog thresholda. Pretposlednji parametar metode adaptiveThreshold je ključan, jer predstavlja veličinu bloka susednih piksela (npr. 15x15) na osnovnu kojih se računa lokalni prag.
###Code
# adaptivni threshold gde se prag racuna = srednja vrednost okolnih piksela
image_ada_bin = cv2.adaptiveThreshold(image_ada, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 5)
plt.figure() # ako je potrebno da se prikaze vise slika u jednoj celiji
plt.imshow(image_ada_bin, 'gray')
# adaptivni threshold gde se prag racuna = tezinska suma okolnih piksela, gde su tezine iz gausove raspodele
image_ada_bin = cv2.adaptiveThreshold(image_ada, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, 5)
plt.figure()
plt.imshow(image_ada_bin, 'gray')
###Output
_____no_output_____
###Markdown
HistogramMožemo koristiti **histogram**, koji će nam dati informaciju o distribuciji osvetljenosti piksela.Vrlo koristan kada je potrebno odrediti prag za globalni threshold.Pseudo-kod histograma za grayscale sliku: ```codeinicijalizovati nula vektor od 256 elemenata za svaki piksel na slici: preuzeti inicijalni intezitet piksela uvecati za 1 broj piksela tog intezitetaplotovati histogram```
###Code
def hist(image):
height, width = image.shape[0:2]
x = range(0, 256)
y = np.zeros(256)
for i in range(0, height):
for j in range(0, width):
pixel = image[i, j]
y[pixel] += 1
return (x, y)
x,y = hist(img_gray)
plt.plot(x, y, 'b')
plt.show()
###Output
_____no_output_____
###Markdown
Koristeći matplotlib:
###Code
plt.hist(img_gray.ravel(), 255, [0, 255])
plt.show()
###Output
_____no_output_____
###Markdown
Koristeći OpenCV:
###Code
hist_full = cv2.calcHist([img_gray], [0], None, [255], [0, 255])
plt.plot(hist_full)
plt.show()
###Output
_____no_output_____
###Markdown
Pretpostavimo da su vrednosti piksela lica između 100 i 200.
###Code
img_tr = (img_gray > 100) * (img_gray < 200)
plt.imshow(img_tr, 'gray')
###Output
_____no_output_____
###Markdown
Konverovanje iz "grayscale" u RGBOvo je zapravo trivijalna operacija koja za svaki kanal boje (RGB) napravi kopiju od originalne grayscale slike. Ovo je zgodno kada nešto što je urađeno u grayscale modelu treba iskoristiti zajedno sa RGB slikom.
###Code
img_tr_rgb = cv2.cvtColor(img_tr.astype('uint8'), cv2.COLOR_GRAY2RGB)
plt.imshow(img*img_tr_rgb) # množenje originalne RGB slike i slike sa izdvojenim pikselima lica
###Output
_____no_output_____
###Markdown
Morfološke operacijeVeliki skup operacija za obradu digitalne slike, gde su te operacije zasnovane na oblicima, odnosno **strukturnim elementima**. U morfološkim operacijama, vrednost svakog piksela rezultujuće slike se zasniva na poređenju odgovarajućeg piksela na originalnoj slici sa svojom okolinom. Veličina i oblik ove okoline predstavljaju strukturni element.
###Code
kernel = np.ones((3, 3)) # strukturni element 3x3 blok
print(kernel)
###Output
_____no_output_____
###Markdown
ErozijaMorfološka erozija postavlja vrednost piksela rez. slike na ```(i,j)``` koordinatama na **minimalnu** vrednost svih piksela u okolini ```(i,j)``` piksela na orig. slici.U suštini erozija umanjuje regione belih piksela, a uvećava regione crnih piksela. Često se koristi za uklanjanje šuma (u vidu sitnih regiona belih piksela).
###Code
plt.imshow(cv2.erode(image_bin, kernel, iterations=1), 'gray')
###Output
_____no_output_____
###Markdown
DilacijaMorfološka dilacija postavlja vrednost piksela rez. slike na ```(i,j)``` koordinatama na **maksimalnu** vrednost svih piksela u okolini ```(i,j)``` piksela na orig. slici.U suštini dilacija uvećava regione belih piksela, a umanjuje regione crnih piksela. Zgodno za izražavanje regiona od interesa.
###Code
# drugaciji strukturni element
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (5,5)) # MORPH_ELIPSE, MORPH_RECT...
print(kernel)
plt.imshow(cv2.dilate(image_bin, kernel, iterations=5), 'gray') # 5 iteracija
###Output
_____no_output_____
###Markdown
Otvaranje i zatvaranje**```otvaranje = erozija + dilacija```**, uklanjanje šuma erozijom i vraćanje originalnog oblika dilacijom.**```zatvaranje = dilacija + erozija```**, zatvaranje sitnih otvora među belim pikselima
###Code
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
print(kernel)
img_ero = cv2.erode(image_bin, kernel, iterations=1)
img_open = cv2.dilate(img_ero, kernel, iterations=1)
plt.imshow(img_open, 'gray')
img_dil = cv2.dilate(image_bin, kernel, iterations=1)
img_close = cv2.erode(img_dil, kernel, iterations=1)
plt.imshow(img_close, 'gray')
###Output
_____no_output_____
###Markdown
Primer detekcije ivica na binarnoj slici korišćenjem dilatacije i erozije:
###Code
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
image_edges = cv2.dilate(image_bin, kernel, iterations=1) - cv2.erode(image_bin, kernel, iterations=1)
plt.imshow(image_edges, 'gray')
###Output
_____no_output_____
###Markdown
Zamućenje (blur)Zamućenje slike se dobija tako što se za svaki piksel slike kao nova vrednost uzima srednja vrednost okolnih piksela, recimo u okolini 5 x 5. Kernel k predstavlja kernel za uniformno zamućenje. Ovo je jednostavnija verzija Gausovskog zamućenja.
###Code
from scipy import signal
k_size = 5
k = (1./k_size*k_size) * np.ones((k_size, k_size))
image_blur = signal.convolve2d(img_gray, k)
plt.imshow(image_blur, 'gray')
###Output
_____no_output_____
###Markdown
Regioni i izdvajanje regionaNajjednostavnije rečeno, region je skup međusobno povezanih belih piksela. Kada se kaže povezanih, misli se na to da se nalaze u neposrednoj okolini. Razlikuju se dve vrste povezanosti: tzv. **4-connectivity** i **8-connectivity**:Postupak kojim se izdvajanju/obeležavaju regioni se naziva **connected components labelling**. Ovo ćemo primeniti na problemu izdvajanja barkoda.
###Code
# ucitavanje slike i convert u RGB
img_barcode = cv2.cvtColor(cv2.imread('images/barcode.jpg'), cv2.COLOR_BGR2RGB)
plt.imshow(img_barcode)
###Output
_____no_output_____
###Markdown
Recimo da želimo da izdvojimo samo linije barkoda sa slike.Za početak, uradimo neke standardne operacije, kao što je konvertovanje u grayscale i adaptivni threshold.
###Code
img_barcode_gs = cv2.cvtColor(img_barcode, cv2.COLOR_RGB2GRAY) # konvert u grayscale
plt.imshow(img_barcode_gs, 'gray')
#ret, image_barcode_bin = cv2.threshold(img_barcode_gs, 80, 255, cv2.THRESH_BINARY)
image_barcode_bin = cv2.adaptiveThreshold(img_barcode_gs, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 35, 10)
plt.imshow(image_barcode_bin, 'gray')
###Output
_____no_output_____
###Markdown
Pronalaženje kontura/regionaKonture, odnosno regioni na slici su grubo rečeno grupe crnih piksela. OpenCV metoda findContours pronalazi sve ove grupe crnih piksela, tj. regione. Druga povratna vrednost metode, odnosno contours je lista pronađeih kontura na slici.Ove konture je zaim moguće iscrtati metodom drawContours, gde je prvi parametar slika na kojoj se iscrtavaju pronađene konture, drugi parametar je lista kontura koje je potrebno iscrtati, treći parametar određuje koju konturu po redosledu iscrtati (-1 znači iscrtavanje svih kontura), četvrti parametar je boja kojom će se obeležiti kontura, a poslednji parametar je debljina linije.
###Code
img, contours, hierarchy = cv2.findContours(image_barcode_bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
img = img_barcode.copy()
cv2.drawContours(img, contours, -1, (255, 0, 0), 1)
plt.imshow(img)
###Output
_____no_output_____
###Markdown
Osobine regionaSvi pronađeni regioni imaju neke svoje karakteristične osobine: površina, obim, konveksni omotač, konveksnost, obuhvatajući pravougaonik, ugao... Ove osobine mogu biti izuzetno korisne kada je neophodno izdvojiti samo određene regione sa slike koji ispoljavaju neku osobinu. Za sve osobine pogledati ovo i ovo.Izdvajamo samo bar-kod sa slike.
###Code
contours_barcode = [] #ovde ce biti samo konture koje pripadaju bar-kodu
for contour in contours: # za svaku konturu
center, size, angle = cv2.minAreaRect(contour) # pronadji pravougaonik minimalne povrsine koji ce obuhvatiti celu konturu
width, height = size
if width > 3 and width < 30 and height > 300 and height < 400: # uslov da kontura pripada bar-kodu
contours_barcode.append(contour) # ova kontura pripada bar-kodu
img = img_barcode.copy()
cv2.drawContours(img, contours_barcode, -1, (255, 0, 0), 1)
plt.imshow(img)
print('Ukupan broj regiona: %d' % len(contours_barcode))
###Output
_____no_output_____ |
Robot_servo_on_and_servo.ipynb | ###Markdown
Write a file to DX100 robot
###Code
import socket
UDP_IP_ADDRESS = '192.168.0.151'
UDP_PORT_NO = 10040
###Output
_____no_output_____
###Markdown
Reading a file from my own IP address
###Code
import socket
UDP_IP = "192.168.0.102"
UDP_PORT = 10040
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(2048) # buffer size is 1024 bytes
print("received message: " + data.hex())
print(str(data))
x = [89, 69, 82, 67, 32, 0, 4, 0, 3, 1, 0]
y = [1, 0, 0, 0]
var = x
var1 = var.extend(y)
print(var1)
abyte = [ i.to_bytes(1, 'big') for i in x]
print(abyte)
print(abyte[1].hex())
byte = abyte[0]
for i in range(len(abyte)-1):
byte = byte + abyte[i+1]
print(byte)
byte = [(byte + i) for i in abyte]
print(byte)
ahex = [ i.hex() for i in abyte]
print(ahex)
print(type(ahex))
print(type(ahex[1]))
print(type(x))
print(type(x[1]))
clientSock.close()
#to write the code that will send our UDP message (turn on)
clientSock.sendto(servo_motor(1), (UDP_IP_ADDRESS, UDP_PORT_NO))
time.sleep(5)# number of seconds
#to write the code that will send our UDP message (turn off)
clientSock.sendto(servo_motor(0), (UDP_IP_ADDRESS, UDP_PORT_NO))
socket.SocketKind
socket.gethostname()
socket.getservbyname()
###Output
_____no_output_____ |
word2vec/Word2Vec product_id.ipynb | ###Markdown
gensim word2vec- 输入文本 - 每行是一个句子(list of str)
###Code
%%time
model = gensim.models.Word2Vec(sentences, size=100, window=longest, min_count=2, workers=4)
vocab = list(model.wv.vocab.keys())
pca = PCA(n_components=2)
pca.fit(model.wv.syn0)
def get_batch(vocab, model, n_batches=3):
output = list()
for i in range(0, n_batches):
rand_int = np.random.randint(len(vocab), size=1)[0] # 从vocabulary中选择一个词
suggestions = model.most_similar(positive=[vocab[rand_int]], topn=5)# 依照word2vec模型选出最相似的5个
suggest = list()
for i in suggestions:
suggest.append(i[0])
output += suggest # 相似词列表
output.append(vocab[rand_int]) # 中心词
return output
def plot_with_labels(low_dim_embs, labels, filename='tsne.png'):
"""From Tensorflow's tutorial."""
assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings"
plt.figure(figsize=(18, 18)) #in inches
for i, label in enumerate(labels):
x, y = low_dim_embs[i,:]
plt.scatter(x, y)
plt.annotate(label,
xy=(x, y),
xytext=(5, 2),
textcoords='offset points',
ha='right',
va='bottom')
# plt.savefig(filename)
plt.show()
embeds = []
labels = []
for item in get_batch(vocab, model, n_batches=1):
embeds.append(model[item])
labels.append(products.loc[int(item)]['product_name'])
embeds = np.array(embeds)
embeds = pca.fit_transform(embeds)
plot_with_labels(embeds, labels)
model.save(constants.W2V_DIR + "product2vec.model")
?? model.score
pca = PCA(n_components=25)
pca.fit(model.wv.syn0)
compressed = pd.DataFrame(pca.transform(model[vocab]), columns=['w2v_dim_%d'%i for i in range(25)])
compressed['product_id'] = vocab
compressed['product_id'] = compressed['product_id'].astype(int)
compressed = pd.merge(products[['product_id']], compressed, on=['product_id'], how='left')
for col in compressed.columns:
compressed[col] = compressed[col].fillna(compressed[col].mean())
with open(constants.FEAT_DATA_DIR + 'p_w2v_feat.pkl', 'wb') as f:
pickle.dump(compressed, f, pickle.HIGHEST_PROTOCOL)
###Output
_____no_output_____ |
Cardiovascular Disease Prediction.ipynb | ###Markdown
**IMPORTING THE DATASET**
###Code
import os
os.environ['KAGGLE_USERNAME'] = "suyash091"
os.environ['KAGGLE_KEY'] = "9775b0a6da90b12a0c284d71e498de43"
!kaggle datasets download -d sulianova/cardiovascular-disease-dataset
###Output
Downloading cardiovascular-disease-dataset.zip to /content
0% 0.00/742k [00:00<?, ?B/s]
100% 742k/742k [00:00<00:00, 46.7MB/s]
###Markdown
**Extracting zipfile**
###Code
!unzip -q '/content/cardiovascular-disease-dataset.zip'
import pandas as pd
###Output
_____no_output_____
###Markdown
**Data Preprocessing**
###Code
#Fixing structure
# Read in the file
with open('/content/cardio_train.csv', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace(';', ',')
# Write the file out again
with open('/content/cardio_train.csv', 'w') as file:
file.write(filedata)
#Load Data
cvd=pd.read_csv('/content/cardio_train.csv')#.apply(lambda x: x/x.max(), axis=0)
cvd.describe()
cvd.head()
model = RandomForestClassifier(n_estimators=100)
outcome_var = ['cardio']
predictor_var = ['age', 'gender', 'height', 'weight','ap_hi','ap_lo', 'cholesterol','gluc','smoke', 'alco', 'active']
#Import models from scikit learn module:
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold #For K-fold cross validation
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn import metrics
import numpy as np
#Generic function for making a classification model and accessing performance:
def classification_model(model, data, predictors, outcome):
model.fit(data[predictors],data[outcome].values.ravel())
predictions = model.predict(data[predictors])
accuracy = metrics.accuracy_score(predictions,data[outcome])
print('Accuracy : %s' % '{0:.3%}'.format(accuracy))
kf = KFold(n_splits=5)
error = []
for train, test in kf.split(data[predictors]):
train_predictors = (data[predictors].iloc[train,:])
train_target = data[outcome].iloc[train]
model.fit(train_predictors, train_target.values.ravel())
error.append(model.score(data[predictors].iloc[test,:], data[outcome].iloc[test]))
print('Cross-Validation Score : %s' % '{0:.3%}'.format(np.mean(error)))
return model.fit(data[predictors],data[outcome].values.ravel())
#outcome_var = ['winner']
#predictor_var = ['team1', 'team2', 'venue', 'toss_winner','city','toss_decision']
history=classification_model(model, cvd,predictor_var,outcome_var)
#inp=list(map(str,[18393, 2, 168, 62.0, 110, 80, 1, 1, 0, 0, 1]))
inp=list(map(str,'20228 1 156 85.0 140 90 3 1 0 0 1'.split()))
inp = np.array(inp).reshape((1, -1))
output=model.predict(inp)
print(output)
from sklearn.externals import joblib
joblib.dump(cvd, 'Cardiomodel.pkl')
###Output
/usr/local/lib/python3.6/dist-packages/sklearn/externals/joblib/__init__.py:15: DeprecationWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.
warnings.warn(msg, category=DeprecationWarning)
|
Lecture-1.ipynb | ###Markdown
Python - Writing Your First Python Code! Welcome! This notebook will teach you the basics of the Python programming language. Although the information presented here is quite basic, it is an important foundation that will help you read and write Python code. By the end of this notebook, you'll know the basics of Python, including how to write basic commands, understand some basic types, and how to perform simple operations on them. Table of Contents Say "Hello" to the world in Python What version of Python are we using? Writing comments in Python Errors in Python Does Python know about your error before it runs your code? Exercise: Your First Program Types of objects in Python Integers Floats Converting from one object type to a different object type Boolean data type Exercise: Types Expressions and Variables Expressions Exercise: Expressions Variables Exercise: Expression and Variables in Python Estimated time needed: 25 min Say "Hello" to the world in Python When learning a new programming language, it is customary to start with an "hello world" example. As simple as it is, this one line of code will ensure that we know how to print a string in output and how to execute code within cells in a notebook. [Tip]: To execute the Python code in the code cell below, click on the cell to select it and press Shift + Enter.
###Code
# Try your first Python output
print('Hello, Python!')
###Output
Hello, Python!
###Markdown
After executing the cell above, you should see that Python prints Hello, Python!. Congratulations on running your first Python code! [Tip:] print() is a function. You passed the string 'Hello, Python!' as an argument to instruct Python on what to print. What version of Python are we using?There are two popular versions of the Python programming language in use today: Python 2 and Python 3. The Python community has decided to move on from Python 2 to Python 3, and many popular libraries have announced that they will no longer support Python 2.Since Python 3 is the future, in this course we will be using it exclusively. How do we know that our notebook is executed by a Python 3 runtime? We can look in the top-right hand corner of this notebook and see "Python 3".We can also ask directly Python and obtain a detailed answer. Try executing the following code:
###Code
# Check the Python Version
import sys
print(sys.version)
3+3
###Output
_____no_output_____
###Markdown
[Tip:] sys is a built-in module that contains many system-specific parameters and functions, including the Python version in use. Before using it, we must explictly import it. Writing comments in PythonIn addition to writing code, note that it's always a good idea to add comments to your code. It will help others understand what you were trying to accomplish (the reason why you wrote a given snippet of code). Not only does this help other people understand your code, it can also serve as a reminder to you when you come back to it weeks or months later.To write comments in Python, use the number symbol before writing your comment. When you run your code, Python will ignore everything past the on a given line.
###Code
# Practice on writing comments
print('Hello, Python!') # This line prints a string
# print('Hi')
###Output
Hello, Python!
###Markdown
After executing the cell above, you should notice that This line prints a string did not appear in the output, because it was a comment (and thus ignored by Python).The second line was also not executed because print('Hi') was preceded by the number sign () as well! Since this isn't an explanatory comment from the programmer, but an actual line of code, we might say that the programmer commented out that second line of code.Errors in PythonEveryone makes mistakes. For many types of mistakes, Python will tell you that you have made a mistake by giving you an error message. It is important to read error messages carefully to really understand where you made a mistake and how you may go about correcting it.For example, if you spell print as frint, Python will display an error message. Give it a try:
###Code
# Print string as error message
frint("Hello, Python!")
###Output
_____no_output_____
###Markdown
The error message tells you: where the error occurred (more useful in large notebook cells or scripts), and what kind of error it was (NameError)Here, Python attempted to run the function frint, but could not determine what frint is since it's not a built-in function and it has not been previously defined by us either.You'll notice that if we make a different type of mistake, by forgetting to close the string, we'll obtain a different error (i.e., a SyntaxError). Try it below:
###Code
# Try to see build in error message
print("Hello, Python!)
###Output
_____no_output_____
###Markdown
Does Python know about your error before it runs your code?Python is what is called an interpreted language. Compiled languages examine your entire program at compile time, and are able to warn you about a whole class of errors prior to execution. In contrast, Python interprets your script line by line as it executes it. Python will stop executing the entire program when it encounters an error (unless the error is expected and handled by the programmer, a more advanced subject that we'll cover later on in this course).Try to run the code in the cell below and see what happens:
###Code
# Print string and error to see the running order
print("This will be printed")
frint("This will cause an error")
print("This will NOT be printed")
###Output
This will be printed
###Markdown
Exercise: Your First ProgramGenerations of programmers have started their coding careers by simply printing "Hello, world!". You will be following in their footsteps.In the code cell below, use the print() function to print out the phrase: Hello, world! Write your code below and press Shift+Enter to execute <!-- Your answer is below:print("Hello, world!")--> Double-click __here__ for the solution.<!-- Your answer is below:print("Hello, world!")--> Now, let's enhance your code with a comment. In the code cell below, print out the phrase: Hello, world! and comment it with the phrase Print the traditional hello world all in one line of code.
###Code
# Write your code below and press Shift+Enter to execute
print("Hello, world!") # Print the traditional hello world
###Output
Hello, world!
###Markdown
Double-click __here__ for the solution.<!-- Your answer is below:print("Hello, world!") Print the traditional hello world--> Types of objects in Python Python is an object-oriented language. There are many different types of objects in Python. Let's start with the most common object types: strings, integers and floats. Anytime you write words (text) in Python, you're using character strings (strings for short). The most common numbers, on the other hand, are integers (e.g. -1, 0, 100) and floats, which represent real numbers (e.g. 3.14, -42.0). The following code cells contain some examples.
###Code
# Integer
11
# Float
2.14
# String
"Hello, Python 101!"
###Output
_____no_output_____
###Markdown
You can get Python to tell you the type of an expression by using the built-in type() function. You'll notice that Python refers to integers as int, floats as float, and character strings as str.
###Code
# Type of 12
type(12)
# Type of 2.14
type(2.14)
# Type of "Hello, Python 101!"
type("Hello, Python 101!")
###Output
_____no_output_____
###Markdown
In the code cell below, use the type() function to check the object type of 12.0.
###Code
# Write your code below. Don't forget to press Shift+Enter to execute the cell
###Output
_____no_output_____
###Markdown
Double-click __here__ for the solution.<!-- Your answer is below:type(12.0)--> Integers Here are some examples of integers. Integers can be negative or positive numbers: We can verify this is the case by using, you guessed it, the type() function:
###Code
# Print the type of -1
type(-1)
# Print the type of 4
type(4)
# Print the type of 0
type(0)
###Output
_____no_output_____
###Markdown
Floats Floats represent real numbers; they are a superset of integer numbers but also include "numbers with decimals". There are some limitations when it comes to machines representing real numbers, but floating point numbers are a good representation in most cases. You can learn more about the specifics of floats for your runtime environment, by checking the value of sys.float_info. This will also tell you what's the largest and smallest number that can be represented with them.Once again, can test some examples with the type() function:
###Code
# Print the type of 1.0
type(1.0) # Notice that 1 is an int, and 1.0 is a float
# Print the type of 0.5
type(0.5)
# Print the type of 0.56
type(0.56)
# System settings about float type
import sys
sys.float_info
###Output
_____no_output_____
###Markdown
Converting from one object type to a different object type You can change the type of the object in Python; this is called typecasting. For example, you can convert an integer into a float (e.g. 2 to 2.0).Let's try it:
###Code
# Verify that this is an integer
type(2)
###Output
_____no_output_____
###Markdown
Converting integers to floatsLet's cast integer 2 to float:
###Code
# Convert 2 to a float
float(2)
# Convert integer 2 to a float and check its type
type(float(2))
###Output
_____no_output_____
###Markdown
When we convert an integer into a float, we don't really change the value (i.e., the significand) of the number. However, if we cast a float into an integer, we could potentially lose some information. For example, if we cast the float 1.1 to integer we will get 1 and lose the decimal information (i.e., 0.1):
###Code
# Casting 1.1 to integer will result in loss of information
int(1.4343)
###Output
_____no_output_____
###Markdown
Converting from strings to integers or floats Sometimes, we can have a string that contains a number within it. If this is the case, we can cast that string that represents a number into an integer using int():
###Code
# Convert a string into an integer
int('1')
###Output
_____no_output_____
###Markdown
But if you try to do so with a string that is not a perfect match for a number, you'll get an error. Try the following:
###Code
# Convert a string into an integer with error
int('1 or 2 people')
###Output
_____no_output_____
###Markdown
You can also convert strings containing floating point numbers into float objects:
###Code
# Convert the string "1.2" into a float
float('1.2')
###Output
_____no_output_____
###Markdown
[Tip:] Note that strings can be represented with single quotes ('1.2') or double quotes ("1.2"), but you can't mix both (e.g., "1.2'). Converting numbers to strings If we can convert strings to numbers, it is only natural to assume that we can convert numbers to strings, right?
###Code
# Convert an integer to a string
str(1)
###Output
_____no_output_____
###Markdown
And there is no reason why we shouldn't be able to make floats into strings as well:
###Code
# Convert a float to a string
str(1.2)
###Output
_____no_output_____
###Markdown
Boolean data type Boolean is another important type in Python. An object of type Boolean can take on one of two values: True or False:
###Code
# Value true
True
###Output
_____no_output_____
###Markdown
Notice that the value True has an uppercase "T". The same is true for False (i.e. you must use the uppercase "F").
###Code
# Value false
False
###Output
_____no_output_____
###Markdown
When you ask Python to display the type of a boolean object it will show bool which stands for boolean:
###Code
# Type of True
type(True)
# Type of False
type(False)
###Output
_____no_output_____
###Markdown
We can cast boolean objects to other data types. If we cast a boolean with a value of True to an integer or float we will get a one. If we cast a boolean with a value of False to an integer or float we will get a zero. Similarly, if we cast a 1 to a Boolean, you get a True. And if we cast a 0 to a Boolean we will get a False. Let's give it a try:
###Code
# Convert True to int
int(True)
# Convert 1 to boolean
bool(1)
# Convert 0 to boolean
bool(0)
# Convert True to float
float(True)
###Output
_____no_output_____
###Markdown
Exercise: Types What is the data type of the result of: 6 / 2?
###Code
# Write your code below. Don't forget to press Shift+Enter to execute the cell
type(6/2)
###Output
_____no_output_____
###Markdown
Double-click __here__ for the solution.<!-- Your answer is below:type(6/2) float--> What is the type of the result of: 6 // 2? (Note the double slash //.)
###Code
# Write your code below. Don't forget to press Shift+Enter to execute the cell
###Output
_____no_output_____
###Markdown
Double-click __here__ for the solution.<!-- Your answer is below:type(6//2) int, as the double slashes stand for integer division --> Expression and Variables Expressions Expressions in Python can include operations among compatible types (e.g., integers and floats). For example, basic arithmetic operations like adding multiple numbers:
###Code
# Addition operation expression
43 + 60 + 16 + 41
###Output
_____no_output_____
###Markdown
We can perform subtraction operations using the minus operator. In this case the result is a negative number:
###Code
# Subtraction operation expression
50 - 60
###Output
_____no_output_____
###Markdown
We can do multiplication using an asterisk:
###Code
# Multiplication operation expression
5 * 5
###Output
_____no_output_____
###Markdown
We can also perform division with the forward slash:
###Code
# Division operation expression
25 / 5
# Division operation expression
25 / 6
###Output
_____no_output_____
###Markdown
As seen in the quiz above, we can use the double slash for integer division, where the result is rounded to the nearest integer:
###Code
# Integer division operation expression
25 // 5
# Integer division operation expression
25 // 6
67.56643/2
###Output
_____no_output_____
###Markdown
Exercise: Expression Let's write an expression that calculates how many hours there are in 160 minutes:
###Code
# Write your code below. Don't forget to press Shift+Enter to execute the cell
160//60
###Output
_____no_output_____
###Markdown
Double-click __here__ for the solution.<!-- Your answer is below:160/60 Or 160//60--> Python follows well accepted mathematical conventions when evaluating mathematical expressions. In the following example, Python adds 30 to the result of the multiplication (i.e., 120).
###Code
# Mathematical expression
30 + 2 * 60
###Output
_____no_output_____
###Markdown
And just like mathematics, expressions enclosed in parentheses have priority. So the following multiplies 32 by 60.
###Code
# Mathematical expression
(30 + 2) * 60
###Output
_____no_output_____
###Markdown
Variables Just like with most programming languages, we can store values in variables, so we can use them later on. For example:
###Code
# Store value into variable
x = 43 + 60 + 16 + 41
###Output
_____no_output_____
###Markdown
To see the value of x in a Notebook, we can simply place it on the last line of a cell:
###Code
# Print out the value in variable
x
###Output
_____no_output_____
###Markdown
We can also perform operations on x and save the result to a new variable:
###Code
# Use another variable to store the result of the operation between variable and value
y = x // 60
y
###Output
_____no_output_____
###Markdown
If we save a value to an existing variable, the new value will overwrite the previous value:
###Code
# Overwrite variable with new value
x = x / 60
x
###Output
_____no_output_____
###Markdown
It's a good practice to use meaningful variable names, so you and others can read the code and understand it more easily:
###Code
# Name the variables meaningfully
total_min = 43 + 42 + 57 # Total length of albums in minutes
total_min
# Name the variables meaningfully
total_hours = total_min / 60 # Total length of albums in hours
total_hours
###Output
_____no_output_____
###Markdown
In the cells above we added the length of three albums in minutes and stored it in total_min. We then divided it by 60 to calculate total length total_hours in hours. You can also do it all at once in a single expression, as long as you use parenthesis to add the albums length before you divide, as shown below.
###Code
# Complicate expression
total_hours = (43 + 42 + 57) / 60 # Total hours in a single expression
total_hours
67.667/2
###Output
_____no_output_____
###Markdown
If you'd rather have total hours as an integer, you can of course replace the floating point division with integer division (i.e., //). Exercise: Expression and Variables in Python What is the value of x where x = 3 + 2 * 2
###Code
# Write your code below. Don't forget to press Shift+Enter to execute the cell
###Output
_____no_output_____
###Markdown
Motivation Why computer modelling? Because it is **cheaper** than real-life experiment, or in the case when real-life experiment **is not possible**. Typical steps of computer modelling1. Formulate the mathematical problem as an **equation** for some **quantities**2. Replace the continious problem by a discrete problem (**discretization**)3. Solve the resulting discrete problem The simplest cycle: Mathematical model - Discretization - Solve DiscretizationThe discretization is replacement of the region by discrete elements: Random notes- Discretization and solve can be connected- Fast solves are needed- Only a subproblem in **design and optimization**- Many physical problems are still too complex for math (turbulence!) ConsiderIt takes a lot to create1. A model2. Discretization3. SolversWhat if the computer time to computer a **forecast for 1 day is morethan 1 day**? Many **process in physics** are modelled as PDEs.- Diffusion processes (heat transfer), electrostatics (circuit design) Poisson equation - Sound propagation (noise on the streets, buildings) -- Helmholtzequation - Electromagnetics -- fMRI (functional magnetic resonance imaging) -Maxwell equations - Fluid flows -- Stokes / Navier Stokes equations These are all partial differential equations! PDE appear in:- Financial math (Black Scholes equation) - Chemical engineering (Smoluchowsky equation)- Nanoworld (Schrodinger equation) What we plan to cover:- Both **discretization** and **fast solvers** part. - Start thinking about the App Period projects **now** - Look in the direction of **computational 3d printing** (i.e. elasticity, shape optimization).- Or image processing :) What we plan to cover (2)- Finite elements (what are they, how to use them for discretization, what software packages to use)- Fast solvers for sparse matrices (i.e. direct solvers, multigrid solvers, incomplete LU factorizations, ...)- Basic integral equations: why do we need integral equations (exterior problems)- Fast multipole method/hierarchical matrices - Oscillatory problems and basic electromagnetics- Connection to practical problems Software packagesSuppose you want to do it all, but you do not want to implement from scratch. What to do? **Use software packages that do it for you**- [FEniCS project](http://fenicsproject.org/) - beautiful finite element package, superhard to install - [FiPy](http://www.ctcms.nist.gov/fipy/) - Finite volume solver- [deal.II](https://www.dealii.org/) - FEM solver, C++ (with some Python interface)- [DUNE](http://dune.mathematik.uni-freiburg.de/) - FEM solver
###Code
from IPython.core.display import HTML
def css_styling():
styles = open("./styles/custom.css", "r").read()
return HTML(styles)
css_styling()
###Output
_____no_output_____ |
ML - Applied Machine Learning - Feature Engineering/03.Explore Data/01.Explore The Data - What Data Are We Using.ipynb | ###Markdown
Explore The Data: What Data Are We Using?Using the Titanic dataset from [this](https://www.kaggle.com/c/titanic/overview) Kaggle competition.This dataset contains information about 891 people who were on board the ship when departed on April 15th, 1912. As noted in the description on Kaggle's website, some people aboard the ship were more likely to survive the wreck than others. There were not enough lifeboats for everybody so women, children, and the upper-class were prioritized. Using the information about these 891 passengers, the challenge is to build a model to predict which people would survive based on the following fields:- **Name** (str) - Name of the passenger- **Pclass** (int) - Ticket class (1st, 2nd, or 3rd)- **Sex** (str) - Gender of the passenger- **Age** (float) - Age in years- **SibSp** (int) - Number of siblings and spouses aboard- **Parch** (int) - Number of parents and children aboard- **Ticket** (str) - Ticket number- **Fare** (float) - Passenger fare- **Cabin** (str) - Cabin number- **Embarked** (str) - Port of embarkation (C = Cherbourg, Q = Queenstown, S = Southampton) Read In Data
###Code
# Read in the data from the data folder
import pandas as pd
titanic_df = pd.read_csv('../Data/titanic.csv')
titanic_df.head()
# Check the number of rows and columns in the data
titanic_df.shape
# Check the type of data stored in each column
titanic_df.dtypes
# See the distribution of our target variable
titanic_df['Survived'].value_counts()
###Output
_____no_output_____ |
_notebooks/Average Sydney Suburb - Data Cleaning.ipynb | ###Markdown
"The Average Sydney Suburb - Data munging in Pandas"- toc: false- branch: master- badges: true- comments: true- categories: [jupyter] The Average Sydney Suburb - Data cleaningI have recently finished an eDx [course](https://courses.edx.org/courses/course-v1:BerkeleyX+Data8.2x+1T2019a/course/) on inferential statistics from Duke university. This course does a good job of using resampling for inferential statistics.Applying what I have learned in this course, I want to figure out the most average Sydeny suburbs in terms of the country of birth of person (__CBOP__) and age.There is a lot of data available via [ABS](https://www.abs.gov.au). I used the [Census table builder](https://www.abs.gov.au/websitedbs/censushome.nsf/home/tablebuilder) to get the CBOP and age data.In this notebook, I will clean and setup the data for my analysis
###Code
#Importing the libraries that I will use
import pandas as pd
import numpy as np
%matplotlib inline
from IPython.display import display
###Output
_____no_output_____
###Markdown
I have downloaded the following files from the 2016 Census that I will need to use for my analysis:- **Population** - Total Sydney population - Top 6 CBOP population for Sydney - Total population for all of Sydney suburbs - Top 6 CBOP population for all of Sydney suburbs- **Age** - Sydney's age in single digits - Sydney's suburb's age in single digitsAs useful as the [Census table builder](https://www.abs.gov.au/websitedbs/censushome.nsf/home/tablebuilder) is, I could not get the data in the format that I needed - hence the need for this cleaning exercise. In the past I have made use of excel and pandas for cleaning data, however in this notebook I will attempt to clean all the data in pandas.Starting with Sydney's CBOP mix. My aim is to create a table with the top 6 CBOP and Others.
###Code
#Read Sydney pop and top 6 cbop
sydney_pop = pd.read_csv('greater_sydney_pop.csv', skiprows = 11)
sydney_cbop = pd.read_csv('top_6_cobp.csv', skiprows = 11)
###Output
_____no_output_____
###Markdown
For the Sydney population table, all I need is the total population value. I can get this from Index 0 and column 4823993
###Code
syd_pop = int(sydney_pop.at[0,'4823993'])
print("Sydney's population: ", syd_pop)
###Output
Sydney's population: 4823993
###Markdown
Now lets take a look at the Sydney CBOP table
###Code
#Using threshold values in drop na to only drop rows with 2 Na values.
#This has the useful side effect of dropping the unnamed column as well
sydney_cbop.dropna(axis = 1, thresh=2, inplace = True)
sydney_cbop.dropna(axis = 0, inplace = True)
#rename BPLP - 4 Digit Level column to Population
sydney_cbop.rename(columns = {sydney_cbop.columns[0]:'Population'}, inplace = True)
#Drop info index
sydney_cbop.drop('INFO', inplace = True)
#convert population numbers to integer
sydney_cbop['Population'] = sydney_cbop['Population'].apply(pd.to_numeric)
#Rename the total index value to CBOP Total. This will be used later to calculate the value of other countries
sydney_cbop.rename({'Total': 'CBOP Total'}, inplace = True)
sydney_cbop.info()
print(sydney_cbop)
###Output
<class 'pandas.core.frame.DataFrame'>
Index: 7 entries, England to CBOP Total
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Population 7 non-null int64
dtypes: int64(1)
memory usage: 112.0+ bytes
Population
England 151617
Australia 2752123
China (excludes SARs and Taiwan) 224682
India 130579
Vietnam 81041
New Zealand 86522
CBOP Total 3426561
###Markdown
Next step is to add the population of people who are not from any of the 6 top countries
###Code
sydney_cbop.loc['CBOP Total'] = syd_pop - sydney_cbop.at['CBOP Total', 'Population']
sydney_cbop.rename({'CBOP Total' : 'Others'}, inplace = True)
sydney_cbop.Population.sum()
print(sydney_cbop)
print('\nTotal Sydney Population ', sydney_cbop.Population.sum())
###Output
Population
England 151617
Australia 2752123
China (excludes SARs and Taiwan) 224682
India 130579
Vietnam 81041
New Zealand 86522
Others 1397432
Total Sydney Population 4823996
###Markdown
All set!, we now have a table with the top 6 natonalities (CBOP) of Sydney and an others column. Next step is to repeat this process for every suburb in the greater Sydney area._Note: It took me about 2 hours to figure out the best way to clean these two small dataframes and boil it down to a few lines of code. I am putting this here as a reminder to not get overwhelmed when I see posts where things like these seem to be the simplest of steps. Having gone through this exercise, its clear that data cleaning is very important and not as easy as it seems. Atleast when you are just getting started. Keep at it!!_
###Code
#Load the top 6 CBOP by Suburb and total population by suburb files
suburb_cbop = pd.read_csv('suburb_top_6_cobp.csv', skiprows = 11)
suburb_pop = pd.read_csv('total_suburb_population.csv', skiprows = 11)
###Output
_____no_output_____
###Markdown
Additional challenges in this dataset: 1) Index needs to be reset and forward filled to remove the NAN values from the index 2) When extracting the data from ABS, although I filtered on Sydney, it still gave me a list of all suburbs. The difference here is that for suburbs that are not in the Greater Sydney area, the population is 0. This should be easier to remove
###Code
#Reset Index
suburb_cbop.reset_index(inplace = True)
#Forward fill the country name and copy only the country column. We need the NaNs for cleaning purposes
suburb_cbop['index'] = suburb_cbop.ffill()['index']
suburb_cbop
#Set index back to country
suburb_cbop.set_index('index', inplace = True)
suburb_cbop.index.rename('CBOP', inplace = True)
#Removing rows with 2 NaN values
suburb_cbop.dropna(axis = 1, thresh = 2, inplace = True)
suburb_cbop.dropna(axis = 0, thresh = 2, inplace = True)
col_names = ['Suburb', 'Population']
suburb_cbop.columns = col_names
suburb_cbop.info()
###Output
<class 'pandas.core.frame.DataFrame'>
Index: 31682 entries, England to Total
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Suburb 31682 non-null object
1 Population 31682 non-null float64
dtypes: float64(1), object(1)
memory usage: 742.5+ KB
###Markdown
Now that we have removed the NaN values, lets look at the numbers and clean those up as well. But it is not as simple as it seems. There could be suburbs in Sydney which do not have any person from one of the top 6 nationalities. In that case, I want to preserve the 0 associated with that particular nationality for my analysis. So before I start cleaning up the numbers, lets first clean up the total suburb population dataframe
###Code
suburb_pop.dropna(axis = 1, thresh = 2, inplace = True)
suburb_pop.dropna(axis = 0, thresh = 1, inplace = True)
#Drop info column
suburb_pop.drop('INFO', inplace = True)
suburb_pop.columns = ['Population']
#Convert population to integer
suburb_pop['Population'] = suburb_pop['Population'].apply(pd.to_numeric)
suburb_pop.rename_axis('Suburb', inplace = True)
print(suburb_pop.info())
print("Sydney Population: ", suburb_pop.Population.sum())
###Output
<class 'pandas.core.frame.DataFrame'>
Index: 4526 entries, Aarons Pass to Migratory - Offshore - Shipping (NSW)
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Population 4526 non-null int64
dtypes: int64(1)
memory usage: 70.7+ KB
None
Sydney Population: 4823982
###Markdown
The suburb_pop table now has the population of every suburb in Greater Sydney. For the remaining suburbs the population would be zero. So if we drop the 0 populations we should be left with Sydney suburbs only
###Code
#Get index names of suburbs with zero populations
zero_suburbs = suburb_pop[suburb_pop.Population == 0].index
#Drop these index names
suburb_pop.drop(zero_suburbs, inplace=True)
suburb_pop.info()
###Output
<class 'pandas.core.frame.DataFrame'>
Index: 893 entries, Abbotsbury to Zetland
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Population 893 non-null int64
dtypes: int64(1)
memory usage: 14.0+ KB
###Markdown
Dropping the 0 population suburbs leaves us with 893 suburbs. I can also use the same index names to update the top nationalities data frame (*suburb_cbop*). For that I would first need to set the suburb as the index and then drop
###Code
suburb_cbop.reset_index(inplace = True)
suburb_cbop.set_index('Suburb', inplace = True)
suburb_cbop.loc[()]
suburb_cbop.drop(zero_suburbs, inplace = True)
suburb_cbop.info()
suburb_cbop.reset_index(inplace = True)
suburb_cbop.set_index(['CBOP','Suburb'], inplace = True)
suburb_cbop
print(suburb_cbop.loc['Total', 'Zetland'])
print(suburb_pop.loc['Zetland'])
suburb_cbop.loc()
###Output
Population 6618.0
Name: (Total, Zetland), dtype: float64
Population 10072
Name: Zetland, dtype: int64
###Markdown
Finally we are now in a position to create an others row for each suburb in Sydney. The others row will contain the number of people who are not from the top 6 countries
###Code
#Joining the suburb top 6 with suburb totap population dataframes and extracting the 'Total' index only
others_temp = suburb_cbop.join(suburb_pop, on='Suburb', rsuffix = "r").loc[('Total', slice(None))]
#Calculating the others population value
others_temp.Population = others_temp.Populationr - others_temp.Population
others_temp.drop(['Populationr'], axis=1, inplace = True)
#Creating a final dataframe with others population value in Population_r column
suburb_cbop_final = suburb_cbop.join(others_temp, on='Suburb', rsuffix = '_r')
#Setting the Total index value to Nan
suburb_cbop_final.loc[('Total', slice(None)),'Population'] = np.nan
#renaming index value Total to Others
suburb_cbop_final.rename(index={'Total':'Others'}, inplace = True)
#Setting the right population value in the Others index
suburb_cbop_final['Population'] = np.where(suburb_cbop_final['Population'].isnull(),
suburb_cbop_final['Population_r'],
suburb_cbop_final['Population'])
suburb_cbop_final.drop(['Population_r'], axis=1, inplace = True)
suburb_cbop_final
###Output
_____no_output_____
###Markdown
That took a lot of steps and although I have setup what I wanted to, I refuse to believe that I cant find a more efficient way to do this calculation. Lets try this again
###Code
#resetting the index in the suburb cbop file
suburb_cbop.reset_index(inplace = True)
suburb_cbop.set_index('Suburb', inplace=True)
suburb_cbop_final = suburb_cbop.join(suburb_pop, on='Suburb', rsuffix = "r")
suburb_cbop_final['Population'] = np.where(suburb_cbop_final['CBOP'] == 'Total',
suburb_cbop_final['Populationr'] - suburb_cbop_final['Population'],
suburb_cbop_final['Population'])
suburb_cbop_final.drop(['Populationr'], axis=1, inplace = True)
suburb_cbop_final
#As a final step, renaming Total to Others
suburb_cbop_final.reset_index(inplace=True)
suburb_cbop_final.set_index('CBOP', inplace = True)
suburb_cbop_final.rename({'Total': 'Others'}, inplace = True)
###Output
_____no_output_____
###Markdown
That was simpler. Not I will save my clean files for part two.
###Code
suburb_cbop_final
sydney_cbop.to_csv('Sydney_CBOP_Clean.csv')
suburb_cbop_final.to_csv('Sydney_Suburb_CBOP_Clean.csv')
###Output
_____no_output_____ |
component-library/nlp/nlp-classify-text-simple.ipynb | ###Markdown
nlp-transform-snippets creates snippets out of large text files
###Code
!pip3 install wget==3.2
import wget
import logging
import numpy as np
import os
import re
import shutil
import sys
import tarfile
import time
# file name for training data zip
input_filename = os.environ.get('input_filename ', 'data.zip')
# resulting model zip file name
output_model_zip = os.environ.get('output_model_zip', 'model.zip')
# temporal data storage for local execution
data_dir = os.environ.get('data_dir', '../../data/')
parameters = list(
map(
lambda s: re.sub('$', '"', s),
map(
lambda s: s.replace('=', '="'),
filter(
lambda s: s.find('=') > -1 and bool(re.match('[A-Za-z0-9_]*=[.\/A-Za-z0-9]*', s)),
sys.argv
)
)
)
)
for parameter in parameters:
logging.warning('Parameter: '+parameter)
exec(parameter)
source_folder=str(time.time())
shutil.unpack_archive(data_dir + input_filename, extract_dir=data_dir + source_folder)
# TODO generalize
letter = 'abcdefghijklmnopqrstuvwxyz'
digits = '0123456789'
others = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
alphabet = letter + digits + others
print('alphabet size:', len(alphabet))
# all-zeroes padding vector:
pad_vector = [0 for x in alphabet]
# pre-calculated one-hot vectors:
supported_chars_map = {}
for i, ch in enumerate(alphabet):
vec = [0 for x in alphabet]
vec[i] = 1
supported_chars_map[ch] = vec
def get_source_snippets(file_name, breakup=True):
# Read the file content and lower-case:
text = ""
with open(file_name, mode='r') as file:
text = file.read().lower()
lines = text.split('\n')
nlines = len(lines)
if breakup and nlines > 50:
aThird = nlines//3
twoThirds = 2*aThird
text1 = '\n'.join(lines[:aThird])
text2 = '\n'.join(lines[aThird:twoThirds])
text3 = '\n'.join(lines[twoThirds:])
return [text1, text2, text3]
return [text]
def turn_sample_to_vector(sample, sample_vectors_size=1024,
normalize_whitespace=True):
if normalize_whitespace:
# Map (most) white-space to space and compact to single one:
sample = sample.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ')
sample = re.sub('\s+', ' ', sample)
# Encode the characters to one-hot vectors:
sample_vectors = []
for ch in sample:
if ch in supported_chars_map:
sample_vectors.append(supported_chars_map[ch])
# Truncate to fixed length:
sample_vectors = sample_vectors[0:sample_vectors_size]
# Pad with 0 vectors:
if len(sample_vectors) < sample_vectors_size:
for i in range(0, sample_vectors_size - len(sample_vectors)):
sample_vectors.append(pad_vector)
return np.array(sample_vectors)
def turn_file_to_vectors(file_name, sample_vectors_size=1024, normalize_whitespace=True, breakup=True):
samples = get_source_snippets(file_name, breakup)
return [turn_sample_to_vector(s, sample_vectors_size, normalize_whitespace) for s in samples]
def get_input_and_labels(root_folder, sample_vectors_size=1024, breakup=True):
X = []
Y = []
for i, lang in enumerate(langs):
print('Processing language:', lang)
# One-hot class label vector:
class_label = [0 for x in range(0, num_classes)]
class_label[i] = 1
# For all files in language folder:
folder = os.path.join(root_folder, lang)
for fn in os.listdir(folder):
if fn.startswith("."):
continue # Skip hidden files and Jupyterlab cache directories
file_name = os.path.join(folder, fn)
sample_vectors = turn_file_to_vectors(file_name,
sample_vectors_size=sample_vectors_size,
breakup=breakup)
for fv in sample_vectors:
X.append(fv) # the sample feature vector
Y.append(class_label) # the class ground-truth
return np.array(X, dtype=np.int8), np.array(Y, dtype=np.int8)
# TODO generalize
langs = [
"C",
"C#",
"C++",
"D",
"Haskell",
"Java",
"JavaScript",
"PHP",
"Python",
"Rust"
]
num_classes = len(langs)
x, y = get_input_and_labels(root_folder=data_dir + source_folder + '/train') #TODO use data folder
# Shuffle data
shuffle_indices = np.random.permutation(np.arange(len(y)))
x_shuffled = x[shuffle_indices]
y_shuffled = y[shuffle_indices]
print('samples shape', x_shuffled.shape)
print('class labels shape:', y_shuffled.shape)
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Activation, Dense, Dropout, Flatten, Input
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Concatenate
# Model Hyperparameters
kernel_sizes = (3, 9, 19)
pooling_sizes = (3, 9, 19)
num_filters = 128
dropout_prob = 0.5
hidden_dims = 128
stage_in = Input(shape=(1024, 68))
convs = []
for i in range(0, len(kernel_sizes)):
conv = Conv1D(filters=num_filters,
kernel_size=kernel_sizes[i],
padding='valid',
activation='relu',
strides=1)(stage_in)
pool = MaxPooling1D(pool_size=pooling_sizes[i])(conv)
flatten = Flatten()(pool)
convs.append(flatten)
if len(kernel_sizes) > 1:
out = Concatenate()(convs)
else:
out = convs[0]
stages = Model(inputs=stage_in, outputs=out)
model = Sequential([
stages,
Dense(hidden_dims, activation='relu'),
Dropout(dropout_prob),
Dense(num_classes, activation='softmax')
])
model.summary()
# Note: also need pydot and GraphViz installed for this.
#from tensorflow.keras.utils import plot_model
#plot_model(model, show_shapes=True, expand_nested=True)
batch_size = 64
num_epochs = 20
val_split = 0.1
model.compile(loss='categorical_crossentropy', optimizer='adam',
metrics=['accuracy'])
history = model.fit(x_shuffled, y_shuffled, batch_size=batch_size,
epochs=num_epochs, validation_split=val_split,
verbose=1)
model_folder=str(time.time())
model.save(data_dir + model_folder)
shutil.make_archive(data_dir + output_model_zip.split('.zip')[0], 'zip', data_dir + model_folder)
###Output
_____no_output_____
###Markdown
nlp-transform-snippets creates snippets out of large text files
###Code
!pip3 install wget==3.2
import wget
import logging
import numpy as np
import os
import re
import shutil
import sys
import tarfile
import time
# file name for training data zip
input_filename = os.environ.get('input_filename ', 'data.zip')
# resulting model zip file name
output_model_zip = os.environ.get('output_model_zip', 'model.zip')
# temporal data storage for local execution
data_dir = os.environ.get('data_dir', '../../data/')
parameters = list(
map(
lambda s: re.sub('$', '"', s),
map(
lambda s: s.replace('=', '="'),
filter(
lambda s: s.find('=') > -1 and bool(re.match('[A-Za-z0-9_]*=[.\/A-Za-z0-9]*', s)),
sys.argv
)
)
)
)
for parameter in parameters:
logging.warning('Parameter: '+parameter)
exec(parameter)
source_folder=str(time.time())
shutil.unpack_archive(data_dir + input_filename, extract_dir=data_dir + source_folder)
# TODO generalize
letter = 'abcdefghijklmnopqrstuvwxyz'
digits = '0123456789'
others = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
alphabet = letter + digits + others
print('alphabet size:', len(alphabet))
# all-zeroes padding vector:
pad_vector = [0 for x in alphabet]
# pre-calculated one-hot vectors:
supported_chars_map = {}
for i, ch in enumerate(alphabet):
vec = [0 for x in alphabet]
vec[i] = 1
supported_chars_map[ch] = vec
def get_source_snippets(file_name, breakup=True):
# Read the file content and lower-case:
text = ""
with open(file_name, mode='r') as file:
text = file.read().lower()
lines = text.split('\n')
nlines = len(lines)
if breakup and nlines > 50:
aThird = nlines//3
twoThirds = 2*aThird
text1 = '\n'.join(lines[:aThird])
text2 = '\n'.join(lines[aThird:twoThirds])
text3 = '\n'.join(lines[twoThirds:])
return [text1, text2, text3]
return [text]
def turn_sample_to_vector(sample, sample_vectors_size=1024,
normalize_whitespace=True):
if normalize_whitespace:
# Map (most) white-space to space and compact to single one:
sample = sample.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ')
sample = re.sub('\s+', ' ', sample)
# Encode the characters to one-hot vectors:
sample_vectors = []
for ch in sample:
if ch in supported_chars_map:
sample_vectors.append(supported_chars_map[ch])
# Truncate to fixed length:
sample_vectors = sample_vectors[0:sample_vectors_size]
# Pad with 0 vectors:
if len(sample_vectors) < sample_vectors_size:
for i in range(0, sample_vectors_size - len(sample_vectors)):
sample_vectors.append(pad_vector)
return np.array(sample_vectors)
def turn_file_to_vectors(file_name, sample_vectors_size=1024, normalize_whitespace=True, breakup=True):
samples = get_source_snippets(file_name, breakup)
return [turn_sample_to_vector(s, sample_vectors_size, normalize_whitespace) for s in samples]
def get_input_and_labels(root_folder, sample_vectors_size=1024, breakup=True):
X = []
Y = []
for i, lang in enumerate(langs):
print('Processing language:', lang)
# One-hot class label vector:
class_label = [0 for x in range(0, num_classes)]
class_label[i] = 1
# For all files in language folder:
folder = os.path.join(root_folder, lang)
for fn in os.listdir(folder):
if fn.startswith("."):
continue # Skip hidden files and Jupyterlab cache directories
file_name = os.path.join(folder, fn)
sample_vectors = turn_file_to_vectors(file_name,
sample_vectors_size=sample_vectors_size,
breakup=breakup)
for fv in sample_vectors:
X.append(fv) # the sample feature vector
Y.append(class_label) # the class ground-truth
return np.array(X, dtype=np.int8), np.array(Y, dtype=np.int8)
# TODO generalize
langs = [
"C",
"C#",
"C++",
"D",
"Haskell",
"Java",
"JavaScript",
"PHP",
"Python",
"Rust"
]
num_classes = len(langs)
x, y = get_input_and_labels(root_folder=data_dir + source_folder + '/train') #TODO use data folder
# Shuffle data
shuffle_indices = np.random.permutation(np.arange(len(y)))
x_shuffled = x[shuffle_indices]
y_shuffled = y[shuffle_indices]
print('samples shape', x_shuffled.shape)
print('class labels shape:', y_shuffled.shape)
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Activation, Dense, Dropout, Flatten, Input
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Concatenate
# Model Hyperparameters
kernel_sizes = (3, 9, 19)
pooling_sizes = (3, 9, 19)
num_filters = 128
dropout_prob = 0.5
hidden_dims = 128
stage_in = Input(shape=(1024, 68))
convs = []
for i in range(0, len(kernel_sizes)):
conv = Conv1D(filters=num_filters,
kernel_size=kernel_sizes[i],
padding='valid',
activation='relu',
strides=1)(stage_in)
pool = MaxPooling1D(pool_size=pooling_sizes[i])(conv)
flatten = Flatten()(pool)
convs.append(flatten)
if len(kernel_sizes) > 1:
out = Concatenate()(convs)
else:
out = convs[0]
stages = Model(inputs=stage_in, outputs=out)
model = Sequential([
stages,
Dense(hidden_dims, activation='relu'),
Dropout(dropout_prob),
Dense(num_classes, activation='softmax')
])
model.summary()
# Note: also need pydot and GraphViz installed for this.
#from tensorflow.keras.utils import plot_model
#plot_model(model, show_shapes=True, expand_nested=True)
batch_size = 64
num_epochs = 20
val_split = 0.1
model.compile(loss='categorical_crossentropy', optimizer='adam',
metrics=['accuracy'])
history = model.fit(x_shuffled, y_shuffled, batch_size=batch_size,
epochs=num_epochs, validation_split=val_split,
verbose=1)
model_folder=str(time.time())
model.save(data_dir + model_folder)
shutil.make_archive(data_dir + output_model_zip.split('.zip')[0], 'zip', data_dir + model_folder)
###Output
_____no_output_____ |
content/lessons/10/Watch-Me-Code/WMC2-Dict-Methods.ipynb | ###Markdown
Watch Me Code 2: Dictionary Methods
###Code
student = { 'Name' : 'Michael', 'GPA': 3.2, 'Ischool' : True }
print(student)
# KeyError, keys must match exactly
student['gpa']
try:
print(student['Age'])
except KeyError:
print('The key "Age" does not exist.')
list(student.values())
list(student.keys())
for key in student.keys():
print(student[key])
del student['GPA']
print(student)
###Output
{'Ischool': True, 'Name': 'Michael'}
###Markdown
Watch Me Code 2: Dictionary Methods
###Code
student = { 'Name' : 'Michael', 'GPA': 3.2, 'Ischool' : True }
print(student)
# KeyError, keys must match exactly
student['gpa']
try:
print(student['Age'])
except KeyError:
print('The key "Age" does not exist.')
list(student.values())
list(student.keys())
for key in student.keys():
print(student[key])
del student['GPA']
print(student)
###Output
{'Ischool': True, 'Name': 'Michael'}
###Markdown
Watch Me Code 2: Dictionary Methods
###Code
student = { 'Name' : 'Michael', 'GPA': 3.2, 'Ischool' : True }
print(student)
# KeyError, keys must match exactly
student['gpa']
try:
print(student['Age'])
except KeyError:
print('The key "Age" does not exist.')
list(student.values())
list(student.keys())
for key in student.keys():
print(student[key])
del student['GPA']
print(student)
###Output
{'Ischool': True, 'Name': 'Michael'}
###Markdown
Watch Me Code 2: Dictionary Methods
###Code
student = { 'Name' : 'Michael', 'GPA': 3.2, 'Ischool' : True }
print(student)
# KeyError, keys must match exactly
print(student['GPA'])
try:
print(student['Age'])
except KeyError:
print('The key "Age" does not exist.')
list(student.values())
list(student.keys())
for key in student.keys():
print(student[key])
del student['GPA']
print(student)
###Output
{'Ischool': True, 'Name': 'Michael'}
###Markdown
Watch Me Code 2: Dictionary Methods
###Code
student = { 'Name' : 'Michael', 'GPA': 3.2, 'Ischool' : True }
print(student)
# KeyError, keys must match exactly
student['gpa']
try:
print(student['Age'])
except KeyError:
print('The key "Age" does not exist.')
list(student.values())
list(student.keys())
for key in student.keys():
print(student[key])
del student['GPA']
print(student)
###Output
{'Ischool': True, 'Name': 'Michael'}
###Markdown
Watch Me Code 2: Dictionary Methods
###Code
student = { 'Name' : 'Michael', 'GPA': 3.2, 'Ischool' : True }
print(student)
# KeyError, keys must match exactly
student['gpa']
try:
print(student['Age'])
except KeyError:
print('The key "Age" does not exist.')
list(student.values())
list(student.keys())
for key in student.keys():
print(student[key])
del student['GPA']
print(student)
###Output
{'Ischool': True, 'Name': 'Michael'}
###Markdown
Watch Me Code 2: Dictionary Methods
###Code
student = { 'Name' : 'Michael', 'GPA': 3.2, 'Ischool' : True }
print(student)
# KeyError, keys must match exactly
student['gpa']
try:
print(student['Age'])
except KeyError:
print('The key "Age" does not exist.')
list(student.values())
list(student.keys())
for key in student.keys():
print(student[key])
del student['GPA']
print(student)
###Output
{'Ischool': True, 'Name': 'Michael'}
###Markdown
Watch Me Code 2: Dictionary Methods
###Code
student = { 'Name' : 'Michael', 'GPA': 3.2, 'Ischool' : True }
print(student)
# KeyError, keys must match exactly
student['gpa']
try:
print(student['Age'])
except KeyError:
print('The key "Age" does not exist.')
list(student.values())
list(student.keys())
for key in student.keys():
print(student[key])
del student['GPA']
print(student)
###Output
{'Ischool': True, 'Name': 'Michael'}
###Markdown
Watch Me Code 2: Dictionary Methods
###Code
student = { 'Name' : 'Michael', 'GPA': 3.2, 'Ischool' : True }
print(student)
# KeyError, keys must match exactly
student['gpa']
try:
print(student['Age'])
except KeyError:
print('The key "Age" does not exist.')
list(student.values())
list(student.keys())
for key in student.keys():
print(student[key])
del student['GPA']
print(student)
###Output
{'Ischool': True, 'Name': 'Michael'}
|
11 - Introduction to Python/8_Iteration/6_Iterating over Dictionaries (6:21)/Iterating over Dictionaries - Solution_Py3.ipynb | ###Markdown
Iterating over Dictionaries *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).* In this exercise you will use the same dictionaries as the ones we used in the lesson - "prices" and "quantity". This time, don't just calculate all the money Jan spent. Calculate how much she spent on products with a price of 5 dollars or more.
###Code
prices = {
"box_of_spaghetti" : 4,
"lasagna" : 5,
"hamburger" : 2
}
quantity = {
"box_of_spaghetti" : 6,
"lasagna" : 10,
"hamburger" : 0
}
money_spent = 0
for i in quantity:
if prices[i]>=5:
money_spent += prices[i]*quantity[i]
else:
money_spent = money_spent
print (money_spent)
###Output
50
###Markdown
And how much did Jan spent on products that cost less than 5 dollars?
###Code
prices = {
"box_of_spaghetti" : 4,
"lasagna" : 5,
"hamburger" : 2
}
quantity = {
"box_of_spaghetti" : 6,
"lasagna" : 10,
"hamburger" : 0
}
money_spent = 0
for i in quantity:
if prices[i]<5:
money_spent += prices[i]*quantity[i]
else:
money_spent = money_spent
print (money_spent)
###Output
24
|
Chapman/Ch1-Problem_1-18.ipynb | ###Markdown
Excercises Electric Machinery Fundamentals Chapter 1 Problem 1-18
###Code
%pylab notebook
###Output
Populating the interactive namespace from numpy and matplotlib
###Markdown
Description Assume that the voltage applied to a load is $\vec{V} = 208\,V\angle -30^\circ$ and the current flowing through the load $\vec{I} = 2\,A\angle 20^\circ$. (a) * Calculate the complex power $S$ consumed by this load. (b) * Is this load inductive or capacitive? (c) * Calculate the power factor of this load? (d) * Calculate the reactive power consumed or supplied by this load. * Does the load consume reactive power from the source or supply it to the source?
###Code
V = 208.0 * exp(-1j*30/180*pi) # [V]
I = 2.0 * exp( 1j*20/180*pi) # [A]
###Output
_____no_output_____
###Markdown
SOLUTION (a)The complex power $S$ consumed by this load is:$$ S = V\cdot I^* $$
###Code
S = V * conjugate(I) # The complex conjugate of a complex number is
# obtained by changing the sign of its imaginary part.
S_angle = arctan(S.imag/S.real)
print('S = {:.1f} VA ∠{:.1f}°'.format(*(abs(S), S_angle/pi*180)))
print('====================')
###Output
S = 416.0 VA ∠-50.0°
====================
###Markdown
(b)This is a capacitive load. (c)The power factor of this load is **leading** and:
###Code
PF = cos(S_angle)
print('PF = {:.3f} leading'.format(PF))
print('==================')
###Output
PF = 0.643 leading
==================
###Markdown
(d)This load supplies reactive power to the source. The reactive power of the load is:$$ Q = VI\sin\theta = S\sin\theta$$
###Code
Q = abs(S)*sin(S_angle)
print('Q = {:.1f} var'.format(Q))
print('==============')
###Output
Q = -318.7 var
==============
###Markdown
Excercises Electric Machinery Fundamentals Chapter 1 Problem 1-18
###Code
%pylab inline
###Output
Populating the interactive namespace from numpy and matplotlib
###Markdown
Description Assume that the voltage applied to a load is $\vec{V} = 208\,V\angle -30^\circ$ and the current flowing through the load $\vec{I} = 2\,A\angle 20^\circ$. (a) * Calculate the complex power $S$ consumed by this load. (b) * Is this load inductive or capacitive? (c) * Calculate the power factor of this load? (d) * Calculate the reactive power consumed or supplied by this load. * Does the load consume reactive power from the source or supply it to the source?
###Code
V = 208.0 * exp(-1j*30/180*pi) # [V]
I = 2.0 * exp( 1j*20/180*pi) # [A]
###Output
_____no_output_____
###Markdown
SOLUTION (a)The complex power $S$ consumed by this load is:$$ S = V\cdot I^* $$
###Code
S = V * conjugate(I) # The complex conjugate of a complex number is
# obtained by changing the sign of its imaginary part.
S_angle = arctan(S.imag/S.real)
print('S = {:.1f} VA ∠{:.1f}°'.format(*(abs(S), S_angle/pi*180)))
print('====================')
###Output
S = 416.0 VA ∠-50.0°
====================
###Markdown
(b)This is a capacitive load. (c)The power factor of this load is **leading** and:
###Code
PF = cos(S_angle)
print('PF = {:.3f} leading'.format(PF))
print('==================')
###Output
PF = 0.643 leading
==================
###Markdown
(d)This load supplies reactive power to the source. The reactive power of the load is:$$ Q = VI\sin\theta = S\sin\theta$$
###Code
Q = abs(S)*sin(S_angle)
print('Q = {:.1f} var'.format(Q))
print('==============')
###Output
Q = -318.7 var
==============
|
notebooks/por revisar/mushrooms.ipynb | ###Markdown
Identificación de hongos venenosos=== Se desea determinar si un hongo es comestible o no a partir de sus características físicas. Para ello, se tiene una muestra de 8124 instancias de hongos provenientes de 23 especies de la familia Agaricus y Lepiota, los cuales han sido clasificados como comestibles, venenosos o de comestibilidad indeterminada. Se desea construir un sistema de clasificación que permita determinar si un hongo puede ser comestible o no. Por el tipo de problema en cuestión, los hongos de comestibilidad desconocida fueron asignados a la clase de hongos definitivamente venenosos, ya que no se puede correr el riesgo de dar un hongo potencialmente venenoso a una persona para su consumo.La información contenida en la muestra es la siguiente: 1. cap-shape: bell=b,conical=c,convex=x,flat=f, knobbed=k,sunken=s 2. cap-surface: fibrous=f,grooves=g,scaly=y,smooth=s 3. cap-color: brown=n,buff=b,cinnamon=c,gray=g,green=r, pink=p,purple=u,red=e,white=w,yellow=y 4. bruises?: bruises=t,no=f 5. odor: almond=a,anise=l,creosote=c,fishy=y,foul=f, musty=m,none=n,pungent=p,spicy=s 6. gill-attachment: attached=a,descending=d,free=f,notched=n 7. gill-spacing: close=c,crowded=w,distant=d 8. gill-size: broad=b,narrow=n 9. gill-color: black=k,brown=n,buff=b,chocolate=h,gray=g, green=r,orange=o,pink=p,purple=u,red=e, white=w,yellow=y 10. stalk-shape: enlarging=e,tapering=t 11. stalk-root: bulbous=b,club=c,cup=u,equal=e, rhizomorphs=z,rooted=r,missing=? 12. stalk-surface-above-ring: fibrous=f,scaly=y,silky=k,smooth=s 13. stalk-surface-below-ring: fibrous=f,scaly=y,silky=k,smooth=s 14. stalk-color-above-ring: brown=n,buff=b,cinnamon=c,gray=g,orange=o, pink=p,red=e,white=w,yellow=y 15. stalk-color-below-ring: brown=n,buff=b,cinnamon=c,gray=g,orange=o, pink=p,red=e,white=w,yellow=y 16. veil-type: partial=p,universal=u 17. veil-color: brown=n,orange=o,white=w,yellow=y 18. ring-number: none=n,one=o,two=t 19. ring-type: cobwebby=c,evanescent=e,flaring=f,large=l, none=n,pendant=p,sheathing=s,zone=z 20. spore-print-color: black=k,brown=n,buff=b,chocolate=h,green=r, orange=o,purple=u,white=w,yellow=y 21. population: abundant=a,clustered=c,numerous=n, scattered=s,several=v,solitary=y 22. habitat: grasses=g,leaves=l,meadows=m,paths=p, urban=u,waste=w,woods=dPara este ejemplo, se usa la información decrita en: https://archive.ics.uci.edu/ml/datasets/mushroomLas siguientes reglas han sido establecidas como el benchmark para este dataset: P_1) odor=NOT(almond.OR.anise.OR.none) 120 poisonous cases missed, 98.52% accuracy P_2) spore-print-color=green 48 cases missed, 99.41% accuracy P_3) odor=none.AND.stalk-surface-below-ring=scaly.AND. (stalk-color-above-ring=NOT.brown) 8 cases missed, 99.90% accuracy P_4) habitat=leaves.AND.cap-color=white 100% accuracy La regla P_4) también podría ser especificada como: P_4') population=clustered.AND.cap_color=white
###Code
##
## Preparacion
##
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
df = pd.read_csv(
"https://raw.githubusercontent.com/jdvelasq/datalabs/master/datasets/mushrooms.csv",
sep = ',', # separador de campos
thousands = None, # separador de miles para números
decimal = '.') # separador de los decimales para números
df.info()
df.columns
###Output
_____no_output_____ |
00-simple-notebook.ipynb | ###Markdown
Simple notebookThis notebook is just to test that the installation works fine
###Code
import torch
import matplotlib.pyplot as plt
from torchvision import datasets, transforms
batch_size = 32
transform_train = transforms.Compose([
transforms.ToTensor()
])
transform_test = transforms.Compose([
transforms.ToTensor()
])
# datasets (MNIST)
mnist_train = datasets.MNIST('/data', train=True, download=True, transform=transform_train)
mnist_test = datasets.MNIST('/data', train=False, download=True, transform=transform_test)
# dataloaders
train_loader = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, pin_memory=True)
test_loader = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False, pin_memory=True)
def visualize_batch(batch, labels, ncols=8):
nrows = (batch.shape[0] + ncols - 1) // ncols
plt.figure(figsize=(15, 2*nrows))
for i in range(batch.shape[0]):
plt.subplot(nrows, ncols, i+1)
plt.imshow(batch[i].permute(1, 2, 0).squeeze(), interpolation='bilinear')
plt.title(labels[i])
plt.axis('off')
plt.show()
batch, labels = next(iter(train_loader))
visualize_batch(batch, [str(int(lbl)) for lbl in labels])
###Output
_____no_output_____ |
twitterAPI-en.ipynb | ###Markdown
Collect Data using Twitter API
###Code
tweets = api.search(KEYWORD)
columns = ['created', 'tweet_text']
df = pd.DataFrame(columns = columns)
print("Getting Data...")
dataSize = 100
for i in range(dataSize):
tweets = api.search(KEYWORD)
for tweet in tweets:
tweet_text = tweet.text
created = tweet.created_at
row = [created, tweet_text]
series = pd.Series(row, index = df.columns)
df = df.append(series, ignore_index = True)
progress_bar.progress_bar(i, dataSize)
progress_bar.progress_bar(dataSize, dataSize)
print("\nGetting Data Completed...")
df.head(3)
###Output
Getting Data...
[====================================================================================================] 100%
Getting Data Completed...
###Markdown
Extract Keywords
###Code
def text_cleaning(text):
regex = re.compile('[^ A-Za-z]+') # For English
result = regex.sub('', text)
return result
df['clean_text'] = df['tweet_text'].apply(lambda x : text_cleaning(x))
df.head()
# Other languages' stopwords available here: https://www.ranks.nl/stopwords
stopwords_path = os.path.join('data', 'english_stopwords.txt') # For English
with open(stopwords_path, encoding='utf8') as f:
stopwords = f.readlines()
stopwords = [x.strip() for x in stopwords]
def get_nouns(x):
words = list(x.split())
# Remove words shorter or equal to length of 2 and remove stopwords
nouns = [word for word in words if len(word) > 2 and word not in stopwords]
return nouns
df['nouns'] = df['clean_text'].apply(lambda x : get_nouns(x))
print(df.shape)
df.head(3)
transactions = df['nouns'].tolist()
transactions = [transaction for transaction in transactions if transaction]
print(transactions[:3])
###Output
[['Synapsesaillc', 'Microsoft', 'Cloud', 'Healthcare', 'expands', 'portfolio', 'Azure', 'Healthcare', 'APIsFor', 'info', 'visit', 'httpstcoUsKXEgf'], ['ctrlshft', 'hiiii', 'studytwt', 'lifetwt', 'Zari', 'sheher', 'istpt', 'currently', 'enrolled', 'ICT', 'studentlikes', 'stationery', 'journa'], ['MarkRuffalo', 'Cant', 'wait', 'see', 'TaikaWaititi', 'Finally', 'More', 'First', 'People', 'programming']]
###Markdown
Analyze Keyword using Association Rule
###Code
# Setup your own apriori settings based on the keyword for best representation
results = list(apriori(transactions, min_support=0.1, min_confidence=0.3, min_lift=1, max_length=2))
print(results[:3])
#results = list(apriori(transactions,min_support=0.05,min_confidence=0.1,min_lift=5,max_length=2))
columns = ['source', 'target', 'support']
network_df = pd.DataFrame(columns = columns)
for result in results:
if len(result.items) == 2:
items = [x for x in result.items]
row = [items[0], items[1], result.support]
series = pd.Series(row, index = network_df.columns)
network_df = network_df.append(series, ignore_index=True)
network_df.head()
tweet_corpus = ''.join(df['clean_text'].tolist())
print(tweet_corpus[:500])
nouns = get_nouns(tweet_corpus)
count = Counter(nouns)
remove_char_counter = Counter({x : count[x] for x in count if len(x) > 1})
node_df = pd.DataFrame(remove_char_counter.items(), columns = ['node', 'nodesize'])
node_df = node_df[node_df['nodesize'] >= 100]
node_df.head()
###Output
_____no_output_____
###Markdown
Visualize Keyword Network
###Code
def drawNetwork(G, node_df, plt):
for idx, row in node_df.iterrows():
G.add_node(row['node'], nodesize=row['nodesize'])
for idx, row in network_df.iterrows():
G.add_weighted_edges_from([(row['source'], row['target'], row['support'])])
pos = nx.spring_layout(G, k=0.6, iterations=50)
sizes = [G.nodes[node]['nodesize']*25 for node in G]
nx.draw(G, pos=pos, node_size=sizes)
nx.draw_networkx_labels(G, pos=pos, font_family='AppleGothic', font_size=25)
ax = plt.gca()
plt.show()
plt.figure(figsize=(25,25))
G = nx.Graph()
drawNetwork(G, node_df, plt)
###Output
_____no_output_____ |
Machine_Learning_Ignite_4_Results.ipynb | ###Markdown
**SQL Server Machine Learning Platform** What will you learn today?* How to get started on Machine Learning? * Where does our [documentation](https://docs.microsoft.com/en-us/sql/advanced-analytics/?view=sql-server-ver15) live? * Machine Learning Extension in Azure Data Studio and the concept of Dataspaces. (Work in progress)* What datset will we use?* Building a Machine Learning Model with local Python.* Building a Machine Learning Model using Python leveraging Spark in the SQL Server 2019 Big Data Cluster.* Building a Machine Learning Model using R in leveraging Spark in the SQL Server 2019 Big Data Cluster.* How are we leveraging hardware acceleration for Machine Learning specific workloads?* How we do store models in enterprises? * What is MlFlow ? * Our contributions and commitment to MlFlow.* How do we load the data to SQL Server using Spark?* How do we load the data to SQL Server using Streamsets?* How do we install Machine Learning packages in SQL Server ?* How do we do predict on the stored data using the model in SQL Server?* How do we do predict on the stored data using the model in Azure SQL Database?* What is ONNX?* How do we convert the model to ONNX?* How do we natively score on Azure SQL Database Edge?* What is AppDeploy?* How do we now run the model in the container in SQL Server 2019 Big Data Cluster?* How do we convert the model to be running as a web app in SQL Server 2019 Big Data Cluster ? **Let's take a look at the dataset** Boston Housing DatasetHousing data contains 506 census tracts of Boston from the 1970 census.The data has following features, *medv* being the target variable:* crim - per capita crime rate by town* zn - proportion of residential land zoned for lots over 25,000 sq.ft* indus - proportion of non-retail business acres per town* chas - Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)* nox - nitric oxides concentration (parts per 10 million)* rm - average number of rooms per dwelling* age - proportion of owner-occupied units built prior to 1940* dis - weighted distances to five Boston employment centres* rad - index of accessibility to radial highways* tax - full-value property-tax rate per USD 10,000* ptratio- pupil-teacher ratio by town* b 1000(B - 0.63)^2, where B is the proportion of blacks by town* lstat - percentage of lower status of the population* medv - median value of owner-occupied homes in USD 1000’s **Building a Machine Learning Model with Local Python** Not recommended approach for Enterprises.
###Code
import numpy as np
import pandas as pd
import sklearn
import sklearn.datasets
from sklearn.datasets import load_boston
boston = load_boston()
boston
###Output
_____no_output_____
###Markdown
Prepare the data
###Code
df = pd.DataFrame(data=np.c_[boston['data'], boston['target']], columns=boston['feature_names'].tolist() + ['MEDV'])
# x contains all predictors (features)
x = df.drop(['MEDV'], axis = 1)
# y is what we are trying to predict - the median value
y = df.iloc[:,-1]
# Split the data frame into features and target
x_train = df.drop(['MEDV'], axis = 1)
y_train = df.iloc[:,-1]
print("\n*** Training data set x\n")
print(x_train.head())
print("\n*** Training data set y\n")
print(y_train.head())
###Output
*** Training data set x
CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX \
0 0.00632 18.0 2.31 0.0 0.538 6.575 65.2 4.0900 1.0 296.0
1 0.02731 0.0 7.07 0.0 0.469 6.421 78.9 4.9671 2.0 242.0
2 0.02729 0.0 7.07 0.0 0.469 7.185 61.1 4.9671 2.0 242.0
3 0.03237 0.0 2.18 0.0 0.458 6.998 45.8 6.0622 3.0 222.0
4 0.06905 0.0 2.18 0.0 0.458 7.147 54.2 6.0622 3.0 222.0
PTRATIO B LSTAT
0 15.3 396.90 4.98
1 17.8 396.90 9.14
2 17.8 392.83 4.03
3 18.7 394.63 2.94
4 18.7 396.90 5.33
*** Training data set y
0 24.0
1 21.6
2 34.7
3 33.4
4 36.2
Name: MEDV, dtype: float64
###Markdown
Building a Linear Regression Model
###Code
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import RobustScaler
continuous_transformer = Pipeline(steps=[('scaler', RobustScaler())])
# All columns are numeric - normalize them
preprocessor = ColumnTransformer(
transformers=[
('continuous', continuous_transformer, [i for i in range(len(x_train.columns))])])
model = Pipeline(
steps=[
('preprocessor', preprocessor),
('regressor', LinearRegression())])
# Train the model
model.fit(x_train, y_train)
###Output
_____no_output_____
###Markdown
Let's predict !
###Code
y_pred = model.predict(x_train)
###Output
_____no_output_____
###Markdown
Score the model
###Code
from sklearn.metrics import r2_score, mean_squared_error
sklearn_r2_score = r2_score(y_train, y_pred)
sklearn_mse = mean_squared_error(y_train, y_pred)
print('*** Scikit-learn r2 score: {}'.format(sklearn_r2_score))
print('*** Scikit-learn MSE: {}'.format(sklearn_mse))
###Output
*** Scikit-learn r2 score: 0.7406426641094094
*** Scikit-learn MSE: 21.894831181729206
###Markdown
Save the model
###Code
from joblib import dump, load
dump(model, 'filename.joblib')
model = load('filename.joblib')
model.predict(x_train)
###Output
_____no_output_____
###Markdown
Predict for each feature set
###Code
predictions = []
for i in range(5):
pdata = x_train.iloc[i:(i+1),:]
p = model.predict(pdata)
print("tuples")
print(pdata)
print(f"predicted: {p}")
predictions.append(p)
print(predictions)
###Output
tuples
CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO \
0 0.00632 18.0 2.31 0.0 0.538 6.575 65.2 4.09 1.0 296.0 15.3
B LSTAT
0 396.9 4.98
predicted: [30.00384338]
tuples
CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO \
1 0.02731 0.0 7.07 0.0 0.469 6.421 78.9 4.9671 2.0 242.0 17.8
B LSTAT
1 396.9 9.14
predicted: [25.02556238]
tuples
CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO \
2 0.02729 0.0 7.07 0.0 0.469 7.185 61.1 4.9671 2.0 242.0 17.8
B LSTAT
2 392.83 4.03
predicted: [30.56759672]
tuples
CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO \
3 0.03237 0.0 2.18 0.0 0.458 6.998 45.8 6.0622 3.0 222.0 18.7
B LSTAT
3 394.63 2.94
predicted: [28.60703649]
tuples
CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO \
4 0.06905 0.0 2.18 0.0 0.458 7.147 54.2 6.0622 3.0 222.0 18.7
B LSTAT
4 396.9 5.33
predicted: [27.94352423]
[array([30.00384338]), array([25.02556238]), array([30.56759672]), array([28.60703649]), array([27.94352423])]
###Markdown
Convert the Kernel to PySpark
**Building Machine Learning Model in Python using Spark in SQL Server 2019 Big Data Cluster**
Recommended approach for Enterprises.
###Code
import sklearn
import numpy as np
import pandas as pd
import sklearn.datasets
from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder, RobustScaler
from sklearn.compose import ColumnTransformer, make_column_transformer
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.neural_network import MLPRegressor
from sklearn.pipeline import Pipeline
###Output
Starting Spark application
###Markdown
Example: Load libraries into the cluster.
###Code
import subprocess
# Install JobLib
stdout = subprocess.check_output(
"pip3 install joblib",
stderr=subprocess.STDOUT,
shell=True).decode("utf-8")
print(stdout)
###Output
_____no_output_____
###Markdown
Load the data from HDFS
###Code
house_df = (spark.read.option("inferSchema", "true")
.option("header", "true")
.csv("/BostonData/BostonHousing.csv"))
house_df.show(10)
###Output
_____no_output_____
###Markdown
Prepare data for Machine Learning
###Code
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import RobustScaler
# Convert the Spark data frame to pandas
df = house_df.toPandas()
x_train = df.drop(['medv'], axis = 1)
y_train = df.iloc[:,-1]
###Output
_____no_output_____
###Markdown
Build a Linear Regression Model
###Code
continuous_transformer = Pipeline(steps=[('scaler', RobustScaler())])
# All columns are numeric - normalize them
preprocessor = ColumnTransformer(
transformers=[
('continuous', continuous_transformer, [i for i in range(len(x_train.columns))])])
model = Pipeline(
steps=[
('preprocessor', preprocessor),
('regressor', LinearRegression())])
# Train the model
lr_model = model.fit(x_train, y_train)
###Output
_____no_output_____
###Markdown
Let's Predict !
###Code
y_pred = model.predict(x_train)
print(y_pred)
###Output
_____no_output_____
###Markdown
Score the Model
###Code
from sklearn.metrics import r2_score, mean_squared_error
sklearn_r2_score = r2_score(y_train, y_pred)
sklearn_mse = mean_squared_error(y_train, y_pred)
print('*** Scikit-learn r2 score: {}'.format(sklearn_r2_score))
print('*** Scikit-learn MSE: {}'.format(sklearn_mse))
###Output
_____no_output_____
###Markdown
Save the model in HDFS
###Code
from joblib import dump, load
dump(model, 'filename.joblib')
import subprocess
cmd='/opt/hadoop/bin/hadoop fs -copyFromLocal -f filename.joblib /user/rony/'
subprocess.check_output(cmd.split())
###Output
_____no_output_____
###Markdown
Convert the Kernel to Spark | R in the Kernel
**Building Machine Learning Model in R using Spark in SQL Server 2019 Big Data Cluster**
Recommended approach for Enterprises. Install packages in the cluster
###Code
install.packages('caTools')
###Output
Starting Spark application
###Markdown
Load the library.
###Code
library(caTools)
###Output
_____no_output_____
###Markdown
Load the Boston Housing dataset
###Code
library(MASS)
housing <- Boston
str(housing)
###Output
_____no_output_____
###Markdown
Load summary of the data
###Code
summary(housing)
###Output
_____no_output_____
###Markdown
Train and Test Data
Lets split the data into train and test data using caTools library.
###Code
set.seed(123)
split <- sample.split(housing,SplitRatio =0.75)
train <- subset(housing,split==TRUE)
test <- subset(housing,split==FALSE)
###Output
_____no_output_____
###Markdown
Training our Model
Lets build our model considering that crim,rm,tax,lstat as the major influencers on the target variable.
General Form
The General Linear regression model in R :
Univariate Model : model<−lm(y∼x,data)
Multivariate Model : model<−lm(y∼.,data)
###Code
model <- lm(medv ~ crim + rm + tax + lstat, data = train)
summary(model)
###Output
_____no_output_____
###Markdown
Predictions
Let’s test our model by predicting on our testing dataset.
###Code
test$predicted.medv <- predict(model,test)
test$predicted.medv
###Output
_____no_output_____
###Markdown
Evaluating the model
###Code
error <- test$medv-test$predicted.medv
rmse <- sqrt(mean(error)^2)
rmse
###Output
_____no_output_____
###Markdown
Convert the Kernel to PySpark **Load the data into SQL using the Spark to SQL Connector**
###Code
house_df = (spark.read.option("inferSchema", "true")
.option("header", "true")
.csv("/BostonData/BostonHousing.csv"))
house_df.show(10)
#Write from Spark to SQL table using MSSQL Spark Connector
import os
# Read credentials for server
servername = "jdbc:sqlserver://master-0.master-svc"
df = (spark.read.option("inferSchema", "true")
.option("header", "true")
.csv("/user/rony/credentials.txt"))
credentials = df.filter(df.servername == servername).collect()
print("Use MSSQL connector to write to master SQL instance ")
#servername="jdbc:sqlserver://10.193.17.192:31433"
dbname = "BostonData"
url = servername + ";" + "databaseName=" + dbname + ";"
datasource_name = "Boston"
dbtable = "Boston"
user = credentials[0].username
password = credentials[0].password
#com.microsoft.sqlserver.jdbc.spark
try:
house_df.write \
.format("com.microsoft.sqlserver.jdbc.spark") \
.mode("overwrite") \
.option("url", url) \
.option("dbtable", dbtable) \
.option("user", user) \
.option("password", password) \
.option("dataPoolDataSource",datasource_name)\
.save()
except ValueError as error :
print("MSSQL Connector write failed", error)
print("MSSQL Connector write(overwrite) succeeded ")
###Output
_____no_output_____
###Markdown
**Partner Engagements** **Load the data into SQL Server Big Data Clusters from Kafka using StreamSets** StreamSets Demo **Accelerating Spark ML over SQL Server 2019 Big Data Cluster**[InAccel Blog Post](https://medium.com/@inaccel/accelerating-spark-ml-over-sql-server-2019-big-data-cluster-instantly-542159267052) **Package Management in SQL Server**
###Code
EXEC sp_execute_external_script
@language=N'Python',
@script=N'import pkg_resources
import pandas
OutputDataSet = pandas.DataFrame([(d.project_name, d.version) for d in pkg_resources.working_set])
'
###Output
_____no_output_____
###Markdown
Convert the Kernel to Python 3 Get credentials for each server from credentials.txt.
###Code
import sqlmlutils
# For Linux SQL Server, you must specify the ODBC Driver and the username/password because there is no Trusted_Connection/Implied Authentication support yet.
import os
credentials_dict = {}
cwd = os.getcwd()
with open('/Users/submarine/Downloads/IgniteML/MachineLearning/credentials.txt') as f:
for line in f:
login_information = line.split(',')
key = login_information[0]
value = [login_information[1], login_information[2]]
credentials_dict[key] = value
servername = "13.82.197.135:31433"
username = credentials_dict[servername][0]
password = credentials_dict[servername][1]
server = "13.82.197.135"
connection = sqlmlutils.ConnectionInfo(driver="ODBC Driver 17 for SQL Server", server=server, port=1433, uid=username, pwd=password, database="ADUG")
sqlpy = sqlmlutils.SQLPythonExecutor(connection)
pkgmanager = sqlmlutils.SQLPackageManager(connection)
pkgmanager.install("glue", upgrade=True)
pkgmanager.uninstall("jinja2")
###Output
_____no_output_____
###Markdown
**Model Management in SQL Server** Recommended approach for Enterprises. What is MlFlow?What is MlFlow?MlFlow is an open-source model management system.* Create experiments* Track machine learning models, parameters, and metrics* Visualize the resultsWe have enhanced MlFlow to log machine learning models into SQL Server and exploit SQL Server's data governance, security and model management features. Convert the Kernel to PySpark Import MlFlow
###Code
import mlflow
import mlflow.sklearn
import os
# Read credentials for server
servername = "13.82.197.135:31433"
df = (spark.read.option("inferSchema", "true")
.option("header", "true")
.csv("/user/rony/credentials.txt"))
credentials = df.filter(df.servername == servername).collect()
username = credentials[0].username
password = credentials[0].password
mlflow.set_tracking_uri('http://40.85.166.63:5000/')
db_uri_artifact = "mssql+pyodbc://" + username + ":" + password + "@" + "server"+"/MlFlow?driver=ODBC+Driver+17+for+SQL+Server"
#create new experiment
exp_name = "artifact_test_experiment_04"
mlflow.create_experiment(exp_name, artifact_location=db_uri_artifact)
mlflow.set_experiment(exp_name)
###Output
_____no_output_____
###Markdown
Build a Model wrapped with MlFlow
###Code
import subprocess
# Install PyODBC
stdout = subprocess.check_output(
"pip3 install pyodbc",
stderr=subprocess.STDOUT,
shell=True).decode("utf-8")
print(stdout)
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import RobustScaler
house_df = (spark.read.option("inferSchema", "true")
.option("header", "true")
.csv("/BostonData/BostonHousing.csv"))
# Convert the Spark data frame to pandas
df = house_df.toPandas()
x_train = df.drop(['medv'], axis = 1)
y_train = df.iloc[:,-1]
continuous_transformer = Pipeline(steps=[('scaler', RobustScaler())])
# All columns are numeric - normalize them
preprocessor = ColumnTransformer(
transformers=[
('continuous', continuous_transformer, [i for i in range(len(x_train.columns))])])
model = Pipeline(
steps=[
('preprocessor', preprocessor),
('regressor', LinearRegression())])
# Train the model
lr_model = model.fit(x_train, y_train)
with mlflow.start_run(nested=True):
name = model.__class__.__name__
mlflow.sklearn.log_model(lr_model,name)
###Output
_____no_output_____
###Markdown
Convert the Kernel to SQL
Viewing the models in SQL Server as the backend datastore for MlFlow
###Code
SELECT * FROM [MlFlow].[dbo].[artifacts]
###Output
_____no_output_____
###Markdown
**Deploy the models to SQL Server using MlFlow**
###Code
import mlflow.database
db_uri_deployment = "mssql+pyodbc://[email protected]:1433/modelstore?driver=ODBC+Driver+17+for+SQL+Server"
mlflow.database.deploy(model_uri=model_uri, db_uri=db_uri_deployment, flavor='onnx', table_name=None, column_name=None)
print("Deployed the model to Azure SQL Database.")
###Output
_____no_output_____
###Markdown
**Scoring the models in SQL Server**
Recommended approach for Enterprises. **In Azure SQL Database using R**
###Code
select len(data), description from models
declare @model varbinary(max) = (select [data] from models where description = 'R Model')
exec sp_execute_external_script
@language = N'R',
@script = N'
rmodel <- unserialize(model);
OutputDataset <- data.frame(MEDV=predict(rmodel, InputDataset))
',
@input_data_1 = N'select top(10)* from features',
@input_data_1_name = N'InputDataset',
@output_data_1_name = N'OutputDataset',
@params = N'@model varbinary(max)',
@model = @model
WITH RESULT SETS ((MEDV float));
###Output
_____no_output_____
###Markdown
**In SQL Server Big Data Cluster using Python**
###Code
select * from [MlFlow].dbo.artifacts where artifact_id = 3
declare @model varbinary(max) = (select artifact_content from [MlFlow].dbo.artifacts where artifact_id = 3)
exec sp_execute_external_script
@language = N'Python',
@script = N'
import pandas
import pickle
import sklearn
scikit_model = pickle.loads(model)
output_dataset = pandas.DataFrame(data=scikit_model.predict(input_dataset), columns=["MEDV"])
',
@input_data_1 = N'select top(10)* from [BostonData].dbo.Boston',
@input_data_1_name = N'input_dataset',
@output_data_1_name = N'output_dataset',
@params = N'@model varbinary(max)',
@model = @model
WITH RESULT SETS ((MEDV float));
###Output
_____no_output_____
###Markdown
**Azure SQL Database Edge** Recommended approach for Enterprises.
###Code
import numpy as np
import onnxmltools
import onnxruntime as rt
import pandas as pd
import skl2onnx
import sklearn
import sklearn.datasets
from sklearn.datasets import load_boston
boston = load_boston()
df = pd.DataFrame(data=np.c_[boston['data'], boston['target']], columns=boston['feature_names'].tolist() + ['MEDV'])
# x contains all predictors (features). in this version a single column is used (NOX)
x_train = pd.DataFrame(df.iloc[:,df.columns.tolist().index('NOX')])
# y is what we are trying to predict - the median value
y_train = pd.DataFrame(df.iloc[:,-1])
print("\n*** Training data set x\n")
print(x_train.head())
print("\n*** Training data set y\n")
print(y_train.head())
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import RobustScaler
continuous_transformer = Pipeline(steps=[('scaler', RobustScaler())])
# All columns are numeric - normalize them
preprocessor = ColumnTransformer(
transformers=[
('continuous', continuous_transformer, [i for i in range(len(x_train.columns))])])
noxmodel = Pipeline(
steps=[
('preprocessor', preprocessor),
('regressor', LinearRegression())])
# Train the model
noxmodel.fit(x_train, y_train)
preds = []
for i in range(5):
pdata = x_train.iloc[i:(i+1),:]
p = noxmodel.predict(pdata)
print("tuples")
print(pdata)
print("predicted:",p)
preds.append(p)
print(preds)
###Output
tuples
CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO \
0 0.00632 18.0 2.31 0.0 0.538 6.575 65.2 4.09 1.0 296.0 15.3
B LSTAT
0 396.9 4.98
predicted: [30.00384338]
tuples
CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO \
1 0.02731 0.0 7.07 0.0 0.469 6.421 78.9 4.9671 2.0 242.0 17.8
B LSTAT
1 396.9 9.14
predicted: [25.02556238]
tuples
CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO \
2 0.02729 0.0 7.07 0.0 0.469 7.185 61.1 4.9671 2.0 242.0 17.8
B LSTAT
2 392.83 4.03
predicted: [30.56759672]
tuples
CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO \
3 0.03237 0.0 2.18 0.0 0.458 6.998 45.8 6.0622 3.0 222.0 18.7
B LSTAT
3 394.63 2.94
predicted: [28.60703649]
tuples
CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO \
4 0.06905 0.0 2.18 0.0 0.458 7.147 54.2 6.0622 3.0 222.0 18.7
B LSTAT
4 396.9 5.33
predicted: [27.94352423]
[array([30.00384338]), array([25.02556238]), array([30.56759672]), array([28.60703649]), array([27.94352423])]
###Markdown
**What is ONNX ?**Using skl2onnx, we will convert our LinearRegression model to the ONNX format and save it locally.
###Code
from skl2onnx.common.data_types import FloatTensorType, Int64TensorType, DoubleTensorType
def convert_dataframe_schema(df, drop=None, batch_axis=False):
inputs = []
nrows = None if batch_axis else 1
for k, v in zip(df.columns, df.dtypes):
if drop is not None and k in drop:
continue
if v == 'int64':
t = Int64TensorType([nrows, 1])
elif v == 'float32':
t = FloatTensorType([nrows, 1])
elif v == 'float64':
t = DoubleTensorType([nrows, 1])
else:
raise Exception("Bad type")
inputs.append((k, t))
return inputs
# Convert the scikit model to onnx format
onnx_model = skl2onnx.convert_sklearn(noxmodel, 'Boston NOX Data', convert_dataframe_schema(x_train))
# Save the onnx model locally
# onnx_model_path = 'boston1.model.onnx'
# onnxmltools.utils.save_model(onnx_model, onnx_model_path)
###Output
_____no_output_____
###Markdown
**Test the ONNX model**After converting the model to ONNX format, we score the model to show little to no degradation in performance.*ONNX Runtime uses floats instead of doubles which explains small potential discrepencies.*
###Code
import onnxruntime as rt
sess = rt.InferenceSession(onnx_model.SerializeToString())
y_pred = np.full(shape=(len(x_train)), fill_value=np.nan)
for i in range(len(x_train)):
inputs = {}
for j in range(len(x_train.columns)):
inputs[x_train.columns[j]] = np.full(shape=(1,1), fill_value=x_train.iloc[i,j])
sess_pred = sess.run(None, inputs)
y_pred[i] = sess_pred[0][0][0]
onnx_r2_score = sklearn.metrics.r2_score(y_train, y_pred)
onnx_mse = sklearn.metrics.mean_squared_error(y_train, y_pred)
print()
print('*** Onnx r2 score: {}'.format(onnx_r2_score))
print('*** Onnx MSE: {}\n'.format(onnx_mse))
print()
###Output
*** Onnx r2 score: 0.18260303162826075
*** Onnx MSE: 69.00428927333752
###Markdown
**Insert the ONNX model into Azure SQL Database Edge**Now, we will store the model in SQL Server. We will create a database ```onnx``` with a ```models``` table to store the ONNX model. In the connection string, you will need to specify the **server address, username, and password**. You will need to also import the *pyodbc* package.
###Code
import pyodbc
import os
credentials_dict = {}
with open('/Users/submarine/Downloads/IgniteML/MachineLearning/credentials.txt') as f:
for line in f:
login_information = line.split(',')
key = login_information[0]
value = [login_information[1], login_information[2]]
credentials_dict[key] = value
server = "10.193.17.192" # SQL Server DB Edge IP address
username = credentials_dict[server][0] # SQL Server username
password = credentials_dict[server][1] # SQL Server password
# Connect to the master DB to create the new onnx database
connection_string = "Driver={ODBC Driver 17 for SQL Server};Server=" + server + ";Database=master;UID=" + username + ";PWD=" + password + ";"
conn = pyodbc.connect(connection_string, autocommit=True)
cursor = conn.cursor()
database = 'edgeonnxdb'
query = 'DROP DATABASE IF EXISTS ' + database
cursor.execute(query)
conn.commit()
# Create onnx database
query = 'CREATE DATABASE ' + database
cursor.execute(query)
conn.commit()
# Connect to onnx database
db_connection_string = "Driver={ODBC Driver 17 for SQL Server};Server=" + server + ";Database=" + database + ";UID=" + username + ";PWD=" + password + ";"
conn = pyodbc.connect(db_connection_string, autocommit=True)
cursor = conn.cursor()
table_name = 'models'
# Drop the table if it exists
query = f'drop table if exists {table_name}'
cursor.execute(query)
conn.commit()
# Create the model table
query = f'create table {table_name} ( ' \
f'[id] [int] IDENTITY(1,1) NOT NULL, ' \
f'[data] [varbinary](max) NULL, ' \
f'[description] varchar(1000))'
cursor.execute(query)
conn.commit()
# Insert the ONNX model into the models table
query = f"insert into {table_name} ([description], [data]) values ('Onnx Model',?)"
model_bits = onnx_model.SerializeToString()
insert_params = (pyodbc.Binary(model_bits))
cursor.execute(query, insert_params)
conn.commit()
###Output
_____no_output_____
###Markdown
**Load the data into SQL Server**We will create two tables, **features** and **target**, to store subsets of the boston housing dataset. * Features will contain all data being used to predict the target, median value. * Target contains the median value for each record in the dataset. You will need to import the *sqlalchemy* package.
###Code
import sqlalchemy
from sqlalchemy import create_engine
import urllib
db_connection_string = "Driver={ODBC Driver 17 for SQL Server};Server=" + server + ";Database=" + database + ";UID=" + username + ";PWD=" + password + ";"
conn = pyodbc.connect(db_connection_string)
cursor = conn.cursor()
features_table_name = 'features'
# Drop the table if it exists
query = f'drop table if exists {features_table_name}'
cursor.execute(query)
conn.commit()
# Create the features table
query = \
f'create table {features_table_name} ( ' \
f' [CRIM] float, ' \
f' [ZN] float, ' \
f' [INDUS] float, ' \
f' [CHAS] float, ' \
f' [NOX] float, ' \
f' [RM] float, ' \
f' [AGE] float, ' \
f' [DIS] float, ' \
f' [RAD] float, ' \
f' [TAX] float, ' \
f' [PTRATIO] float, ' \
f' [B] float, ' \
f' [LSTAT] float, ' \
f' [id] int)'
cursor.execute(query)
conn.commit()
target_table_name = 'target'
# Create the target table
query = \
f'create table {target_table_name} ( ' \
f' [MEDV] float, ' \
f' [id] int)'
x_train['id'] = range(1, len(x_train)+1)
y_train['id'] = range(1, len(y_train)+1)
print(x_train.head())
print(y_train.head())
###Output
NOX id
0 0.538 1
1 0.469 2
2 0.469 3
3 0.458 4
4 0.458 5
MEDV id
0 24.0 1
1 21.6 2
2 34.7 3
3 33.4 4
4 36.2 5
###Markdown
Finally, using sqlalchemy, we insert the `x_train` and `y_train` pandas dataframes into tables `features` and `target`, respectively.
###Code
db_connection_string = 'mssql+pyodbc://' + username + ':' + password + '@' + server + '/' + database + '?driver=ODBC+Driver+17+for+SQL+Server'
sql_engine = sqlalchemy.create_engine(db_connection_string)
x_train.to_sql(features_table_name, sql_engine, if_exists='append', index=False)
y_train.to_sql(target_table_name, sql_engine, if_exists='append', index=False)
###Output
_____no_output_____
###Markdown
You will now be able to view the data in SQL. Convert the Kernel to SQL **Native PREDICT on Azure SQL Database Edge** Below, using the stored ONNX model, we predict the median value of a house based on other features from the boston housing dataset.
###Code
USE onnx
DECLARE @model varbinary(max) = (SELECT DATA FROM dbo.models WHERE id = 1);
WITH predict_input as (SELECT TOP (1000) [id]
,CRIM
,ZN
,INDUS
,CHAS
,NOX
,RM
,AGE
,DIS
,RAD
,TAX
,PTRATIO
,B
,LSTAT
FROM [onnx].[dbo].[features])
SELECT predict_input.id, p.variable1 AS MEDV FROM PREDICT (MODEL = @model, DATA = predict_input) WITH (variable1 float) AS p
###Output
_____no_output_____ |
examples/reference/elements/bokeh/Area.ipynb | ###Markdown
**Title**: Area Element**Dependencies**: Plotly**Backends**: [Bokeh](./Area.ipynb), [Matplotlib](../matplotlib/Area.ipynb), [Plotly](../plotly/Area.ipynb)
###Code
import numpy as np
import holoviews as hv
hv.extension('bokeh')
###Output
_____no_output_____
###Markdown
``Area`` elements are ``Curve`` elements where the area below the line is filled. Like ``Curve`` elements, ``Area`` elements are used to display the development of quantitative values over an interval or time period. ``Area`` Elements may also be stacked to display multiple data series in a cumulative fashion over the value dimension.The data of an ``Area`` Element should be tabular with one key dimension representing the samples over the interval or the timeseries and one or two value dimensions. A single value dimension will fill the area between the curve and the x-axis, while two value dimensions will fill the area between the curves. See the [Tabular Datasets](../../../user_guide/08-Tabular_Datasets.ipynb) user guide for supported data formats, which include arrays, pandas dataframes and dictionaries of arrays. Area under the curveBy default the Area Element draws just the area under the curve, i.e. the region between the curve and the origin.
###Code
xs = np.linspace(0, np.pi*4, 40)
hv.Area((xs, np.sin(xs)))
###Output
_____no_output_____
###Markdown
Area between curvesWhen supplied a second value dimension the area is defined as the area between two curves.
###Code
X = np.linspace(0,3,200)
Y = X**2 + 3
Y2 = np.exp(X) + 2
Y3 = np.cos(X)
hv.Area((X, Y, Y2), vdims=['y', 'y2']) * hv.Area((X, Y, Y3), vdims=['y', 'y3'])
###Output
_____no_output_____
###Markdown
Stacked areas Areas are also useful to visualize multiple variables changing over time, but in order to be able to compare them the areas need to be stacked. To do this, use the ``Area.stack`` classmethod to stack multiple ``Area`` elements in an (Nd)Overlay.In this example we will generate a set of 5 arrays representing percentages and create an ``Overlay`` of them. Then we simply call the ``stack`` method with this overlay to get a stacked area chart.
###Code
values = np.random.rand(5, 20)
percentages = (values/values.sum(axis=0)).T*100
overlay = hv.Overlay([hv.Area(percentages[:, i], vdims=[hv.Dimension('value', unit='%')]) for i in range(5)])
overlay + hv.Area.stack(overlay)
###Output
_____no_output_____
###Markdown
Title Area Element Dependencies Bokeh Backends Bokeh Matplotlib Plotly
###Code
import numpy as np
import holoviews as hv
hv.extension('bokeh')
###Output
_____no_output_____
###Markdown
``Area`` elements are ``Curve`` elements where the area below the line is filled. Like ``Curve`` elements, ``Area`` elements are used to display the development of quantitative values over an interval or time period. ``Area`` Elements may also be stacked to display multiple data series in a cumulative fashion over the value dimension.The data of an ``Area`` Element should be tabular with one key dimension representing the samples over the interval or the timeseries and one or two value dimensions. A single value dimension will fill the area between the curve and the x-axis, while two value dimensions will fill the area between the curves. See the [Tabular Datasets](../../../user_guide/08-Tabular_Datasets.ipynb) user guide for supported data formats, which include arrays, pandas dataframes and dictionaries of arrays. Area under the curveBy default the Area Element draws just the area under the curve, i.e. the region between the curve and the origin.
###Code
xs = np.linspace(0, np.pi*4, 40)
hv.Area((xs, np.sin(xs)))
###Output
_____no_output_____
###Markdown
Area between curvesWhen supplied a second value dimension the area is defined as the area between two curves.
###Code
X = np.linspace(0,3,200)
Y = X**2 + 3
Y2 = np.exp(X) + 2
Y3 = np.cos(X)
hv.Area((X, Y, Y2), vdims=['y', 'y2']) * hv.Area((X, Y, Y3), vdims=['y', 'y3'])
###Output
_____no_output_____
###Markdown
Stacked areas Areas are also useful to visualize multiple variables changing over time, but in order to be able to compare them the areas need to be stacked. To do this, use the ``Area.stack`` classmethod to stack multiple ``Area`` elements in an (Nd)Overlay.In this example we will generate a set of 5 arrays representing percentages and create an ``Overlay`` of them. Then we simply call the ``stack`` method with this overlay to get a stacked area chart.
###Code
values = np.random.rand(5, 20)
percentages = (values/values.sum(axis=0)).T*100
overlay = hv.Overlay([hv.Area(percentages[:, i], vdims=[hv.Dimension('value', unit='%')]) for i in range(5)])
overlay + hv.Area.stack(overlay)
###Output
_____no_output_____
###Markdown
Title Area Element Dependencies Bokeh Backends Bokeh Matplotlib
###Code
import numpy as np
import holoviews as hv
hv.extension('bokeh')
###Output
_____no_output_____
###Markdown
``Area`` elements are ``Curve`` elements where the area below the line is filled. Like ``Curve`` elements, ``Area`` elements are used to display the development of quantitative values over an interval or time period. ``Area`` Elements may also be stacked to display multiple data series in a cumulative fashion over the value dimension.The data of an ``Area`` Element should be tabular with one key dimension representing the samples over the interval or the timeseries and one or two value dimensions. A single value dimension will fill the area between the curve and the x-axis, while two value dimensions will fill the area between the curves. See the [Tabular Datasets](../../../user_guide/07-Tabular_Datasets.ipynb) user guide for supported data formats, which include arrays, pandas dataframes and dictionaries of arrays. Area under the curveBy default the Area Element draws just the area under the curve, i.e. the region between the curve and the origin.
###Code
xs = np.linspace(0, np.pi*4, 40)
hv.Area((xs, np.sin(xs)))
###Output
_____no_output_____
###Markdown
Area between curvesWhen supplied a second value dimension the area is defined as the area between two curves.
###Code
X = np.linspace(0,3,200)
Y = X**2 + 3
Y2 = np.exp(X) + 2
Y3 = np.cos(X)
hv.Area((X, Y, Y2), vdims=['y', 'y2']) * hv.Area((X, Y, Y3), vdims=['y', 'y3'])
###Output
_____no_output_____
###Markdown
Stacked areas Areas are also useful to visualize multiple variables changing over time, but in order to be able to compare them the areas need to be stacked. To do this, use the ``Area.stack`` classmethod to stack multiple ``Area`` elements in an (Nd)Overlay.In this example we will generate a set of 5 arrays representing percentages and create an ``Overlay`` of them. Then we simply call the ``stack`` method with this overlay to get a stacked area chart.
###Code
values = np.random.rand(5, 20)
percentages = (values/values.sum(axis=0)).T*100
overlay = hv.Overlay([hv.Area(percentages[:, i], vdims=[hv.Dimension('value', unit='%')]) for i in range(5)])
overlay + hv.Area.stack(overlay)
###Output
_____no_output_____
###Markdown
Title Area Element Dependencies Bokeh Backends Bokeh Matplotlib
###Code
import numpy as np
import holoviews as hv
hv.extension('bokeh')
###Output
_____no_output_____
###Markdown
``Area`` elements are ``Curve`` elements where the area below the line is filled. Like ``Curve`` elements, ``Area`` elements are used to display the development of quantitative values over an interval or time period. ``Area`` Elements may also be stacked to display multiple data series in a cumulative fashion over the value dimension.The data of an ``Area`` Element should be tabular with one key dimension representing the samples over the interval or the timeseries and one or two value dimensions. A single value dimension will fill the area between the curve and the x-axis, while two value dimensions will fill the area between the curves. See the [Tabular Datasets](../../../user_guide/07-Tabular_Datasets.ipynb) user guide for supported data formats, which include arrays, pandas dataframes and dictionaries of arrays. Area under the curveBy default the Area Element draws just the area under the curve, i.e. the region between the curve and the origin.
###Code
xs = np.linspace(0, np.pi*4, 40)
hv.Area((xs, np.sin(xs)))
###Output
_____no_output_____
###Markdown
Area between curvesWhen supplied a second value dimension the area is defined as the area between two curves.
###Code
X = np.linspace(0,3,200)
Y = X**2 + 3
Y2 = np.exp(X) + 2
Y3 = np.cos(X)
hv.Area((X, Y, Y2), vdims=['y', 'y2']) * hv.Area((X, Y, Y3), vdims=['y', 'y3'])
###Output
_____no_output_____
###Markdown
Stacked areas Areas are also useful to visualize multiple variables changing over time, but in order to be able to compare them the areas need to be stacked. To do this, use the ``Area.stack`` classmethod to stack multiple ``Area`` elements in an (Nd)Overlay.In this example we will generate a set of 5 arrays representing percentages and create an ``Overlay`` of them. Then we simply call the ``stack`` method with this overlay to get a stacked area chart.
###Code
values = np.random.rand(5, 20)
percentages = (values/values.sum(axis=0)).T*100
overlay = hv.Overlay([hv.Area(percentages[:, i], vdims=[hv.Dimension('value', unit='%')]) for i in range(5)])
overlay + hv.Area.stack(overlay)
###Output
_____no_output_____ |
experiments/tuned_1/metehan/trials/2/trial.ipynb | ###Markdown
PTN TemplateThis notebook serves as a template for single dataset PTN experiments It can be run on its own by setting STANDALONE to True (do a find for "STANDALONE" to see where) But it is intended to be executed as part of a *papermill.py script. See any of the experimentes with a papermill script to get started with that workflow.
###Code
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os, json, sys, time, random
import numpy as np
import torch
from torch.optim import Adam
from easydict import EasyDict
import matplotlib.pyplot as plt
from steves_models.steves_ptn import Steves_Prototypical_Network
from steves_utils.lazy_iterable_wrapper import Lazy_Iterable_Wrapper
from steves_utils.iterable_aggregator import Iterable_Aggregator
from steves_utils.ptn_train_eval_test_jig import PTN_Train_Eval_Test_Jig
from steves_utils.torch_sequential_builder import build_sequential
from steves_utils.torch_utils import get_dataset_metrics, ptn_confusion_by_domain_over_dataloader
from steves_utils.utils_v2 import (per_domain_accuracy_from_confusion, get_datasets_base_path)
from steves_utils.PTN.utils import independent_accuracy_assesment
from steves_utils.stratified_dataset.episodic_accessor import Episodic_Accessor_Factory
from steves_utils.ptn_do_report import (
get_loss_curve,
get_results_table,
get_parameters_table,
get_domain_accuracies,
)
from steves_utils.transforms import get_chained_transform
###Output
_____no_output_____
###Markdown
Required ParametersThese are allowed parameters, not defaultsEach of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present)Papermill uses the cell tag "parameters" to inject the real parameters below this cell.Enable tags to see what I mean
###Code
required_parameters = {
"experiment_name",
"lr",
"device",
"seed",
"dataset_seed",
"labels_source",
"labels_target",
"domains_source",
"domains_target",
"num_examples_per_domain_per_label_source",
"num_examples_per_domain_per_label_target",
"n_shot",
"n_way",
"n_query",
"train_k_factor",
"val_k_factor",
"test_k_factor",
"n_epoch",
"patience",
"criteria_for_best",
"x_transforms_source",
"x_transforms_target",
"episode_transforms_source",
"episode_transforms_target",
"pickle_name",
"x_net",
"NUM_LOGS_PER_EPOCH",
"BEST_MODEL_PATH",
"torch_default_dtype"
}
standalone_parameters = {}
standalone_parameters["experiment_name"] = "STANDALONE PTN"
standalone_parameters["lr"] = 0.0001
standalone_parameters["device"] = "cuda"
standalone_parameters["seed"] = 1337
standalone_parameters["dataset_seed"] = 1337
standalone_parameters["num_examples_per_domain_per_label_source"]=100
standalone_parameters["num_examples_per_domain_per_label_target"]=100
standalone_parameters["n_shot"] = 3
standalone_parameters["n_query"] = 2
standalone_parameters["train_k_factor"] = 1
standalone_parameters["val_k_factor"] = 2
standalone_parameters["test_k_factor"] = 2
standalone_parameters["n_epoch"] = 100
standalone_parameters["patience"] = 10
standalone_parameters["criteria_for_best"] = "target_accuracy"
standalone_parameters["x_transforms_source"] = ["unit_power"]
standalone_parameters["x_transforms_target"] = ["unit_power"]
standalone_parameters["episode_transforms_source"] = []
standalone_parameters["episode_transforms_target"] = []
standalone_parameters["torch_default_dtype"] = "torch.float32"
standalone_parameters["x_net"] = [
{"class": "nnReshape", "kargs": {"shape":[-1, 1, 2, 256]}},
{"class": "Conv2d", "kargs": { "in_channels":1, "out_channels":256, "kernel_size":(1,7), "bias":False, "padding":(0,3), },},
{"class": "ReLU", "kargs": {"inplace": True}},
{"class": "BatchNorm2d", "kargs": {"num_features":256}},
{"class": "Conv2d", "kargs": { "in_channels":256, "out_channels":80, "kernel_size":(2,7), "bias":True, "padding":(0,3), },},
{"class": "ReLU", "kargs": {"inplace": True}},
{"class": "BatchNorm2d", "kargs": {"num_features":80}},
{"class": "Flatten", "kargs": {}},
{"class": "Linear", "kargs": {"in_features": 80*256, "out_features": 256}}, # 80 units per IQ pair
{"class": "ReLU", "kargs": {"inplace": True}},
{"class": "BatchNorm1d", "kargs": {"num_features":256}},
{"class": "Linear", "kargs": {"in_features": 256, "out_features": 256}},
]
# Parameters relevant to results
# These parameters will basically never need to change
standalone_parameters["NUM_LOGS_PER_EPOCH"] = 10
standalone_parameters["BEST_MODEL_PATH"] = "./best_model.pth"
# uncomment for CORES dataset
from steves_utils.CORES.utils import (
ALL_NODES,
ALL_NODES_MINIMUM_1000_EXAMPLES,
ALL_DAYS
)
standalone_parameters["labels_source"] = ALL_NODES
standalone_parameters["labels_target"] = ALL_NODES
standalone_parameters["domains_source"] = [1]
standalone_parameters["domains_target"] = [2,3,4,5]
standalone_parameters["pickle_name"] = "cores.stratified_ds.2022A.pkl"
# Uncomment these for ORACLE dataset
# from steves_utils.ORACLE.utils_v2 import (
# ALL_DISTANCES_FEET,
# ALL_RUNS,
# ALL_SERIAL_NUMBERS,
# )
# standalone_parameters["labels_source"] = ALL_SERIAL_NUMBERS
# standalone_parameters["labels_target"] = ALL_SERIAL_NUMBERS
# standalone_parameters["domains_source"] = [8,20, 38,50]
# standalone_parameters["domains_target"] = [14, 26, 32, 44, 56]
# standalone_parameters["pickle_name"] = "oracle.frame_indexed.stratified_ds.2022A.pkl"
# standalone_parameters["num_examples_per_domain_per_label_source"]=1000
# standalone_parameters["num_examples_per_domain_per_label_target"]=1000
# Uncomment these for Metahan dataset
# standalone_parameters["labels_source"] = list(range(19))
# standalone_parameters["labels_target"] = list(range(19))
# standalone_parameters["domains_source"] = [0]
# standalone_parameters["domains_target"] = [1]
# standalone_parameters["pickle_name"] = "metehan.stratified_ds.2022A.pkl"
# standalone_parameters["n_way"] = len(standalone_parameters["labels_source"])
# standalone_parameters["num_examples_per_domain_per_label_source"]=200
# standalone_parameters["num_examples_per_domain_per_label_target"]=100
standalone_parameters["n_way"] = len(standalone_parameters["labels_source"])
# Parameters
parameters = {
"experiment_name": "tuned_1_metehan",
"device": "cuda",
"lr": 0.001,
"seed": 1337,
"dataset_seed": 1337,
"labels_source": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
"labels_target": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
"x_transforms_source": ["times_zero"],
"x_transforms_target": ["times_zero"],
"episode_transforms_source": [],
"episode_transforms_target": [],
"domains_source": [1],
"domains_target": [0, 2],
"num_examples_per_domain_per_label_source": 100,
"num_examples_per_domain_per_label_target": 100,
"n_shot": 3,
"n_way": 19,
"n_query": 2,
"train_k_factor": 3,
"val_k_factor": 2,
"test_k_factor": 2,
"torch_default_dtype": "torch.float32",
"n_epoch": 50,
"patience": 3,
"criteria_for_best": "target_loss",
"x_net": [
{"class": "nnReshape", "kargs": {"shape": [-1, 1, 2, 256]}},
{
"class": "Conv2d",
"kargs": {
"in_channels": 1,
"out_channels": 256,
"kernel_size": [1, 7],
"bias": False,
"padding": [0, 3],
},
},
{"class": "ReLU", "kargs": {"inplace": True}},
{"class": "BatchNorm2d", "kargs": {"num_features": 256}},
{
"class": "Conv2d",
"kargs": {
"in_channels": 256,
"out_channels": 80,
"kernel_size": [2, 7],
"bias": True,
"padding": [0, 3],
},
},
{"class": "ReLU", "kargs": {"inplace": True}},
{"class": "BatchNorm2d", "kargs": {"num_features": 80}},
{"class": "Flatten", "kargs": {}},
{"class": "Linear", "kargs": {"in_features": 20480, "out_features": 256}},
{"class": "ReLU", "kargs": {"inplace": True}},
{"class": "BatchNorm1d", "kargs": {"num_features": 256}},
{"class": "Linear", "kargs": {"in_features": 256, "out_features": 256}},
],
"NUM_LOGS_PER_EPOCH": 10,
"BEST_MODEL_PATH": "./best_model.pth",
"pickle_name": "metehan.stratified_ds.2022A.pkl",
}
# Set this to True if you want to run this template directly
STANDALONE = False
if STANDALONE:
print("parameters not injected, running with standalone_parameters")
parameters = standalone_parameters
if not 'parameters' in locals() and not 'parameters' in globals():
raise Exception("Parameter injection failed")
#Use an easy dict for all the parameters
p = EasyDict(parameters)
supplied_keys = set(p.keys())
if supplied_keys != required_parameters:
print("Parameters are incorrect")
if len(supplied_keys - required_parameters)>0: print("Shouldn't have:", str(supplied_keys - required_parameters))
if len(required_parameters - supplied_keys)>0: print("Need to have:", str(required_parameters - supplied_keys))
raise RuntimeError("Parameters are incorrect")
###################################
# Set the RNGs and make it all deterministic
###################################
np.random.seed(p.seed)
random.seed(p.seed)
torch.manual_seed(p.seed)
torch.use_deterministic_algorithms(True)
###########################################
# The stratified datasets honor this
###########################################
torch.set_default_dtype(eval(p.torch_default_dtype))
###################################
# Build the network(s)
# Note: It's critical to do this AFTER setting the RNG
# (This is due to the randomized initial weights)
###################################
x_net = build_sequential(p.x_net)
start_time_secs = time.time()
###################################
# Build the dataset
###################################
if p.x_transforms_source == []: x_transform_source = None
else: x_transform_source = get_chained_transform(p.x_transforms_source)
if p.x_transforms_target == []: x_transform_target = None
else: x_transform_target = get_chained_transform(p.x_transforms_target)
if p.episode_transforms_source == []: episode_transform_source = None
else: raise Exception("episode_transform_source not implemented")
if p.episode_transforms_target == []: episode_transform_target = None
else: raise Exception("episode_transform_target not implemented")
eaf_source = Episodic_Accessor_Factory(
labels=p.labels_source,
domains=p.domains_source,
num_examples_per_domain_per_label=p.num_examples_per_domain_per_label_source,
iterator_seed=p.seed,
dataset_seed=p.dataset_seed,
n_shot=p.n_shot,
n_way=p.n_way,
n_query=p.n_query,
train_val_test_k_factors=(p.train_k_factor,p.val_k_factor,p.test_k_factor),
pickle_path=os.path.join(get_datasets_base_path(), p.pickle_name),
x_transform_func=x_transform_source,
example_transform_func=episode_transform_source,
)
train_original_source, val_original_source, test_original_source = eaf_source.get_train(), eaf_source.get_val(), eaf_source.get_test()
eaf_target = Episodic_Accessor_Factory(
labels=p.labels_target,
domains=p.domains_target,
num_examples_per_domain_per_label=p.num_examples_per_domain_per_label_target,
iterator_seed=p.seed,
dataset_seed=p.dataset_seed,
n_shot=p.n_shot,
n_way=p.n_way,
n_query=p.n_query,
train_val_test_k_factors=(p.train_k_factor,p.val_k_factor,p.test_k_factor),
pickle_path=os.path.join(get_datasets_base_path(), p.pickle_name),
x_transform_func=x_transform_target,
example_transform_func=episode_transform_target,
)
train_original_target, val_original_target, test_original_target = eaf_target.get_train(), eaf_target.get_val(), eaf_target.get_test()
transform_lambda = lambda ex: ex[1] # Original is (<domain>, <episode>) so we strip down to episode only
train_processed_source = Lazy_Iterable_Wrapper(train_original_source, transform_lambda)
val_processed_source = Lazy_Iterable_Wrapper(val_original_source, transform_lambda)
test_processed_source = Lazy_Iterable_Wrapper(test_original_source, transform_lambda)
train_processed_target = Lazy_Iterable_Wrapper(train_original_target, transform_lambda)
val_processed_target = Lazy_Iterable_Wrapper(val_original_target, transform_lambda)
test_processed_target = Lazy_Iterable_Wrapper(test_original_target, transform_lambda)
datasets = EasyDict({
"source": {
"original": {"train":train_original_source, "val":val_original_source, "test":test_original_source},
"processed": {"train":train_processed_source, "val":val_processed_source, "test":test_processed_source}
},
"target": {
"original": {"train":train_original_target, "val":val_original_target, "test":test_original_target},
"processed": {"train":train_processed_target, "val":val_processed_target, "test":test_processed_target}
},
})
# Some quick unit tests on the data
from steves_utils.transforms import get_average_power, get_average_magnitude
q_x, q_y, s_x, s_y, truth = next(iter(train_processed_source))
assert q_x.dtype == eval(p.torch_default_dtype)
assert s_x.dtype == eval(p.torch_default_dtype)
print("Visually inspect these to see if they line up with expected values given the transforms")
print('x_transforms_source', p.x_transforms_source)
print('x_transforms_target', p.x_transforms_target)
print("Average magnitude, source:", get_average_magnitude(q_x[0].numpy()))
print("Average power, source:", get_average_power(q_x[0].numpy()))
q_x, q_y, s_x, s_y, truth = next(iter(train_processed_target))
print("Average magnitude, target:", get_average_magnitude(q_x[0].numpy()))
print("Average power, target:", get_average_power(q_x[0].numpy()))
###################################
# Build the model
###################################
model = Steves_Prototypical_Network(x_net, device=p.device, x_shape=(2,256))
optimizer = Adam(params=model.parameters(), lr=p.lr)
###################################
# train
###################################
jig = PTN_Train_Eval_Test_Jig(model, p.BEST_MODEL_PATH, p.device)
jig.train(
train_iterable=datasets.source.processed.train,
source_val_iterable=datasets.source.processed.val,
target_val_iterable=datasets.target.processed.val,
num_epochs=p.n_epoch,
num_logs_per_epoch=p.NUM_LOGS_PER_EPOCH,
patience=p.patience,
optimizer=optimizer,
criteria_for_best=p.criteria_for_best,
)
total_experiment_time_secs = time.time() - start_time_secs
###################################
# Evaluate the model
###################################
source_test_label_accuracy, source_test_label_loss = jig.test(datasets.source.processed.test)
target_test_label_accuracy, target_test_label_loss = jig.test(datasets.target.processed.test)
source_val_label_accuracy, source_val_label_loss = jig.test(datasets.source.processed.val)
target_val_label_accuracy, target_val_label_loss = jig.test(datasets.target.processed.val)
history = jig.get_history()
total_epochs_trained = len(history["epoch_indices"])
val_dl = Iterable_Aggregator((datasets.source.original.val,datasets.target.original.val))
confusion = ptn_confusion_by_domain_over_dataloader(model, p.device, val_dl)
per_domain_accuracy = per_domain_accuracy_from_confusion(confusion)
# Add a key to per_domain_accuracy for if it was a source domain
for domain, accuracy in per_domain_accuracy.items():
per_domain_accuracy[domain] = {
"accuracy": accuracy,
"source?": domain in p.domains_source
}
# Do an independent accuracy assesment JUST TO BE SURE!
# _source_test_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.test, p.device)
# _target_test_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.test, p.device)
# _source_val_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.val, p.device)
# _target_val_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.val, p.device)
# assert(_source_test_label_accuracy == source_test_label_accuracy)
# assert(_target_test_label_accuracy == target_test_label_accuracy)
# assert(_source_val_label_accuracy == source_val_label_accuracy)
# assert(_target_val_label_accuracy == target_val_label_accuracy)
experiment = {
"experiment_name": p.experiment_name,
"parameters": dict(p),
"results": {
"source_test_label_accuracy": source_test_label_accuracy,
"source_test_label_loss": source_test_label_loss,
"target_test_label_accuracy": target_test_label_accuracy,
"target_test_label_loss": target_test_label_loss,
"source_val_label_accuracy": source_val_label_accuracy,
"source_val_label_loss": source_val_label_loss,
"target_val_label_accuracy": target_val_label_accuracy,
"target_val_label_loss": target_val_label_loss,
"total_epochs_trained": total_epochs_trained,
"total_experiment_time_secs": total_experiment_time_secs,
"confusion": confusion,
"per_domain_accuracy": per_domain_accuracy,
},
"history": history,
"dataset_metrics": get_dataset_metrics(datasets, "ptn"),
}
ax = get_loss_curve(experiment)
plt.show()
get_results_table(experiment)
get_domain_accuracies(experiment)
print("Source Test Label Accuracy:", experiment["results"]["source_test_label_accuracy"], "Target Test Label Accuracy:", experiment["results"]["target_test_label_accuracy"])
print("Source Val Label Accuracy:", experiment["results"]["source_val_label_accuracy"], "Target Val Label Accuracy:", experiment["results"]["target_val_label_accuracy"])
json.dumps(experiment)
###Output
_____no_output_____ |
kaggle/titanic/notebooks/EDA and Data Wrangling.ipynb | ###Markdown
Importing libraries
###Code
import pandas as pd # data analysis
import numpy as np # scientific computing
import seaborn as sn # plotting
import matplotlib.pyplot as plt # plotting
%matplotlib inline
from imblearn.under_sampling import RandomUnderSampler # for random sampling
from sklearn.preprocessing import StandardScaler # for scaling the data
###Output
_____no_output_____
###Markdown
Data overview
###Code
ds_train = pd.read_csv("../dataset/train.csv")
ds_train.head(7)
###Output
_____no_output_____
###Markdown
Exploratory Data Analysis Checking for Missing Data
###Code
# missing values in each column
ds_train.isnull().sum()
# total missing values
ds_train.isnull().sum().sum()
# variables
X = ds_train.columns
Y = ds_train.isnull().sum()
# setting plot size
plt.figure(figsize = (10, 5))
# plotting
sn.barplot(x = X, y = Y)
# adding labels
plt.xticks(rotation = 90)
plt.ylabel("# of missing values")
for i in range(len(X)):
plt.text(i, Y[i], Y[i], ha = 'center')
plt.show()
sn.heatmap(ds_train.isnull(), yticklabels = False, cbar = False)
plt.show()
###Output
_____no_output_____
###Markdown
Notes on missing dataAge: it is reasonable replace the missing values with some form of imputation.Cabin: either will be dropped or transformed into a different variable.Embarked: drop the 2 rows with missing values Handling missing data Age
###Code
plt.figure(figsize = (10, 9))
sn.boxplot(data = ds_train, x = 'Pclass', y = 'Age', palette = 'winter')
plt.show()
###Output
_____no_output_____
###Markdown
Notes on AgeIt seems 'Age' is correlated with 'Pclass'. Then, replace 'Age' null values based on 'Pclass'.
###Code
nafill_pclass1 = np.mean(ds_train[ds_train['Pclass'] == 1]['Age'].dropna()).round()
nafill_pclass1
nafill_pclass2 = np.median(ds_train[ds_train['Pclass'] == 2]['Age'].dropna()).round()
nafill_pclass2
nafill_pclass3 = np.median(ds_train[ds_train['Pclass'] == 3]['Age'].dropna()).round()
nafill_pclass3
# replace missing values
def nafill_age(ds):
age = ds['Age']
pclass = ds['Pclass']
if pd.isnull(age):
if pclass == 1:
return nafill_pclass1
elif pclass == 2:
return nafill_pclass2
else:
return nafill_pclass3
else:
return age
# replace NAs
ds_train['Age'] = ds_train[['Age', 'Pclass']].apply(nafill_age, axis = 1)
ds_train['Age'].isnull().sum()
###Output
_____no_output_____
###Markdown
Cabin && embarked
###Code
# drop 'Cabin' column entirely
ds_train.drop('Cabin', axis = 1, inplace = True)
# drop 'Embarked' NA rows
ds_train.dropna(inplace = True)
ds_train.head(7)
ds_train.isnull().sum()
###Output
_____no_output_____
###Markdown
Transforming categorical data
###Code
ds_train['Sex'].nunique()
ds_train['Embarked'].nunique()
sex = pd.get_dummies(ds_train['Sex'], drop_first = True)
sex.head(3)
embarked = pd.get_dummies(ds_train['Embarked'], drop_first = True)
embarked.head(3)
# rename columns
sex.rename(columns = {"male": "Sex_male"}, inplace = True)
embarked.rename(columns = {"Q": "Embarked_Q",
"S": "Embarked_S"}, inplace = True)
ds_train = pd.concat([ds_train, sex, embarked], axis = 1)
ds_train.head(7)
###Output
_____no_output_____
###Markdown
Removing unneccessary columns
###Code
ds_train.drop(['PassengerId', 'Name', 'Sex', 'Ticket', 'Embarked'], axis = 1, inplace = True)
ds_train.head(7)
###Output
_____no_output_____
###Markdown
Checking if the dataset is balanced or unbalanced
###Code
sn.countplot(data = ds_train, x = 'Survived')
plt.show()
###Output
_____no_output_____
###Markdown
It seems our dataset is not balanced, undersampling should work. Undersampling
###Code
Y = ds_train['Survived']
X = ds_train.drop('Survived', axis = 1)
rus = RandomUnderSampler(random_state = 0)
X_resampled, Y_resampled = rus.fit_resample(X, Y)
len(X_resampled) == len(Y_resampled)
ds_train_balanced = pd.concat([X_resampled, Y_resampled], axis = 1)
ds_train_balanced.head(7)
sn.countplot(data = ds_train_balanced, x = 'Survived')
plt.show()
###Output
_____no_output_____
###Markdown
The data set is balanced!
###Code
# Saving the data set:
# There will be 2 data sets; I would like to test them and take a look at the results:
# 1. 'final_train.csv' => balanced
# 2. 'final_train_std.csv' => balanced, standardized
ds_train_balanced_std = ds_train_balanced
ds_train_balanced.to_csv('../dataset/final_train.csv')
###Output
_____no_output_____
###Markdown
Performing standartization upon Age and Fare (to scale it down)
###Code
scaler = StandardScaler()
ds_train_balanced_std[['Age', 'Fare']] = scaler.fit_transform(ds_train_balanced_std[['Age', 'Fare']])
ds_train_balanced_std.head(7)
ds_train_balanced_std.to_csv('../dataset/final_train_std.csv')
###Output
_____no_output_____ |
JupyterNotebooks/Labs/Lab 2.ipynb | ###Markdown
Lab Two---Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Conditionals - If - Else - Else If
###Code
// Make an if statement
if (true) {
System.out.println("Angelina");
}
// Make an if, else statement where the else statement triggers
if (!true) {
System.out.println("Angelina");
} else{
System.out.println("Chirichella");
}
// Make an if, else if, else statement where the else if statement triggers
if (!true) {
System.out.println("Angelina");
} else if(true){
System.out.println("Chirichella");
} else{
System.out.println("My name is Angelina Chirichella");
}
// Make 2 variables and use them in an if else conditional
int num1 = 2;
int num2 = 4;
if (num1 == num2){
System.out.println("The numbers are equal!");
} else {
System.out.println("The numbers are not equal.");
}
// Make an if statement using 2 variables and an AND(&&) statement
boolean monday = true;
boolean thursday = false;
if (monday && !thursday){
System.out.println("I have class today.");
} else {
System.out.println("I do not have class today");
}
// Make an if statement using 2 variables and an OR(||) statement
int a = 20;
int b = 40;
if (a > b || b == 40) {
System.out.println("If statement with an or operator.");
} else {
System.out.println("Else statement.");
}
###Output
If statement with an or operator.
###Markdown
Lab Two Ryan Gonfiantini---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
I_do_my_homework = True
if (I_do_my_homework):
print("I can go out")
if (True):
print("we are going to applebee's")
# Create an if else statement
I_do_my_homework = False
if I_do_my_homework:
print("I can go out")
else:
print("I have to stay home")
# Create an if elif else statement
x = 5
y = 3
if (x+y > 15):
print("It works")
elif (x+y < 15):
print("That works better")
else:
print("Thats the answer")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for value in range(0,9):
print(value)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
# Get the length of the list above and print it.
colors = {"Blue", "Yellow", "Red", "Green", "Purple", "Magenta", "Lilac"}
for items in colors:
print(items)
# Create a while loop that ends after 6 times through. Print something for each pass.
i = 1
while i < 10:
print(i)
if i == 6:
break
i += 1
# Create a function to add 2 numbers together. Print out the number
x = 5
y = 5
print (x + y)
# Create a function that tells you if a number is odd or even and print the result.
num = int(input("enter a number: "))
if (num % 2) == 0:
print(str(num) + " is even")
else:
print(str(num) + " is odd")
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class dog:
def __init__(self, weight: int, age: int, name: str):
self.name = name
self.age = age
self.weight = weight
def who_is_this(self):
print("My dogs name is " + self.name)
print("Her age is " + self.age)
print("Her weight is " + self.weight)
if __name__ == "__main__":
Gonf = dog("60 pounds", "2 years old", "Quonnie")
Gonf.who_is_this()
###Output
My dogs name is Quonnie
Her age is 2 years old
Her weight is 60 pounds
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
i_like_halo = True
if i_like_halo:
print("Halo is the best video game series of all time.")
# Create an if else statement
you_like_halo = False
if you_like_halo:
print("I see you are cultured as well.")
else:
print("You need to reevaluate your life.")
# Create an if elif else statement
vikings_have_superbowl_win = False
packers_are_overrated = True
vikings_are_cooler = True
if vikings_have_superbowl_win:
print("We're not cursed!")
elif packers_are_overrated and vikings_are_cooler:
print("Maybe one day...")
else:
print("I live in constant dissappointment.")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for value in range(10):
print(value)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
# Get the length of the list above and print it.
for items in arr:
print(items)
print(len(arr))
# Create a while loop that ends after 6 times through. Print something for each pass.
start = 0
finish = 6
while start != finish:
print("You gotta keep going.")
start += 1
else:
print("You made it!")
# Create a function to add 2 numbers together. Print out the number
import random
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for values in arr:
print(random.choice(arr) + random.choice(arr))
# Create a function that tells you if a number is odd or even and print the result.
for items in range(20):
if items % 2 == 0:
print(str(items) + ": This number is even.")
elif items % 2 == 1:
print(str(items) + ": This number is odd.")
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name: str, height: int, weight: int, breed: str):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
if __name__ == "__main__":
Bub = Dog("Bub", 34, 90, "lab")
Bub.info()
###Output
Name: Bub
Weight: 90 Pounds
Height: 34 Inches
Breed: lab
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
X=55
Y=2
if X>Y:
print("X is greater than Y")
# Create an if else statement
X=2
Y=55
if X>Y:
print("X is greater than Y")
else:
print("Y is greater than X")
# Create an if elif else statement
X=2
Y=55
if X>Y:
print("X is greater than Y")
elif X==Y:
print("X and y are equal")
else:
print("Y is greater than X")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for X in range(10):
print(X)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for x in arr:
print(x)
# Get the length of the list above and print it.
# Create a while loop that ends after 6 times through. Print something for each pass.
count = 0
while count <= 5:
print(count)
count = count+1
# Create a function to add 2 numbers together. Print out the number
def add_function(X,Y):
print(X+Y)
add_function(5,5)
# Create a function that tells you if a number is odd or even and print the result.
def my_function(X):
if X % 2 ==0:
print("This number is even")
else:
print("This number is odd")
my_function(101)
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
###Output
_____no_output_____
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github.
###Code
for value in range (7):
print(arr[value])
print(value)
###Output
_____no_output_____
###Markdown
Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
num = 21231
sent = "Hey I'm a string"
bTrue = True
bFalse = False
decimal = 123.12312
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
x = 4
y = 6
print(x + y)
print(x - y)
print(x / y)
print(x * y)
print(x % y)
# Using 2 variables and addition print the number 57
x = 45
y = 12
print(x + y)
# Change this variable to a string and print
number_into_string = 37
print(str(number_into_string))
# Change this variable to a integer and print
string_into_number = '10'
print(int(string_into_number))
# Change this variable to a float and print
string_into_float = '299.99'
print(float(string_into_float))
# Change this variable to a boolean and print
number_into_boolean = 37
print(bool(number_into_boolean))
# Make me a list of any type
["Aimary", "Maddie", "Emma", "Bella", "Sebastian", "Cameron"]
###Output
_____no_output_____
###Markdown
Lab Two---Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Conditionals - If - Else - Else If
###Code
// Make an if statement
if (true) {
System.out.println("hello");
}
// Make an if, else statement where the else statement triggers
if (!true) {
System.out.println("this statement is true");
} else {
System.out.println("this statement is a paradox");
}
// Make an if, else if, else statement where the else if statement triggers
if (!true) {
System.out.println("I am tired ");
} else if (true){
System.out.println("I should continue to do homework");
} else {
System.out.println("I should sleep");
}
// Make 2 variables and use them in an if else conditional
boolean march = true;
boolean ninth = true;
if (march && ninth) {
System.out.println("It's my birthday");
}else {
System.out.println("It's my unbirthday");
}
// Make an if statement using 2 variables and an AND(&&) statement
boolean morning = true;
boolean tured = true;
if (morning && tired) {
System.out.println("put the pot of coffee on");
}
// Make an if statement using 2 variables and an OR(||) statement
boolean tea = true;
boolean coffee = false;
if (!coffee || tea) {
System.out.println("Make sure the tea is caffinated");
}
###Output
Make sure the tea is caffinated
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
age = 2147483650
greeting = 'Hello Class'
is_hungry = False
height = 69.3
print(age)
print(greeting)
print(is_hungry)
print(height)
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
age = 12
old = 70
young = 5
baby = 1
print(age+age)
print(old-young)
print(baby/old)
print(age*old)
# Using 2 variables and addition print the number 57
uno = 17
dos = 40
print(uno + dos)
# Change this variable to a string and print
number_into_string = '37'
# Change this variable to a integer and print
string_into_number = 10
# Change this variable to a float and print
string_into_float = 299.99
# Change this variable to a boolean and print
number_into_boolean = True
# Make me a list of any type
numbers = [1,2,3,4]
letters = ["a","b","c"]
###Output
_____no_output_____
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
l=700
m=900
if(l<m):
print("l is smaller than m")
# Create an if else statement
jax=123
box=456
if(jax>box):
print("jax is greater than box")
else:
print("box is greater than jax")
# Create an if elif else statement
apple=890
bananna=576
if(apple<bananna):
print("apple is less than bananna")
elif(apple == bananna):
print("apple is equal to bananna")
else:
print("apple is greater than bananna")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for x in range(10):
print(x)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for x in arr:
print(x)
# Get the length of the list above and print it.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
len(arr)
# Create a while loop that ends after 6 times through. Print something for each pass.
var1=0
while var1<42:
print(var1)
var1 += 7
# Create a function to add 2 numbers together. Print out the number
def my_function(num1,num2):
print(num1 + num2)
my_function(59,58)
# Create a function that tells you if a number is odd or even and print the result.
def my_function(num1):
if(num1%2 == 0):
print("The number is even")
else:
print("The number is odd")
my_function(35)
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
shitzu = Dog("frisco" ,40, 2, "shitzu")
shitzu.info()
###Output
Name: frisco
Weight: 2 Pounds
Height: 40 Inches
Breed: shitzu
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
did_well_on_test = True
if did_well_on_test:
print("Great Job!")
# Create an if else statement
did_well_on_test = False
if did_well_on_test:
print("Great job!")
else:
print("Better luck next time!")
# Create an if elif else statement
one_kid = False
its_twins = True
theyre_identical = True
if one_kid:
print ("Congratulations on the baby!")
elif its_twins and theyre_identical:
print ("Congratuations on identical twins!")
else:
print("Congratuations on twins!")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for number in range(10):
print(number)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for item in arr:
print(item)
# Get the length of the list above and print it.
len(arr)
#Create a while loop that ends after 6 times through. Print something for each pass.
a=1
while a<7:
print(a)
a += 1
# Create a function to add 2 numbers together. Print out the number
a = 10
b = 20
sum = a+b
print (sum)
# Create a function that tells you if a number is odd or even and print the result.
num = 100
if (num % 2 ==0):
print("The number is even")
else:
print("The number is odd")
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
if __name__ == "__main__":
Lucky = Dog("Lucky", 27, 71, "Golden Retriever")
Lucky.info()
###Output
Name: Lucky
Weight: 71 Pounds
Height: 27 Inches
Breed: Golden Retriever
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
string = "hello"
print(string)
int = 7
print(int)
Boolean = (1==0)
print(Boolean)
int = 7
Floatnumber = float(int)
print(Floatnumber)
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
a = 5
b = 7
sum = a + b
print(sum)
a = 10
b = 8
sum = a - b
print(sum)
a = 8
b = 4
sum = a / b
print(sum)
a = 10
b = 3
c = a % b
print(a, "mod", b, "=", c, sep = " ")
2*'hello'
# Using 2 variables and addition print the number 57
a = 7
b = 50
floatnumber = float(b)
sum = a + floatnumber
print(sum)
# Change this variable to a string and print
string = "37"
print(string)
# Change this variable to a integer and print
int = 10
print(int)
# Change this variable to a float and print
int = 299.99
floatnumber = float(int)
print(floatnumber)
# Change this variable to a boolean and print
boolean = (37==37)
print(boolean)
# Make me a list of any type
list = [1, "hello", 6]
print(list)
###Output
[1, 'hello', 6]
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement.
Complete = True
if True:
print("complete")
# Create an if else statement.
Complete = False
if Complete:
print("complete")
else:
print("incomplete")
# Create an if elif else statement
Download_Failed = False
Processes_Complete = True
Program_Running = False
if Download_Failed:
print("Failed")
elif Processes_Complete and Program_Running:
print("A stunning success story")
else:
print("what the heck is wrong and why can't I figure it out")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for value in range(10):
print(value)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for color in arr:
print(color)
# Get the length of the list above and print it.
print(len(arr))
# Create a while loop that ends after 6 times through. Print something for each pass.
number = 0
while number < 6:
print("almost there")
number += 1
# Create a function to add 2 numbers together. Print out the number
def addition(input1, input2):
total = input1 + input2
print(total)
addition(37, 10)
# Create a function that tells you if a number is odd or even and print the result.
def input_to_calc(number):
if number % 2 == 0:
print("Even")
else:
print("odd")
input_to_calc(45)
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
Chey = Dog(60, 36, "Cheyenne", "mutt")
Chey.info()
###Output
Name: 60
Weight: Cheyenne Pounds
Height: 36 Inches
Breed: mutt
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
question_1 = 5
question_2 = "STRING"
question_3 = True
question_4 = 5.0
print(question_1)
print(question_2)
print(question_3)
print(question_4)
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
addition_example = 3+3
subtraction_example = 5-4
division_example = 100/10
multiplication_example = 5*5
modulo_example = 29382042934703847 % 3
print(addition_example)
print(subtraction_example)
print(division_example)
print(multiplication_example)
print(modulo_example)
# Using 2 variables and addition print the number 57
first_num = 20
second_num = 37
print(first_num + second_num)
# Change this variable to a string and print
number_into_string = str(37)
print(number_into_string)
# Change this variable to a integer and print
string_into_number = int('10')
print(string_into_number)
# Change this variable to a float and print
string_into_float = float('299.99')
print(string_into_float)
# Change this variable to a boolean and print
number_into_boolean = bool(37)
print(number_into_boolean)
# Make me a list of any type
fruit_list = ['Apples', 'Oranges', 'Bananas']
###Output
['Apples', 'Oranges', 'Bananas']
###Markdown
Lab Two---Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Conditionals - If - Else - Else If
###Code
// Make an if statement
if (true) {
System.out.println("Hello!");
}
// Make an if, else statement where the else statement triggers
if (!true) {
System.out.println("I will have pizza.");
} else {
System.out.println("I will have a burger.");
}
// Make an if, else if, else statement where the else if statement triggers
if (!true) {
System.out.println("I will have pizza.");
} else if (true){
System.out.println("I will have a burger.");
} else {
System.out.println("I will have sushi.");
}
// Make 2 variables and use them in an if else conditional
boolean cupcakes = false;
boolean cheesecake = true;
if (!cupcakes && cheesecake) {
System.out.println("I don't have dessert");
} else{
System.out.println("Yay I have dessert");
}
// Make an if statement using 2 variables and an AND(&&) statement
boolean bread= true;
boolean cheese = false;
if (bread && !cheese) {
System.out.println("Yay I can make a grilled cheese sandwich!");
}
// Make an if statement using 2 variables and an OR(||) statement
boolean chocolate_icecream = true;
boolean vanilla_icecream= false;
if (chocolate_icecream || !vanilla_icecream) {
System.out.println("I can have ice cream!");
}
###Output
I can have ice cream!
###Markdown
Lab Two---Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Conditionals - If - Else - Else If
###Code
// Make an if statement
if (true) {
System.out.println("hello");
}
// Make an if, else statement where the else statement triggers
if (!true) {
System.out.println("hello");
} else {
System.out.println("Have a great day");
}
// Make an if, else if, else statement where the else if statement triggers
if (!true) {
System.out.println("hello");
} else if (true){
System.out.println("How are you");
} else {
System.out.println("Have a great day");
}
// Make 2 variables and use them in an if else conditional
int number1 = 3;
int number2 = 6;
if (number1 == number2) {
System.out.println("they are equal");
} else {
System.out.println("they are not equal");
}
// Make an if statement using 2 variables and an AND(&&) statement
int a = 45;
int b = 56;
if (a<b && b == 56) {
System.out.println("this is an example");
}
else {
System.out.println("this is an else statement");
}
// Make an if statement using 2 variables and an OR(||) statement
int c = 34;
int d = 67;
if(c < d || d == 78 ) {
System.out.println("This is an example");
}
else{
System.out.println("this is an else statement");
}
###Output
This is an example
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
has_money = True
if has_money:
print("Your going shopping today!")
# Create an if else statement
has_money = False
if has_money:
print("Your going shopping today!")
else:
print("Take a nap.")
# Create an if elif else statement
has_money = False
no_money = True
if has_money:
print("Your going shopping today!")
elif no_money:
print("You can go on a walk.")
else:
print("Take a nap.")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for value in range(10):
print(value)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for item in arr:
print(item)
# Get the length of the list above and print it.
print(len(arr))
# Create a while loop that ends after 6 times through. Print something for each pass.
animals = ["dog", "cat", "bird", "fox", "rabbit", "turtle", "horse"]
counting = 0
while counting < 6:
counting +=1
print(animals)
print(animals)
# Get the length of the list above and print it.
print(len(animals))
# Create a function to add 2 numbers together. Print out the number
#this was not required
# Create a function that tells you if a number is odd or even and print the result.
#if (number%2) == 0:
# print(number, "is an even number")
#else:
# print(number, "is an odd number")
#not required
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
ollie = Dog("Ollie", "22", "10", "Corgi")
ollie.info()
###Output
Name: Ollie
Weight: 10 Pounds
Height: 22 Inches
Breed: Corgi
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
interger = 5
string = ("potato")
boolean = True
float = .1
print (interger)
print (string)
print (boolean)
print (float)
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
addition = 2 + 5
subtraction = 5 - 2
division = 10 / 2
modulo = 10 % 5
print (addition)
print (subtraction)
print (division)
print (modulo)
# Using 2 variables and addition print the number 57
firstNumber = 25
secondNumber = 32
answer = firstNumber + secondNumber
print (answer)
# Change this variable to a string and print
number_into_string = "37"
# Change this variable to a integer and print
string_into_number = 10
# Change this variable to a float and print
string_into_float = 299.99
# Change this variable to a boolean and print
number_into_boolean = True
print (number_into_string)
print (string_into_number)
print (string_into_float)
print (number_into_boolean)
# Make me a list of any type
list = [1,2,3,4,5]
###Output
_____no_output_____
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
has_paper = True
has_pen = True
if has_paper and has_pen:
print('I can write my paper because the senario was true')
# Create an if else statement
worked_yesterday = False
if worked_yesterday:
print("I am really tired from work yesterday.")
else:
print("I have lots of energy today!")
# Create an if elif else statement
worked_yesterday = False
Have_work_today = True
Going_to_beach_today = False
if worked_yesterday:
print("I am tired today.")
elif Have_work_today and Going_to_beach_today:
print("I have a busy day today.")
else:
print("I have to work today.")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for value in range(10):
print(value)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for item in arr:
print(item)
# Get the length of the list above and print it.
for value in range(7):
print(value)
# Create a while loop that ends after 6 times through. Print something for each pass.
import random
secret_number = random.randint(0, 7)
position = 0
while position != secret_number:
print("We haven't found the secret number yet")
position += 1
print("We found the secret number, it was:" , secret_number)
# Create a function to add 2 numbers together. Print out the number
# Create a function that tells you if a number is odd or even and print the result.
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name: str, height: int, weight: int, breed: str):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
if __name__ == "__main__":
Rose = Dog("Rosie", 9, 6, "Yorkie")
Rose.info()
###Output
Name: Rosie
Weight: 6 Pounds
Height: 9 Inches
Breed: Yorkie
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
integer_variable = 4
string_variable = "This a test"
boolean_variable = True
float_variable = 7.35
print(integer_variable)
print(string_variable)
print(boolean_variable)
print(float_variable)
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
a = 1 + 1
b = 5 - 2
c = 25 / 5
d = 5 * 4
e = 5%2
print(a,b,c,d,e)
# Using 2 variables and addition print the number 57
x = 53 -30
y=4.25 * 8
print(x+y)
# Change this variable to a string and print
number_into_string = 37
print(str(37))
# Change this variable to a integer and print
string_into_number = '10'
print(int(10))
# Change this variable to a float and print
string_into_float = '299.99'
print(float('299.99'))
# Change this variable to a boolean and print
number_into_boolean = 37
print(bool(37))
# Make me a list of any type
mylist = ["The Motel", "Pepperoni", "Julian", "Randy Lahey"]
print(mylist)
###Output
['The Motel', 'Pepperoni', 'Julian', 'Randy Lahey']
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
# Integer
age = 20
# String
name = "Eddie Capone"
# Boolean
has_a_girlfriend = False
# Float
weight = 195.6
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
input1 = 10
input2 = 2
# Addition
print(input1 + input2)
# Subtraction
print(input1 - input2)
# Division
print(input1 / input2)
# Multiplication
print(input1 * input2)
# Modulo
print(input1 % input2)
# Using 2 variables and addition print the number 57
input1 = 52
input2 = 5
print(input1 + input2)
# Change this variable to a string and print
number_into_string = 37
my_variable = 37
print("I have "+ str(my_variable) +" lacrosse balls at my house")
# Change this variable to a integer and print
string_into_number = '10'
Dieci = 10
Dieci = int(Dieci)
print(type(Dieci))
print(Dieci)
# Change this variable to a float and print
string_into_float = '299.99'
number = 299.99
number = float(number)
print(type(number))
print(number)
# Change this variable to a boolean and print
number_into_boolean = 37
my_variable = bool(my_variable)
print(type(my_variable))
print(my_variable)
# Make me a list of any type
# list of states in the U.S.
states_in_US = ["New York", "Wisconsin", "Wyoming", "California"]
###Output
_____no_output_____
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
intvar = 1
strvar = "Hello World"
boolvar = True
floatvar = 1.0
print(intvar)
print(strvar)
print(boolvar)
print(floatvar)
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
var1 = 9
var2 = 3
add = var1 + var2
sub = var1 - var2
div = var1 / var2
mult = var1 * var2
mod = var1 % var2
print(add)
print(sub)
print(div)
print(mult)
print(mod)
# Using 2 variables and addition print the number 57
hello = 23
world = 34
CMPT120 = hello + world
print(CMPT120)
# Change this variable to a string and print
number_into_string = str(37)
print(number_into_string)
# Change this variable to a integer and print
string_into_number = int('10')
print(string_into_number)
# Change this variable to a float and print
string_into_float = float('299.99')
print(string_into_float)
# Change this variable to a boolean and print
number_into_boolean = bool(37)
print(number_into_boolean)
# Make me a list of any type
lst = ['this', 'is', 'a', 'list']
print(lst[-1])
###Output
list
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
bool=True
if True:
print("hello")
# Create an if else statement
bool=False
if bool:
print("hello")
else:
print("goodbye")
# Create an if elif else statement
get_paid=True
is_fired=False
if get_paid:
print("good week")
elif is_fired:
print("bad week")
else:
print("standard week")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for number in range(10):
print(number)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for color in arr:
print(color)
print(len(arr))
# Get the length of the list above and print it.
# Create a while loop that ends after 6 times through. Print something for each pass.
count=0
while count<=6:
print(count)
count+=1
# Create a function to add 2 numbers together. Print out the number
def add(a,b):
print(a+b)
add(7,8)
# Create a function that tells you if a number is odd or even and print the result.
def even_odd(a):
if a%2==0:
print("even")
else:
print("odd")
even_odd(8)
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
king=Dog("king", 30.7, 12.2, "german shepard")
king.info()
###Output
Name: king
Weight: 12.2 Pounds
Height: 30.7 Inches
Breed: german shepard
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement jjjj
# Create an if else statement
# Create an if elif else statement
# Create a for loop using range(). Go from 0 to 9. Print out each number.
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
# Get the length of the list above and print it.
# Create a while loop that ends after 6 times through. Print something for each pass.
# Create a function to add 2 numbers together. Print out the number
# Create a function that tells you if a number is odd or even and print the result.
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
###Output
_____no_output_____
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
[[x,y,z] for x in range(5) for y in range(1) for z in range(1)]
# Create an if else statement
money = False
if money:
print("I'm going to go buy a burger from Mcdonalds")
else:
print("Guess I'll starve")
# Create an if elif else statement
Hungry = True
has_eaten = True
is_full = False
if has_eaten:
print ("Im eating a cheeseburger.")
elif Hungry and is_full:
print ("Im hungry gimmie food!")
else:
print ("Guess I'll starve.")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
number = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for item in number:
print(item)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for item in arr:
print(item)
# Get the length of the list above and print it.
for value in range(7):
print(value)
# Create a while loop that ends after 6 times through. Print something for each pass.
import random
number = random.randint(0, 6)
position = 0
while position != number:
print("This is not the number I was thinking.")
position += 1
print("This is it! The number I was thinking was:", number)
# Create a function to add 2 numbers together. Print out the number
def addition(input1, input2):
total = input1 + input2
print(total)
addition (10,94)
# Create a function that tells you if a number is odd or even and print the result.
def odd_or_even(number):
if number % 2 == 0:
print("Its odd")
else:
print("Its Even")
odd_or_even(0)
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
Shibu = Dog("Sushi", "10", "14", "Shibu")
Shibu.info()
###Output
Name: Sushi
Weight: 14 Pounds
Height: 10 Inches
Breed: Shibu
###Markdown
Lab Two---Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Conditionals - If - Else - Else If
###Code
// Make an if statement
int var1 = 10;
if (var1 > 9) {
System.out.println("Double digits");
}
// Make an if, else statement where the else statement triggers
if (!true) {
System.out.println("Truth");
} else {
System.out.println("Lie");
}
// Make an if, else if, else statement where the else if statement triggers
int var1 = 15;
if (var1 > 20) {
System.out.println("Big number");
} else if (var1 > 10) {
System.out.println("Medium number");
} else {
System.out.println("Small number");
}
// Make 2 variables and use them in an if else conditional
int p1score = 81;
int p2score = 78;
if (p1score > p2score) {
System.out.println("Player 1 wins!");
} else {
System.out.println("Player 2 wins!");
}
// Make an if statement using 2 variables and an AND(&&) statement
boolean chocolate = true;
boolean milk = true;
if (chocolate && milk) {
System.out.println("Chocolate milk");
}
// Make an if statement using 2 variables and an OR(||) statement
boolean weights = true;
boolean cardio = false;
if (weights || cardio) {
System.out.println("Work Out");
}
###Output
Work Out
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
Job1 = True
HW = True
if Job1 and HW:
print("I can play smash bros today")
# Create an if else statement
hungry = True
if hungry:
print("I'm going to buy some food")
else:
print("I'm just bored and dont need to eat")
# Create an if elif else statement
no_motivation = True
money_need = False
if no_motivation:
print("not going to work")
elif money_need:
print("not going to work")
else:
print("going to work")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
ab = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for item in ab:
print(item)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
# Get the length of the list above and print it.
print(len(arr))
# Create a while loop that ends after 6 times through. Print something for each pass.
arr = [5, 6, 1, 25, 26, 74]
for item in arr:
print("this is loop " + str(item))
# Create a function to add 2 numbers together. Print out the number
import random
num1 = random.randint(0,100)
num2 = random.randint(0,100)
print(num1, "+", num2, "=", num1+num2)
# Create a function that tells you if a number is odd or even and print the result.
num = int(input("Enter a number _"))
if (num % 2) == 0:
print("{0} is an even number".format(num))
else:
print("{0} is an odd number".format(num))
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
if __name__ == "__main__":
Brutus = Dog("Brutus", 39, 5, "Spaniel Mix")
Brutus.info()
###Output
Name: Brutus
Weight: 5 Pounds
Height: 39 Inches
Breed: Spaniel Mix
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
integer = 223
string = 'flight and speed'
boolean = True
floats = 32.43
print (integer, string, boolean, floats)
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
clomber = 15
number = 60
bread = 34
print (clomber + number + bread)
print (number - bread - clomber)
print (number/clomber)
print (bread * number * bread)
print (number%bread)
# Using 2 variables and addition print the number 57
numbered = 23
anothnum = 34
print (numbered + anothnum)
# Change this variable to a string and print
number_into_string = 37
number_into_string = str(number_into_string)
print(number_into_string)
# Change this variable to a integer and print
string_into_number = '10'
string_into_number = int(string_into_number)
print (string_into_number)
# Change this variable to a float and print
string_into_float = '299.99'
string_into_float = float(string_into_float)
print (string_into_float)
# Change this variable to a boolean and print
number_into_boolean = 37
number_into_boolean = bool(number_into_boolean)
print (number_into_boolean)
# Make me a list of any type
coollist = ["burger", "food", "fries", "soda"]
print (coollist)
###Output
['burger', 'food', 'fries', 'soda']
###Markdown
Lab Two---Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Conditionals - If - Else - Else If
###Code
// Make an if statement
if (true) {
System.out.println("Welcome to Software Dev I");
}
// Make an if, else statement where the else statement triggers
if (false) {
System.out.println("Welcome to Software Dev I");
} else {
System.out.println("Coding is fun");
}
// Make an if, else if, else statement where the else if statement triggers
if (!true) {
System.out.println("Welcome to Software Dev I");
} else if (true){
System.out.println("Marist 2024");
} else {
System.out.println("Coding is fun");
}
// Make 2 variables and use them in an if else conditional
int x = 5;
int y = 10;
if (x+y > 13) {
System.out.println("It is big enough");
} else {
System.out.println("it is too small");
}
// Make an if statement using 2 variables and an AND(&&) statement
boolean cheese = true;
boolean crackers = true;
if (cheese && crackers) {
System.out.println("I can make a cheese and crackers");
} else {
System.out.println("I cannot make cheese and crackers");
}
// Make an if statement using 2 variables and an OR(||) statement
boolean blucheese = true;
boolean ranch = true;
if (!blucheese || ranch) {
System.out.println("My wings have sauce!");
} else {
System.out.println("My wings are dry");
}
###Output
My wings have sauce!
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
has_bread = True
has_chicken = True
if has_bread and has_chicken:
print("I can make a chicken sandwich")
# Create an if else statement
passed_class = True
if passed_class:
print("Good job, you passed!")
else:
print("Better luck next time")
# Create an if elif else statement
covered_spread = False
patriots_won = True
won_bet = False
if covered_spread:
print("This is awesome!")
elif patriots_won and won_bet:
print("At least the patriots one...")
else:
print("This day is awful")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for value in range(10):
print(value)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for item in arr:
print(item)
# Get the length of the list above and print it.
# Create a while loop that ends after 6 times through. Print something for each pass.
import random
secret_number = random.randint(0,6)
position = 0
while position != secret_number:
print("Looking for the secret number")
position += 1
print("We found the secret number, it was:", secret_number)
# Create a function to add 2 numbers together. Print out the number
a = 5
b = 7
sum_two_numbers = a + b
print(sum_two_numbers)
# Create a function that tells you if a number is odd or even and print the result.
a = 7
is_odd = True
if is_odd:
print("a is odd")
else:
print("a is not odd")
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
###Output
_____no_output_____
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
num = 12
name = "Brenden"
status = False
dec = 4.056
print(num)
print(name)
print(status)
print(dec)
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
less = 5
more = 20
# Should be 25
print(less + more)
# Should be 15
print(more - less)
# Should be 4
print(more/less)
# Should be 100
print(more * less)
# Should be 0
print(more % less)
# Using 2 variables and addition print the number 57
num1 = 57
num2 = 0
print(num1 + num2)
# Change this variable to a string and print
number_into_string = 37
print(str(number_into_string))
# Change this variable to a integer and print
string_into_number = '10'
print(int(string_into_number))
# Change this variable to a float and print
string_into_float = '299.99'
print(float(string_into_float))
# Change this variable to a boolean and print
number_into_boolean = 37
print(bool(number_into_boolean))
# Make me a list of any type
list = ["This", "is", "a", "list", "of", "strings"]
###Output
['This', 'is', 'a', 'list', 'of', 'strings']
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
is_a_New_Yorker = True
if is_a_New_Yorker:
print("Forget about it")
# Create an if else statement
is_a_New_Yorker = False
if is_a_New_Yorker:
print("Forget about it")
else:
print("Hey, I'm walking here!")
# Create an if elif else statement
is_a_New_Yorker = False
is_American = True
is_clumbsy = False
if is_a_New_Yorker:
print("Forget about it")
elif is_American and is_clumbsy:
print("Watch it! That was your fault.")
else:
print("Hey, I'm walking here!")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for value in range(0,1,2,3,4,5,6,7,8,9):
print(int)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for value in arr:
print(value)
# Get the length of the list above and print it.
for len in arr:
print(len)
# Create a while loop that ends after 6 times through. Print something for each pass.
import random
lucky_number = random.randint (0,10)
position = 0
if position != lucky_number:
print("Keep going.")
position += 1
print("The lucky number is:", lucky_number)
# Create a function to add 2 numbers together. Print out the number
a = 37
b = 10
c = (a + b)
print(c)
# Create a function that tells you if a number is odd or even and print the result.
x = random.randint(0,10)
divided_by_two = (x % 2)
no_remainder = 0
x % 2 = 0
if x is even:
print(x % 2)
else:
print: x != even
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = Ein
self.height = 2
self.weight = 50
self.breed = breed
def info(self):
print("Ein:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
if __name__ == "__main__":
Fido = Dog("Ein", 14, 35, "Welsh_Corgi")
Fido.who_is_this()
###Output
_____no_output_____
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
class_count=32
print(class_count)
filet="I have no clue what I\'m doing"
print(filet)
x=3
y=4
print(x+y<y)
nothing=3.3/6.5
print(nothing+nothing)
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
hippo=100
blueface=50
print(hippo+blueface)
print(hippo-blueface)
print(hippo*blueface)
print(hippo/blueface)
print(hippo%blueface)
# Using 2 variables and addition print the number 57
x=50
y=7
print(x+y)
# Change this variable to a string and print
number_into_string = 37
# Change this variable to a integer and print
string_into_number = '10'
# Change this variable to a float and print
string_into_float = '299.99'
# Change this variable to a boolean and print
number_into_boolean = 37
number_into_string=37
print(str(number_into_string))
frow='10'
print(int(frow))
x='299.9'
print(float(x))
y=37+47<2
print(bool(y))
# Make me a list of any type
Names=['Jebron', 'Lames', 'Filay', 'Milly']
print(Names)
###Output
['Jebron', 'Lames', 'Filay', 'Milly']
###Markdown
Lab Two---Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Conditionals - If - Else - Else If
###Code
// Make an if statement
if (true) {
System.out.println("nice");
}
// Make an if, else statement where the else statement triggers
if (false) {
System.out.println("nice");
} else {
System.out.println("not nice");
}
// Make an if, else if, else statement where the else if statement triggers
if (false) {
System.out.println("nice");
} else if (true){
System.out.println("hella nice");
} else {
System.out.println("not nice");
}
// Make 2 variables and use them in an if else conditional
boolean x= true;
boolean y= true;
if (x) {
System.out.println("x marks the spot");
} else {
System.out.println("no treasure");
}
// Make an if statement using 2 variables and an AND(&&) statement
boolean ham = true;
boolean cheese= true;
if (ham && cheese) {
System.out.println("you have croque monsieur");
}
// Make an if statement using 2 variables and an OR(||) statement
boolean ham = false;
boolean BLT= true;
if (ham || BLT) {
System.out.println("You have a boring or great sandwich");
}
###Output
You have a boring or great sandwich
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
# Using 2 variables and addition print the number 57
# Change this variable to a string and print
number_into_string = 37
# Change this variable to a integer and print
string_into_number = '10'
# Change this variable to a float and print
string_into_float = '299.99'
# Change this variable to a boolean and print
number_into_boolean = 37
# Make me a list of any type
###Output
_____no_output_____
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
has_dr_pepper = True
if has_dr_pepper:
print("Enjoy Refreshing Bev")
# Create an if else statement
has_dr_pepper = False
if has_dr_pepper:
print("Enjoy Refreshing Bev")
else:
print("Enjoy Tap Water I Guess")
# Create an if elif else statement
has_dr_pepper = False
Has_trasportation = True
has_money = False
if has_dr_pepper:
Print("Enjoy Refreshing Bev")
elif Has_trasportation and has_money:
print("Go and Buy Dr. Pepper")
else:
print("damn that sucks dude")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for number in range(10):
print(number)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
# Get the length of the list above and print it.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for color in arr:
print(color)
print(len(arr))
# Create a while loop that ends after 6 times through. Print something for each pass.
import random
fingers_behind_my_back = random.randint(0, 10)
position = 0
while position != fingers_behind_my_back:
print("nope, try again")
position += 1
print("you guessed it!:" , fingers_behind_my_back)
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
Mitzy = Dog("Mitzy" , "12" , "9" , "Chiuahuahua")
Mitzy.info()
###Output
Name: Mitzy
Weight: 9 Pounds
Height: 12 Inches
Breed: Chiuahuahua
###Markdown
Lab Two---Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Conditionals - If - Else - Else If
###Code
// Make an if statement
if (true) {
System.out.println("If: This is an if statement");
}
// Make an if, else statement where the else statement triggers
if (false) {
System.out.println("If: This is an if statement");
}else {
System.out.println("Else: This is an else statement");
}
// Make an if, else if, else statement where the else if statement triggers
int number = 3;
if (number>4) {
System.out.println("If: This is an if statement");
} else if (number <= 4){
System.out.println("Else If: This is an else if statement");
} else {
System.out.println("Else: This is an else statement");
}
// Make 2 variables and use them in an if else conditional
int a = 3;
int b = 2;
if (a > b){
System.out.println("If: This is an if statement");
} else {
System.out.println("Else: This is an else statement");
}
// Make an if statement using 2 variables and an AND(&&) statement
int c = 10;
int d = 20;
if (c < d && c == 10){
System.out.println("If: This is an if with an and operator statement");
} else{
System.out.println("Else: This is an else statement");
}
// Make an if statement using 2 variables and an OR(||) statement
int c = 10;
int d = 20;
if (c < d || d == 20){
System.out.println("If: This is an if with an or and operator statement");
} else {
System.out.println("Else: This is an else statement");
}
###Output
If: This is an if with an or and operator statement
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
if (37==37):
print("37")
# Create an if else statement
if (1==2):
print("nope")
else:
print("yes")
# Create an if elif else statement
numApples = 3
numOranges = 2
if numApples < numOranges:
print("less apples")
elif numApples > numOranges:
print("more apples")
else:
print("equal apples and oranges")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for num in range(0,10):
print(num)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for color in arr:
print(color)
# Get the length of the list above and print it.
print("The length of arr is:", len(arr))
# Create a while loop that ends after 6 times through. Print something for each pass.
i = 0
while i<6:
print(i)
i += 1
# Create a function to add 2 numbers together. Print out the number
def Addition(num1, num2):
return num1 + num2
print(Addition(5,7))
# Create a function that tells you if a number is odd or even and print the result.
def Parity(num):
parity = ""
if num % 2 == 1:
parity = "odd"
else:
parity = "even"
return parity
print(Parity(2))
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
dog = Dog("Moose", 8, 15, "Chihuahua")
dog.info()
###Output
Name: Moose
Weight: 15 Pounds
Height: 8 Inches
Breed: Chihuahua
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
has_peanut_butter = True
has_jelly = True
if has_peanut_butter and has_jelly:
print("Peanut Butter Jelly Time!")
# Create an if else statement
passing_class = False
if passing_class:
print("Congratlations, you recieve an A!")
else:
print("You failed this course, please try again next semester")
# Create an if elif else statement
has_chocolate_chips = False
has_sugar = False
has_flour = True
if has_chocolate_chips:
print("Chocolate Time!")
elif has_sugar and has_flour:
print("Baking Time, cookies or cake?")
else:
print("Time to run to the store for supplies!")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for value in range(10):
print(value)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for value in arr:
print(value)
# Get the length of the list above and print it.
color_count = len(arr)
print(color_count)
# Create a while loop that ends after 6 times through. Print something for each pass.
import random
lucky_number = random.randint(0, 6)
position = 0
while position != lucky_number:
print("Still searching..")
position += 1
print("Found the lucky number:", lucky_number)
# Create a function to add 2 numbers together. Print out the number
value1 = 543
value2 = 395
print(value1 + value2)
# Create a function that tells you if a number is odd or even and print the result.
number = 12346
if number %2 == 0:
print("Even Number")
else:
print("Odd Number")
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog:
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Dog's Name: " + self.name)
print("Dog's Height: " + str(self.height) + " Inches")
print("Dog's Weight: " + str(self.weight) + " Pounds")
print("Dog's Breed: " + self.breed)
if __name__ == "__main__":
Scout = Dog("Scout", 14, 50, "Laborador Mix")
Scout.info()
###Output
Dog's Name: Scout
Dog's Height: 14 Inches
Dog's Weight: 50 Pounds
Dog's Breed: Laborador Mix
###Markdown
Lab 2 Intro to Programming CMPT 120 Due: 02/16/2022 by MidnightThe second assignment should also be fairly simple. We’re going to be looking at the doc on getting your forked repo synced with mine. I’d advise that you download [GitHub Desktop | Simple collaboration from your desktop.](https://desktop.github.com/) Considering dealing with terminals has been a little tedious. As shown in class it is possible to do these things in the terminal. We may want to revisit that a little further into class when people are a little more comfortable if they’d like.After doing so we need to clone your forked repo and then sync it. To do this you can follow the steps here. [Cloning a repository from GitHub to GitHub Desktop.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-a-repository-from-github-to-github-desktop) After you clone you can look into this guide to [How to sync your forked repo with original Repo in Github Desktop.](https://stackoverflow.com/questions/46110615/how-to-sync-your-forked-repo-with-original-repo-in-github-desktop)If you didn't install Visual Studio Code in the last lab the link is [here](https://code.visualstudio.com)When you open it you'll wanna click the 4 boxes on the left bar. Type in Python and install that plugin. That will get the Jupyter support that we need.Once this is done we can open our GitHub repo which is usually downloaded to our Documents folder. I usually will open it at the folder level!From here open this lab in VSCode and fill out the lab below with your answers! (You may have to select a kernel, you should only have one and it'll be python unlike my screenshot) If you need to change it click the box icon in the upper right corner of the screen. (in my screenshot it has 3.9.0 next to it)After that you’ll need to push the changes that you synced so that I can see them and you can get credit and that is here. [Pushing changes to GitHub](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/pushing-changes-to-github)Grading will be based on content, accuracy, thoroughness, and adherence to instructions for credit up to a single homework assignment. First submit the assignment by pushing your synced repository to your GitHub account on [https://github.com/](https://github.com/). You’ll know if you did this properly because you’ll have the Lesson Two notebook. You’ll also have the file for the lab. Second, on iLearn, submit the assignment with a screenshot of your synced repo on Github. Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Defining variables- Using math- Manipulating variables- Changing data types- Playing with lists
###Code
# Define 4 variables, one of each type listed: [Integer, String, Boolean, Float]. Print all 4.
class_count=32
print(class_count)
hi="greeting"
print(hi)
is_alive=True
is_dead=False
print(is_alive)
height=5.82
print(height)
# With whatever variables you'd like demonstrate the following: [Addition, Subtraction, Division, Multiplication, Modulo]. Print all 5.
Dogs=24
cats=19
print(Dogs+cats)
print(Dogs-cats)
print(Dogs/cats)
print(Dogs*cats)
print(Dogs%cats)
# Using 2 variables and addition print the number 57
boys=30
girls=27
print(boys+girls)
# Change this variable to a string and print
number_into_string = 37
# Change this variable to a integer and print
string_into_number = '10'
# Change this variable to a float and print
string_into_float = '299.99'
# Change this variable to a boolean and print
number_into_boolean = 37
number_into_string=32
print(str(number_into_string))
boy="10"
print(int(boy))
print(float(boy))
int=30
print(bool(int))
# Make me a list of any type
letters=['a','b','c','d','e']
print(letters)
###Output
['a', 'b', 'c', 'd', 'e']
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
# Create an if else statement
# Create an if elif else statement
# Create a for loop using range(). Go from 0 to 9. Print out each number.
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
# Get the length of the list above and print it.
# Create a while loop that ends after 6 times through. Print something for each pass.
# Create a function to add 2 numbers together. Print out the number
# Create a function that tells you if a number is odd or even and print the result.
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
###Output
_____no_output_____
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
if True:
print ("Bot is ready.")
# Create an if else statement
if False:
print ("Bot is ready.")
else:
print ("Bot is not ready.")
# Create an if elif else statement
if False:
print ("Bot is not ready.")
elif True:
print ("Bot is ready.")
else:
print("Bot is extra ready.")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for number in range(10):
print(number)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
# Get the length of the list above and print it.
for item in arr:
print(item)
print(len(arr))
# Create a while loop that ends after 6 times through. Print something for each pass.
List = [1,2,3,4,5,6,7]
List = 0
while List < 6:
print (List)
List += 1
# Create a function to add 2 numbers together. Print out the number
Ommitted
# Create a function that tells you if a number is odd or even and print the result.
Ommitted
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
Coco = Dog("Coco", "15", "10", "Poodle")
Coco.info()
###Output
Name: Coco
Weight: 10 Pounds
Height: 15 Inches
Breed: Poodle
###Markdown
Lab Two---Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Conditionals - If - Else - Else If
###Code
// Make an if statement
System.out.println("Is 10 greater than 5?");
if (5 < 10) {
System.out.println("True");
}
// Make an if, else statement where the else statement triggers
System.out.println("Is 5 greater than 10?");
if (5 > 10) {
System.out.println("Yes it is");
}
else {
System.out.println("No, it is not");
}
// Make an if, else if, else statement where the else if statement triggers
System.out.println("Is 5 equal to 5?");
if (5 < 10) {
System.out.println("Yes, it is");
}
else if (5 == 5) {
System.out.println("Yes, it is");
}
else {
System.out.println("No it is not");
}
// Make 2 variables and use them in an if else conditional
int x = 5;
int y = 10;
System.out.println("Which number is greater? 5 or 10?");
if (x > y) {
System.out.println("5 is greater");
}
else {
System.out.println("10 is greater");
}
// Make an if statement using 2 variables and an AND(&&) statement
// Make an if statement using 2 variables and an OR(||) statement
###Output
_____no_output_____
###Markdown
Lab Two---Ok for this lab we're going to reiterate a lot of the things that we went over in class.Our Goals are:- Conditionals - If - Else - Else If
###Code
// Make an if statement
boolean present = true;
if (present = true) {
System.out.println("Hello there! Welcome to today's CMPT 220L class!");
}
// Make an if, else statement where the else statement triggers
boolean GoodHealth = false;
if (GoodHealth = true) {
System.out.println("You are looking good! No need to seek medical help at this moment.");
} else {
System.out.println("Hmmm...something does not look right. Please talk to your doctor about the issues presented in this form");
}
// Make an if, else if, else statement where the else if statement triggers
int Answer = 5;
if (Answer == 5) {
System.out.println("That's it! You got the question right - GREAT JOB!");
}
else if (Answer == 4) {
System.out.println("Darn! Your answer is incorrect. Try to get the next one right!");
} else if (Answer == 2) {
System.out.println("Darn! Your answer is incorrect. Try to get the next one right!");
} else if (Answer == -1) {
System.out.println("Darn! Your answer is incorrect. Try to get the next one right!");
} else {
System.out.println("Hmmm...something does not look right. We cannot accept that answer.");
}
// Make 2 variables and use them in an if else conditional
String name_1 = "Mike";
String name_2 = "Rachael";
if (name_1 == "Daniel") {
} if (name_2 == "Carol") {
System.out.println("Oh my! This computer recognizes this couple! They plan on going to prom together this year!");
} else {
System.out.println("That's a shame - that couple cannot be recognized.");
}
// Make an if statement using 2 variables and an AND(&&) statement
int Test_score_1 = 98;
int Test_score_2 = 74;
if (((Test_score_1 + Test_score_2) / 2) >=80 && ((Test_score_1 + Test_score_2) / 2) <90) {
System.out.println("Okay - after your test results and the rules of this class, both student will recieve a grade of 'B'.");
}
// Make an if statement using 2 variables and an OR(||) statement
String Exposure = "y";
String Test = "negative";
if (Exposure == "y" || Test == "positive") {
System.out.println("Oh no! Due to your recent close exposure with a community member positive for COVID-19 and/or your own positive COVID-19 test, you and anyone you live with should individually isolate for the next 10-14 days. Do not leave your room and monitor any symptoms that arise.");
}
###Output
Oh no! Due to your recent close exposure with a community member positive for COVID-19 and/or your own positive COVID-19 test, you and anyone you live with should individually isolate for the next 10-14 days. Do not leave your room and monitor any symptoms that arise.
###Markdown
Lab Two---For this lab we're going to get into logicOur Goals are:- Using Conditionals- Using Loops- Creating a Function- Using a Class
###Code
# Create an if statement
has_pasta = True
has_sauce = True
if has_pasta and has_sauce:
print ("Can make spaghetti")
# Create an if else statement
has_fishingrod = True
if has_fishingrod:
print ("We are going to fish")
else:
print ("We are going home")
# Create an if elif else statement
has_fishingrod = True
will_catchABigFish= True
will_eatGood = True
if has_fishingrod:
print ("We are going to Fish")
elif will_catchABigFish and will_eatGood:
print ("We will be full tonight anyways")
else:
print ("We will starve")
# Create a for loop using range(). Go from 0 to 9. Print out each number.
for value in range(10):
print (value)
# Create a for loop iterating through this list and printing out the value.
arr = ['Blue', 'Yellow', 'Red', 'Green', 'Purple', 'Magenta', 'Lilac']
for item in arr:
print (item)
# Get the length of the list above and print it.
for value in range(6):
print (value)
# Create a while loop that ends after 6 times through. Print something for each pass.
counter = 1
while counter != 7:
print("We have looped " + str(counter) + "times.")
counter = counter + 1
# Create a function to add 2 numbers together. Print out the number
def addition(num1, num2):
print(num1 + num2)
addition(25, 30)
# Create a function that tells you if a number is odd or even and print the result.
def evenorOdd(number1):
if (number1 % 2 == 0):
print("Is Even")
else:
print("Is Odd")
evenorOdd(21)
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed = breed
def info(self):
print("Name:", self.name)
print("Weight:", str(self.weight) + " Pounds")
print("Height:", str(self.height) + " Inches")
print("Breed:", self.breed)
myDog = Dog("Derrick", 24, 35, "Terrier")
myDog.info ()
###Output
Name: Derrick
Weight: 35 Pounds
Height: 24 Inches
Breed: Terrier
|
loop.ipynb | ###Markdown
###Code
1.
i = 1
while(i<=10):
print(i)
i += 1
2.
rows = 5
for i in range(rows,0,-1):
for j in range(i,0,-1):
print(j, end=' ')
print("\r")
3.
def getSum(n):
sum = 0
for digit in str(n):
sum += int(digit)
return sum
n=input()
print(getSum(n))
n = int(input("Nhap so: "))
sum = 0
for num in range(1, n + 1, 1):
sum = sum + num
print("Tong la: ", sum)
4.
num = int(input())
for i in range(1, 11):
print(num, 'x', i, '=', num * i)
5.
a = input([])
for x in range(len(a)):
print (a[x])
n=int(input("Nhap so: "))
count=0
while(n>0):
count=count+1
n=n//10
print("Tong cacs chu so:",count)
A=[1,2,3,4,5]
for i in reversed(A) :
print(i)
x=[-10,-9,-8,-7,-6,-5,-4,-3,-2,-1]
for i in x:
print (i)
lower = int(input("nhap khoang duoi: "))
upper = int(input("nhap khoang tren: "))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
n = int(input("So khoang"))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("nhap mot so")
elif nterms == 1:
print("Fibonacci chay den",n,":")
print(n1)
else:
print("Day Fibonacci:")
while count < n:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
num= int(input("number: "))
factorial = 1
if num < 0:
print("nhap sai")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
n=int(input("nhap so: "))
reverse=0
while(n>0):
dig=n%10
reverse=reverse*10+dig
n=n//10
print("So dao nguoc:",reverse)
list = [31, 13, 34, 85, 0, 99, 1, 3]
print("list la :")
print(list)
print("Cac so le la: ")
for i in range(1, len(list), 2):
print(list[i])
def cube(x):
return x * x * x
n = int(input(" Nhap so: "))
cube1 = cube(n)
print("Lap phuong cua {0} = {1}".format(n, cube1))
###Output
Nhap so: 7
Lap phuong cua 7 = 343
###Markdown
Loop and condition for loop and while loop
###Code
L =['appple','grape','greetings','kerosene','mobile']
for item in L:
print(item)
###Output
appple
grape
greetings
kerosene
mobile
###Markdown
Range
###Code
range(5),range(1,50),sum(range(50))
###Output
_____no_output_____
###Markdown
Iterating loop and adding the iterTing index to blank list
###Code
L = []
for k in range(10):
L.append(5*k) # multiple of 5
L
###Output
_____no_output_____
###Markdown
Double loop or nested for loop Create a double loop with i and j with range 10 and also populate the dictionary with key as (i,j) and value as 10*i +j when i=j and 100*i+j when i! =j
###Code
D ={}
for i in range(10):
for j in range(10):
if i == j:
D.update({(i,j) : 10*i +j})
elif i!= j:
D.update({(i,j) : 100*i +j})
print(D)
###Output
{(0, 0): 0, (0, 1): 1, (0, 2): 2, (0, 3): 3, (0, 4): 4, (0, 5): 5, (0, 6): 6, (0, 7): 7, (0, 8): 8, (0, 9): 9, (1, 0): 100, (1, 1): 11, (1, 2): 102, (1, 3): 103, (1, 4): 104, (1, 5): 105, (1, 6): 106, (1, 7): 107, (1, 8): 108, (1, 9): 109, (2, 0): 200, (2, 1): 201, (2, 2): 22, (2, 3): 203, (2, 4): 204, (2, 5): 205, (2, 6): 206, (2, 7): 207, (2, 8): 208, (2, 9): 209, (3, 0): 300, (3, 1): 301, (3, 2): 302, (3, 3): 33, (3, 4): 304, (3, 5): 305, (3, 6): 306, (3, 7): 307, (3, 8): 308, (3, 9): 309, (4, 0): 400, (4, 1): 401, (4, 2): 402, (4, 3): 403, (4, 4): 44, (4, 5): 405, (4, 6): 406, (4, 7): 407, (4, 8): 408, (4, 9): 409, (5, 0): 500, (5, 1): 501, (5, 2): 502, (5, 3): 503, (5, 4): 504, (5, 5): 55, (5, 6): 506, (5, 7): 507, (5, 8): 508, (5, 9): 509, (6, 0): 600, (6, 1): 601, (6, 2): 602, (6, 3): 603, (6, 4): 604, (6, 5): 605, (6, 6): 66, (6, 7): 607, (6, 8): 608, (6, 9): 609, (7, 0): 700, (7, 1): 701, (7, 2): 702, (7, 3): 703, (7, 4): 704, (7, 5): 705, (7, 6): 706, (7, 7): 77, (7, 8): 708, (7, 9): 709, (8, 0): 800, (8, 1): 801, (8, 2): 802, (8, 3): 803, (8, 4): 804, (8, 5): 805, (8, 6): 806, (8, 7): 807, (8, 8): 88, (8, 9): 809, (9, 0): 900, (9, 1): 901, (9, 2): 902, (9, 3): 903, (9, 4): 904, (9, 5): 905, (9, 6): 906, (9, 7): 907, (9, 8): 908, (9, 9): 99}
###Markdown
To iterate two elements from two seperate Lists. It is not like nested for loop.
###Code
for item ,j,k in zip(['apple','banana','kite','cellophone','pencil'],\
range(5),[12,34,55,36,87]):
print(item,"@",j,"@",k)
###Output
apple @ 0 @ 12
banana @ 1 @ 34
kite @ 2 @ 55
cellophone @ 3 @ 36
pencil @ 4 @ 87
###Markdown
To iterate and ennumerate both together
###Code
for i,item in enumerate(['pen','jug','copy','jellifish','blackhole']):
print("The",i,"th element is: ",item)
###Output
The 0 th element is: pen
The 1 th element is: jug
The 2 th element is: copy
The 3 th element is: jellifish
The 4 th element is: blackhole
###Markdown
To create a list with for loop
###Code
A = [35*k**2+12*k+1 for k in range(50)]
print(A)
B = [[6*x**2+5*y+3 for x in range(5)]for y in range(5)]
print(B)
###Output
[[3, 9, 27, 57, 99], [8, 14, 32, 62, 104], [13, 19, 37, 67, 109], [18, 24, 42, 72, 114], [23, 29, 47, 77, 119]]
###Markdown
To iterate over list of list
###Code
for i in range(5):
for j in range(5):
print("The","(",i,",",j,")","th element is:",B[i][j])
###Output
The ( 0 , 0 ) th element is: 3
The ( 0 , 1 ) th element is: 9
The ( 0 , 2 ) th element is: 27
The ( 0 , 3 ) th element is: 57
The ( 0 , 4 ) th element is: 99
The ( 1 , 0 ) th element is: 8
The ( 1 , 1 ) th element is: 14
The ( 1 , 2 ) th element is: 32
The ( 1 , 3 ) th element is: 62
The ( 1 , 4 ) th element is: 104
The ( 2 , 0 ) th element is: 13
The ( 2 , 1 ) th element is: 19
The ( 2 , 2 ) th element is: 37
The ( 2 , 3 ) th element is: 67
The ( 2 , 4 ) th element is: 109
The ( 3 , 0 ) th element is: 18
The ( 3 , 1 ) th element is: 24
The ( 3 , 2 ) th element is: 42
The ( 3 , 3 ) th element is: 72
The ( 3 , 4 ) th element is: 114
The ( 4 , 0 ) th element is: 23
The ( 4 , 1 ) th element is: 29
The ( 4 , 2 ) th element is: 47
The ( 4 , 3 ) th element is: 77
The ( 4 , 4 ) th element is: 119
###Markdown
While loop
###Code
i=0
while i<7:
print(i,"th turn")
i=i+1
###Output
0 th turn
1 th turn
2 th turn
3 th turn
4 th turn
5 th turn
6 th turn
###Markdown
To break for loop implementing if condition
###Code
for i in range(10):
print(i)
if i==5:
break
###Output
0
1
2
3
4
5
###Markdown
Testing of if conditions
###Code
import random as random
for i in range(10):
r = random.uniform(1,10)
if r<2 and r>0:
print("It is samaller than 2 and greater than 1","|", r)
elif r<4 and r>2:
print("It is samaller than 4 and greater than 2","|", r)
elif r<6 and r>4:
print("It is samaller than 6 and greater than 4","|", r)
elif r<8 and r>6:
print("It is samaller than 8 and greater than 6","|", r)
elif r<10 and r>8:
print("It is samaller than 10 and greater than 8","|", r)
import random as random
for i in range(5):
r = random.uniform(1,10)
if r<2 and r>0:
print("It is samaller than 2 and greater than 1","|", r)
elif r<4 and r>2:
print("It is samaller than 4 and greater than 2","|", r)
elif r<6 and r>4:
print("It is samaller than 6 and greater than 4","|", r)
elif r<8 and r>6:
print("It is samaller than 8 and greater than 6","|", r)
elif r<10 and r>8:
print("It is samaller than 10 and greater than 8","|", r)
import random as random
for i in range(10):
r = random.uniform(4,10)
if r<2 and r>0:
print("It is samaller than 2 and greater than 1","|", r)
elif r<4 and r>2:
print("It is samaller than 4 and greater than 2","|", r)
elif r<6 and r>4:
print("It is samaller than 6 and greater than 4","|", r)
elif r<8 and r>6:
print("It is samaller than 8 and greater than 6","|", r)
elif r<10 and r>8:
print("It is samaller than 10 and greater than 8","|", r)
###Output
It is samaller than 6 and greater than 4 | 4.956695200877877
It is samaller than 6 and greater than 4 | 4.772395956806793
It is samaller than 8 and greater than 6 | 6.122171687918092
It is samaller than 10 and greater than 8 | 9.545200432090455
It is samaller than 8 and greater than 6 | 7.97811315274013
It is samaller than 6 and greater than 4 | 4.060186758165481
It is samaller than 8 and greater than 6 | 7.8111012819566
It is samaller than 6 and greater than 4 | 4.330841020331907
It is samaller than 10 and greater than 8 | 8.03203613064867
It is samaller than 10 and greater than 8 | 9.55622724319506
###Markdown
To find the sum from 0 to 1000
###Code
s=0
for i in range(1000+1):
s=s+i
s
###Output
_____no_output_____
###Markdown
To find sum from 0 to 1000(only even)
###Code
s=0
se=[]
for i in range(1001):
if i%2==0:
se.append(i)
sum(se)
###Output
_____no_output_____
###Markdown
To find the sum from 0 to 1000(only odd)
###Code
s=0
so=[]
for i in range(1001):
if i%2==1:
so.append(i)
sum(so)
###Output
_____no_output_____
###Markdown
Loops and Conditions loops provides the methods of iteration while condition allows or blocks the code execution when specified conditionis meet. For Loop and while Loop
###Code
L = ['apple', 'banana','kite','cellphone']
for item in L:
print(item)
range(5), range(5,100), sum(range(100))
L=[]
for k in range(10):
L.append(10*k)
L
D = {}
for i in range(5):
for j in range(5):
if i == j :
D.update({(i,j) : 10*i+j})
elif i!=j :
D.update({(i,j): 100*i+j})
print(D)
for i, item in enumerate(['apple', 'banana','kite','cellphone']):
print("The",i,"th element is:", item)
A=[10*k**2+5*k+1 for k in range(10)]
print(A)
AA=[[10*x**2+5*y+1 for x in range(3)] for y in range(3)]
print(AA)
for i in range(3):
for j in range(3):
print("The", "(",i,",",j,")","th element is: ", AA[i][j])
i=0
while i<5:
print( i, "th turn")
i = i+1
for i in range(10):
print(i)
if i == 3:
break
import random as random
for i in range(10):
r = random.uniform(1,10)
if r<2 and r>0:
print("It is smaller than 2 and greater than 1","|",r)
elif r<4 and r>2:
print("It is smaller than 4 and greater than 2","|",r)
elif r<6 and r>4:
print("It is smaller tha 6 and greater than 4","|",r)
elif r<8 and r>6:
print("It is smaller than 8 and greate than 6","|",r)
elif r<10 and r>8:
print("It is smaller than 10 and greater than 8","|",r)
s = 0
for i in range(1000+1):
s = s+i
s
s = 0
LE = []
for i in range(1001):
if i%2 ==0:
LE.append(i)
s= s+i
s, sum(LE)
###Output
_____no_output_____ |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.