code
stringlengths
38
801k
repo_path
stringlengths
6
263
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Speech command prediction with federated learning # # This is an example of federated leraning for audio data # The objective of this model is to predict speech command correctly. # # I borrowed almost all codes from this repository. Thank a lot! # https://github.com/tugstugi/pytorch-speech-commands.git # We skip a few steps like WeightedRandomSampler and lr_scheduler for for simplicity # # Federated learning parts is taken from PySyft tutorial. # https://github.com/OpenMined/PySyft/blob/master/examples/tutorials/Part%2006%20-%20Federated%20Learning%20on%20MNIST%20using%20a%20CNN.ipynb # # you can learn # 1. how to handle audio datasets # 2. how to apply federated learning concepts on audio datasets # # + # fist let's do setup for jupyter note book # ignore warnings import warnings warnings.filterwarnings('ignore') # some jupyter specific settings # %reload_ext autoreload # %autoreload 2 # %matplotlib inline # - # import dependencies. # mostly torch relatd import torch from torchvision.transforms import Compose from torch.utils.data.sampler import WeightedRandomSampler from torch.utils.data import DataLoader from torch.utils.data import Dataset import torch.nn as nn import math import time from tqdm import * import os import librosa import numpy as np import random import shutil # then, we need set default type as torch.cuda.FloatTensor # you get type error without this as of 9/1/2020 torch.set_default_tensor_type(torch.cuda.FloatTensor) # # let's define tutorials objective here # # We're training a model which take audio wav file as input and output the index of speech commands. # # - Input: wav audio file # - Output: index of speech commands # # So it's a classification problem. # # In this tutorial, we have 12 classes to predict. # unknown, silence, yes, no, up, down, left, right, on, off, stop, go # let's define classes here # CLASSES = 'unknown, silence, yes, no, up, down, left, right, on, off, stop, go'.split(', ') # use subset of classes CLASSES = 'unknown, silence, yes, no, left, right'.split(', ') # # let's prepare datasets # # we download speech command datasets from here # http://download.tensorflow.org/data/speech_commands_v0.01.tar.gz # + # prepare datasets # create directory if not exist # we put data on datasets directory if os.path.isdir('./datasets') is False: try: os.mkdir('./datasets') except OSError: print ("Creation of the directory datasets failed") if os.path.isdir('./datasets/speech_commands') is True: print("datasets seems to exists.") else : # download data # ! wget -O datasets/speech_commands_v0.01.tar.gz http://download.tensorflow.org/data/speech_commands_v0.01.tar.gz # create directory os.mkdir('./datasets/speech_commands') # create audio directory if os.path.isdir('./datasets/speech_commands/audio') is False: try: os.mkdir('./datasets/speech_commands/audio') except OSError: print ("Creation of the directory datasets/speech_commands/audio failed") # untar files. # ! tar -xzf datasets/speech_commands_v0.01.tar.gz -C datasets/speech_commands/audio # + # once you downloaded datasets, # you can split datasets into training and validation datasets. # we split with csv file. # mode files def move_files(src_folder, to_folder, list_file): with open(list_file) as f: for line in f.readlines(): line = line.rstrip() dirname = os.path.dirname(line) dest = os.path.join(to_folder, dirname) if not os.path.exists(dest): os.mkdir(dest) shutil.move(os.path.join(src_folder, line), dest) # - # move files def prepare_dataset(): audio_folder = "datasets/speech_commands/audio" validation_path = "datasets/speech_commands/audio/validation_list.txt" test_path = "datasets/speech_commands/audio/testing_list.txt" valid_folder = "datasets/speech_commands/valid" test_folder = "datasets/speech_commands/test" train_folder = "datasets/speech_commands/train" if os.path.isdir(valid_folder) is False: os.mkdir(valid_folder) if os.path.isdir(test_folder) is False: os.mkdir(test_folder) move_files(audio_folder, test_folder, test_path) move_files(audio_folder, valid_folder, validation_path) os.rename(audio_folder, train_folder) # create datasets if os.path.isdir('./datasets/speech_commands/train') is False: prepare_dataset() # # Check datasets # # Now we have datasets. # Let's check one of data # + # seems like category is in the paths. # input data is wav audio file and output is index of "right" import IPython.display example_path = "datasets/speech_commands/train/right/9f4098cb_nohash_0.wav" IPython.display.Audio(example_path) # - # + # here we define functions to process audio. # basically convert raw audio into stft and convert stft into mel spectrogram and do some augmentation. # poits is since we deal with audio like images in this tutorial, we need every audio exact 1 seconds. # I mean all audio has exact same duration. # - # this is just returning true or false ramdomly def should_apply_transform(prob=0.5): """Transforms are only randomly applied with the given probability.""" return random.random() < prob # change ampletude for data augmentation class ChangeAmplitude(object): """Changes amplitude of an audio randomly.""" def __init__(self, amplitude_range=(0.7, 1.1)): self.amplitude_range = amplitude_range def __call__(self, data): if not should_apply_transform(): return data data['samples'] = data['samples'] * random.uniform(*self.amplitude_range) return data # change speedch and pitch for data augmentation class ChangeSpeedAndPitchAudio(object): """Change the speed of an audio. This transform also changes the pitch of the audio.""" def __init__(self, max_scale=0.2): self.max_scale = max_scale def __call__(self, data): if not should_apply_transform(): return data samples = data['samples'] sample_rate = data['sample_rate'] scale = random.uniform(-self.max_scale, self.max_scale) speed_fac = 1.0 / (1 + scale) data['samples'] = np.interp(np.arange(0, len(samples), speed_fac), np.arange(0,len(samples)), samples).astype(np.float32) return data # function to fix audio length # Because our architecture is not RNN-based but CNN-based, we need shapes of all input data exact same. class FixAudioLength(object): """Either pads or truncates an audio into a fixed length.""" def __init__(self, time=1): self.time = time def __call__(self, data): samples = data['samples'] sample_rate = data['sample_rate'] length = int(self.time * sample_rate) if length < len(samples): data['samples'] = samples[:length] elif length > len(samples): data['samples'] = np.pad(samples, (0, length - len(samples)), "constant") return data # convert raw audio samping into stft class ToSTFT(object): """Applies on an audio the short time fourier transform.""" def __init__(self, n_fft=2048, hop_length=512): self.n_fft = n_fft self.hop_length = hop_length def __call__(self, data): samples = data['samples'] sample_rate = data['sample_rate'] data['n_fft'] = self.n_fft data['hop_length'] = self.hop_length data['stft'] = librosa.stft(samples, n_fft=self.n_fft, hop_length=self.hop_length) data['stft_shape'] = data['stft'].shape return data class StretchAudioOnSTFT(object): """Stretches an audio on the frequency domain.""" def __init__(self, max_scale=0.2): self.max_scale = max_scale def __call__(self, data): if not should_apply_transform(): return data stft = data['stft'] sample_rate = data['sample_rate'] hop_length = data['hop_length'] scale = random.uniform(-self.max_scale, self.max_scale) stft_stretch = librosa.core.phase_vocoder(stft, 1+scale, hop_length=hop_length) data['stft'] = stft_stretch return data class TimeshiftAudioOnSTFT(object): """A simple timeshift on the frequency domain without multiplying with exp.""" def __init__(self, max_shift=8): self.max_shift = max_shift def __call__(self, data): if not should_apply_transform(): return data stft = data['stft'] shift = random.randint(-self.max_shift, self.max_shift) a = -min(0, shift) b = max(0, shift) stft = np.pad(stft, ((0, 0), (a, b)), "constant") if a == 0: stft = stft[:,b:] else: stft = stft[:,0:-a] data['stft'] = stft return data class FixSTFTDimension(object): """Either pads or truncates in the time axis on the frequency domain, applied after stretching, time shifting etc.""" def __call__(self, data): stft = data['stft'] t_len = stft.shape[1] orig_t_len = data['stft_shape'][1] if t_len > orig_t_len: stft = stft[:,0:orig_t_len] elif t_len < orig_t_len: stft = np.pad(stft, ((0, 0), (0, orig_t_len-t_len)), "constant") data['stft'] = stft return data # + # here we dedfine data augmentatio functions data_aug_transform = Compose([ ChangeAmplitude(), ChangeSpeedAndPitchAudio(), FixAudioLength(), ToSTFT(), StretchAudioOnSTFT(), TimeshiftAudioOnSTFT(), FixSTFTDimension()]) # - # # Background Noise Augmentation # Adding background noise on the fly is a good way to generalize audio model. # we send dataset to remote machines (workers) later with fedelted() command and it seems to be working. # But I haven't tested addig noise augmentation on real remote training settings. # # What if noise file does not exist on remote machine??? # here we define a way to add background noise class BackgroundNoiseDataset(Dataset): """Dataset for silence / background noise.""" def __init__(self, folder, transform=None, sample_rate=16000, sample_length=1): audio_files = [d for d in os.listdir(folder) if os.path.isfile(os.path.join(folder, d)) and d.endswith('.wav')] samples = [] for f in audio_files: path = os.path.join(folder, f) s, sr = librosa.load(path, sample_rate) samples.append(s) samples = np.hstack(samples) c = int(sample_rate * sample_length) r = len(samples) // c self.samples = samples[:r*c].reshape(-1, c) self.sample_rate = sample_rate self.classes = CLASSES self.transform = transform self.path = folder def __len__(self): return len(self.samples) def __getitem__(self, index): data = {'samples': self.samples[index], 'sample_rate': self.sample_rate, 'target': 1, 'path': self.path} if self.transform is not None: data = self.transform(data) return data # we pick background noise randomly. so use dataset class background_noise_dir = "./datasets/speech_commands/train/_background_noise_" bg_dataset = BackgroundNoiseDataset(background_noise_dir, data_aug_transform) # function to add background noise on datasets class AddBackgroundNoiseOnSTFT(Dataset): """Adds a random background noise on the frequency domain.""" def __init__(self, bg_dataset, max_percentage=0.45): self.bg_dataset = bg_dataset self.max_percentage = max_percentage def __call__(self, data): if not should_apply_transform(): return data noise = random.choice(self.bg_dataset)['stft'] percentage = random.uniform(0, self.max_percentage) data['stft'] = data['stft'] * (1 - percentage) + noise * percentage return data # create a function add_bg_noise = AddBackgroundNoiseOnSTFT(bg_dataset) # # MelSpectrogram # # In this tutorial we use mel spectrogram as input format. # Since our data format is still stft so far , this is the time to convert stft into mel spectrogram. # # mel spectrogram is one of best practices to handle audio data. # This blog explains mel spectrogram well. # https://towardsdatascience.com/getting-to-know-the-mel-spectrogram-31bca3e2d9d0 # # + # function to convert data from STFT into MelSpectrogram class ToMelSpectrogramFromSTFT(object): """Creates the mel spectrogram from the short time fourier transform of a file. The result is a 32x32 matrix.""" def __init__(self, n_mels=32): self.n_mels = n_mels def __call__(self, data): stft = data['stft'] sample_rate = data['sample_rate'] n_fft = data['n_fft'] mel_basis = librosa.filters.mel(sample_rate, n_fft, self.n_mels) s = np.dot(mel_basis, np.abs(stft)**2.0) data['mel_spectrogram'] = librosa.power_to_db(s, ref=np.max) return data # - class DeleteSTFT(object): """Pytorch doesn't like complex numbers, use this transform to remove STFT after computing the mel spectrogram.""" def __call__(self, data): del data['stft'] return data class ToTensor(object): """Converts into a tensor.""" def __init__(self, np_name, tensor_name, normalize=None): self.np_name = np_name self.tensor_name = tensor_name self.normalize = normalize def __call__(self, data): tensor = torch.FloatTensor(data[self.np_name]) if self.normalize is not None: mean, std = self.normalize tensor -= mean tensor /= std data[self.tensor_name] = tensor return data # + # make a couple of functions to one # set the feature count of mel spectrogram as 32. n_mels = 32 train_feature_transform = Compose([ ToMelSpectrogramFromSTFT(n_mels=n_mels), DeleteSTFT(), ToTensor('mel_spectrogram', 'input')]) # - # # Dataset Class # # So far... # - We download data. # - split data into training and valdation. # - define data augmentation # - define adding noise daga augmentation # - define functions to convert raw audio to stft format # - define funcitons to convert stft format into mel spectrogram format. # # lets use above to define dataset class # function to load audio. class LoadAudio(object): """Loads an audio into a numpy array.""" def __init__(self, sample_rate=16000): self.sample_rate = sample_rate def __call__(self, data): path = data['path'] if path: samples, sample_rate = librosa.load(path, self.sample_rate) else: # silence sample_rate = self.sample_rate samples = np.zeros(sample_rate, dtype=np.float32) data['samples'] = samples data['sample_rate'] = sample_rate return data # + # datasets class # you can try subset of entire datasets with use_rate because distributing datasets to remote machines take time... from random import shuffle from random import randrange class SpeechCommandsDataset(Dataset): """Google speech commands dataset. Only 'yes', 'no', 'up', 'down', 'left', 'right', 'on', 'off', 'stop' and 'go' are treated as known classes. All other classes are used as 'unknown' samples. See for more information: https://www.kaggle.com/c/tensorflow-speech-recognition-challenge """ def __init__(self, folder, transform=None, classes=CLASSES, silence_percentage=0.1, use_rate=1.0): all_classes = [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d)) and not d.startswith('_')] #for c in classes[2:]: # assert c in all_classes class_to_idx = {classes[i]: i for i in range(len(classes))} for c in all_classes: if c not in class_to_idx: class_to_idx[c] = 0 # we use subset of datasets # use 10 % of unkown. data = [] for c in all_classes: d = os.path.join(folder, c) target = class_to_idx[c] if c in classes: for f in os.listdir(d): path = os.path.join(d, f) data.append((path, target)) # else: # # add unkown # if randrange(10) < 1: # for f in os.listdir(d): # path = os.path.join(d, f) # data.append((path, target)) shuffle(data) if use_rate != 1.0: sample_count = int(len(data) * use_rate) data = data[:sample_count] # add silence target = class_to_idx['silence'] data += [('', target)] * int(len(data) * silence_percentage) self.classes = classes self.data = data self.transform = transform def __len__(self): return len(self.data) def __getitem__(self, index): path, target = self.data[index] data = {'path': path, 'target': target} if self.transform is not None: data = self.transform(data) return data['input'], target def make_weights_for_balanced_classes(self): """adopted from https://discuss.pytorch.org/t/balanced-sampling-between-classes-with-torchvision-dataloader/2703/3""" nclasses = len(self.classes) count = np.zeros(nclasses) for item in self.data: count[item[1]] += 1 N = float(sum(count)) weight_per_class = N / count weight = np.zeros(len(self)) for idx, item in enumerate(self.data): weight[idx] = weight_per_class[item[1]] return weight # + # finally we define dataset here # specify the percent of entire datasets # use_rate = 0.5 use_rate = 1.0 train_dataset_dir = "./datasets/speech_commands/train" train_dataset = SpeechCommandsDataset(train_dataset_dir, Compose([LoadAudio(), data_aug_transform, add_bg_noise, train_feature_transform]), use_rate=use_rate) # - # check data count len(train_dataset) # this is a function to create melSpectrogram datasets from audio directly to skip data augumentation # this is used in validation data class ToMelSpectrogram(object): """Creates the mel spectrogram from an audio. The result is a 32x32 matrix.""" def __init__(self, n_mels=32): self.n_mels = n_mels def __call__(self, data): samples = data['samples'] sample_rate = data['sample_rate'] s = librosa.feature.melspectrogram(samples, sr=sample_rate, n_mels=self.n_mels) data['mel_spectrogram'] = librosa.power_to_db(s, ref=np.max) return data valid_feature_transform = Compose([ ToMelSpectrogram(n_mels=n_mels), ToTensor('mel_spectrogram', 'input')]) # + # define validation datasets valid_dataset_dir = "./datasets/speech_commands/valid" valid_dataset = SpeechCommandsDataset(valid_dataset_dir, Compose([LoadAudio(), FixAudioLength(), valid_feature_transform])) # - len(valid_dataset) # # Dataloader # Finally we can apply federated learning here. # Validation datasets is just normal but we use PySyft library to split training dataset into 2 machines (workers) called Bob and Alice. # + # define dataloaders # batch size is 64 batch_size = 64 # we define training dataloader later right after importing PySyft, library for privacy preserving deep learning # define validation dataloader, which is just normal dataloader valid_dataloader = DataLoader(valid_dataset, batch_size=batch_size, shuffle=False) # - # # Setup for federated leaning # In this tutorial we traing our model with federated learning. # To do that, we do # - import syft # - create 2 machines (workders) called bob and alice # - split training datasets and send them to bob and alice # # Note: In real business situation, each machines should have data in the first place. import syft as sy # <-- NEW: import the Pysyft library hook = sy.TorchHook(torch) # <-- NEW: hook PyTorch ie add extra functionalities to support Federated Learning bob = sy.VirtualWorker(hook, id="bob") # <-- NEW: define remote worker bob alice = sy.VirtualWorker(hook, id="alice") # <-- NEW: and alice # defaine federated dataloader # it takes time. be patient. federated_train_loader = sy.FederatedDataLoader( train_dataset.federate((bob, alice)), batch_size=batch_size, ) # # Model # we define architecture here. # We use ResNet34 in this tutorial. # ResNet is one of popular architecture for image problems. # define conv block def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) # define res block class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out # define ResNet class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, in_channels=3): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) self.avgpool = nn.AvgPool2d(1, stride=1) self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) # x = x.view(x.size(0), -1) x = x.view(x.shape[0], -1) x = self.fc(x) return x # define resnet34 def resnet34(pretrained=False, **kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url('https://download.pytorch.org/models/resnet34-333f7ec4.pth')) return model # create model model = resnet34(num_classes=len(CLASSES), in_channels=1) # + # device setting. # pleas use gpu, this example is too heavy for cpu training. # if use_gpu: # device = torch.device("cuda") # else: # device = torch.device("cpu") device = torch.device("cuda") # - # move model to gpu if you use gpu model = model.to(device) # loss function is normal crossentrophy criterion = torch.nn.CrossEntropyLoss() # + from syft.federated.floptimizer import Optims # define optimizer # adamw seems to be better learning_rate = 1e-4 weight_decay = 1e-2 # from syft.federated.floptimizer import Optims # workers = ['bob', 'alice'] # optims = Optims(workers, optim=torch.optim.SGD(params=model.parameters(), lr=learning_rate )) from syft.federated.floptimizer import Optims workers = ['bob', 'alice'] optims = Optims(workers, optim=torch.optim.AdamW(params=model.parameters(), lr=learning_rate, weight_decay=weight_decay )) # - start_timestamp = int(time.time()*1000) start_epoch = 0 # max_epochs = 30 max_epochs = 12 # max_epochs = 1 best_accuracy = 0 best_loss = 1e100 global_step = 0 # ! ls -tl checkpoints # + # if you want to fine-tune model, make finetune True finetune = False if finetune is True: # load saved weights weight_path = "./checkpoints/best-acc-speech-commands-checkpoint-basic1.pth" state = torch.load( weight_path, map_location=torch.device("cpu")) _ = model.load_state_dict(state['state_dict']) # - # # Trining loop # + full_name = "speech_command_with_fl" def train(epoch): global global_step # print("epoch %3d with lr=%.02e" % (epoch, get_lr())) phase = 'train' model.train() # Set model to training mode running_loss = 0.0 it = 0 correct = 0 total = 0 # pbar = tqdm(train_dataloader, unit="audios", unit_scale=train_dataloader.batch_size) # use federated_train_loader pbar = tqdm(federated_train_loader, unit="audios", unit_scale=batch_size) for batch in pbar: inputs = batch[0] targets = batch[1] # get optimaizer on the same location with data _optimizer = optims.get_optim(inputs.location.id) # reset grad _optimizer.zero_grad() # send model to data.location model.send(inputs.location) inputs = torch.unsqueeze(inputs, 1) inputs = inputs.to(device) targets = targets.to(device) # forward/backward outputs = model(inputs) # get loss loss = criterion(outputs, targets) # backward and step loss.backward() _optimizer.step() # get model back model.get() # <-- NEW: get the model back # get loss back loss = loss.get() # <-- NEW: get the loss back # statistics it += 1 global_step += 1 # running_loss += loss.data[0] running_loss += loss.item() pred = outputs.max(1, keepdim=True)[1] # keep is to statistics _correct = pred.eq(targets.view_as(pred)).sum() correct += _correct.get().item() total += targets.shape[0] # update the progress bar pbar.set_postfix({ 'loss': "%.05f" % (running_loss / it), 'acc': "%.02f%%" % (100*correct/total) }) accuracy = correct/total epoch_loss = running_loss / it print('%s/accuracy' % phase, 100*accuracy, epoch) print('%s/epoch_loss' % phase, epoch_loss, epoch) # - def valid(epoch): global best_accuracy, best_loss, global_step phase = 'valid' # model.eval() # Set model to evaluate mode # for pysyft 0.2.8 you need training mode for batchnorm model.train() running_loss = 0.0 it = 0 correct = 0 total = 0 for batch in valid_dataloader: inputs = batch[0] targets = batch[1] inputs = torch.unsqueeze(inputs, 1) inputs = inputs.to(device) targets = targets.to(device) # forward outputs = model(inputs) loss = criterion(outputs, targets) # statistics it += 1 global_step += 1 running_loss += loss.item() pred = outputs.data.max(1, keepdim=True)[1] _correct = pred.eq(targets.view_as(pred)).sum().item() correct += _correct total += targets.size(0) accuracy = correct/total epoch_loss = running_loss / it print('%s/accuracy' % phase, 100*accuracy, epoch) print('%s/epoch_loss' % phase, epoch_loss, epoch) checkpoint = { 'epoch': epoch, 'step': global_step, 'state_dict': model.state_dict(), 'loss': epoch_loss, 'accuracy': accuracy, 'optimizer': optims.get_optim(bob.id).state_dict(), } if accuracy > best_accuracy: best_accuracy = accuracy torch.save(checkpoint, 'checkpoints/best-loss-speech-commands-checkpoint-%s.pth' % full_name) torch.save(model, '%d-%s-best-loss.pth' % (start_timestamp, full_name)) if epoch_loss < best_loss: best_loss = epoch_loss torch.save(checkpoint, 'checkpoints/best-acc-speech-commands-checkpoint-%s.pth' % full_name) torch.save(model, '%d-%s-best-acc.pth' % (start_timestamp, full_name)) torch.save(checkpoint, 'checkpoints/last-speech-commands-checkpoint.pth') del checkpoint # reduce memory return epoch_loss # + start_epoch = 0 if os.path.isdir('./checkpoints') is False: try: os.mkdir('./checkpoints') except OSError: print ("Creation of the directory %s failed" % path) since = time.time() for epoch in range(start_epoch, max_epochs): train(epoch) epoch_loss = valid(epoch) time_elapsed = time.time() - since time_str = 'total time elapsed: {:.0f}h {:.0f}m {:.0f}s '.format(time_elapsed // 3600, time_elapsed % 3600 // 60, time_elapsed % 60) print("finished") # - # + # raise Exception("stop") # - # # Evaluation # set default type torch.FloatTensor) torch.set_default_tensor_type(torch.FloatTensor) # + # First, let's see a data sample import IPython.display example_path = "./datasets/speech_commands/train/right/9f4098cb_nohash_0.wav" IPython.display.Audio(example_path) # - # define model again model2 = resnet34(num_classes=len(CLASSES), in_channels=1) # ! ls -lt checkpoints # + # load saved weights # weight_path2 = "./checkpoints/best-acc-speech-commands-checkpoint-basic1.pth" weight_path2 = "./checkpoints/best-acc-speech-commands-checkpoint-speech_command_with_fl.pth" state2 = torch.load( weight_path2, map_location=torch.device("cpu")) # - _ = model2.load_state_dict(state2['state_dict']) # + # load audio # this is exact steps to load validation datasets # our load audio function need this format sample_data = { 'path': example_path, } # load audio _load_audio = LoadAudio() _audio_sample = _load_audio(sample_data) len(_audio_sample["samples"]) # - # fix duration _fixAudioLength = FixAudioLength() _fixed_sample = _fixAudioLength(_audio_sample) # apply validation transform _processed_input = valid_feature_transform(_fixed_sample) # adjust shape _processed_input = _processed_input['input'][None][None] _processed_input.shape # get prediction # _ = model2.eval() # for pysyft 0.2.8 you need training mode for batchnorm _ = model2.eval() _eval_output = model2(_processed_input) _eval_pred = _eval_output.max(1, keepdim=True)[1] _eval_pred CLASSES
nbs/train_speech_command_federated-adamw.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Run MLFlow Model in Seldon Core # # This notebook shows how you can easily train a model using [MLFlow](https://mlflow.org/) and serve requests within Seldon Core on Kubernetes. # # Dependencies # # * ```pip install seldon-core``` # * ```pip install mlflow``` # # # ## Train Example MlFlow Model # !git clone https://github.com/mlflow/mlflow # !python mlflow/examples/sklearn_elasticnet_wine/train.py # ## Test Inference Locally # !pygmentize MyMlflowModel.py # !s2i build -E environment_rest . seldonio/seldon-core-s2i-python3:0.13 mlflow_model:0.1 # !docker run --name "mlflow_model" -d --rm -p 5000:5000 mlflow_model:0.1 # !curl -H "Content-Type: application/x-www-form-urlencoded" -g 0.0.0.0:5000/predict -d 'json={"data":{"names":["alcohol", "chlorides", "citric acid", "density", "fixed acidity", "free sulfur dioxide", "pH", "residual sugar", "sulphates", "total sulfur dioxide", "volatile acidity"],"ndarray":[[12.8, 0.029, 0.48, 0.98, 6.2, 29, 3.33, 1.2, 0.39, 75, 0.66]]}}' # !curl -H "Content-Type: application/x-www-form-urlencoded" -g 0.0.0.0:5000/predict -d 'json={"data":{"ndarray":[[12.8, 0.029, 0.48, 0.98, 6.2, 29, 3.33, 1.2, 0.39, 75, 0.66]]}}' # !docker rm mlflow_model --force # ## Test Inference on Minikube # # **Due to a [minikube/s2i issue](https://github.com/SeldonIO/seldon-core/issues/253) you will need [s2i >= 1.1.13](https://github.com/openshift/source-to-image/releases/tag/v1.1.13)** # !minikube start --memory 4096 # !kubectl create clusterrolebinding kube-system-cluster-admin --clusterrole=cluster-admin --serviceaccount=kube-system:default # !helm init # !kubectl rollout status deploy/tiller-deploy -n kube-system # !helm install ../../../helm-charts/seldon-core-operator --name seldon-core --set usageMetrics.enabled=true --namespace seldon-system # !kubectl rollout status deploy/seldon-controller-manager -n seldon-system # ## Setup Ingress # Please note: There are reported gRPC issues with ambassador (see https://github.com/SeldonIO/seldon-core/issues/473). # !helm install stable/ambassador --name ambassador --set crds.keep=false # !kubectl rollout status deployment.apps/ambassador # !eval $(minikube docker-env) && s2i build -E environment_rest . seldonio/seldon-core-s2i-python3:0.13 mlflow_model:0.1 # !kubectl create -f deployment.json # !kubectl rollout status deployment/mlflow-dep-mlflow-pred-d580056 # !seldon-core-api-tester contract.json `minikube ip` `kubectl get svc ambassador -o jsonpath='{.spec.ports[0].nodePort}'` \ # mlflow-example --namespace seldon -p # !minikube delete
examples/models/mlflow_model/mlflow.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Task #2 # # A template code for training an RBM on Rydberg atom data (the full dataset) is provided below. For the first part of this task (determining the minimum number of hidden units), start with 1 hidden units. # # Imports and loadining in data: # + import numpy as np import torch from RBM_helper import RBM from tqdm import tqdm import matplotlib.pyplot as plt import Rydberg_energy_calculator training_data = torch.from_numpy(np.loadtxt("Rydberg_data.txt")) # - # Define the RBM: # + def train_rbm(training_data,epochs,num_samples,n_vis,n_hin,N_draws=1000): ''' Train a restricted Boltzmann Machine Args: training_data: epochs: num_samples: N_draws: Returns: Array: An N_draw array containing the energies ''' # Instantiate the RBM rbm = RBM(n_vis, n_hin) # Carry out the training over the defined number of epochs for e in range(1, epochs+1): # do one epoch of training rbm.train(training_data) E_samples = np.zeros(N_draws) for k in tqdm(range(0,N_draws)): init_state = torch.zeros(num_samples, n_vis) RBM_samples = rbm.draw_samples(100, init_state) energies = Rydberg_energy_calculator.energy(RBM_samples, rbm.wavefunction) E_samples[k] = energies.item() return E_samples def confidence_interval(x): ''' Compute the 68% and 96% confidence inteval of a data set Args: x: numpy array Returns: Tuple: array1,array2 where array1 and array2 are each numpy arrays of length=3 array1 = [lower_68%_bound, median , upper_68%_bound] array2 = [lower_96%_bound, median , upper_96%_bound] ''' x_68 = np.percentile(x, [16,50,84]) x_96 = np.percentile(x, [2,50,98]) return x_68,x_96 # - # # Training the RBM as a function of the number of hidden layers # + epochs = 1000 num_samples = training_data.shape[0] exact_energy = -4.1203519096 tol = 3*1e-4 # The desired tolerance level n_hid_max=20 N_draws =50 # The number of samples to draw at the end for statistics n_hidden_array = [] E_68_nhidden = [] E_96_nhidden = [] for nk in range(1,n_hid_max,2): n_hidden_array.append(nk) n_training_data = training_data.shape[1] n_hin = nk E_samples = train_rbm(training_data,epochs,n_vis=n_training_data,n_hin=n_hin,num_samples=num_samples,N_draws=N_draws) E_68,E_96 = confidence_interval(E_samples) E_68_nhidden.append(E_68) E_96_nhidden.append(E_96) print(nk,E_68[1],exact_energy, abs(E_68[1]-exact_energy)) # + # Preprocess the results in order to generate the plot E_96_nhidden = np.array(E_96_nhidden) E_68_nhidden = np.array(E_68_nhidden) delta_E_med = abs(E_96_nhidden[:,1]-exact_energy) #/tol delta_E_lower_68 = abs(E_68_nhidden[:,0]-exact_energy)#/tol delta_E_upper_68 = abs(E_68_nhidden[:,2]-exact_energy)#/tol delta_E_lower_96 = abs(E_96_nhidden[:,0]-exact_energy)#/tol delta_E_upper_96 = abs(E_96_nhidden[:,2]-exact_energy)#/tol # Determine the number of hidden nodes required for uncertainty band to overlap tolerance level n_hidden_tol_indx = np.argmin(delta_E_med) n_hidden_tol = n_hidden_array[n_hidden_tol_indx] print('='*100) print('The minimum number of hidden units to reach tolerance level is: ',n_hidden_tol) print('='*100) # - # We now plot the achieved tolerance of the RBM as a function of the number of hidden units. plt.figure(figsize=(15,5)) plt.title(r'Number of hidden units vs $|\Delta E |$',size=15) plt.plot(n_hidden_array,delta_E_med,label='median',color='blue') plt.fill_between(n_hidden_array,delta_E_lower_68, delta_E_upper_68,color='blue',alpha='0.5',edgecolor='b') plt.fill_between(n_hidden_array,delta_E_lower_96, delta_E_upper_96,color='blue',alpha='0.2',edgecolor='b') plt.plot(n_hidden_array,tol*np.ones(len(n_hidden_array)),label='Tolerance level= '+str(round(tol,5)),color='r') plt.vlines( n_hidden_array[n_hidden_tol_indx],ymin=0,ymax=tol*1.3,label='tolerance-reached') plt.xlabel('N-hidden units',size=15) plt.ylabel(r'$|\Delta E|$ [eV]',size=15) plt.legend() plt.show() # From the above plot, we find that a reasonable tolerance level for the algorithm is tol=$3 \cdot 10^{-4}$. We have also drawn several samples from the final trained RBM in order to plot the 68% confidence bands in darker blue and the 96% confidence bands in lighter blue. # # At this level of tolerance, the best number of hidden units required to remain below the tolerance level was $n_{\rm hidden }=5$. # # Training the RBM as a function of the amount of data # # In the next blocks we keep the number of hidden layers fixed using the value we found in the previous blocks and vary the amount of data that we use for training. # + epochs = 1000 num_samples = training_data.shape[0] exact_energy = -4.1203519096 N_draws =50 # The number of samples to draw at the end n_samples_array = [] E_68_nsamples = [] E_96_nsamples = [] for nk in range(500,training_data.shape[0],2500): n_samples_array.append(nk) n_training_data = training_data.shape[1] n_hin = n_hidden_tol # The optimal number of hidden layers E_samples = train_rbm(training_data,epochs,n_vis=n_training_data,n_hin=n_hin,num_samples=nk,N_draws=N_draws) E_68,E_96 = confidence_interval(E_samples) E_68_nsamples.append(E_68) E_96_nsamples.append(E_96) # + E_96_nsamples = np.array(E_96_nsamples) E_68_nsamples= np.array(E_68_nsamples) ddelta_E_med = abs(E_68_nsamples[:,1]-exact_energy) ddelta_E_lower_68 = abs(E_68_nsamples[:,0]-exact_energy) ddelta_E_upper_68 = abs(E_68_nsamples[:,2]-exact_energy) ddelta_E_lower_96 = abs(E_96_nsamples[:,0]-exact_energy) ddelta_E_upper_96 = abs(E_96_nsamples[:,2]-exact_energy) # - # Finally we plot the median values of the achieved tolerance levels with the 68% and 96% confidence intervals. plt.figure(figsize=(15,5)) plt.title(r'Number of Data samples vs $|\Delta E |$',size=15) plt.plot(n_samples_array,ddelta_E_med,label='median',color='blue') plt.fill_between(n_samples_array,ddelta_E_lower_68, ddelta_E_upper_68,color='blue',alpha='0.5',edgecolor='b') plt.fill_between(n_samples_array,ddelta_E_lower_96, ddelta_E_upper_96,color='blue',alpha='0.2',edgecolor='b') plt.plot(n_samples_array,tol*np.ones(len(n_samples_array)),label='Tolerance level= '+str(round(tol,5)),color='red') plt.xlabel('Data samples',size=15) plt.ylabel(r'$|\Delta E|$ [eV]',size=15) plt.legend() plt.show() # From the above plot, we see that as the amount of training data increases, the variance of th results decreases. # The median of the achieved tolerance level remains about the same for all calculations. To achieve the # minimum variance/ amount of data samples, we need approximately $N_{\rm data}= 15,000$ training samples.
Project_1_RBM_and_Tomography/.ipynb_checkpoints/Task2-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ___ # # <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> # ___ # # Merging, Joining, and Concatenating # # There are 3 main ways of combining DataFrames together: Merging, Joining and Concatenating. In this lecture we will discuss these 3 methods with examples. # # ____ # ### Example DataFrames import pandas as pd df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}, index=[0, 1, 2, 3]) df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'], 'B': ['B4', 'B5', 'B6', 'B7'], 'C': ['C4', 'C5', 'C6', 'C7'], 'D': ['D4', 'D5', 'D6', 'D7']}, index=[4, 5, 6, 7]) df3 = pd.DataFrame({'A': ['A8', 'A9', 'A10', 'A11'], 'B': ['B8', 'B9', 'B10', 'B11'], 'C': ['C8', 'C9', 'C10', 'C11'], 'D': ['D8', 'D9', 'D10', 'D11']}, index=[8, 9, 10, 11]) df1 df2 df3 # ## Concatenation # # Concatenation basically glues together DataFrames. Keep in mind that dimensions should match along the axis you are concatenating on. You can use **pd.concat** and pass in a list of DataFrames to concatenate together: pd.concat([df1,df2,df3]) pd.concat([df1,df2,df3],axis=1) # _____ # ## Example DataFrames # + left = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'], 'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3']}) right = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}) # - left right # ___ # ## Merging # # The **merge** function allows you to merge DataFrames together using a similar logic as merging SQL Tables together. For example: pd.merge(left,right,how='inner',on='key') # Or to show a more complicated example: # + left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'], 'key2': ['K0', 'K1', 'K0', 'K1'], 'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3']}) right = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'], 'key2': ['K0', 'K0', 'K0', 'K0'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}) # - pd.merge(left, right, on=['key1', 'key2']) pd.merge(left, right, how='outer', on=['key1', 'key2']) pd.merge(left, right, how='right', on=['key1', 'key2']) pd.merge(left, right, how='left', on=['key1', 'key2']) # ## Joining # Joining is a convenient method for combining the columns of two potentially differently-indexed DataFrames into a single result DataFrame. # + left = pd.DataFrame({'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2']}, index=['K0', 'K1', 'K2']) right = pd.DataFrame({'C': ['C0', 'C2', 'C3'], 'D': ['D0', 'D2', 'D3']}, index=['K0', 'K2', 'K3']) # - left.join(right) left.join(right, how='outer') # # Great Job!
Data Science and Machine Learning Bootcamp - JP/03.Python-for-Data-Analysis-Pandas/06-Merging, Joining, and Concatenating.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # !pip install pyspark from pyspark.sql import SparkSession spark=SparkSession.builder.appName('App5').getOrCreate() spark from pyspark.sql import SparkSession spark=SparkSession.builder.appName('App5').getOrCreate() spark.read.option('header','true').csv('Salaries.csv').show() df_pyspark=spark.read.option('header','true').csv('Salaries.csv',inferSchema=True) df_pyspark.show() df_pyspark.printSchema() # + # GroupBy # - df_pyspark.groupBy('Country').sum('Salary') df_pyspark.groupBy('Country').sum('Salary').show() df_pyspark.groupBy('Country','City').sum('Salary').show() df_pyspark.groupBy('Country').mean('Salary').show() df_pyspark.select().count() df_pyspark.groupBy('Country').count().show() df_pyspark.agg({'Salary':'sum'}).show()
.ipynb_checkpoints/PySpark Dataframes -5- Aggregate and GroupBy-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python2 # --- # + import json # %run ../Python_files/util.py # tmc_ref_speed_dict.keys # AM: 7:00 am - 9:00 am # MD: 11:00 am - 13:00 pm # PM: 17:00 pm - 19:00 pm # NT: 21:00 pm - 23:00 pm data_folder = '/home/jzh/INRIX/All_INRIX_2012_filtered_journal/' # + month = 10 # Load JSON data input_file = data_folder + 'filtered_month_%s_%s_NT_dict_journal.json' %(month, 1) with open(input_file, 'r') as json_file: temp_dict_1 = json.load(json_file) input_file = data_folder + 'filtered_month_%s_%s_NT_dict_journal.json' %(month, 2) with open(input_file, 'r') as json_file: temp_dict_2 = json.load(json_file) input_file = data_folder + 'filtered_month_%s_%s_NT_dict_journal.json' %(month, 3) with open(input_file, 'r') as json_file: temp_dict_3 = json.load(json_file) input_file = data_folder + 'filtered_month_%s_%s_NT_dict_journal.json' %(month, 4) with open(input_file, 'r') as json_file: temp_dict_4 = json.load(json_file) input_file = data_folder + 'filtered_month_%s_%s_NT_dict_journal.json' %(month, 5) with open(input_file, 'r') as json_file: temp_dict_5 = json.load(json_file) input_file = data_folder + 'filtered_month_%s_%s_NT_dict_journal.json' %(month, 6) with open(input_file, 'r') as json_file: temp_dict_6 = json.load(json_file) input_file = data_folder + 'filtered_month_%s_%s_NT_dict_journal.json' %(month, 7) with open(input_file, 'r') as json_file: temp_dict_7 = json.load(json_file) input_file = data_folder + 'filtered_month_%s_%s_NT_dict_journal.json' %(month, 8) with open(input_file, 'r') as json_file: temp_dict_8 = json.load(json_file) # - temp_dict_1.update(temp_dict_2) temp_dict_1.update(temp_dict_3) temp_dict_1.update(temp_dict_4) temp_dict_1.update(temp_dict_5) temp_dict_1.update(temp_dict_6) temp_dict_1.update(temp_dict_7) temp_dict_1.update(temp_dict_8) # Writing JSON data input_file_NT = data_folder + 'filtered_month_%s_NT_dict_journal.json' %(month) with open(input_file_NT, 'w') as json_file_NT: json.dump(temp_dict_1, json_file_NT)
01_INRIX_data_preprocessing_journal18/INRIX_data_preprocessing_07_extract_speed_data_filter_dict_journal_merge_Oct_NT.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Implementacion inicial de k means # # ### En esta implementacion para hacerlo mas grafico se trabaja siempre con 3 clusters y dos dimensiones from sklearn.datasets import make_blobs import numpy as np import matplotlib.pyplot as plt x, y = make_blobs(n_samples = 1000) # ### Divide Data # Dividimos el data set en los clusters dependiendo del valor de x def divideData(x, y): x1 = np.array([x[i, :] for i in range(x.shape[0]) if y[i] == 0]) x2 = np.array([x[i, :] for i in range(x.shape[0]) if y[i] == 1]) x3 = np.array([x[i, :] for i in range(x.shape[0]) if y[i] == 2]) return x1, x2, x3 # ### Funcion para enseñar el dataset o para enseñar el movimiento de los centroides y el cambio de color de los puntos def show(x1, x2, x3, centroids = None): if x1.shape[0] != 0: plt.scatter(x1[:, 0], x1[:, 1], c="red", label = "c1") if x2.shape[0] != 0: plt.scatter(x2[:, 0], x2[:, 1], c="blue", label = "c2") if x2.shape[0] != 0: plt.scatter(x3[:, 0], x3[:, 1], c="green", label = "c3") if centroids is not None: plt.scatter(centroids[0, 0], centroids[0, 1], c="salmon", marker = "D", linewidths=5) plt.scatter(centroids[1, 0], centroids[1, 1], c="cyan", marker = "D", linewidths=5) plt.scatter(centroids[2, 0], centroids[2, 1], c="lime", marker = "D", linewidths=5) plt.legend() plt.show() x1, x2, x3 = divideData(x, y) show(x1, x2, x3) # ### Algoritmo k means # # Primero asignamos los datos al centroide, luego movemos el centroide de lugar y # repetimos esto hasta que no se perciba ningun cambio # + from scipy.spatial import distance from IPython.display import clear_output import time def calculateDistanceAndAssign(data, centroids): y = np.zeros(data.shape[0]) for i, d in enumerate(data): y[i] = np.argmin(np.array([distance.euclidean(d, centroid) for centroid in centroids])) return y def moveCentroid(x1, x2, x3): centroids = np.zeros((3, x1.shape[1])) centroids[0] = np.average(x1, axis = 0) centroids[1] = np.average(x2, axis = 0) centroids[2] = np.average(x3, axis = 0) return centroids def k_means_2d(data, n_clusters): min_x = np.min(data[:, 0]) max_x = np.max(data[:, 0]) min_y = np.min(data[:, 1]) max_y = np.max(data[:, 1]) centroids = np.column_stack(( np.random.uniform(low = min_x, high = max_x, size= (3,)), np.random.uniform(low = min_y, high = max_y, size= (3,)) )) y = np.zeros(data.shape[0]) changing = True while changing: y_new = calculateDistanceAndAssign(data, centroids) if np.array_equal(y, y_new): changing = False else: y = y_new print(y.shape) x1, x2, x3 = divideData(data, y) while x1.shape[0] == 0 or x2.shape[0] == 0 or x3.shape[0] == 0: print("empty_cluster!") centroids = np.column_stack(( np.random.uniform(low = min_x, high = max_x, size= (3,)), np.random.uniform(low = min_y, high = max_y, size= (3,)) )) y = calculateDistanceAndAssign(data, centroids) x1, x2, x3 = divideData(data, y) show(x1, x2, x3, centroids = centroids) clear_output(wait = True) time.sleep(0.5) centroids = moveCentroid(x1, x2, x3) show(x1, x2, x3, centroids = centroids) # - x, y = make_blobs(n_samples = 50) x1, x2, x3 = divideData(x, y) show(x1, x2, x3) k_means_2d(x, 3) # + # # # # # # # # # # # #
paralelismo/k_means/k_means_ilustrator.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Visualize the different participation loss functions that have been used # # This notebook should simply help to understand how the different loss definition for participation of neurons differ. Note, that participation is hard to phrase as loss, as it depends on the history of trials. # %matplotlib notebook from ipywidgets import * import numpy as np import matplotlib.pyplot as plt # ### Used sigmoid # # Here, we simply show how the sigmoid has to behave, when used in the loss defined below. At value 0, the sigmoid must evaluate to the desired participation level c. The sigmoid should additionally be shaped, such that derivations from the optimal trace lead to the two attractors 0 and 1 (neuron should be inactive or active if trace not optimal). # + K = 100 C = 0.5 shift = lambda k, c : 1/k * np.log((1-c)/c) sigmoid = lambda x, s, k : 1/(1+np.exp(-k * (x-s))) x = np.linspace(-1, 1, 1000) fig = plt.figure() plt.title('Sigmoid') ax = fig.add_subplot(1, 1, 1) line, = ax.plot(x, sigmoid(x, shift(K, C), K)) plt.axvline(x=0, linestyle='dashed', color='k') point, = ax.plot([0], [C], marker='o', markersize=3, color="red") def update_k(k = 100): global K K = k line.set_ydata(sigmoid(x, shift(K, C), K)) fig.canvas.draw() def update_c(c = 0.5): global C C=c line.set_ydata(sigmoid(x, shift(K, C), K)) point.set_ydata([C]) fig.canvas.draw() interact(update_k, k=(0.01,110, 0.1)); interact(update_c, c=(0.01,0.99, 0.01)); # - # ### A simple participation loss # # The simple loss definition here allows the trace to be maintained outside of the scope of backprop. I.e., the loss is defined as # # (gamma * trace(t-1) + (1-gamma) * x - c)^2 # # where trace(t-1) is an external input to the neural network (thus a constant for backprop). # # This loss definition has the severe drawback, that the optimum (minima) is heavily instable (jumping around). So optimization of this loss might be quite difficult. # + T2 = 0.5 # trace C2 = 0.5 # desired activity level g = 0.99 # gamma fpr exp. smoothing lr = 10000 # learning rate lambda loss = lambda x, c , t: lr * (g*t + (1-g)*x - c)**2 x2 = np.linspace(-100, 100, 1000) fig2 = plt.figure() plt.title('Participation Loss - simple') ax2 = fig2.add_subplot(1, 1, 1) line2, = ax2.plot(x2, loss(x2, C2, T2)) # root root = lambda c, t: -1/(1-g)*(g*t - c) point2, = ax2.plot([root(C2, T2)], [0], marker='o', markersize=3, color="red") def update_ts(t = 0.5): global T2 T2 = t line2.set_ydata(loss(x2, C2, T2)) point2.set_xdata([root(C2, T2)]) fig2.canvas.draw() def update_cs(c = 0.5): global C2 C2=c line2.set_ydata(loss(x2, C2, T2)) point2.set_xdata([root(C2, T2)]) fig2.canvas.draw() interact(update_ts, t=(0.01,0.99, 0.01)); interact(update_cs, c=(0.01,0.99, 0.01)); # - # ### Loss with clear attractors. # # This loss has two clear attractor, if the trace is non optimal (which are 0 and 1). Note, that when translated to binomial neurons, neurons can only have the values 0 or 1. Therefore, this loss definition is helpful to stabilize the optimization process and additionally to get a binary behavior of neurons. # + T3 = 0.5 # trace C3 = 0.5 # desired activity level g3 = 0.99 # gamma fpr exp. smoothing lr3 = 10000 # learning rate lambda root_old = lambda c, t: -1/(1-g3)*(g3*t - c) loss_f = lambda x, c , t: lr3 * (g3*t + (1-g3)*x - c + (1-g3)*(root_old(c,t)-sigmoid(c-t,shift(100.,c),100.)))**2 x3 = np.linspace(-1, 2, 1000) fig3 = plt.figure() plt.title('Participation Loss - stabilized') ax3 = fig3.add_subplot(1, 1, 1) line3, = ax3.plot(x3, loss_f(x3, C3, T3)) # root root_new = lambda c, t: -1/(1-g3)*(g3*t - c + (1-g3)*(root_old(c,t)-sigmoid(c-t,shift(100.,c),100.))) point3, = ax3.plot([root_new(C3, T3)], [0], marker='o', markersize=3, color="red") def update_tf(t = 0.5): global T3 T3 = t line3.set_ydata(loss_f(x3, C3, T3)) point3.set_xdata([root_new(C3, T3)]) fig3.canvas.draw() def update_cf(c = 0.5): global C3 C3=c line3.set_ydata(loss_f(x3, C3, T3)) point3.set_xdata([root_new(C3, T3)]) fig3.canvas.draw() interact(update_tf, t=(0.01,0.99, 0.01)); interact(update_cf, c=(0.01,0.99, 0.01)); # + # Here, we nicely see, that the loss wouldn't be convex anymore, as soon as we replace the last trace value with # the current trace value inside the sigmoid. However, for small gamma values it has almost no influence. delete_quotation_marks = """ T3 = 0.5 # trace C3 = 0.5 # desired activity level g3 = 0.5 # gamma fpr exp. smoothing lr3 = 10000 # learning rate lambda root_old = lambda c, t: -1/(1-g3)*(g3*t - c) loss_f = lambda x, c , t: lr3 * (g3*t + (1-g3)*x - c + (1-g3)*(root_old(c,t)-sigmoid(c-(g3*t + (1-g3)*x),shift(100.,c),100.)))**2 x3 = np.linspace(-1, 2, 1000) fig3 = plt.figure() plt.title('Participation Loss - stabilized') ax3 = fig3.add_subplot(1, 1, 1) line3, = ax3.plot(x3, loss_f(x3, C3, T3)) def update_tf(t = 0.5): global T3 T3 = t line3.set_ydata(loss_f(x3, C3, T3)) fig3.canvas.draw() def update_cf(c = 0.5): global C3 C3=c line3.set_ydata(loss_f(x3, C3, T3)) fig3.canvas.draw() interact(update_tf, t=(0.01,0.99, 0.01)); interact(update_cf, c=(0.01,0.99, 0.01)); """
sanity_check/participation_loss_visualization.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %matplotlib inline import pandas as pd idx = pd.IndexSlice from IPython.core.display import HTML css = open('style-table.css').read() + open('style-notebook.css').read() HTML('<style>{}</style>'.format(css)) # %%time cast = pd.DataFrame.from_csv('data/cast.csv', index_col=None) cast.head() # %%time release_dates = pd.read_csv('data/release_dates.csv', index_col=None, parse_dates=['date'], infer_datetime_format=True) release_dates.head() titles = cast[['title', 'year']].drop_duplicates().reset_index(drop=True) titles.head() # ### Years # + # 1. How many movies are listed in the `titles` dataframe? len(titles) # + # 1. What is the name and year of the very first movie ever made? titles.sort_values('year').head(1) # + # 1. How many years into the future does the IMDB database list movie titles? titles.sort_values('year').tail(3)#.year - 2015 # + # 1. How many movies listed in `titles` came out in 1950? len(titles[titles.year == 1950]) # or: (titles.year == 1950).sum() # + # 1. How many movies came out in 1960? len(titles[titles.year == 1960]) # + # 1. How many movies came out in each year of the 1970s? # (Hint: try a Python "for" loop.) for y in range(1970, 1980): print(y, (titles.year == y).sum()) # + # 1. How many movies came out during your own lifetime, # from the year of your birth through 2014? len(titles[(titles.year >= 1974) & (titles.year <= 2014)]) # + # 2. Use "value_counts" to determine how many movies came out # in each year of the 1970s. titles[titles.year // 10 == 197].year.value_counts().sort_index() # + # 3. Use "groupby" to determine how many movies came out in each year of the 1970s. titles.groupby('year').size().loc[1970:1979] # - # ### Titles # + # 1. What are the names of the movies made through 1906? titles[titles.year <= 1906][['title']] # + # 1. What movies have titles that fall between Star Trek and Star Wars in the alphabet? titles[(titles.title >= 'Star Trek') & (titles.title <= 'Star Wars')] # + # 2. Use an index and .loc[] to find the movies whose titles fall between Star Trek # and Star Wars in the alphabet. t = titles.copy() t = t.set_index('title').sort_index() t.loc['Star Trek':'Star Wars'] # + # 2. Use an index and .loc[] to retrieve the names of the movies made through 1906. titles.set_index('year').sort_index().loc[1800:1906] # + # 2. What are the 15 most common movie titles in film history? titles.title.value_counts().head(15) # + # Use this for session 3? i = cast.set_index('name').sort_index() # - a = i.loc['<NAME>',['year','n']].groupby('year').agg(['min', 'mean', 'max']) a.loc[:1942].plot(kind='area', stacked=False) a # + # 5. What are the 5 longest movie titles ever? pd.set_option('max_colwidth', 300) t = titles.copy() t['len'] = t.title.str.len() t = t.sort_values('len', ascending=False) t.head() # + # 5. What are the 15 most popular movie titles, if you strip off the suffixes like # (II) and (III) that the IMDB adds to distinguish movies shown in the same year? titles.title.str.extract('^([^(]*)').value_counts().head(15) # - # ### How many movies actors have been in # + # 1. How many movies has <NAME> acted in? len(cast[cast.name == '<NAME>']) # + # 1. How many movies did <NAME> appear in? c = cast c = c[c.name == '<NAME>'] len(c) # + # 1. In how many of his movies was <NAME> the lead (`n==1`)? c = cast c = c[c.name == '<NAME>'] c = c[c.n == 1] len(c) # - # ### Pulling and displaying movie credits # + # 1. List the movies, sorted by year, in which <NAME> starred as lead actor. c = cast c = c[c.name == '<NAME>'] c = c[c.n == 1] c.sort_values('year') # + # 1. Who was credited in the 1972 version of Sleuth, in order by `n` rank? c = cast c = c[c.title == 'Sleuth'] c = c[c.year == 1972] c.sort_values('n') # - # ### Common character names # + # 2. What are the 11 most common character names in movie history? cast.character.value_counts().head(11) # + # 3. Which actors have played the role “Zombie” the most times? c = cast c = c[c.character == 'Zombie'] c = c.groupby('name').size().order() c.tail(5) # + # 3. Which ten people have appeared most often as “Herself” over the history of film? c = cast c = c[c.character == 'Herself'] c = c.groupby('name').size().order() c.tail(10) # + # 3. Which ten people have appeared most often as “Himself” over the history of film? c = cast c = c[c.character == 'Himself'] c = c.groupby('name').size().order() c.tail(10) # + # 4. Take the 50 most common character names in film. # Which are most often played by men? c = cast clist = c.character.value_counts().head(50) clist.head() # - clist.tail() cast_by_character = cast.sort_values('character').set_index('character') c = cast_by_character.loc[clist.index][['type']] c = c.reset_index() c = c.groupby(['character', 'type']).size() c = c.unstack() c['ratio'] = c.actress / (c.actor + c.actress) c = c.sort_values('ratio') c.head() # + # 4. …which of those 50 characters are most often played by women? c.tail() # + # 4. …which of those 50 characters have a ratio closest to 0.5? c[(c.ratio > 0.4) & (c.ratio < 0.6)] # - # ### Who has been in the most movies # + # 2. Which actors or actresses appeared in the most movies in the year 1945? cast[cast.year == 1945].name.value_counts().head(10) # + # 2. Which actors or actresses appeared in the most movies in the year 1985? cast[cast.year == 1985].name.value_counts().head(10) # + # %%time # 2. Create a `cast_by_title_year` dataframe indexed by title and year # to use in the next few questions. cast_by_title_year = cast.set_index(['title', 'year']).sort_index() cast_by_title_year.head() # + # %%time # 2. Use `cast_by_title_year` to find the stars of the film Inception # and order them by `n` before displaying the top 10. cast_by_title_year.loc['Inception'].sort_values('n').head(10) # + # 2. Use `cast_by_title_year` to find the first 10 stars in the 1996 film Hamlet, # and order them by `n`. cast_by_title_year.loc['Hamlet',1996].sort_values('n').head(10) # + # %%time # 2. Write a `for` loop that, for the top 9 actors in the 1977 movie Star Wars, # determines how many movies they starred in after 1977. names = cast_by_title_year.loc['Star Wars',1977].sort_values('n').head(9).name for name in names: print(name, len(cast[(cast.name == name) & (cast.year > 1977)])) # + # 2. Create an indexed version of `cast` that, once built, lets you answer # the previous question with a `for` loop that finishes in under a second. i = cast.set_index('name').sort_index() # - # %%time for name in names: c = i.loc[name] c = c[c.year > 1977] #c = c[(c.character != 'Himself') & (c.character != 'Herself')] print(name, len(c)) # + # 3. How many people were cast in each of the movies named "Hamlet”? c = cast c = c[c.title == 'Hamlet'] c = c.groupby('year').size() c # - # + # 5. How many actors are in the cast of each version of Hamlet, # including Hamlets with IMDB name collisions like "Hamlet (II)" # and "Hamlet (III)"? [BAD] c = cast_by_title_year # c.loc['Hamlet':'Hamlet (Z'].index.value_counts() - Drat # c.loc['Hamlet':'Hamlet (Z'].groupby(level=0).size() - Drat # c.loc['Hamlet':'Hamlet (Z'].groupby(level=1).size() - Drat c.loc['Hamlet':'Hamlet (Z'].groupby(level=[0,1]).size() # Or: #c = cast[(cast.title >= 'Hamlet') & (cast.title < 'Hamlet (Z')] #c.groupby(['title', 'year']).size() # - # ### Actors and Actresses # + # 4. Build a dataframe with a row for each year with two columns: # the number of roles for actors in that year's films, # and the number of roles for actresses. aa = cast[['year', 'type']].groupby(['year', 'type']).size() aa = aa.loc[:2014].unstack() aa.head() # + # 4. Use that dataframe to make a kind='area' plot showing the total # number of roles available over the history of film. aa.plot(kind='area') # - f = aa.actor / (aa.actor + aa.actress) f.plot(ylim=[0,1], kind='area') c = cast #c = c[c.year // 10 == 198] c = c[c.n <= 3] c = c.groupby(['year', 'type', 'n']).size() c = c.unstack(1) c.swaplevel(0,1).loc[1].plot(ylim=0, kind='area') #f = c.actor / (c.actor + c.actress) #f = f.unstack() #f.plot(ylim=[0,1]) # ### Rank over time # + # 2. Define “leading actor” as an actor or actress whose `n==1` # and “supporting actor” as `n==2` — what is the average year # of all the supporting roles <NAME> has had? c = cast c = c[c.name == '<NAME>'] print(c[c.n == 2].year.mean()) # + # 2. What is the average year of <NAME>’s leading roles — # is her career moving forwards toward leading roles # or backwards towards supporting ones? print(c[c.n == 1].year.mean()) # + # 2. Did <NAME> move forward or back over his career? c = cast c = c[c.name == '<NAME>'] print(c[c.n == 2].year.mean()) print(c[c.n == 1].year.mean()) # + # 2. What about <NAME>? c = cast c = c[c.name == '<NAME>'] print(c[c.n == 2].year.mean()) print(c[c.n == 1].year.mean()) # - c = cast #c = c[c.year // 10 == 195] c = c[c.n.notnull()].groupby('name').n.agg(['size', 'mean']) c.head() c = c[c['size'] >= 10] c = c.sort_values('mean') c.head(60) # ### Release dates release_dates.head() # + # 5. In which month is a movie whose name starts with the text # "The Lord of the Rings" most likely to be released? r = release_dates r = r[r.title.str.startswith('The Lord of the Rings')] r = r[r.country == 'USA'] r.date.dt.month.value_counts() # + # 5. In which months is a movie whose name ends in the word "Christmas" # most likely to be released? r = release_dates r = r[r.title.str.endswith('Christmas')] r = r[r.country == 'USA'] r.date.dt.month.value_counts() # - rd = release_dates.set_index(['title', 'year']).sort_index() rd.head() rd.loc[[('#Beings', 2015), ('#Horror', 2015)]] c = cast c = c[c.name == '<NAME>'][['title', 'year']].drop_duplicates() #c = c.join(rd, ['title', 'year']) #c = c[c.country == 'USA'] #c.date.dt.month.value_counts().sort_index().plot(kind='bar') c.values # + # ASK # rd.loc[c] # rd.loc[c.values] # rd.loc[list(c.values)] # + # 5. In what months of the year have Helen Mirren movies been most often released? c = cast c = c[c.name == '<NAME>'][['title', 'year']].drop_duplicates() c = c.join(rd, ['title', 'year']) c = c[c.country == 'USA'] c.date.dt.month.value_counts().sort_index().plot(kind='bar') # + # 5. …<NAME> movies? c = cast c = c[c.name == '<NAME>'][['title', 'year']].drop_duplicates() c = c.join(rd, ['title', 'year']) c = c[c.country == 'USA'] c.date.dt.month.value_counts().sort_index().plot(kind='bar') # + # 5. …<NAME> movies? c = cast c = c[c.name == '<NAME>'][['title', 'year']].drop_duplicates() c = c.join(rd, ['title', 'year']) c = c[c.country == 'USA'] c.date.dt.month.value_counts().sort_index().plot(kind='bar') # + # %%time # 5. Use join() to build a table of release dates indexed by actor, # and use it to re-run the previous three questions efficiently. c = cast c = c[['name', 'title', 'year']] c = c.join(rd, ['title', 'year']) c = c[c.country == 'USA'] c = c.set_index('name').sort_index() releases = c releases.head() # - releases.loc['Tom Cruise'].date.dt.month.value_counts().sort_index().plot(kind='bar') # + # pivot(self, index=None, columns=None, values=None) # - cast.head() c = cast c = c[c.year >= 1990] c = c[c.year <= 1993] c = c[c.name == '<NAME>'] #c = c[c.title == 'Inception'] #c = c[c.n.notnull()] #c = c.pivot('name', 'year', 'title') c.fillna('') release_dates.head() r = release_dates r = r[r.title.str.startswith('Star Wars: Episode')] r = r[r.country.str.startswith('U')] r.pivot('title', 'country', 'date') #r.pivot('country', 'title', 'date') r = release_dates r = r[r.title.str.startswith('Star Wars: Episode')] r = r[r.country.str.startswith('U')] r.set_index(['title', 'country'])[['date']].unstack() cast.head() # + t = titles t.head() # - c = cast c = c[c.title == 'Hamlet'] c = c.set_index(['year', 'character'])#.unstack('type') c c = cast c = c[c.title == 'Hamlet'] c = c.set_index(['year', 'type'])#.unstack('type') c
pycon-pandas-tutorial/All.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # #### **Title**: HexTiles Element # # **Dependencies** Matplotlib # # **Backends** [Matplotlib](./HexTiles.ipynb), [Bokeh]('../bokeh/HexTiles.ipynb') import numpy as np import holoviews as hv hv.extension('matplotlib') # %output fig='svg' size=200 # ``HexTiles`` provide a representation of the data as a bivariate histogram useful for visualizing the structure in larger datasets. The ``HexTiles`` are computed by tesselating the x-, y-ranges of the data, storing the number of points falling in each hexagonal bin. By default ``HexTiles`` simply counts the data in each bin but it also supports weighted aggregations. Currently only linearly spaced bins are supported when using the bokeh backend. # # As a simple example we will generate 100,000 normally distributed points and plot them using ``HexTiles``: np.random.seed(44) hex_tiles = hv.HexTiles(np.random.randn(100000, 2)) hex_tiles.options(colorbar=True) # Note that the hover shows a ``Count`` by default, representing the number of points falling within each bin. # # It is also possible to provide additional value dimensions and define an ``aggregator`` to aggregate by value. If multiple value dimensions are defined the dimension to be colormapped may be defined using the ``size``. Note however that multiple value dimensions are allowed and will be displayed in the hover tooltip. # + xs, ys = np.random.randn(2, 1000) hex_with_values = hv.HexTiles((xs, ys, xs*(ys/2.), (xs**2)*ys), vdims=['Values', 'Hover Values']) hex_with_values.options(aggregator=np.sum) *\ hv.Points(hex_with_values).options(s=3, color='black') # - # By default ``HexTiles`` do not plot bins that do not contain any data but using the ``min_count`` option it is possible to plot bins with zero values as well or alternatively set a higher cutoff. Using this options can result in a more visually appealing plot particularly when overlaid with other elements. # # Here we will plot the same distributions as above and overlay a ``Bivariate`` plot of the same data: x, y = np.hstack([np.random.randn(2, 10000), np.random.randn(2, 10000)*0.8+2]) hex_two_distributions = hv.HexTiles((x, y)) hex_two_distributions.options(min_count=0) *\ hv.Bivariate(hex_two_distributions).options(show_legend=False, linewidth=3)
examples/reference/elements/matplotlib/HexTiles.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Function Arguments # # + def greet(name, msg): """ This function greets to person with the provided message """ print("Hello {0} , {1}".format(name, msg)) #call the function with arguments greet("satish", "Good Morning") # + #suppose if we pass one argument greet("satish") #will get an error # - # # Different Forms of Arguments # # 1. Default Arguments # We can provide a default value to an argument by using the assignment operator (=). # + def greet(name, msg="Good Morning"): """ This function greets to person with the provided message if message is not provided, it defaults to "Good Morning" """ print("Hello {0} , {1}".format(name, msg)) greet("satish", "Good Night") # - #with out msg argument greet("satish") # Once we have a default argument, all the arguments to its right must also have default values. # def greet(msg="Good Morning", name) # # #will get a SyntaxError : non-default argument follows default argument # # 2. Keyword Arguments # kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function # # Example: def greet(**kwargs): """ This function greets to person with the provided message """ if kwargs: print("Hello {0} , {1}".format(kwargs['name'], kwargs['msg'])) greet(name="satish", msg="Good Morning") # # 3. Arbitary Arguments # Sometimes, we do not know in advance the number of arguments that will be passed into a function.Python allows us to handle this kind of situation through function calls with arbitrary number of arguments. # # Example: # + def greet(*names): """ This function greets all persons in the names tuple """ print(names) for name in names: print("Hello, {0} ".format(name)) greet("satish", "murali", "naveen", "srikanth") # -
3.2.Function Arguments.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="09kv2dmwRq-i" # Theory: Multiple regression is a machine learning algorithm to predict a dependent variable with two or more predictors. Multiple regression has numerous real-world applications in three problem domains: examining relationships between variables, making numerical predictions and time series forecasting. # + [markdown] id="Zk18Qo98RIN-" # Importing Files # + id="qyRyvauvm9tT" import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from pandas.plotting import scatter_matrix # from sklearn.preprocessing import Imputer from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression # + [markdown] id="pDYQHJ_JRz_j" # impportiong dataset # + id="-7slA-IQOvJD" housing = pd.read_csv("/content/sample_data/california_housing_train.csv") # + colab={"base_uri": "https://localhost:8080/"} id="rTyIPoorO6Tb" outputId="77d910a5-95b0-4e5d-8d9c-c8d69d2abb82" print("The number of rows and colums are {} and also called shape of the matrix".format(housing.shape)) print("Columns names are \n {}".format(housing.columns)) # + colab={"base_uri": "https://localhost:8080/"} id="lVCdkBbeO7vV" outputId="ebb235df-976e-4519-c879-e196d29afcd2" print(housing.head()) # + colab={"base_uri": "https://localhost:8080/"} id="glPADzBWPAof" outputId="f0b9ce6f-0594-4b65-957a-ca633277cbce" print(housing.tail()) # + colab={"base_uri": "https://localhost:8080/"} id="J_X5NWWOPHgj" outputId="bfab8b2f-56c0-4866-e9ae-15ad75135a25" print(housing.dtypes) # + colab={"base_uri": "https://localhost:8080/", "height": 915} id="7ISnFUCBPPOg" outputId="c7040633-64eb-492a-b492-42a77a4a6ffb" fig = plt.figure() scatter_matrix(housing,figsize =(15,15),alpha=0.9,diagonal="kde",marker="o"); # + colab={"base_uri": "https://localhost:8080/", "height": 879} id="Oz3--3S_PY3c" outputId="50dba377-fd37-4b00-924b-7dd721d0778e" housing.hist(figsize=(15,15),bins=50); # + colab={"base_uri": "https://localhost:8080/"} id="Va-E78IUPpYF" outputId="186622c8-49a4-4bdd-e28f-eec948bc1736" housing.isnull().sum() # + colab={"base_uri": "https://localhost:8080/"} id="-hsJ2Ij2PtqQ" outputId="cc177845-5adf-42ff-9f19-5180df6c0fe0" print ("Total_bedrooms column Mode is "+str(housing["total_bedrooms"].mode())+"\n") print(housing["total_bedrooms"].describe()) # + colab={"base_uri": "https://localhost:8080/"} id="Ir88K8jVP50V" outputId="a6485b1c-b5de-4317-e85c-67076c27b5ed" housing_ind = housing.drop("median_house_value",axis=1) print(housing_ind.head()) housing_dep = housing["median_house_value"] print("Medain Housing Values") print(housing_dep.head()) # + colab={"base_uri": "https://localhost:8080/"} id="sqM5MV9fP-LN" outputId="ee95cfa2-8c0c-4dba-fb88-e7a8aa59be61" X_train,X_test,y_train,y_test = train_test_split(housing_ind,housing_dep,test_size=0.2,random_state=42) print(X_train.shape) print(y_train.shape) # + colab={"base_uri": "https://localhost:8080/"} id="ZX5NyLmEQep9" outputId="5b5af37d-1767-4b1b-b61e-a6cb67fa64f5" #initantiate the linear regression linearRegModel = LinearRegression(n_jobs=-1) #fit the model to the training data (learn the coefficients) linearRegModel.fit(X_train,y_train) #print the intercept and coefficients print("Intercept is "+str(linearRegModel.intercept_)) print("coefficients is "+str(linearRegModel.coef_)) # + id="NwG7PX7DQim8" y_pred = linearRegModel.predict(X_test) # + colab={"base_uri": "https://localhost:8080/"} id="30La2A-OQlfC" outputId="2b7c2fef-9c63-4a21-8926-74f077207251" print(len(y_pred)) print(len(y_test)) print(y_pred[0:5]) print(y_test[0:5]) # + colab={"base_uri": "https://localhost:8080/", "height": 907} id="-JQJpnmvQqxT" outputId="d9b84cc5-053b-419a-a01f-d7e189ad9248" test = pd.DataFrame({'Predicted':y_pred,'Actual':y_test}) fig= plt.figure(figsize=(16,8)) test = test.reset_index() test = test.drop(['index'],axis=1) plt.plot(test[:50]) plt.legend(['Actual','Predicted']) sns.jointplot(x='Actual',y='Predicted',data=test,kind='reg',);
MultipleRegression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="U2ha9OWxf0jw" # Lambda School Data Science # # *Unit 2, Sprint 3, Module 3* # # --- # + [markdown] colab_type="text" id="-hTictxWYih7" # # Permutation & Boosting # # - Get **permutation importances** for model interpretation and feature selection # - Use xgboost for **gradient boosting** # + [markdown] colab_type="text" id="wMejJg0w8v76" # ### Setup # # Run the code cell below. You can work locally (follow the [local setup instructions](https://lambdaschool.github.io/ds/unit2/local/)) or on Colab. # # Libraries: # # - category_encoders # - [**eli5**](https://eli5.readthedocs.io/en/latest/) # - matplotlib # - numpy # - pandas # - scikit-learn # - [**xgboost**](https://xgboost.readthedocs.io/en/latest/) # + colab={} colab_type="code" id="BFQMky3CYih-" # %%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/' # !pip install category_encoders==2.* # !pip install eli5 # If you're working locally: else: DATA_PATH = '../data/' # - # We'll go back to Tanzania Waterpumps for this lesson. # + colab={} colab_type="code" id="z-TExplb_Slf" import numpy as np import pandas as pd from sklearn.model_selection import train_test_split # Merge train_features.csv & train_labels.csv train = pd.merge(pd.read_csv(DATA_PATH+'waterpumps/train_features.csv'), pd.read_csv(DATA_PATH+'waterpumps/train_labels.csv')) # Read test_features.csv & sample_submission.csv test = pd.read_csv(DATA_PATH+'waterpumps/test_features.csv') sample_submission = pd.read_csv(DATA_PATH+'waterpumps/sample_submission.csv') # Split train into train & val train, val = train_test_split(train, train_size=0.80, test_size=0.20, stratify=train['status_group'], random_state=42) def wrangle(X): """Wrangle train, validate, and test sets in the same way""" # Prevent SettingWithCopyWarning X = X.copy() # About 3% of the time, latitude has small values near zero, # outside Tanzania, so we'll treat these values like zero. X['latitude'] = X['latitude'].replace(-2e-08, 0) # When columns have zeros and shouldn't, they are like null values. # So we will replace the zeros with nulls, and impute missing values later. # Also create a "missing indicator" column, because the fact that # values are missing may be a predictive signal. cols_with_zeros = ['longitude', 'latitude', 'construction_year', 'gps_height', 'population'] for col in cols_with_zeros: X[col] = X[col].replace(0, np.nan) X[col+'_MISSING'] = X[col].isnull() # Drop duplicate columns duplicates = ['quantity_group', 'payment_type'] X = X.drop(columns=duplicates) # Drop recorded_by (never varies) and id (always varies, random) unusable_variance = ['recorded_by', 'id'] X = X.drop(columns=unusable_variance) # Convert date_recorded to datetime X['date_recorded'] = pd.to_datetime(X['date_recorded'], infer_datetime_format=True) # Extract components from date_recorded, then drop the original column X['year_recorded'] = X['date_recorded'].dt.year X['month_recorded'] = X['date_recorded'].dt.month X['day_recorded'] = X['date_recorded'].dt.day X = X.drop(columns='date_recorded') # Engineer feature: how many years from construction_year to date_recorded X['years'] = X['year_recorded'] - X['construction_year'] X['years_MISSING'] = X['years'].isnull() # return the wrangled dataframe return X train = wrangle(train) val = wrangle(val) test = wrangle(test) # + colab={} colab_type="code" id="rhg8PQKt_jzP" # Arrange data into X features matrix and y target vector target = 'status_group' X_train = train.drop(columns=target) y_train = train[target] X_val = val.drop(columns=target) y_val = val[target] X_test = test # + colab={} colab_type="code" id="m8lB4z5l_eml" import category_encoders as ce from sklearn.impute import SimpleImputer from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline pipeline = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(strategy='median'), RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1) ) # Fit on train, score on val pipeline.fit(X_train, y_train) print('Validation Accuracy', pipeline.score(X_val, y_val)) # - # # Get permutation importances for model interpretation and feature selection # ## Overview # Default Feature Importances are fast, but Permutation Importances may be more accurate. # # These links go deeper with explanations and examples: # # - Permutation Importances # - [Kaggle / <NAME>: Machine Learning Explainability](https://www.kaggle.com/dansbecker/permutation-importance) # - [<NAME>: Interpretable Machine Learning](https://christophm.github.io/interpretable-ml-book/feature-importance.html) # - (Default) Feature Importances # - [Ando Saabas: Selecting good features, Part 3, Random Forests](https://blog.datadive.net/selecting-good-features-part-iii-random-forests/) # - [<NAME>, et al: Beware Default Random Forest Importances](https://explained.ai/rf-importance/index.html) # + [markdown] colab_type="text" id="7HOayKBOYiit" # There are three types of feature importances: # + [markdown] colab_type="text" id="4bRhsxENYiiu" # ### 1. (Default) Feature Importances # # Fastest, good for first estimates, but be aware: # # # # >**When the dataset has two (or more) correlated features, then from the point of view of the model, any of these correlated features can be used as the predictor, with no concrete preference of one over the others.** But once one of them is used, the importance of others is significantly reduced since effectively the impurity they can remove is already removed by the first feature. As a consequence, they will have a lower reported importance. This is not an issue when we want to use feature selection to reduce overfitting, since it makes sense to remove features that are mostly duplicated by other features. But when interpreting the data, it can lead to the incorrect conclusion that one of the variables is a strong predictor while the others in the same group are unimportant, while actually they are very close in terms of their relationship with the response variable. — [Selecting good features – Part III: random forests](https://blog.datadive.net/selecting-good-features-part-iii-random-forests/) # # # # > **The scikit-learn Random Forest feature importance ... tends to inflate the importance of continuous or high-cardinality categorical variables.** ... Breiman and Cutler, the inventors of Random Forests, indicate that this method of “adding up the gini decreases for each individual variable over all trees in the forest gives a **fast** variable importance that is often very consistent with the permutation importance measure.” — [Beware Default Random Forest Importances](https://explained.ai/rf-importance/index.html) # # # # + colab={} colab_type="code" id="BNVm6f7mYiiu" # Get feature importances rf = pipeline.named_steps['randomforestclassifier'] importances = pd.Series(rf.feature_importances_, X_train.columns) # Plot feature importances # %matplotlib inline import matplotlib.pyplot as plt n = 20 plt.figure(figsize=(10,n/2)) plt.title(f'Top {n} features') importances.sort_values()[-n:].plot.barh(color='grey'); # + [markdown] colab_type="text" id="y8HzLcCBYiiv" # ### 2. Drop-Column Importance # # The best in theory, but too slow in practice # + colab={} colab_type="code" id="DQAOlERnYiiw" column = 'quantity' # Fit without column pipeline = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(strategy='median'), RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1) ) pipeline.fit(X_train.drop(columns=column), y_train) score_without = pipeline.score(X_val.drop(columns=column), y_val) print(f'Validation Accuracy without {column}: {score_without}') # Fit with column pipeline = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(strategy='median'), RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1) ) pipeline.fit(X_train, y_train) score_with = pipeline.score(X_val, y_val) print(f'Validation Accuracy with {column}: {score_with}') # Compare the error with & without column print(f'Drop-Column Importance for {column}: {score_with - score_without}') # + [markdown] colab_type="text" id="6Vu39wGkYiix" # ### 3. Permutation Importance # # Permutation Importance is a good compromise between Feature Importance based on impurity reduction (which is the fastest) and Drop Column Importance (which is the "best.") # # [The ELI5 library documentation explains,](https://eli5.readthedocs.io/en/latest/blackbox/permutation_importance.html) # # > Importance can be measured by looking at how much the score (accuracy, F1, R^2, etc. - any score we’re interested in) decreases when a feature is not available. # > # > To do that one can remove feature from the dataset, re-train the estimator and check the score. But it requires re-training an estimator for each feature, which can be computationally intensive. ... # > # >To avoid re-training the estimator we can remove a feature only from the test part of the dataset, and compute score without using this feature. It doesn’t work as-is, because estimators expect feature to be present. So instead of removing a feature we can replace it with random noise - feature column is still there, but it no longer contains useful information. This method works if noise is drawn from the same distribution as original feature values (as otherwise estimator may fail). The simplest way to get such noise is to shuffle values for a feature, i.e. use other examples’ feature values - this is how permutation importance is computed. # > # >The method is most suitable for computing feature importances when a number of columns (features) is not huge; it can be resource-intensive otherwise. # + [markdown] colab_type="text" id="GYCiEx7zYiiy" # ### Do-It-Yourself way, for intuition # + colab={} colab_type="code" id="TksOf_n2Yiiy" # How to permute of shuffle a column # Before: sequence of feature to be permuted feature = 'quantity' X_val[feature].head() # + #before: dist X_val[feature].value_counts() # - # shuffle time X_val_permuted = X_val.copy() X_val_permuted[feature] = np.random.permutation(X_val[feature]) # Check the sequence changed X_val_permuted[feature].head() # AFter: Dist. Dist the same X_val_permuted[feature].value_counts() # get permiuation importance, no refit needed score_permuted = pipeline.score(X_val_permuted, y_val) print('val acc with feature', score_with) print(score_permuted) print('diff:', (score_with - score_permuted)) # + # Rerun with diff feature feature = 'wpt_name' X_val_permuted = X_val.copy() X_val_permuted[feature] = np.random.permutation(X_val[feature]) score_permuted = pipeline.score(X_val_permuted, y_val) print('val acc with feature', score_with) print(score_permuted) print('diff:', (score_with - score_permuted)) # + [markdown] colab_type="text" id="0LYk19SNYii7" # ### With eli5 library # # For more documentation on using this library, see: # - [eli5.sklearn.PermutationImportance](https://eli5.readthedocs.io/en/latest/autodocs/sklearn.html#eli5.sklearn.permutation_importance.PermutationImportance) # - [eli5.show_weights](https://eli5.readthedocs.io/en/latest/autodocs/eli5.html#eli5.show_weights) # - [scikit-learn user guide, `scoring` parameter](https://scikit-learn.org/stable/modules/model_evaluation.html#the-scoring-parameter-defining-model-evaluation-rules) # # eli5 doesn't work with pipelines. # + colab={} colab_type="code" id="hpSemTkFFP8i" # Ignore warnings transformers = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(strategy='median') ) X_train_transformed = transformers.fit_transform(X_train) X_val_transformed = transformers.transform(X_val) model = RandomForestClassifier(n_estimators=100, random_state= 42) model.fit(X_train_transformed, y_train) # + import eli5 from eli5.sklearn import PermutationImportance permuter = PermutationImportance( model, scoring= 'accuracy', n_iter = 5, random_state=42 ) permuter.fit(X_val_transformed, y_val) # - feature_names = X_val.columns.tolist() pd.Series(permuter.feature_importances_, feature_names).sort_values() # 2. display permutaiton importances eli5.show_weights( permuter, top=None, # number of features to show, no limit feature_names= feature_names, # must be a list ) # + [markdown] colab_type="text" id="q07yW9k-Yii8" # ### We can use importances for feature selection # # For example, we can remove features with zero importance. The model trains faster and the score does not decrease. # + colab={} colab_type="code" id="tZrPFyEMYii9" print('shape before remove', X_train.shape) # - minimum_importance = 0 mask = permuter.feature_importances_ > minimum_importance features= X_train.columns[mask] X_train = X_train[features] # shape after X_train.shape # + X_val = X_val[features] pipeline = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(strategy='median'), RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1) ) # Fit on train, score on val pipeline.fit(X_train, y_train) print('Validation Accuracy', pipeline.score(X_val, y_val)) # + [markdown] colab_type="text" id="fl67bCR7WY6j" # # Use xgboost for gradient boosting # - # ## Overview # In the Random Forest lesson, you learned this advice: # # #### Try Tree Ensembles when you do machine learning with labeled, tabular data # - "Tree Ensembles" means Random Forest or **Gradient Boosting** models. # - [Tree Ensembles often have the best predictive accuracy](https://arxiv.org/abs/1708.05070) with labeled, tabular data. # - Why? Because trees can fit non-linear, non-[monotonic](https://en.wikipedia.org/wiki/Monotonic_function) relationships, and [interactions](https://christophm.github.io/interpretable-ml-book/interaction.html) between features. # - A single decision tree, grown to unlimited depth, will [overfit](http://www.r2d3.us/visual-intro-to-machine-learning-part-1/). We solve this problem by ensembling trees, with bagging (Random Forest) or **[boosting](https://www.youtube.com/watch?v=GM3CDQfQ4sw)** (Gradient Boosting). # - Random Forest's advantage: may be less sensitive to hyperparameters. **Gradient Boosting's advantage:** may get better predictive accuracy. # Like Random Forest, Gradient Boosting uses ensembles of trees. But the details of the ensembling technique are different: # # ### Understand the difference between boosting & bagging # # Boosting (used by Gradient Boosting) is different than Bagging (used by Random Forests). # # Here's an excerpt from [_An Introduction to Statistical Learning_](http://www-bcf.usc.edu/~gareth/ISL/ISLR%20Seventh%20Printing.pdf) Chapter 8.2.3, Boosting: # # >Recall that bagging involves creating multiple copies of the original training data set using the bootstrap, fitting a separate decision tree to each copy, and then combining all of the trees in order to create a single predictive model. # > # >**Boosting works in a similar way, except that the trees are grown _sequentially_: each tree is grown using information from previously grown trees.** # > # >Unlike fitting a single large decision tree to the data, which amounts to _fitting the data hard_ and potentially overfitting, the boosting approach instead _learns slowly._ Given the current model, we fit a decision tree to the residuals from the model. # > # >We then add this new decision tree into the fitted function in order to update the residuals. Each of these trees can be rather small, with just a few terminal nodes. **By fitting small trees to the residuals, we slowly improve fˆ in areas where it does not perform well.** # > # >Note that in boosting, unlike in bagging, the construction of each tree depends strongly on the trees that have already been grown. # # This high-level overview is all you need to know for now. If you want to go deeper, we recommend you watch the StatQuest videos on gradient boosting! # Let's write some code. We have lots of options for which libraries to use: # # #### Python libraries for Gradient Boosting # - [scikit-learn Gradient Tree Boosting](https://scikit-learn.org/stable/modules/ensemble.html#gradient-boosting) — slower than other libraries, but [the new version may be better](https://twitter.com/amuellerml/status/1129443826945396737) # - Anaconda: already installed # - Google Colab: already installed # - [xgboost](https://xgboost.readthedocs.io/en/latest/) — can accept missing values and enforce [monotonic constraints](https://xiaoxiaowang87.github.io/monotonicity_constraint/) # - Anaconda, Mac/Linux: `conda install -c conda-forge xgboost` # - Windows: `conda install -c anaconda py-xgboost` # - Google Colab: already installed # - [LightGBM](https://lightgbm.readthedocs.io/en/latest/) — can accept missing values and enforce [monotonic constraints](https://blog.datadive.net/monotonicity-constraints-in-machine-learning/) # - Anaconda: `conda install -c conda-forge lightgbm` # - Google Colab: already installed # - [CatBoost](https://catboost.ai/) — can accept missing values and use [categorical features](https://catboost.ai/docs/concepts/algorithm-main-stages_cat-to-numberic.html) without preprocessing # - Anaconda: `conda install -c conda-forge catboost` # - Google Colab: `pip install catboost` # In this lesson, you'll use a new library, xgboost — But it has an API that's almost the same as scikit-learn, so it won't be a hard adjustment! # # #### [XGBoost Python API Reference: Scikit-Learn API](https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.sklearn) # + colab={} colab_type="code" id="wsnJRKjfWYph" from xgboost import XGBClassifier # - pipeline = make_pipeline( ce.OrdinalEncoder(), # SimpleImputer(strategy='median'), missing values accepted in this XGBClassifier(n_estimators=100, random_state=42, n_jobs=-1) ) pipeline.fit(X_train, y_train) # + from sklearn.metrics import accuracy_score y_pred = pipeline.predict(X_val) print('val accuracy:', accuracy_score(y_val,y_pred)) # not as good, because need to tune hyperparameters # + [markdown] colab_type="text" id="eCjVSlD_XJr2" # #### [Avoid Overfitting By Early Stopping With XGBoost In Python](https://machinelearningmastery.com/avoid-overfitting-by-early-stopping-with-xgboost-in-python/) # # Why is early stopping better than a For loop, or GridSearchCV, to optimize `n_estimators`? # # With early stopping, if `n_iterations` is our number of iterations, then we fit `n_iterations` decision trees. # # With a for loop, or GridSearchCV, we'd fit `sum(range(1,n_rounds+1))` trees. # # But it doesn't work well with pipelines. You may need to re-run multiple times with different values of other parameters such as `max_depth` and `learning_rate`. # # #### XGBoost parameters # - [Notes on parameter tuning](https://xgboost.readthedocs.io/en/latest/tutorials/param_tuning.html) # - [Parameters documentation](https://xgboost.readthedocs.io/en/latest/parameter.html) # # + colab={} colab_type="code" id="ZNX3IKftXBFS" # Early stopping, encoder = ce.OrdinalEncoder() X_train_encoded = encoder.fit_transform(X_train) X_val_encoded = encoder.transform(X_val) model = XGBClassifier( n_estimators= 1000, # up to 1000, depends on early stop max_depth = 7, learning_rate= 0.5, # try higher learning rate ) eval_set = [(X_train_encoded, y_train), (X_val_encoded, y_val)] model.fit(X_train_encoded,y_train, eval_set = eval_set, eval_metric= 'merror', early_stopping_rounds = 50) #stop if score not improved in 50 rounds # + # PLot them results = model.evals_result() train_error = results['validation_0']['merror'] validation_error = results['validation_1']['merror'] epoch = list(range(1, len(train_error)+1)) plt.plot(epoch, train_error, label = "Train") plt.plot(epoch, validation_error, label = 'Validation') plt.ylabel("Classification Error") plt.xlabel('Model Complexity') plt.legend() plt.title("Validation curve for XGBoost model") plt.ylim((0.18,0.22)) # zoom # + [markdown] colab_type="text" id="ZF7-ml6BhRRf" # ### Try adjusting these hyperparameters # # #### Random Forest # - class_weight (for imbalanced classes) # - max_depth (usually high, can try decreasing) # - n_estimators (too low underfits, too high wastes time) # - min_samples_leaf (increase if overfitting) # - max_features (decrease for more diverse trees) # # #### Xgboost # - scale_pos_weight (for imbalanced classes) # - max_depth (usually low, can try increasing) # - n_estimators (too low underfits, too high wastes time/overfits) — Use Early Stopping! # - learning_rate (too low underfits, too high overfits) # # For more ideas, see [Notes on Parameter Tuning](https://xgboost.readthedocs.io/en/latest/tutorials/param_tuning.html) and [DART booster](https://xgboost.readthedocs.io/en/latest/tutorials/dart.html). # - # ## Challenge # # You will use your portfolio project dataset for all assignments this sprint. Complete these tasks for your project, and document your work. # # - Continue to clean and explore your data. Make exploratory visualizations. # - Fit a model. Does it beat your baseline? # - Try xgboost. # - Get your model's permutation importances. # # You should try to complete an initial model today, because the rest of the week, we're making model interpretation visualizations. # # But, if you aren't ready to try xgboost and permutation importances with your dataset today, you can practice with another dataset instead. You may choose any dataset you've worked with previously.
module3-permutation-boosting/LS_DS_233.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="PvOw_n8bVvLK" # # Solving Linear Systems # + id="04ALkqV7VuSD" import numpy as np import matplotlib.pyplot as plt import torch import tensorflow as tf # + [markdown] id="uWRPU_kpV2Sm" # ## 4.1 The Substitution Strategy # **Method 1: Substitution** # - Use whenever there's a variable in system with coefficient of 1, use the following trick! For the following system: # # $$ y = 3x $$ # $$ -5x + 2y = 2 $$ # # Re-arrange the equation of isolate an unknown - $ y$: # $$ 2y = 2 + 5x $$ # $$ y = \frac{2 + 5x}{2} = 1 + \frac{5x}{2} $$ # # + id="k0OZOAr93RaY" x = np.linspace(-10, 10, 1000) # starta, finish, n points y1 = 3 * x y2 = 1 + (5 * x) /2 # + colab={"base_uri": "https://localhost:8080/", "height": 360} id="_Cese6-I3lZM" outputId="a3ca1ebb-a103-4c29-eec8-a29092973475" fig, ax = plt.subplots(figsize=(8, 5)) plt.title('System of equations', fontsize=20) plt.xlabel('x', fontsize=15) plt.ylabel('y', fontsize=15) ax.set_xlim([0, 3.0]) ax.set_ylim([0, 8]) ax.plot(x, y1, color='green') ax.plot(x, y2, color='red') plt.axvline(2.0, color='purple', linestyle='--') plt.axhline(6, color='purple', linestyle='--') plt.show() # + [markdown] id="JJTWn6XNV8vu" # ## 4.2 Substitution Exercises # + [markdown] id="KM6P0JVUZF-O" # 1. # $x + y = 6$ # $2x + 3y = 16$ # <br /> # 2. # $-x + 4y = 0$ # $2x - 5y = -6$ # <br /> # 3. # $y = 4x + 1$ # $-4x + y = 2$ # <br /> # <br /> # $(x, y) = (2, 4)$ <br /> # $(x, y) = (-8, -2)$ <br /> # $No solution!$ # + colab={"base_uri": "https://localhost:8080/", "height": 338} id="4d7cCFoJ5sQP" outputId="fd3a0f55-3a4f-4d26-843b-ac4d9fa63a5b" fig, ax = plt.subplots(1, 3, figsize=(18, 5)) y1 = 6 - x y2 = (16 - (2 * x)) / 3 y3 = x / 4 y4 = ((2 * x) + 6) / 5 y5 = 4*x + 1 y6 = 2 + 4 * x ax[0].set_title('1 solution', fontsize=15) ax[0].set_xlim([-5, 10]) ax[0].set_ylim([-5, 15]) ax[0].plot(x, y1, color='red') ax[0].plot(x, y2, color='green') ax[1].set_title('1 solution', fontsize=15) ax[1].set_xlim([-10, 0]) ax[1].set_ylim([-3, 0]) ax[1].plot(x, y3, color='red') ax[1].plot(x, y4, color='green') ax[2].set_title('Parallel. No solution', fontsize=15) ax[2].set_xlim([-10, -5]) ax[2].set_ylim([-30, -20]) ax[2].plot(x, y5, color='red') ax[2].plot(x, y6, color='green') plt.show() # + [markdown] id="6i0_BXCzV-K3" # ## 4.3 The Elimination Strategy # - Typically best option if no variable in system has coefficient of 1. # - Use _addition property_ of equations to eliminate variables. # - If necessary, multiply one or both equations to make elimination of a variable possible. # # For example, solve for the unknowns in the following system: # $2x - 3y = 15$ # $x + 10y = 14$ # by multiplying the first equation by -2 and adding the equations. # # $(x, y) = (6, -1)$ # + colab={"base_uri": "https://localhost:8080/", "height": 269} id="5K34jvIL5fuZ" outputId="e8d7422b-7401-49c1-e961-4099f6de72c9" x = np.linspace(0, 20, 1000) y1 = ((2 * x) - 15) / 3 y2 = 14 - x plt.xlim([5, 20]) plt.ylim([-2, 8]) plt.plot(x, y1, c='red') plt.plot(x, y2, c='g') plt.show() # + [markdown] id="FMiveC-3V_oI" # ## 4.4 Elimination Exercises # + [markdown] id="wXxESYDHfYtc" # 1. # $4x - 3y = 25$ # $-3x + 8y = 10$ # <br /> # 2. # $-9x - 15y = 15$ # $3x + 5y = -10$ # <br /> # 3. # $4x + 2y = 4$ # $-5x - 3y = -7$ # <br /> # <br /> # $(x, y) = (10, 5)$ <br /> # $No solution!$<br /> # $(x, y) = (-1, 4)$ # + colab={"base_uri": "https://localhost:8080/", "height": 356} id="r76f1Gve9WrU" outputId="61a093a4-dd89-4a50-96d5-bf22b571ea06" x = np.linspace(-50, 50, 1000) y1 = (25 - (4 * x)) / -3 y2 = (10 + (3 * x)) / 8 y3 = (15 + (9 * x)) / -15 y4 = (-10 - (3 * x)) / 5 y5 = (4 - 4 * x) / 2 y6 = (-5 * x + 7) / 3 fig, ax = plt.subplots(1, 3, figsize=(18, 5)) ys = [[y1, y2], [y3, y4], [y5, y6]] fig.suptitle('Equations and their solutions', fontsize=20) for i in range(3): ax[i].set_xlim([-20, 20]) ax[i].set_ylim([-20, 20]) ax[i].plot(x, ys[i][0], c='g') ax[i].plot(x, ys[i][1], c='r') ax[0].set_title('1 solution', fontsize=15) ax[1].set_title('Parallel. No solution', fontsize=15) ax[2].set_title('1 solution', fontsize=15) plt.show()
01 Linear Algebra for Machine Learning (Jon Krohn)/04 Solving Linear Systems.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd # + method = 'gram-ood' # or 'gram-ood' model = 'vgg' # or 'resnet', 'densenet', 'mobilenet' devs = np.loadtxt('../results/{}/final_{}'.format(method, model)) img_names = np.genfromtxt('../results/{}/names_{}'.format(method, model), dtype='str') devs_norm = (devs - devs.min()) / (devs.max() - devs.min()) dic_names_devs = {x:y for x,y in zip(img_names, devs_norm)} predictions = pd.read_csv('predictions.csv') cols = ['image', 'MEL', 'NV', 'BCC', 'AK', 'BKL', 'DF', 'VASC', 'SCC', 'UNK'] vals = list() print("Building the submission...") for _, row in predictions.iterrows(): name = row['image'] new_unk = dic_names_devs[name] new_row = row[cols].values new_row[-1] = new_unk vals.append(new_row) new_pred = pd.DataFrame(vals, columns=cols) new_pred.to_csv("submissions/{}_{}.csv".format(method, model), index=False) print("Done!") # -
isic_submit/merge/merge_pred_unk.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # name: python2 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/DianaMosquera/Diana-M/blob/master/ML1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="L3olC_dfMoHf" colab_type="text" # **Machine Learning Fundamentals** # © Deep Learning Indaba. Apache License 2.0. # + [markdown] id="VgmuvXJEM2OB" colab_type="text" # Introducción # El objetivo de esta practica es entender la idea de clasificación (clasificación de cosas en categorías) utilizando un modelo de ML. Jugar un poco con la relación entre los parámetros de un clasificador y el límite de decisión (una línea que separa las categorías) también idea de una función de pérdida o cost function. Y luego empezar a usar Tensorflow. # # Objetivos de aprendizaje: # # *Comprender la idea de clasificación # # *Comprender el concepto de separabilidad (lineal) de un conjunto de datos # # *Comprender cuáles son los parámetros de un clasificador y cómo se relacionan con el límite de decisión # # *Poder explicar brevemente qué es Tensorflow # + [markdown] id="x-ay-rIMN7xt" colab_type="text" # **Importar librerías** # + id="2v3TxzC0N_ay" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="772f4970-2e93-41ab-aae2-bc41c9cf7c12" # !pip install -q moviepy > /dev/null 2>&1 # !pip install -q imageio > /dev/null 2>&1 # !pip install -q tensorflow==2.0.0-beta0 > /dev/null 2>&1 import tensorflow as tf import numpy as np # Numpy is an efficient linear algebra library. import matplotlib.pyplot as plt # Matplotlib is used to generate plots of data. from matplotlib import animation, rc from IPython import display try: tf.executing_eagerly() print("TensorFlow executing eagerly: {}".format(tf.executing_eagerly())) except ValueError: print('Already running eagerly') # + [markdown] id="pC4Q6myTmGef" colab_type="text" # **Outline:** La clasificación en el aprendizaje automático implica aprender a etiquetar ejemplos en una (o más) categorías discretas. Esto difiere de otra tarea común en el aprendizaje automático llamada regresión, que implica aprender una asignación de entradas a una salida de valor continuo. # # 1.Comenzamos presentando un conjunto de datos de puntos rojos y azules que queremos separar. # # 2.Introducimos y exploramos la idea de la separabilidad lineal. # # 3.Definimos una pérdida como una medida de cuán bueno de un separador es una línea particular # # 4.Presentamos brevemente TensorFlow y mostramos cómo se puede usar para encontrar automáticamente el mínimo de una función de pérdida. # + [markdown] id="yzK484vonHtQ" colab_type="text" # **Dear data** # # Ejecuta el código en la celda a continuación y observa el diagrama resultante. Debe producir un conjunto de datos 2D simple que consta de 2 clases de puntos, las clases están representadas por los colores azul y rojo. # # Nuestra tarea es construir un clasificador binario que pueda distinguir entre los puntos rojo y azul (al rojo y al azul se les conoce como las clases de los puntos), utilizando solo las coordenadas 2-D de un punto. # # En otras palabras, queremos una función que tome como entrada un vector 2-D que represente las coordenadas de un punto y devuelva un valor de 1 o 0 que indica si el punto es rojo o azul. Aquí hemos codificado los colores rojo y azul en los números 1 y 0 (¡lo que facilita el trabajo en matemáticas y código!) # # Nota: hems codificado arbitrariamente rojo como 1 y azul como 0, ¡también puedes hacerlo al revés siempre que seas coherente! # + [markdown] id="4JBtG5MSp7iZ" colab_type="text" # **Helper functions (run me)** # + id="n_theLTWp-Uo" colab_type="code" colab={} # this is a helper function to assist with plotting the dataset below def plot_dataset(inputs, labels): # Plot the given 2D inputs and labels using Matplotlib. plt.scatter( inputs[:, 0], inputs[:, 1], c=['red' if label > 0 else 'blue' for label in labels]) plt.axis('equal') plt.xlabel('x1') plt.ylabel('x2') # + [markdown] id="255AJXZCqFx2" colab_type="text" # **Data** # + id="M8N6n3R0qGVf" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 283} outputId="1279ab7c-1420-48b6-e00d-32bb14013cc4" #@title Generate the Dataset {run: "auto"} # Define the centre(s) of the points centre = 1.8 #@param {type:"slider", min:0, max:2, step:0.1} points_in_class = 20 # How many points we want per class # A fixed random seed is a common "trick" used in ML that allows us to recreate # the same data when there is a random element involved. np.random.seed(0) # Generate random points in the "red" class red_inputs = np.random.normal(loc=centre, scale=1.0, size=[points_in_class, 2]) # Generate random points in the "blue" class blue_inputs = np.random.normal(loc=-centre, scale=1.0, size=[points_in_class, 2]) # Put these together inputs = np.concatenate((red_inputs, blue_inputs), axis=0) # The class (label) is 1 for red or 0 for blue red_labels = np.ones(points_in_class) blue_labels = np.zeros(points_in_class) labels = np.concatenate((red_labels, blue_labels), axis=0) # num_data_points is the total data set size num_data_points = 2 * points_in_class plot_dataset(inputs, labels) # + [markdown] id="1kg9iLAeqYLb" colab_type="text" # **¿Cómo se ven los datos?** # # Las entradas son vectores bidimensionales (puntos en un espacio bidimensional). Aquí están las coordenadas de 4 puntos, que hemos elegido deliberadamente para que los puntos 1 y 2 sean "rojos" y los puntos 3 y 4 sean "azules". # + id="8PEwJ3IJqbPi" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="0e095416-c372-4f70-ffd6-365c1c1ca89d" print('Input 1:\t', inputs[0]) print('Input 2:\t', inputs[1]) print('Input 3:\t', inputs[-1]) print('Input 4:\t', inputs[-2]) # + [markdown] id="O-7lYkwLqlZ4" colab_type="text" # Las etiquetas son 0 (azul) o 1 (rojo). Aquí están las etiquetas correspondientes a los puntos anteriores: # + id="vOv1I62Pqmlj" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="8aec8a5a-3e6c-4f67-80e0-f045372201b7" print('Label 1:\t', labels[0]) print('Label 2:\t', labels[1]) print('Label 3:\t', labels[-1]) print('Label 4:\t', labels[-2]) # + [markdown] id="hdTjA8psqyy1" colab_type="text" # **Separabilidad lineal** # # Para un conjunto de datos bidimensional con 2 clases, podemos decir que el conjunto de datos es linealmente separable si es posible dibujar una línea (1-D) que separe los ejemplos de cada clase. # # En este caso, querríamos una línea entre los puntos rojo y azul de modo que todos los puntos rojos se encuentren en un lado de la línea y todos los puntos azules en el otro. La separabilidad lineal de un conjunto de datos D-dimensional con 2 clases significa que existe un solo plano (D-1) -dimensional (hiper-) que separa las clases (un hiperplano es una generalización de una línea recta a muchas dimensiones). # # # **Tarea exploratoria** # # En la celda de código bajo el encabezado "Los datos", cambia el control deslizante para el valor central. Esto actualizará automáticamente el valor en el código y volverá a dibujar el gráfico. # # ¿A qué valor de centro el conjunto de datos se vuelve linealmente separable? # # **Pregunta para discusión** # # ¿Puedes pensar en algunos conjuntos de datos 2D, de 2 clases, similares al anterior, que son separables (los puntos de las 2 clases no se superponen entre sí), pero no son linealmente separables? # # Dibuja algunos ejemplos en papel o complétalos con Matplotlib y mira qué pasa # + [markdown] id="lOe7_TW6tCdU" colab_type="text" # **Drawing the line** # Si te acuerdas de la escuela, una ecuación $w_1x_1 + w_2x_2 = 0$ puede representar una línea en 2 dimensiones, con ejes de coordenadas $x_1$ and $x_2$,que pasa por el origen (0, 0). # # También podemos escribir esto en forma de vector como: $\mathbf{w}^T\mathbf{x} = 0$, donde $\mathbf{w}^T = [w_1, w_2]$ y $\mathbf{x}^T = [x_1, x_2]$. # # **Nota**: Nuestra línea de arriba pasará por el origen (0,0). Si queremos describir una línea que no pasa por el origen, necesitamos agregar un término de sesgo o bias. # # Cuando una línea (o más generalmente, un hiperplano) se define de esta manera, llamamos a los **parámetros** $\mathbf{w} = (w_1, w_2)$ un **vector normal** para la línea. El vector normal es ortogonal (perpendicular) a la línea. Queremos construir una línea que separe los puntos rojo y azul, lo que llamaremos un **límite de decisión**. El nombre "límite de decisión" proviene del hecho de que la línea describe el límite en el espacio de entrada donde la salida (decisión) del modelo cambia de una clase a otra. # # En la siguiente celda, trazamos nuestro conjunto de datos junto con un vector normal $\mathbf{w}$ y un límite de decisión. Puede ajustar los valores de $w_1$ y $w_2$ utilizando los controles deslizantes de la derecha. Observa el efecto que tienen los valores en el vector normal dibujado en rojo y el límite de decisión en negro. Ajusta los valores para que la línea negra separe los puntos azul y rojo (es decir, puntos rojos en un lado y azules en el otro). # # Tu línea también debe tener el vector normal apuntando en la dirección de los puntos rojos. La razón por la cual la dirección es significativa es que queremos clasificar eventualmente los puntos en un lado de la línea (límite de decisión) como rojos y el otro como azules. # # ¿Es posible encontrar una línea a través del origen que separe perfectamente los puntos? # # **Nota:** Cada una de nuestras entradas es un vector 2-D, compuesto por dos valores de coordenadas. Nos referimos a estos 2 ejes de coordenadas como $x_1$ y $x_2$. Por ejemplo, si tenemos una entrada $(1, 2)$, entonces diríamos$x_1 = 1$ y $x_2 = 2$ para ese punto. # + id="sAKLjjU0vWbI" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 337} outputId="1a0054b9-9d57-4057-ee53-c495f99a210e" #@title Effect of parameters {run: "auto"} # Define the parameters w1 = 0.8 #@param { type: "slider", min: -5, max: 5, step: 0.1 } w2 = 1 #@param { type: "slider", min: -5, max: 5, step: 0.1 } plot_dataset(inputs, labels) # Add the weight vector to the plot. We plot it in red, as it has to "point" # in the direction of the red points. ax = plt.axes() ax.arrow(0, 0, w1, w2, head_width=0.3, head_length=0.3, fc='r', ec='r') # Plot part of the decision boundary in black. It is orthogonal to the weight # vector. t = 2 # this is how long the line should be plt.plot([-t * w2, t * w2], [t * w1, -t * w1], 'k-') plt.xlim([-4, 4]) plt.ylim([-4, 4]) plt.show() # + [markdown] id="1MVQS8NHwi8D" colab_type="text" # **Clasificación** # # Dado un vector normal $w$, podemos evaluar a qué lado del límite de decisión se encuentra un punto particular $x_i = (x_i, 1, x_i, 2)$ evaluando $\mathbf{w^Tx_i}$. Si $\mathbf{w^Tx_i}> 0$, el punto $x_i$ se encuentra a un lado del límite (en la dirección del vector normal), y podemos clasificar ese punto como perteneciente a la clase $1$ (en nuestro caso, "rojo"). # # Si $\mathbf{w^Tx_i}> 0$, el punto se encuentra en el otro lado y se puede clasificar como clase $0$ (en nuestro caso, "azul"). Finalmente, si $\mathbf{w^Tx_i} = 0$, el punto se encuentra en el límite de decisión y podemos decidir si clasificarlo como $0$ o $1$, o ignorarlo. # + [markdown] id="48Hk5OrV0jRF" colab_type="text" # **¿Qué tan "buena" es la línea?** # # Si jugaste con el código anterior, es posible que hayas desarrollado cierta intuición sobre cómo las diferentes configuraciones de los parámetros influyen en la ubicación final del límite de decisión. ¡El propósito del machine learning es ajustar automáticamente los valores de $w_1$ y $w_2$ para encontrar un límite de decisión adecuado! Pero para hacer esto, necesitamos especificar matemáticamente alguna pérdida o función objetiva. # # La pérdida es una función de los parámetros $w_1$ y $w_2$ y nos dice cuán buena es una determinada configuración de los valores de los parámetros para clasificar los datos. Esta función se define de tal manera que alcanza su configuración óptima cuando se minimiza, es decir, cuanto menor sea su valor, mejor será la separación entre las clases. Una propiedad adicional que puede tener una función de pérdida que a menudo es crucial para el aprendizaje automático es ser diferenciable. Una función de pérdida diferenciable nos permite utilizar la optimización basada en gradiente para encontrar su valor mínimo y los valores óptimos correspondientes de $w_1$ y $w_2$. # # Para este problema de clasificación, consideramos la función de pérdida de entropía cruzada binaria o binary cross-entropy para medir qué tan buenas son las predicciones del modelo. Esta función de pérdida compara la predicción del modelo para cada ejemplo, $x_i$, con el objetivo verdadero $y_i$ (a menudo nos referimos a la etiqueta verdadera asociada con una entrada como "objetivo"). Luego aplica la función de registro no lineal para penalizar al modelo por estar más lejos de la clase verdadera. # # La función de entropía cruzada binaria utiliza una operación llamada función sigmoidea. Esta función permite que nuestro clasificador genere cualquier valor real. La función de pérdida de entropía cruzada binaria, sin embargo, espera que las predicciones hechas por un clasificador estén entre 0 y 1. La función sigmoidea "aplasta" cualquier entrada de número real para ubicarse en el intervalo $(0,1)$. # + [markdown] id="zU1cb0c01tIM" colab_type="text" # Para los que quieren entender esto de una manera más profunda o sea matemática, la ecuación para la pérdida de entropía cruzada binaria, en un conjunto de datos con $N$ puntos, se define de la siguiente manera: # # \begin{align} # l(\mathbf{w}; \mathbf{\hat{y}}, \mathbf{y}) = -\frac{1}{N}\sum_{i=1}^N y_i log(\hat{y}_i) + (1-y_i)log(1-\hat{y}_i) # \end{align} # # Dónde: # # $\hat{y}_i = \operatorname{sigmoid}(\mathbf{w}^T\mathbf{x_i})$ y el $\operatorname{sigmoid}$ se define como: # # $$ # \mathrm{sigmoid}(a) = \frac{1}{1 + e^{-a}} . # $$ # # Puedes consultar este blog para más información: # (https://towardsdatascience.com/understanding-binary-cross-entropy-log-loss-a-visual-explanation-a3ac6025181a). # # Ahora volvamos a programar para cualquier $W_1$ y $W_2$ # + id="k0O0Mb963yMj" colab_type="code" colab={} def compute_loss(w1, w2, inputs, labels): total_log_likelihood = 0 N = len(inputs) # Add the contribution of each datapoint to the loss for (x1, x2), target in zip(inputs, labels): # As our targets are 0 or 1, our prediction function must output a value between 0 and 1. # The sigmoid function 'squashes' any value to lie between 0 and 1: prediction = tf.sigmoid(w1*x1 + w2*x2) # Compute the local loss term # We add 1e-10 to make the log operations numerically stable (i.e. avoid taking the log of 0.) log_likelihood = target * tf.math.log(prediction + 1e-10) + (1.-target)*tf.math.log(1.-prediction + 1e-10) total_log_likelihood += log_likelihood loss = -total_log_likelihood average_loss = loss / N return average_loss # + [markdown] id="YS7fkVj169hU" colab_type="text" # **Optional section: More on the sigmoid function** # + [markdown] id="GYnxTBTJ7Hi9" colab_type="text" # **Pregunta:** # # Qué crees que es importante al diseñar una buena función de pérdida, es decir, ¿qué debe hacer la función de pérdida cuando el modelo produce una predicción buena / mala? # # Si deseas, puedes revisar con matemáticas, muestra cómo la función sigmoidea (y la función binaria de entropía cruzada) es buena para evaluar la calidad de las predicciones utilizando las siguientes preguntas: # + id="sc8FkFVW7a_6" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 286} outputId="e0bab368-5dc1-45bb-d5e0-1236a8cbfd76" ax = plt.axes() xs = np.arange(-10,10) ax.plot(xs, 1 / (1 + np.exp(-xs))) # + [markdown] id="DcmvZ3St8RRp" colab_type="text" # Como se señaló anteriormente, la función sigmoidea se define como # $$ # \mathrm{sigmoid}(a) = \frac{1}{1 + e^{-a}} . # $$ # ¿Puedes mostrar eso? # $$ # 1 - \mathrm{sigmoid}(a) = \frac{1}{1 + e^{a}} , # $$ # y dibujar ambos en una hoja de papel? # # * ¿Cuál es su valor cuando $a = \mathbf{w}^{T}\mathbf{x}$ es positivo? ¿negativo? y cero? # * ¿Qué sucede con su valor cuando$a = \mathbf{w}^{T}\mathbf{x}$ se hace más grande? # * ¿Cuál es el valor de $\mathrm{sigmoid}(\mathbf{w^Tx})$ cuando $\mathbf{w}^T\mathbf{x} = 0$? ¿Cómo cambia esto cómo clasificamos los puntos a ambos lados del límite de decisión? # # ** SUGERENCIA **: Recuerda que la idea de la función de pérdida es devolver valores pequeños cuando el clasificador hace buenas predicciones y valores grandes cuando el clasificador hace malas predicciones. # # * Si no te siente cómodo con las matemáticas *, recuerde que el objetivo principal de esta pregunta es ** resaltar la importancia de la pérdida binaria de entropía cruzada ** y ** NO ** las matemáticas, ¡así que a concéntrarse en los conceptos! # + [markdown] id="VtgSdEJ_9XNa" colab_type="text" # **Pregunta extra** # # Derivamos la función compute_loss () anterior basada en minimizar la pérdida logarítmica del error de predicción. Esto está relacionado con un concepto llamado 'entropía cruzada'. Pero otra forma de derivar exactamente la misma función de pérdida es maximizando la probabilidad de los datos bajo el modelo $P(y | x, w_1, w_2)$. Si está familiarizado con este concepto (por ejemplo, a partir de estadísticas), vea si también puede derivarlo de esta manera. # # ###Lectura adicional opcional # Más información [cross-entropy loss](http://ml-cheatsheet.readthedocs.io/en/latest/loss_functions.html) y otra info interesante [information theory](https://rdipietro.github.io/friendly-intro-to-cross-entropy-loss/). # # + [markdown] id="fu5CpvJ39-xQ" colab_type="text" # ## Loss value for your chosen $w_1$ and $w_2$ # + [markdown] id="t48VVVRb-5QL" colab_type="text" # La siguiente línea de código calcula el valor de pérdida para los valores elegidos de $w_1$ y $w_2$. Intenta cambiar los valores de $w_1$ y $w_2$ con los controles deslizantes. # # ¿Puedes ver cómo una mejor separación resulta en una pérdida menor? # # **Nota:** Si has usado una versión anterior de TensorFlow anteriormente, ¡puede ser confuso cómo funciona esta celda de código! # + id="t3A08-mw-6JM" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 300} outputId="3335626f-3e46-4b28-b9cc-13fd0a34d6de" #@title Effect of parameters on the loss {run: "auto"} # Define the parameters w1 = -1 #@param { type: "slider", min: -5, max: 5, step: 0.1 } w2 = 1 #@param { type: "slider", min: -5, max: 5, step: 0.1 } plot_dataset(inputs, labels) # Add the weight vector to the plot. We plot it in red, as it has to "point" # in the direction of the red points. ax = plt.axes() ax.arrow(0, 0, w1, w2, head_width=0.3, head_length=0.3, fc='r', ec='r') # Plot part of the decision boundary in black. It is orthogonal to the weight # vector. t = 2 # this is how long the line should be plt.plot([-t * w2, t * w2], [t * w1, -t * w1], 'k-') plt.xlim([-4, 4]) plt.ylim([-4, 4]) plt.show() compute_loss(w1, w2, inputs, labels).numpy() # + [markdown] id="UMxTA0tT_BMd" colab_type="text" # ## Visualising the loss function # + [markdown] id="KAuAIREh_b6v" colab_type="text" # Podemos visualizar la función de pérdida para nuestro conjunto de datos trazando su valor en cada punto de una cuadrícula completa de valores de parámetros $w_1$ y $w-2$. Hacemos esto usando un diagrama de contorno, que es una técnica para visualizar una función tridimensional en un diagrama bidimensional dejando que el color represente la tercera dimensión. Todos los puntos con el mismo color tienen el mismo valor de pérdida. # + id="JOyD2cwB_jle" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="0a99a114-a921-4849-f8f6-1880a0287594" # We define a function so we can re-use this code later def plot_contours(): # Generate a whole bunch of (w1, w2) points in a grid ind = np.linspace(-5, 5, 50) w1grid, w2grid = np.meshgrid(ind, ind) # Compute the loss for each point in the grid losses = [] for w1s, w2s in zip(w1grid, w2grid): loss = compute_loss(w1s, w2s, inputs, labels) losses.append(loss) # Pack the loss values for every value of w1 & w2 into one (50,50) array losses_array = np.concatenate(losses).reshape(50,50) # Now plot the resulting loss function as a contour plot over the whole grid of (w1, w2) values. fig = plt.figure() plt.contourf(w1grid, w2grid, losses_array, 20, cmap=plt.cm.jet) cbar = plt.colorbar() cbar.ax.set_ylabel('Binary cross-entropy loss value') plt.xlabel('w1 value') plt.ylabel('w2 value') plt.title('Total loss for different values of w1 and w2') plot_contours() # + [markdown] id="DYSf2HHr_xGG" colab_type="text" # En la barra de la derecha, a medida que el color va de rojo a azul, el valor de pérdida disminuye y disminuye hasta alcanzar el valor más pequeño (azul oscuro). # # Dado que queremos que la pérdida sea lo más pequeña posible, queremos que nuestros valores de $w_1$ y $w_2$ produzcan una pérdida en el área azul oscuro de la gráfica de contorno. Esto se logra dentro de un cierto rango de valores para $w_1$ y $w_2$. # # Pregunta: ¿Puedes leer qué valores de $w_1$ y $w_2$ te darán la menor pérdida? # # ¿Son estos valores similares a los que encontró anteriormente para separar linealmente los datos? # # **Pregunta**: Dependiendo del punto central que elijas, el valor más pequeño para la pérdida puede no ser 0. ¿En qué circunstancias es este el caso? # + [markdown] id="tURyPnIsARPd" colab_type="text" # ##Optimizando la pérdida usando TensorFlow # + [markdown] id="d5wSPuzuEHFB" colab_type="text" # Ahora que tenemos una función que nos da la pérdida para diferentes valores de $ w_1 $ y $ w_2 $, queremos un método automatizado para encontrar los valores que minimicen la función de pérdida. Aquí es donde entra en juego la optimización por **descenso de gradiente**. La idea es que para cada (batch of) puntos de datos, calculemos la pérdida utilizando los valores actuales de $ w_1 $ y $ w_2 $ en los datos. Luego calculamos el **gradiente** (o derivado) de la función de pérdida en los valores actuales de $ w_1 $ y $ w_2 $. El negativo del gradiente apunta en la dirección del *steepest descent* a lo largo de la función de pérdida. Al ajustar los valores de $ w_1 $ y $ w_2 $ en la dirección del gradiente negativo, nos acercamos al mínimo de la función de pérdida (siempre que la función de pérdida tenga un "buen comportamiento"). El gran paso que damos está mediado por la **tasa de aprendizaje**. Para hacer esto más fácilmente, usaremos TensorFlow. # # # + [markdown] id="umnG0bZfFFlf" colab_type="text" # ##Optional extra reading: TensorFlow # + [markdown] id="SLnrhiZqFUDs" colab_type="text" # *TensorFlow* (TF) es una biblioteca de software de código abierto para el cálculo numérico que utiliza el concepto de tensores. Puedes pensar en los tensores como una generalización de matrices a dimensiones superiores, o más o menos equivalentes a matrices multidimensionales. Los escalares son tensores de 0 dimensiones, los vectores son de 1 dimensión, las matrices estándar son de 2 dimensiones y los tensores de dimensiones superiores tienen 3 o más dimensiones. Puedes pensar que las dimensiones representan grupos de números que significan lo mismo. Por ejemplo, para las imágenes, a menudo utilizamos tensores tridimensionales donde la primera dimensión representa los canales de color rojo, verde y azul de la imagen, y los dos siguientes son las columnas y filas de píxeles de la imagen. # # **Nota:** No te confundas cuando las personas digan "vector 2-D" o "vector 3-D", que se refiere a un tensor unidimensional que tiene tamaño 2 o 3. # # La principal ventaja de usar TensorFlow es que puede derivar automáticamente los gradientes de muchas expresiones matemáticas que involucran tensores. Lo logra a través de un proceso llamado "diferenciación automática". Tensorflow también admite múltiples "núcleos", lo que le permite ejecutar fácilmente su código en procesadores normales (CPU), tarjetas gráficas (GPU) y otros aceleradores de hardware más exóticos como las Unidades de procesamiento de tensor (TPU) de Google # # Tensorflow en realidad proporciona dos modos de operación, el primero, llamado "modo gráfico", crea un gráfico de cálculo por adelantado y luego introduce datos en el gráfico. Al construir el gráfico por adelantado, Tensorflow puede aplicar optimizaciones al gráfico que le permiten extraer el máximo rendimiento del hardware que está ejecutando. El segundo modo, llamado "Eager-mode", es mucho más nuevo y evalúa las operaciones de Tensor de manera imperativa (en el orden en que las escribe), similar a NumPy y PyTorch. Eager-mode es un poco menos eficiente pero mucho más intuitivo, especialmente si nunca antes ha usado un estilo de programación "definir y ejecutar" (como el modo gráfico). # + [markdown] id="NP58SXd4IX_9" colab_type="text" # ### Usando Tensorflow para optimizar la pérdida # Utilizamos TensorFlow para optimizar los parámetros del modelo con descenso de gradiente. Recorremos el conjunto de datos varias veces (llamadas "epochs") y trazamos el límite de decisión final junto con un diagrama que muestra cómo los parámetros y la pérdida cambiaron durante las épocas. # # **Nota**: TensorFlow probablemente es excesivo para este ejemplo, porque el gradiente es muy fácil de calcular. # + id="9WfZrYzOIsLz" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 612} outputId="8f05ffa8-e0c9-43eb-da63-f7e208e83593" lr = 0.33 # The learning rate # Initialise Tensorflow variables representing our parameters. # We need to use TensorFlow variables here rather than Numpy or Python ones so # that TensorFlow is able to compute gradients. w1 = tf.Variable(-2.0, dtype=tf.float64) w2 = tf.Variable(-4.0, dtype=tf.float64) print(w1.dtype) plot_contours() # Loop over the dataset multiple times parameter_values = [] for epoch in range(100): plt.scatter(w1.numpy(), w2.numpy(), marker='o', color='black') # The GradientTape is how TF keeps track of gradients in Eager-mode with tf.GradientTape() as tape: loss = compute_loss(w1, w2, inputs, labels) # Now we take a step in parameter space in the direction of the gradient to move the parameters closer (hopefully!) to their optimum dw1, dw2 = tape.gradient(loss, [w1, w2]) # Step 'lr units' in the direction of the negative gradient # We achieve this by subtracting lr * dw1 and lr * dw2 from the w1 and w2 variables w1.assign_sub(lr*dw1) w2.assign_sub(lr*dw2) print('Finished optimisation, the final values of w1 and w2 are:') print(w1.numpy(), w2.numpy(), loss) # Plot the final point on the loss surface. plt.scatter(w1.numpy(), w2.numpy(), marker='x', color='red') plt.show() # Plot the final decision boundary plot_dataset(inputs, labels) ax = plt.axes() ax.arrow(0, 0, w1.numpy(), w2.numpy(), head_width=0.3, head_length=0.3, fc='r', ec='r') plt.plot([-2 * w2.numpy(), 2 * w2.numpy()], [2 * w1.numpy(), -2 * w1.numpy()], 'k-') plt.xlim([-4, 4]) plt.ylim([-4, 4]) plt.show() # + [markdown] id="A64hpgS_JHRO" colab_type="text" # ¿Puedes ver cómo el modelo atraviesa el diagrama de contorno hasta que minimiza la pérdida? # # ¿Cómo se corresponden los valores finales de $w_1$ y $w_2$ encontrados por Tensorflow con los valores que encontró manualmente? Si no lo son, ¿puedes explicar por qué? # # ## Tareas opcionales # Si has trabajado en esta práctica, has respondido todas las preguntas y sientes que comprendes bien lo que está sucediendo, intenta las siguientes tareas: # # 1. Agregue un parámetro **sesgo** a la ecuación para el límite de decisión y visualiza cómo eso cambia el límite de decisión, la pérdida y la solución final encontrada por Tensorflow. # 2. Agregue un **regularizador**, por ejemplo, el regularizador L2 (consulta el apéndice a continuación para obtener más información): ¿cómo afecta el diagrama de contorno de los parámetros frente a la pérdida? ¿Cómo afecta la pérdida el cambio en la fuerza de la regularización? # # + [markdown] id="6fBeWX3bLidt" colab_type="text" # # Appendix # + [markdown] id="AUWGht6VLs-Y" colab_type="text" # Dos de los métodos de regularización más simples son la regularización L1 y L2 (o mejor conocidos como _Lasso_ y _Ridge_ regresión si has utilizado la regresión lineal antes). Ambos métodos regularizan el modelo agregando un término a la pérdida que penaliza el modelo si se vuelve demasiado complejo. # La regularización L1 agrega un término basado en la norma L1: # # $loss_{L1} = loss + \lambda \sum_i |w_i|$ # # donde $\lambda$ es un parámetro que controla la cantidad de regularización, y $w_i$ son los parámetros del modelo. La regularización de L1 tiene el efecto de obligar a algunos parámetros a reducirse a 0, eliminándolos efectivamente del modelo. # # La regularización L2 agrega de manera similar un término basado en la norma L2: # # $loss_{L2} = loss + \lambda \sum_i w_i^2$. # # La regularización de L2 tiene el efecto de evitar que cualquiera de los parámetros se vuelva demasiado grande y sobrecargar a los demás. # # En algunos casos, puede funcionar bien usar tanto la regularización L1 como la L2. # # Para obtener más información, (http://enhancedatascience.com/2017/07/04/machine-learning-explained-regularization/) y (https://towardsdatascience.com/l1-and- l2-regularization-method-ce25e7fc831c). # + id="Jve2vevsMN13" colab_type="code" colab={}
ML1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="GzfdMfk10NE6" # ## **Linear Regression with Python Scikit Learn** # In this section we will see how the Python Scikit-Learn library for machine learning can be used to implement regression functions. We will start with simple linear regression involving two variables. # # ### **Simple Linear Regression** # In this regression task we will predict the percentage of marks that a student is expected to score based upon the number of hours they studied. This is a simple linear regression task as it involves just two variables. # + colab={} colab_type="code" id="V9QN2ZxC38pB" # Importing all libraries required in this notebook import pandas as pd import numpy as np import matplotlib.pyplot as plt # %matplotlib inline # + colab={"base_uri": "https://localhost:8080/", "height": 376} colab_type="code" executionInfo={"elapsed": 2534, "status": "ok", "timestamp": 1544113345787, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WI8p7JNWLic/AAAAAAAAAAI/AAAAAAAAAfs/vS8ElgH0p0c/s64/photo.jpg", "userId": "15341571102300750919"}, "user_tz": -480} id="LtU4YMEhqm9m" outputId="5b4b36af-1545-497e-a6dc-7658bab71dbc" # Reading data from remote link url = "http://bit.ly/w-data" s_data = pd.read_csv(url) print("Data imported successfully") s_data.head(10) # + [markdown] colab_type="text" id="RHsPneuM4NgB" # Let's plot our data points on 2-D graph to eyeball our dataset and see if we can manually find any relationship between the data. We can create the plot with the following script: # + colab={"base_uri": "https://localhost:8080/", "height": 294} colab_type="code" executionInfo={"elapsed": 718, "status": "ok", "timestamp": 1544113350499, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WI8p7JNWLic/AAAAAAAAAAI/AAAAAAAAAfs/vS8ElgH0p0c/s64/photo.jpg", "userId": "15341571102300750919"}, "user_tz": -480} id="qxYBZkhAqpn9" outputId="37264af1-786d-4e0c-a668-383264d1ddd1" # Plotting the distribution of scores s_data.plot(x='Hours', y='Scores', style='o') plt.title('Hours vs Percentage') plt.xlabel('Hours Studied') plt.ylabel('Percentage Score') plt.show() # + [markdown] colab_type="text" id="fiQaULio4Rzr" # **From the graph above, we can clearly see that there is a positive linear relation between the number of hours studied and percentage of score.** # + [markdown] colab_type="text" id="WWtEr64M4jdz" # ### **Preparing the data** # # The next step is to divide the data into "attributes" (inputs) and "labels" (outputs). # + colab={} colab_type="code" id="LiJ5210e4tNX" X = s_data.iloc[:, :-1].values y = s_data.iloc[:, 1].values # + [markdown] colab_type="text" id="Riz-ZiZ34fO4" # Now that we have our attributes and labels, the next step is to split this data into training and test sets. We'll do this by using Scikit-Learn's built-in train_test_split() method: # + colab={} colab_type="code" id="udFYso1M4BNw" 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) # + [markdown] colab_type="text" id="a6WXptFU5CkC" # ### **Training the Algorithm** # We have split our data into training and testing sets, and now is finally the time to train our algorithm. # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 701, "status": "ok", "timestamp": 1544113358086, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WI8p7JNWLic/AAAAAAAAAAI/AAAAAAAAAfs/vS8ElgH0p0c/s64/photo.jpg", "userId": "15341571102300750919"}, "user_tz": -480} id="qddCuaS84fpK" outputId="befbd977-772c-4bd1-bb48-ee5dd6bae73c" from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) print("Training complete.") # + colab={"base_uri": "https://localhost:8080/", "height": 265} colab_type="code" executionInfo={"elapsed": 985, "status": "ok", "timestamp": 1544113360867, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WI8p7JNWLic/AAAAAAAAAAI/AAAAAAAAAfs/vS8ElgH0p0c/s64/photo.jpg", "userId": "15341571102300750919"}, "user_tz": -480} id="J61NX2_2-px7" outputId="d20ec1fd-3e2d-4eae-84a2-a0df57d31009" # Plotting the regression line line = regressor.coef_*X+regressor.intercept_ # Plotting for the test data plt.scatter(X, y) plt.plot(X, line); plt.show() # + [markdown] colab_type="text" id="JCQn-g4m5OK2" # ### **Making Predictions** # Now that we have trained our algorithm, it's time to make some predictions. # + colab={"base_uri": "https://localhost:8080/", "height": 102} colab_type="code" executionInfo={"elapsed": 698, "status": "ok", "timestamp": 1544113363729, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WI8p7JNWLic/AAAAAAAAAAI/AAAAAAAAAfs/vS8ElgH0p0c/s64/photo.jpg", "userId": "15341571102300750919"}, "user_tz": -480} id="Tt-Fmzu55EGM" outputId="46f1acf8-91ac-4984-cfbe-e614aa9ea849" print(X_test) # Testing data - In Hours y_pred = regressor.predict(X_test) # Predicting the scores # + colab={"base_uri": "https://localhost:8080/", "height": 204} colab_type="code" executionInfo={"elapsed": 753, "status": "ok", "timestamp": 1544113366918, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WI8p7JNWLic/AAAAAAAAAAI/AAAAAAAAAfs/vS8ElgH0p0c/s64/photo.jpg", "userId": "15341571102300750919"}, "user_tz": -480} id="6bmZUMZh5QLb" outputId="8ea11a9e-c1b7-4fab-ab62-4dcbd2c8607b" # Comparing Actual vs Predicted df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred}) df # + colab={"base_uri": "https://localhost:8080/", "height": 51} colab_type="code" executionInfo={"elapsed": 862, "status": "ok", "timestamp": 1544113370494, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WI8p7JNWLic/AAAAAAAAAAI/AAAAAAAAAfs/vS8ElgH0p0c/s64/photo.jpg", "userId": "15341571102300750919"}, "user_tz": -480} id="KAFO8zbx-AH1" outputId="fcb3830f-3cda-4dcb-f122-84b71f101fae" # You can also test with your own data hours = 9.25 own_pred = regressor.predict(hours) print("No of Hours = {}".format(hours)) print("Predicted Score = {}".format(own_pred[0])) # + [markdown] colab_type="text" id="0AAsPVA_6KmK" # ### **Evaluating the model** # # The final step is to evaluate the performance of algorithm. This step is particularly important to compare how well different algorithms perform on a particular dataset. For simplicity here, we have chosen the mean square error. There are many such metrics. # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 834, "status": "ok", "timestamp": 1544113374919, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WI8p7JNWLic/AAAAAAAAAAI/AAAAAAAAAfs/vS8ElgH0p0c/s64/photo.jpg", "userId": "15341571102300750919"}, "user_tz": -480} id="r5UOrRH-5VCQ" outputId="7b9ddcf1-2848-408f-d81f-7a60652c381e" from sklearn import metrics print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))
SupervisedMachineLearning.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from tinc import * tclient = TincClient() [db.id for db in tclient.disk_buffers] ps = tclient.get_parameter_space("casmParameters") g = tclient.get_disk_buffer("graph3") def PlotConvexHull_DFT(): #MC predicted ground states dp=tclient.get_datapool("resultsData") MC_comp=dp.get_slice("<comp_n(Li)>", "param_chem_pot(a)") MC_FE=dp.get_slice("<formation_energy>", "param_chem_pot(a)") T=tclient.get_parameter("T").value plt.title(str(T)) plt.scatter(MC_comp, MC_FE, color='green') name="ConvexHullPlot.png" plt.savefig(name) with open(name, "rb") as f: return f.read() PlotConvexHull_DFT() ps.enable_cache() def Generate_hull(value): graph_data=ps.run_process(PlotConvexHull_DFT) g.data=graph_data ps.get_root_path() ps.get_current_relative_path() ps._cache_manager.
jupyter-notebooks/Cache to disk buffer.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Case 3. Patient Drug Review # Mr.<NAME><br> # Last edited: 17.03.2019<br> # Cognitive Systems for Health Technology Applications<br> # [Helsinki Metropolia University of Applied Sciences](http://www.metropolia.fi/en/)<br> # ## 0. Table of contents # 1. Objectives # 2. Required libraries # 3. Data description and preprocessing # * Training set # * Split train and validation set # * Compute class-weight for training precess # * Define training and ploting functions # 4. Modeling and compilation # * Model 1 : Embedding + Conv1D + LSTM (original) # * Model 2 : Embedding + Conv1D + LSTM (modified) # * Model 3 : Embedding + Conv1D + Stack of GRU # * Model 4 : Embedding + Conv1D + Bidirectional LSTM # 5. Training and Validation # * Training Model 1 : Embedding + Conv1D + LSTM (original) # * Training Model 2 : Embedding + Conv1D + LSTM (modified) # * Training Model 3 : Embedding + Conv1D + Stack of GRU # * Training Model 4 : Embedding + Conv1D + Bidirectional LSTM # 6. Evaluation # * Selcetion the best of all # * Defining my preprocess function # * Word2Vec embedding # * Comparing Without preprocess / Preprocess / Word2Vec # 7. Results and discussion # * Final model with test set # 8. Conclusions # ## 1. Objectives # This notebook was created for learning to use neural networks to process text data and predict ratings associated to the text. The study case is about patient drug reviews extracted from Drugs.com. Patient reviews on specific drugs along with related conditions and a 10 star patient rating reflecting overall patient satisfaction. # ## 2. Required libraries # + # Import basic libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import time import pickle import string from nltk.tokenize import word_tokenize from nltk.corpus import stopwords import gensim import os import keras from keras import backend as K from keras import layers from keras import models from keras import optimizers from keras.callbacks import ModelCheckpoint from keras.layers import Dense, Activation, Conv1D, GlobalMaxPooling1D, Dropout, LSTM, GRU, Bidirectional, Flatten, MaxPooling1D from keras.layers.embeddings import Embedding from keras.models import Model, load_model, Sequential from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical from keras.initializers import Constant from keras import regularizers from sklearn.metrics import confusion_matrix, classification_report from sklearn.metrics import accuracy_score from sklearn.utils import class_weight import warnings # Library for text cleaning import re from bs4 import BeautifulSoup from nltk.tokenize import WordPunctTokenizer import itertools # - # ## 3. Data description and preprocessing # I used a dataset from https://www.kaggle.com/jessicali9530/kuc-hackathon-winter-2018/home that was used for the Winter 2018 Kaggle University Club Hackathon. # # Data was devided into 2 files (drugsComTrain_raw.csv and drugsComTest_raw.csv) those contain Patient reviews on specific drugs along with related conditions and a 10 star patient rating reflecting overall patient satisfaction. The drugsComTrain_raw.csv contains totally 161,297 records and the drugsComTest_raw.csv contains 53,766 records. # # Columns of both CSV files: # # * uniqueID = Unique ID # * drugName = Name of drug # * condition = Name of condition # * review = Patient review # * rating = 10 star patient rating # * date = Date of review entry # * usefulCount = Number of users who found review useful # ### Training set # I used drugsComTrain_raw.csv as training-set and validation-set. First, I imported data from drugsComTrain_raw.csv and group rating into 3 classes. # * <b>Negative (0) = rating 0 - 4 # * Natural (1) = rating 5 - 6 # * Positive (2) = rating 7 - 10</b> # # Then, I collected those categories into 'label' column. # + # Read the training data data = pd.read_csv(r'./drugsComTrain_raw.csv') # Create labels r = data['rating'] r_replace = r.replace({ 0 : 0, 1 : 0, 2: 0, 3: 0, 4: 0 }) r_replace = r_replace.replace({ 5 : 1, 6 : 1}) r_replace = r_replace.replace({ 7 : 2, 8 : 2, 9 : 2, 10 : 2}) # Add the label column to the data data['label'] = r_replace # Check the new data data.head() # - # I checked distribution of each class to make sure should I do something if the data is unbalance. # Plot distribution of labels data.hist(column = 'label', bins = np.arange(0, 4), align = 'left'); print(data['label'].value_counts()) # As you can see from the above histogram, most of data is in 'Positive class' and it much more than data in 'Natural class'. Using balanced data by ramdom equally select each class, seem not to be a good choice because the smallest class ( Natural class ) has only 14,356 records. If we select 14,356 records for each class, we will get only 43,068 records that quite too small for training model. So, <b>I choose to define class_weight for each class to help to avoid training a bias model</b> after using imbalance data. (I will calculate class_weight after split training-set and validation-set) # # Next, I plotted length of review to find size of sentence that proper for this dataset. # + # Getting lenght of each review length = [] for x in data['review'].values: length.append(len(x.split())) # Plot distribution of length plt.scatter(x = range(len(length)), y = length) plt.show() # Show statistic of length pd.DataFrame(length).describe() # - # ### Split train and validation set # I defined most of variables here. For max_len, I have tried several values (125, 250, 1900) to the best one and I got 500 is the best value for my model. Also for max_feature and embedded_dim, 10000 words for training and 100 dimension of word vector get the best result from my experiment. # + # Define Variable seed = 24 # for randomly split train - validation max_len = 500 # maximum length of sentence max_feature = 10000 # number of word that will be used to train validate_size = 3000 batch_size = 512 epochs = 100 embedded_dim = 100 # - # <b>I decided to use balanced validation-set</b> because I believe that if we use imbalance validation-set and our model is bias model to some classes, it may get high accuracy than another model that doesn't have bias. # # This is how I create my balanced validation-set. I group the dataframe by level column first and then sample each of them with the equal size. # + # Group records by level feature g = data.groupby('label') # Sample records equal to SIZE//2 for each group for balancing the dataset val_df = g.apply(lambda x: x.sample(validate_size//3, random_state = seed)) # Convert the labels to one_hot_category values one_hot_labels_val = to_categorical(val_df['label'].values, num_classes = 3) # Show distribution of datset for each class print("How many records for each class in validation set (after balancing)") val_df['label'].value_counts() # - # After split 3,000 records as validation set, I drop those records from the main dataframe so the rest is uesd as training set (158,297 records). Then, I encoded label into one-hot form to use in training process. # + # The rest of balanced validation set is training set train_df = data.drop(val_df.index.levels[1]) # Convert the labels to one_hot_category values one_hot_labels_train = to_categorical(train_df['label'].values, num_classes = 3) # - # Tokenization is how we break down text into such tokens (word, characters, or n-grams). Like all other neural networks, deep-learning models don’t take as input raw text (they only work with numeric tensors). Vectorizing text is the process of transforming text into numeric tensors. All text-vectorization processes consist of applying some tokenization scheme and then associating numeric vectors with the generated tokens. # # After we 'fit' text to the tokenizer, we generate index that represent each word (the same wrod in different sentense will use the same index). And 'text_to_sequences' transform sentence into a vector that use those indexes of word to represent word in sentences in order. # # 'pad_sequences' is uesd to make each vector has thesame size by adding more zero or cut off the rest. # + # Read a part of the reviews and create training sequences (x_train) tokenizer = Tokenizer(num_words = max_feature) tokenizer.fit_on_texts(data['review']) X_train_normal = pad_sequences(tokenizer.texts_to_sequences(train_df['review']), maxlen = max_len) X_val_normal = pad_sequences(tokenizer.texts_to_sequences(val_df['review']), maxlen = max_len) # - # ### Compute class_weight for training process # I use compute_class_weight function from scikitlearn library to <b>estimate class weights for unbalanced datasets</b>. We will use it when we fit model. class_weights = class_weight.compute_class_weight("balanced", [0,1,2], train_df['label'].values) class_weight_dict = {0: class_weights[0], 1: class_weights[1], 2: class_weights[2]} class_weight_dict # ### Define training and ploting functions # Similarly create a function for model training, for demonstration purposes we use constant values def train_model(model, x, y, vs, cb, model_name, last_path, his_path, e = epochs, bs = batch_size, ie = 0): # Start timing start = time.time() # Training print('Training ', model_name, '...') h = model.fit(x, y, epochs = e, batch_size = bs, verbose = 1, validation_data = vs, callbacks = cb, class_weight=class_weight_dict, initial_epoch=ie) stop = time.time() etime = stop - start print('Done. Elapsed time {:.0f} seconds for {:} epochs, average {:.1f} seconds/epoch.'.format(etime, e, etime/e)) # Save last model model.save(last_path) # Save the history with open(his_path, 'wb') as file_pi: pickle.dump(h.history, file_pi) return h # We use the same plotting commands several times, so create a function for that purpose def plot_history(history, path_baseline="100_his_m1"): # Load baseline history from file with open(path_baseline, "rb") as input_file: baseline_model = pd.DataFrame(pickle.load(input_file)) f, ax = plt.subplots(1, 2, figsize = (16, 7)) acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] base_val_acc = baseline_model['val_acc'] base_val_loss = baseline_model['val_loss'] base_acc = baseline_model['acc'] base_loss = baseline_model['loss'] epochs = range(1, len(acc) + 1) plt.sca(ax[0]) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.plot(epochs, base_acc, 'r:', label='Baseline model acc') plt.plot(epochs, base_val_acc, 'r--', label='Baseline model validation acc') plt.title('Training and validation accuracy') plt.ylim([0, 1]) plt.legend() plt.sca(ax[1]) plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.plot(epochs, base_loss, 'r:', label='Baseline model loss') plt.plot(epochs, base_val_loss, 'r--', label='Baseline model validation loss') plt.title('Training and validation loss') plt.ylim([0, 3]) plt.legend() plt.show() # ## 4. Modeling and compilation # Actually, I already tried to use multiple of architecture, some models work well and some doesn't (as you can see from my draft notebook here). # # So I ended up with follwing 4 models that I select to show in this notebok: # # 1. Embedding + Conv1D + LSTM (original) # 2. Embedding + Conv1D + LSTM (modified) # 3. Embedding + Conv1D + Stack of GRU # 4. Embedding + Conv1D + Bidirectional LSTM # # # ** you can see my tests from <a href="https://github.com/pasinJ/cognitive-systems-for-healthtechnology-applications/blob/master/Case%203%20%20First%20Trial.ipynb">my draft notebook</a> (without comments) if you want ** # ### Model 1 : Embedding + Conv1D + LSTM (original) # I got idea of this model from the last example model in 'Week 7' guideline notebook. After some tuning parameters and try many architectures of model, this got the <b>high accuracy model but the loss function showed very quick overfitting</b>. So, I set <b>this model as the baseline</b> and use it to compare with other models. # # The structure of model 1 is showed as following: m1 = Sequential() m1.add(Embedding(max_feature, embedded_dim, input_length = max_len)) m1.add(Conv1D(32, 7, activation='relu')) m1.add(MaxPooling1D(5)) m1.add(Conv1D(32, 7, activation='relu')) m1.add(LSTM(8, dropout = 0.5, recurrent_dropout = 0.5)) m1.add(Dropout(0.5)) m1.add(Dense(3, activation = 'softmax')) m1.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['acc']) m1.summary() # ### Model 2 : Embedding + Conv1D + LSTM (modified) # This model was modified from the first model by <b>adding more 'Dropout layer' to fight with overfitting</b> scenario. I increased size of filter in 'Conv1D layer' before adding 'Dropout layer' only tend to drop the performance. Increasing output size of 'LSTM layer' and adding more 'Dense layer' also tend to increase the performance. # # (<b>I already try to add 'regluration function' to each layer</b> but 'dropout layer' got a better result) # # The structure of model 2 is showed as following: m2 = Sequential() m2.add(Embedding(max_feature, embedded_dim, input_length = max_len)) m2.add(Dropout(0.3)) m2.add(Conv1D(32, 11, activation='relu')) m2.add(MaxPooling1D(5)) m2.add(Conv1D(32, 11, activation='relu')) m2.add(LSTM(16, dropout = 0.5, recurrent_dropout = 0.5)) m2.add(Dropout(0.3)) m2.add(Dense(16, activation = 'relu')) m2.add(Dropout(0.3)) m2.add(Dense(3, activation = 'softmax')) m2.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['acc']) m2.summary() # ### Model 3 : Embedding + Conv1D + Stack of GRU # It’s sometimes useful to <b>stack several recurrent layers one after the other in order to increase the representational power of a network</b>. I changed one 'LSTM layer' into stack of 2 'GRU layer' (I decided to use GRU in this model because of time consuming and limitation of resource reasons). I still used <b>2 Conv1D and Maxpooling because it help to decrease size of input</b> that make we used shorter time for training (it taked too long without Conv1D and Maxpooling) # # The structure of model 3 is showed as following: m3 = Sequential() m3.add(Embedding(max_feature, embedded_dim, input_length = max_len)) m3.add(Dropout(0.3)) m3.add(Conv1D(32, 11, activation='relu')) m3.add(MaxPooling1D(5)) m3.add(Conv1D(32, 11, activation='relu')) m3.add(GRU(16, dropout = 0.3, recurrent_dropout = 0.5, return_sequences = True)) m3.add(GRU(16, activation = 'relu', dropout = 0.3, recurrent_dropout = 0.5)) m3.add(Dropout(0.3)) m3.add(Dense(16, activation = 'relu')) m3.add(Dropout(0.3)) m3.add(Dense(3, activation = 'softmax')) m3.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['acc']) m3.summary() # ### Model 4 : Embedding + Conv1D + Bidirectional LSTM # The 'Bidiretional recurrent layer' present the same information to a recurrent network in different ways, increasing accuracy and mitigating forgetting issues. By processing a sequence both ways, a <b>bidirectional RNN can catch patterns that may be overlooked by a unidirectional RNN</b>. So, I add 'Bidiretional recurrent layer' to the old 'LSTM layer'. # # The structure of model 4 is showed as following: m4 = Sequential() m4.add(Embedding(max_feature, embedded_dim, input_length = max_len)) m4.add(Dropout(0.3)) m4.add(Conv1D(32, 11, activation='relu')) m4.add(MaxPooling1D(5)) m4.add(Conv1D(32, 11, activation='relu')) m4.add(Bidirectional(LSTM(16, dropout = 0.5, recurrent_dropout = 0.5))) m4.add(Dropout(0.3)) m4.add(Dense(16, activation = 'relu')) m4.add(Dropout(0.3)) m4.add(Dense(3, activation = 'softmax')) m4.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['acc']) m4.summary() # ## 5. Training and Validation # I trained every models with 100 epochs but use batch size of 512 or 1024 depend on complexity of model. I used 'ModelCheckpoint' function for saving epoch that got minimum validation loss and maximum validation accuracy. # ### Training model 1 : Embedding + Conv1D + LSTM (original) # + best_weight_min_loss_m1 = "best_min_loss_m1.hdf5" best_weight_max_acc_m1 = "best_max_acc_m1.hdf5" checkpoint_min_loss_m1 = ModelCheckpoint(best_weight_min_loss_m1, monitor='val_loss', verbose=1, save_best_only=True, mode='min') checkpoint_max_acc_m1 = ModelCheckpoint(best_weight_max_acc_m1, monitor='val_acc', verbose=1, save_best_only=True, mode='max') # Train the first model and plot the history (normal) h1 = train_model(m1, X_train_normal, one_hot_labels_train, (X_val_normal,one_hot_labels_val), [checkpoint_min_loss_m1, checkpoint_max_acc_m1], "Model 1 : Embedding + Conv1D + LSTM (original)", "100_m1.hdf5", "100_his_m1") plot_history(h1) print("Model 1: ") print("val_acc: ", max(h1.history['val_acc'])) print("val_loss: ", min(h1.history['val_loss'])) # - # This training model 1 used total time 10,790 seconds for 100 epochs and average time 107.9 seconds/epoch. # # As you can see from above accuracy and loss graph, accurary is quite stable at 80% rate but loss function incease very quickly that show overfitting of model # # <b>Maximum accuracy (97th epoch) = 0.8056<br> # Minimum loss (3rd epoch) = 0.7138</b> # ### Training model 2 : Embedding + Conv1D + LSTM (modified) # + best_weight_min_loss_m2 = "best_min_loss_m2.hdf5" best_weight_max_acc_m2 = "best_max_acc_m2.hdf5" checkpoint_min_loss_m2 = ModelCheckpoint(best_weight_min_loss_m2, monitor='val_loss', verbose=1, save_best_only=True, mode='min') checkpoint_max_acc_m2 = ModelCheckpoint(best_weight_max_acc_m2, monitor='val_acc', verbose=1, save_best_only=True, mode='max') # Train the first model and plot the history (normal) h2 = train_model(m2, X_train_normal, one_hot_labels_train, (X_val_normal,one_hot_labels_val), [checkpoint_min_loss_m2, checkpoint_max_acc_m2], "Model 2 : Embedding + Conv1D + LSTM (modified)", "100_m2.hdf5", "100_his_m2") plot_history(h2) print("Model 2: ") print("val_acc: ", max(h2.history['val_acc'])) print("val_loss: ", min(h2.history['val_loss'])) # - # This training model 2 used total time 11,434 seconds for 100 epochs and average time 114.3 seconds/epoch. # # As you can see from above accuracy and loss graph, accurary is quite stable at 80% rate but loss function look better than the first model, it show less overfitting. # # <b>Maximum accuracy (89th epoch) = 0.8143<br> # Minimum loss (15th epoch) = 0.6727</b> # ### Training model 3 : Embedding + Conv1D + Stack of GRU # + best_weight_min_loss_m3 = "best_min_loss_m3.hdf5" best_weight_max_acc_m3 = "best_max_acc_m3.hdf5" checkpoint_min_loss_m3 = ModelCheckpoint(best_weight_min_loss_m3, monitor='val_loss', verbose=1, save_best_only=True, mode='min') checkpoint_max_acc_m3 = ModelCheckpoint(best_weight_max_acc_m3, monitor='val_acc', verbose=1, save_best_only=True, mode='max') # Train the first model and plot the history (normal) h3 = train_model(m3, X_train_normal, one_hot_labels_train, (X_val_normal,one_hot_labels_val), [checkpoint_min_loss_m3, checkpoint_max_acc_m3], "Model 3 : Embedding + Conv1D + Stack of GRU", "100_m3.hdf5", "100_his_m3", bs = 1024) plot_history(h3) print("Model 3: ") print("val_acc: ", max(h3.history['val_acc'])) print("val_loss: ", min(h3.history['val_loss'])) # - # This training model 3 used total time 10,899 seconds for 100 epochs and average time 109.0 seconds/epoch. # # As you can see from above accuracy and loss graph, accurary is quite stable at 80% rate and loss function look better than the first model but more overfit than the second model. # # <b>Maximum accuracy (90th epoch) = 0.8160<br> # Minimum loss (11th epoch) = 0.7010</b> # ### Training model 4 : Embedding + Conv1D + Bidirectional LSTM # + best_weight_min_loss_m4 = "best_min_loss_m4.hdf5" best_weight_max_acc_m4 = "best_max_acc_m4.hdf5" checkpoint_min_loss_m4 = ModelCheckpoint(best_weight_min_loss_m4, monitor='val_loss', verbose=1, save_best_only=True, mode='min') checkpoint_max_acc_m4 = ModelCheckpoint(best_weight_max_acc_m4, monitor='val_acc', verbose=1, save_best_only=True, mode='max') # Train the first model and plot the history (normal) h4 = train_model(m4, X_train_normal, one_hot_labels_train, (X_val_normal,one_hot_labels_val), [checkpoint_min_loss_m4, checkpoint_max_acc_m4], "Model 4 : Embedding + Conv1D + Bidirectional LSTM", "100_m4.hdf5", "100_his_m4", bs = 1024) plot_history(h4) print("Model 4: ") print("val_acc: ", max(h4.history['val_acc'])) print("val_loss: ", min(h4.history['val_loss'])) # - # This training model 4 used total time 11,466 seconds for 100 epochs and average time 114.7 seconds/epoch. # # As you can see from above accuracy and loss graph, accurary is quite stable at 80% rate and loss function look better than the first model but more overfit than the second model. # # <b>Maximum accuracy (91th epoch) = 0.8129<br> # Minimum loss (8th epoch) = 0.7080</b> # ## 6. Evaluation # I use this function to showed efficiecy of each model by using the same validation set to compare min_loss and max_acc of each model. # Function to display confusion matrix, classification report, accuracy, specification, sensitivity, and false negative def display_results(path): # Load model from given path m = load_model(path) # Get the true and predicted values y_true = val_df['label'].values y_pred = m.predict(X_val_normal).argmax(1) with warnings.catch_warnings(): warnings.simplefilter("ignore") # Create confusion matrix cm = confusion_matrix(y_true, y_pred, labels=[0,1,2]) print('Confusion matrix:') print(cm) print('') # Calculate accuracy a = accuracy_score(y_true, y_pred) print('Accuracy: {:.4f}'.format(a)) print('') # Clear tensorflow backend session and delete m variable K.clear_session() del m # ### Selcetion the best of all # + print('Result from the min_loss model 1') display_results(best_weight_min_loss_m1) print('=====================================') print('Result from the max_acc model 1') display_results(best_weight_max_acc_m1) print('=====================================') # + print('Result from the min_loss model 2') display_results(best_weight_min_loss_m2) print('=====================================') print('Result from the max_acc model 2') display_results(best_weight_max_acc_m2) print('=====================================') # + print('Result from the min_loss model 3') display_results(best_weight_min_loss_m3) print('=====================================') print('Result from the max_acc model 3') display_results(best_weight_max_acc_m3) print('=====================================') # + print('Result from the min_loss model 4') display_results(best_weight_min_loss_m4) print('=====================================') print('Result from the max_acc model 4') display_results(best_weight_max_acc_m4) print('=====================================') # - # As the result, Top 2 best models (consider from high accuracy) are: # # 1. max_acc Model 3 Embedding + Conv1D + Stack of GRU (at 89th epoch) # * Accuracy = 81.60% # * Loss = 1.1694 # 2. max_acc Model 2 Embedding + Conv1D + LSTM (modified) (at 124th epoch) # * Accuracy = 81.43% # * Loss = 0.9556 # # From above comparison, the best model that I selected was <b>Model 2 Embedding + Conv1D + LSTM (modified)</b> because its accuracy is just a little bit different from model 3 but its loss is lower. # ### Defining my preprocess function # By observing the datset, I found some special mark such as <b>'\r\n' '&#039\;' '&amp\;'</b>. So, I tried to create my own to decode those special mark using 'BeautifulSoup' function and extract some short form of word (ex isn't = is not). I also <b>removed some stopwords</b> in review because those words may occur many times but it doesn't important to model to analyze. However, I defined <b>exception_list for some stopword that is important such as 'not', 'no', and 'nor'</b>, because I believe that negative form in sentence should be important to predict rating review ('good' = positive but 'not good' = negative). # + # Dictionary to extract short form of some words dic = {"isn't":"is not", "aren't":"are not", "wasn't":"was not", "weren't":"were not", "haven't":"have not","hasn't":"has not","hadn't":"had not","won't":"will not", "wouldn't":"would not", "don't":"do not", "doesn't":"does not","didn't":"did not", "can't":"can not","couldn't":"could not","shouldn't":"should not","mightn't":"might not", "mustn't":"must not", "dnt":"do not", "n":"and", "wasnt":"was not", "thks":"thanks", "thk":"thanks", "thank":"thanks", "re":"are", "cant":"can not", "thx":"thanks", "it's": "it is", "i'm": "i am", "he's": "he is", "she's": "she is", "you're": "you are", "we're": "we are", "they're": "they are", "i've": "i have", "you've": "you have", "we've": "we have", "they've": "they have"} # Exception list of stopword exception_list = ["not", "nor", "no", "than", "very"] replace_pattern = re.compile(r'\b(' + '|'.join(dic.keys()) + r')\b') tok = WordPunctTokenizer() # List of stopword in english stop_words = set(stopwords.words('english')) def preprocess_func(text): # Decode lxml special mark soup = BeautifulSoup(text, 'lxml') souped = soup.get_text() try: bom_removed = souped.decode("utf-8-sig").replace(u"\ufffd", "?") except: bom_removed = souped # Lowercase all character lower_case = bom_removed.lower() # Extract short form word pat_handled = replace_pattern.sub(lambda x: dic[x.group()], lower_case) # Remove stopword rm_stopwords = [w for w in tok.tokenize(pat_handled) if (not w in stop_words) or (w in exception_list)] # Getting only alphabet letters_only = [word for word in rm_stopwords if word.isalpha()] return " ".join(letters_only) # - # This is example of text before and after preprocessing: sample_text = train_df.sample()['review'].values print("Original text: ") print(sample_text) print() print("Preprocessed text: ") print(preprocess_func(sample_text[0])) # Then, I apply preprocess function to all dataset and tokenize them. # + # Apply preprocess function to each set X_all_train_pre = data['review'].apply(lambda x : preprocess_func(x)) X_train_pre = train_df['review'].apply(lambda x : preprocess_func(x)) X_val_pre = val_df['review'].apply(lambda x : preprocess_func(x)) # Read a part of the reviews and create training sequences (x_train) tokenizer_pre = Tokenizer(num_words = max_feature) tokenizer_pre.fit_on_texts(X_all_train_pre) X_train_pre = pad_sequences(tokenizer.texts_to_sequences(X_train_pre), maxlen = max_len) X_val_pre = pad_sequences(tokenizer.texts_to_sequences(X_val_pre), maxlen = max_len) # - # ### Word2Vec Embedding # Instead of learning word embeddings jointly with the problem you want to solve, you can load embedding vectors from a precomputed embedding space that you know is highly structured and exhibits useful properties—that captures generic aspects of language structure in case that that you may don't have enough dataset to train your own efficient embbeding layer. # # Instead of training the embedding layer, we can first separately learn word embeddings and then pass to the embedding layer. This approach also allows to use any pre-trained word embedding and also saves the time in training the classification model. <b>I will use the Gensim implementation of Word2Vec in this case.</b> # # Ref: https://towardsdatascience.com/machine-learning-word-embedding-sentiment-classification-using-keras-b83c28087456 # Sentence to list function def preprocess_w2v(lines): review_lines = list() for line in lines: tokens = word_tokenize(line) tokens = [w.lower() for w in tokens] table = str.maketrans('', '', string.punctuation) stripped = [w.translate(table) for w in tokens] review_lines.append(stripped) return review_lines # Apply function to all data all_w2v = preprocess_w2v(data['review'].values.tolist()) train_w2v = preprocess_w2v(train_df['review'].values.tolist()) val_w2v = preprocess_w2v(val_df['review'].values.tolist()) # + # Train Word2Vec model model = gensim.models.Word2Vec(sentences=all_w2v, size=embedded_dim, window=5, workers=4, min_count=1) words = list(model.wv.vocab) print('Vocabulary size: %d' % len(words)) # - # Save word2vec model filename = 'embedding_word2vec.txt' model.wv.save_word2vec_format(filename, binary=False) # Load word2vec model embeddings_index = {} f = open(os.path.join('', 'embedding_word2vec.txt'), encoding = 'utf-8') for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:]) embeddings_index[word] = coefs f.close() # + tokenizer_obj = Tokenizer(num_words = max_feature) tokenizer_obj.fit_on_texts(all_w2v) sequences = tokenizer_obj.texts_to_sequences(train_w2v) sequences_val = tokenizer_obj.texts_to_sequences(val_w2v) train_pad = pad_sequences(sequences, maxlen=max_len) val_pad = pad_sequences(sequences_val, maxlen=max_len) word_index = tokenizer_obj.word_index print('Found %s unique tokens.' % len(word_index)) # + num_words = len(word_index)+1 embedding_matrix = np.zeros((num_words, embedded_dim)) for word, i in word_index.items(): if i > num_words: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector # - # ### Comparing Without preprocess / Preprocess / Word2Vec # I compared my best architecture that was trained by dataset without preprocessing, dataset with preprocessing, and embedding layer with Word2Vec pre-train algorithm. def reinitial_best_model(isw2v=False): # Re-initial the best model m = Sequential() if(isw2v): m.add(Embedding(num_words, embedded_dim, embeddings_initializer = Constant(embedding_matrix), input_length = max_len, trainable = False)) else : m.add(Embedding(max_feature, embedded_dim, input_length = max_len)) m.add(Dropout(0.3)) m.add(Conv1D(32, 11, activation='relu')) m.add(MaxPooling1D(5)) m.add(Conv1D(32, 11, activation='relu')) m.add(LSTM(16, dropout = 0.5, recurrent_dropout = 0.5)) m.add(Dropout(0.3)) m.add(Dense(16, activation = 'relu')) m.add(Dropout(0.3)) m.add(Dense(3, activation = 'softmax')) m.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['acc']) return m # + # Re-initial the best model mbest = reinitial_best_model() # Train the best model with preprocessed data best_weight_min_loss_mbest_pre = "best_min_loss_mbest_pre.hdf5" best_weight_max_acc_mbest_pre = "best_max_acc_mbest_pre.hdf5" checkpoint_min_loss_mbest_pre = ModelCheckpoint(best_weight_min_loss_mbest_pre, monitor='val_loss', verbose=1, save_best_only=True, mode='min') checkpoint_max_acc_mbest_pre = ModelCheckpoint(best_weight_max_acc_mbest_pre, monitor='val_acc', verbose=1, save_best_only=True, mode='max') # Train the first model and plot the history (normal) h_pre = train_model(mbest, X_train_pre, one_hot_labels_train, (X_val_pre, one_hot_labels_val), [checkpoint_min_loss_mbest_pre, checkpoint_max_acc_mbest_pre], "Model 2 with preprocessed data", "100_mbest_pre.hdf5", "100_his_mbest_pre") # + plot_history(h_pre, "100_his_m2") print("Model 2 with preprocessed data: ") print("val_acc: ", max(h_pre.history['val_acc'])) print("val_loss: ", min(h_pre.history['val_loss'])) # Clear model and session del mbest K.clear_session() # - # As the result, <b>this model doesn't perform different from model that was trained by dataset without preprocessing</b>. Moreover, it look like to get less accuracy and higher loss. # + # Re-initial the best model mbest = reinitial_best_model(True) # Train the best model with preprocessed data best_weight_min_loss_mbest_w2v = "best_min_loss_mbest_w2v.hdf5" best_weight_max_acc_mbest_w2v = "best_max_acc_mbest_w2v.hdf5" checkpoint_min_loss_mbest_w2v = ModelCheckpoint(best_weight_min_loss_mbest_w2v, monitor='val_loss', verbose=1, save_best_only=True, mode='min') checkpoint_max_acc_mbest_w2v = ModelCheckpoint(best_weight_max_acc_mbest_w2v, monitor='val_acc', verbose=1, save_best_only=True, mode='max') # Train the first model and plot the history (normal) h_w2v = train_model(mbest, train_pad, one_hot_labels_train, (val_pad, one_hot_labels_val), [checkpoint_min_loss_mbest_w2v, checkpoint_max_acc_mbest_w2v], "Model 2 with Word2Vec", "100_mbest_w2v.hdf5", "100_his_mbest_w2v", bs=1024) plot_history(h_w2v, "100_his_m2") print("Model 2 with word2vec: ") print("val_acc: ", max(h_w2v.history['val_acc'])) print("val_loss: ", min(h_w2v.history['val_loss'])) # - # From above graphs, the accuracy and loss of both training-set and validation-set are very close to each other. We can say that <b>this model doesn't show overfitting, but at the same time its performance is less than the original model</b>. # # So, I chosen the model that was trained by <b>dataset without preprocessing as by best model</b>. # ## 7. Results and Discussion # ### Final model with test set # I imported the test-set data and decided to use balanced test-set to evaluate my final model. # + # Read the training data test = pd.read_csv(r'./drugsComTest_raw.csv') # Create labels based on the original article: Grässer et al. (2018) r_test = test['rating'] r_replace_test = r_test.replace({ 0 : 0, 1 : 0, 2: 0, 3: 0, 4: 0 }) r_replace_test = r_replace_test.replace({ 5 : 1, 6 : 1}) r_replace_test = r_replace_test.replace({ 7 : 2, 8 : 2, 9 : 2, 10 : 2}) # Add the label column to the data test['label'] = r_replace_test # Plot distribution of labels print(test['label'].value_counts()) # + # Group records by level feature g = data.groupby('label') # Sample records equal to SIZE//2 for each group for balancing the dataset test_df = g.apply(lambda x: x.sample(4829, random_state = seed)) # - # Read a part of the reviews and create training sequences (x_train) X_test_normal = pad_sequences(tokenizer.texts_to_sequences(test_df['review']), maxlen = max_len) # As same as the 'display_results' function that I define above, but this time I use test set (53,766 records) that is unseen data to evaluate my final model for getting the final score of my best model. # + print('Result from the BEST model') print('TEST SET') # Load the final model from the given path m_final = load_model("best_max_acc_m2.hdf5") # Get the true and predicted values y_true = test_df['label'].values y_pred = m_final.predict(X_test_normal).argmax(1) with warnings.catch_warnings(): warnings.simplefilter("ignore") # Create confusion matrix cm = confusion_matrix(y_true, y_pred, labels=[0,1,2]) print('Confusion matrix:') print(cm) print('') # Calculate accuracy a = accuracy_score(y_true, y_pred) print('Accuracy: {:.4f}'.format(a)) print('') # Display Classification report cr = classification_report(y_true, y_pred) print('Classification report:') print(cr) # - # ## 8. Conclusions # From this case, I have learned about how to use neural networks to process text data. In this case, using pretraining model doesn't help as the previous case (Case 2). I assume that maybe words in drug review are too specific, so it can't fit with pre-train model that use general word in training. # # Another topic that I have leraned in this assignment is about imbalance dataset. Class_weight defining is technique that I learn in this case to fight with imbalance data. As you can see from the final model evaluation, <b>I use balanced test-set to check that the model is bias or not</b>, and the result show that the model perform very good to every class without bias. # # This case quite take long time for training each model, so I hoped that if I have more time I can try more architectures model and find preprocessing function that can improve performance of my model.
Case 3. Patient Drug Review.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/mfernandes61/python-intro-gapminder/blob/binder/colab/08_data_frames.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="-c6wvyoJxkTr" # --- # title: "Pandas DataFrames" # teaching: 15 # exercises: 15 # questions: # - "How can I do statistical analysis of tabular data?" # objectives: # - "Select individual values from a Pandas dataframe." # - "Select entire rows or entire columns from a dataframe." # - "Select a subset of both rows and columns from a dataframe in a single operation." # - "Select a subset of a dataframe by a single Boolean criterion." # keypoints: # - "Use `DataFrame.iloc[..., ...]` to select values by integer location." # - "Use `:` on its own to mean all columns or all rows." # - "Select multiple columns or rows using `DataFrame.loc` and a named slice." # - "Result of slicing can be used in further operations." # - "Use comparisons to select data based on value." # - "Select values or NaN using a Boolean mask." # --- # # ## Note about Pandas DataFrames/Series # # A [DataFrame][pandas-dataframe] is a collection of [Series][pandas-series]; # The DataFrame is the way Pandas represents a table, and Series is the data-structure # Pandas use to represent a column. # # Pandas is built on top of the [Numpy][numpy] library, which in practice means that # most of the methods defined for Numpy Arrays apply to Pandas Series/DataFrames. # # What makes Pandas so attractive is the powerful interface to access individual records # of the table, proper handling of missing values, and relational-databases operations # between DataFrames. # # ## Selecting values # # To access a value at the position `[i,j]` of a DataFrame, we have two options, depending on # what is the meaning of `i` in use. # Remember that a DataFrame provides an *index* as a way to identify the rows of the table; # a row, then, has a *position* inside the table as well as a *label*, which # uniquely identifies its *entry* in the DataFrame. # # ## Use `DataFrame.iloc[..., ...]` to select values by their (entry) position # # * Can specify location by numerical index analogously to 2D version of character selection in strings. # # ~~~ # import pandas as pd # data = pd.read_csv('data/gapminder_gdp_europe.csv', index_col='country') # print(data.iloc[0, 0]) # ~~~ # {: .language-python} # ~~~ # 1601.056136 # ~~~ # {: .output} # # ## Use `DataFrame.loc[..., ...]` to select values by their (entry) label. # # * Can specify location by row name analogously to 2D version of dictionary keys. # # ~~~ # print(data.loc["Albania", "gdpPercap_1952"]) # ~~~ # {: .language-python} # ~~~ # 1601.056136 # ~~~ # {: .output} # ## Use `:` on its own to mean all columns or all rows. # # * Just like Python's usual slicing notation. # # ~~~ # print(data.loc["Albania", :]) # ~~~ # {: .language-python} # ~~~ # gdpPercap_1952 1601.056136 # gdpPercap_1957 1942.284244 # gdpPercap_1962 2312.888958 # gdpPercap_1967 2760.196931 # gdpPercap_1972 3313.422188 # gdpPercap_1977 3533.003910 # gdpPercap_1982 3630.880722 # gdpPercap_1987 3738.932735 # gdpPercap_1992 2497.437901 # gdpPercap_1997 3193.054604 # gdpPercap_2002 4604.211737 # gdpPercap_2007 5937.029526 # Name: Albania, dtype: float64 # ~~~ # {: .output} # # * Would get the same result printing `data.loc["Albania"]` (without a second index). # # ~~~ # print(data.loc[:, "gdpPercap_1952"]) # ~~~ # {: .language-python} # ~~~ # country # Albania 1601.056136 # Austria 6137.076492 # Belgium 8343.105127 # ⋮ ⋮ ⋮ # Switzerland 14734.232750 # Turkey 1969.100980 # United Kingdom 9979.508487 # Name: gdpPercap_1952, dtype: float64 # ~~~ # {: .output} # # * Would get the same result printing `data["gdpPercap_1952"]` # * Also get the same result printing `data.gdpPercap_1952` (not recommended, because easily confused with `.` notation for methods) # # ## Select multiple columns or rows using `DataFrame.loc` and a named slice. # # ~~~ # print(data.loc['Italy':'Poland', 'gdpPercap_1962':'gdpPercap_1972']) # ~~~ # {: .language-python} # ~~~ # gdpPercap_1962 gdpPercap_1967 gdpPercap_1972 # country # Italy 8243.582340 10022.401310 12269.273780 # Montenegro 4649.593785 5907.850937 7778.414017 # Netherlands 12790.849560 15363.251360 18794.745670 # Norway 13450.401510 16361.876470 18965.055510 # Poland 5338.752143 6557.152776 8006.506993 # ~~~ # {: .output} # # In the above code, we discover that **slicing using `loc` is inclusive at both # ends**, which differs from **slicing using `iloc`**, where slicing indicates # everything up to but not including the final index. # # # ## Result of slicing can be used in further operations. # # * Usually don't just print a slice. # * All the statistical operators that work on entire dataframes # work the same way on slices. # * E.g., calculate max of a slice. # # ~~~ # print(data.loc['Italy':'Poland', 'gdpPercap_1962':'gdpPercap_1972'].max()) # ~~~ # {: .language-python} # ~~~ # gdpPercap_1962 13450.40151 # gdpPercap_1967 16361.87647 # gdpPercap_1972 18965.05551 # dtype: float64 # ~~~ # {: .output} # # ~~~ # print(data.loc['Italy':'Poland', 'gdpPercap_1962':'gdpPercap_1972'].min()) # ~~~ # {: .language-python} # ~~~ # gdpPercap_1962 4649.593785 # gdpPercap_1967 5907.850937 # gdpPercap_1972 7778.414017 # dtype: float64 # ~~~ # {: .output} # # ## Use comparisons to select data based on value. # # * Comparison is applied element by element. # * Returns a similarly-shaped dataframe of `True` and `False`. # # ~~~ # # Use a subset of data to keep output readable. # subset = data.loc['Italy':'Poland', 'gdpPercap_1962':'gdpPercap_1972'] # print('Subset of data:\n', subset) # # # Which values were greater than 10000 ? # print('\nWhere are values large?\n', subset > 10000) # ~~~ # {: .language-python} # ~~~ # Subset of data: # gdpPercap_1962 gdpPercap_1967 gdpPercap_1972 # country # Italy 8243.582340 10022.401310 12269.273780 # Montenegro 4649.593785 5907.850937 7778.414017 # Netherlands 12790.849560 15363.251360 18794.745670 # Norway 13450.401510 16361.876470 18965.055510 # Poland 5338.752143 6557.152776 8006.506993 # # Where are values large? # gdpPercap_1962 gdpPercap_1967 gdpPercap_1972 # country # Italy False True True # Montenegro False False False # Netherlands True True True # Norway True True True # Poland False False False # ~~~ # {: .output} # # ## Select values or NaN using a Boolean mask. # # * A frame full of Booleans is sometimes called a *mask* because of how it can be used. # # ~~~ # mask = subset > 10000 # print(subset[mask]) # ~~~ # {: .language-python} # ~~~ # gdpPercap_1962 gdpPercap_1967 gdpPercap_1972 # country # Italy NaN 10022.40131 12269.27378 # Montenegro NaN NaN NaN # Netherlands 12790.84956 15363.25136 18794.74567 # Norway 13450.40151 16361.87647 18965.05551 # Poland NaN NaN NaN # ~~~ # {: .output} # # * Get the value where the mask is true, and NaN (Not a Number) where it is false. # * Useful because NaNs are ignored by operations like max, min, average, etc. # # ~~~ # print(subset[subset > 10000].describe()) # ~~~ # {: .language-python} # ~~~ # gdpPercap_1962 gdpPercap_1967 gdpPercap_1972 # count 2.000000 3.000000 3.000000 # mean 13120.625535 13915.843047 16676.358320 # std 466.373656 3408.589070 3817.597015 # min 12790.849560 10022.401310 12269.273780 # 25% 12955.737547 12692.826335 15532.009725 # 50% 13120.625535 15363.251360 18794.745670 # 75% 13285.513523 15862.563915 18879.900590 # max 13450.401510 16361.876470 18965.055510 # ~~~ # {: .output} # # ## Group By: split-apply-combine # # Pandas vectorizing methods and grouping operations are features that provide users # much flexibility to analyse their data. # # For instance, let's say we want to have a clearer view on how the European countries # split themselves according to their GDP. # # 1. We may have a glance by splitting the countries in two groups during the years surveyed, # those who presented a GDP *higher* than the European average and those with a *lower* GDP. # 2. We then estimate a *wealthy score* based on the historical (from 1962 to 2007) values, # where we account how many times a country has participated in the groups of *lower* or *higher* GDP # # ~~~ # mask_higher = data > data.mean() # wealth_score = mask_higher.aggregate('sum', axis=1) / len(data.columns) # wealth_score # ~~~ # {: .language-python} # ~~~ # country # Albania 0.000000 # Austria 1.000000 # Belgium 1.000000 # Bosnia and Herzegovina 0.000000 # Bulgaria 0.000000 # Croatia 0.000000 # Czech Republic 0.500000 # Denmark 1.000000 # Finland 1.000000 # France 1.000000 # Germany 1.000000 # Greece 0.333333 # Hungary 0.000000 # Iceland 1.000000 # Ireland 0.333333 # Italy 0.500000 # Montenegro 0.000000 # Netherlands 1.000000 # Norway 1.000000 # Poland 0.000000 # Portugal 0.000000 # Romania 0.000000 # Serbia 0.000000 # Slovak Republic 0.000000 # Slovenia 0.333333 # Spain 0.333333 # Sweden 1.000000 # Switzerland 1.000000 # Turkey 0.000000 # United Kingdom 1.000000 # dtype: float64 # ~~~ # {: .output} # # Finally, for each group in the `wealth_score` table, we sum their (financial) contribution # across the years surveyed using chained methods: # # ~~~ # data.groupby(wealth_score).sum() # ~~~ # {: .language-python} # ~~~ # gdpPercap_1952 gdpPercap_1957 gdpPercap_1962 gdpPercap_1967 \ # 0.000000 36916.854200 46110.918793 56850.065437 71324.848786 # 0.333333 16790.046878 20942.456800 25744.935321 33567.667670 # 0.500000 11807.544405 14505.000150 18380.449470 21421.846200 # 1.000000 104317.277560 127332.008735 149989.154201 178000.350040 # # gdpPercap_1972 gdpPercap_1977 gdpPercap_1982 gdpPercap_1987 \ # 0.000000 88569.346898 104459.358438 113553.768507 119649.599409 # 0.333333 45277.839976 53860.456750 59679.634020 64436.912960 # 0.500000 25377.727380 29056.145370 31914.712050 35517.678220 # 1.000000 215162.343140 241143.412730 263388.781960 296825.131210 # # gdpPercap_1992 gdpPercap_1997 gdpPercap_2002 gdpPercap_2007 # 0.000000 92380.047256 103772.937598 118590.929863 149577.357928 # 0.333333 67918.093220 80876.051580 102086.795210 122803.729520 # 0.500000 36310.666080 40723.538700 45564.308390 51403.028210 # 1.000000 315238.235970 346930.926170 385109.939210 427850.333420 # ~~~ # {: .output} # # # > ## Selection of Individual Values # > # > Assume Pandas has been imported into your notebook # > and the Gapminder GDP data for Europe has been loaded: # > # > ~~~ # > import pandas as pd # > # > df = pd.read_csv('data/gapminder_gdp_europe.csv', index_col='country') # > ~~~ # > {: .language-python} # > # > Write an expression to find the Per Capita GDP of Serbia in 2007. # > > ## Solution # > > The selection can be done by using the labels for both the row ("Serbia") and the column ("gdpPercap_2007"): # > > ~~~ # > > print(df.loc['Serbia', 'gdpPercap_2007']) # > > ~~~ # > > {: .language-python} # > > The output is # > > ~~~ # > > 9786.534714 # > > ~~~ # > >{: .output} # > {: .solution} # {: .challenge} # # > ## Extent of Slicing # > # > 1. Do the two statements below produce the same output? # > 2. Based on this, # > what rule governs what is included (or not) in numerical slices and named slices in Pandas? # > # > ~~~ # > print(df.iloc[0:2, 0:2]) # > print(df.loc['Albania':'Belgium', 'gdpPercap_1952':'gdpPercap_1962']) # > ~~~ # > {: .language-python} # > # > > ## Solution # > > No, they do not produce the same output! The output of the first statement is: # > > ~~~ # > > gdpPercap_1952 gdpPercap_1957 # > > country # > > Albania 1601.056136 1942.284244 # > > Austria 6137.076492 8842.598030 # > > ~~~ # > >{: .output} # > > The second statement gives: # > > ~~~ # > > gdpPercap_1952 gdpPercap_1957 gdpPercap_1962 # > > country # > > Albania 1601.056136 1942.284244 2312.888958 # > > Austria 6137.076492 8842.598030 10750.721110 # > > Belgium 8343.105127 9714.960623 10991.206760 # > > ~~~ # > >{: .output} # > > Clearly, the second statement produces an additional column and an additional row compared to the first statement. # > > What conclusion can we draw? We see that a numerical slice, 0:2, *omits* the final index (i.e. index 2) # > > in the range provided, # > > while a named slice, 'gdpPercap_1952':'gdpPercap_1962', *includes* the final element. # > {: .solution} # {: .challenge} # # > ## Reconstructing Data # > # > Explain what each line in the following short program does: # > what is in `first`, `second`, etc.? # > # > ~~~ # > first = pd.read_csv('data/gapminder_all.csv', index_col='country') # > second = first[first['continent'] == 'Americas'] # > third = second.drop('Puerto Rico') # > fourth = third.drop('continent', axis = 1) # > fourth.to_csv('result.csv') # > ~~~ # > {: .language-python} # > # > > ## Solution # > > Let's go through this piece of code line by line. # > > ~~~ # > > first = pd.read_csv('data/gapminder_all.csv', index_col='country') # > > ~~~ # > > {: .language-python} # > > This line loads the dataset containing the GDP data from all countries into a dataframe called # > > `first`. The `index_col='country'` parameter selects which column to use as the # > > row labels in the dataframe. # > > ~~~ # > > second = first[first['continent'] == 'Americas'] # > > ~~~ # > > {: .language-python} # > > This line makes a selection: only those rows of `first` for which the 'continent' column matches # > > 'Americas' are extracted. Notice how the Boolean expression inside the brackets, # > > `first['continent'] == 'Americas'`, is used to select only those rows where the expression is true. # > > Try printing this expression! Can you print also its individual True/False elements? # > > (hint: first assign the expression to a variable) # > > ~~~ # > > third = second.drop('Puerto Rico') # > > ~~~ # > > {: .language-python} # > > As the syntax suggests, this line drops the row from `second` where the label is 'Puerto Rico'. The # > > resulting dataframe `third` has one row less than the original dataframe `second`. # > > ~~~ # > > fourth = third.drop('continent', axis = 1) # > > ~~~ # > > {: .language-python} # > > Again we apply the drop function, but in this case we are dropping not a row but a whole column. # > > To accomplish this, we need to specify also the `axis` parameter (we want to drop the second column # > > which has index 1). # > > ~~~ # > > fourth.to_csv('result.csv') # > > ~~~ # > > {: .language-python} # > > The final step is to write the data that we have been working on to a csv file. Pandas makes this easy # > > with the `to_csv()` function. The only required argument to the function is the filename. Note that the # > > file will be written in the directory from which you started the Jupyter or Python session. # > {: .solution} # {: .challenge} # # > ## Selecting Indices # > # > Explain in simple terms what `idxmin` and `idxmax` do in the short program below. # > When would you use these methods? # > # > ~~~ # > data = pd.read_csv('data/gapminder_gdp_europe.csv', index_col='country') # > print(data.idxmin()) # > print(data.idxmax()) # > ~~~ # > {: .language-python} # > # > > ## Solution # > > For each column in `data`, `idxmin` will return the index value corresponding to each column's minimum; # > > `idxmax` will do accordingly the same for each column's maximum value. # > > # > > You can use these functions whenever you want to get the row index of the minimum/maximum value and not the actual minimum/maximum value. # > {: .solution} # {: .challenge} # # > ## Practice with Selection # > # > Assume Pandas has been imported and the Gapminder GDP data for Europe has been loaded. # > Write an expression to select each of the following: # > # > 1. GDP per capita for all countries in 1982. # > 2. GDP per capita for Denmark for all years. # > 3. GDP per capita for all countries for years *after* 1985. # > 4. GDP per capita for each country in 2007 as a multiple of # > GDP per capita for that country in 1952. # > # > > ## Solution # > > 1: # > > ~~~ # > > data['gdpPercap_1982'] # > > ~~~ # > > {: .language-python} # > > # > > 2: # > > ~~~ # > > data.loc['Denmark',:] # > > ~~~ # > > {: .language-python} # > > # > > 3: # > > ~~~ # > > data.loc[:,'gdpPercap_1985':] # > > ~~~ # > > {: .language-python} # > > Pandas is smart enough to recognize the number at the end of the column label and does not give you an error, although no column named `gdpPercap_1985` actually exists. This is useful if new columns are added to the CSV file later. # > > # > > 4: # > > ~~~ # > > data['gdpPercap_2007']/data['gdpPercap_1952'] # > > ~~~ # > > {: .language-python} # > {: .solution} # {: .challenge} # # > ## Many Ways of Access # > # > There are at least two ways of accessing a value or slice of a DataFrame: by name or index. # > However, there are many others. For example, a single column or row can be accessed either as a `DataFrame` # > or a `Series` object. # > # > Suggest different ways of doing the following operations on a DataFrame: # > 1. Access a single column # > 2. Access a single row # > 3. Access an individual DataFrame element # > 4. Access several columns # > 5. Access several rows # > 6. Access a subset of specific rows and columns # > 7. Access a subset of row and column ranges # > # {: .challenge} # > # > > ## Solution # > > 1\. Access a single column: # > > ~~~ # > > # by name # > > data["col_name"] # as a Series # > > data[["col_name"]] # as a DataFrame # > > # > > # by name using .loc # > > data.T.loc["col_name"] # as a Series # > > data.T.loc[["col_name"]].T # as a DataFrame # > > # > > # Dot notation (Series) # > > data.col_name # > > # > > # by index (iloc) # > > data.iloc[:, col_index] # as a Series # > > data.iloc[:, [col_index]] # as a DataFrame # > > # > > # using a mask # > > data.T[data.T.index == "col_name"].T # > > ~~~ # > > {: .language-python} # > > # > > 2\. Access a single row: # > > ~~~ # > > # by name using .loc # > > data.loc["row_name"] # as a Series # > > data.loc[["row_name"]] # as a DataFrame # > > # > > # by name # > > data.T["row_name"] # as a Series # > > data.T[["row_name"]].T as a DataFrame # > > # > > # by index # > > data.iloc[row_index] # as a Series # > > data.iloc[[row_index]] # as a DataFrame # > > # > > # using mask # > > data[data.index == "row_name"] # > > ~~~ # > > {: .language-python} # > > # > > 3\. Access an individual DataFrame element: # > > ~~~ # > > # by column/row names # > > data["column_name"]["row_name"] # as a Series # > > # > > data[["col_name"]].loc["row_name"] # as a Series # > > data[["col_name"]].loc[["row_name"]] # as a DataFrame # > > # > > data.loc["row_name"]["col_name"] # as a value # > > data.loc[["row_name"]]["col_name"] # as a Series # > > data.loc[["row_name"]][["col_name"]] # as a DataFrame # > > # > > data.loc["row_name", "col_name"] # as a value # > > data.loc[["row_name"], "col_name"] # as a Series. Preserves index. Column name is moved to `.name`. # > > data.loc["row_name", ["col_name"]] # as a Series. Index is moved to `.name.` Sets index to column name. # > > data.loc[["row_name"], ["col_name"]] # as a DataFrame (preserves original index and column name) # > > # > > # by column/row names: Dot notation # > > data.col_name.row_name # > > # > > # by column/row indices # > > data.iloc[row_index, col_index] # as a value # > > data.iloc[[row_index], col_index] # as a Series. Preserves index. Column name is moved to `.name` # > > data.iloc[row_index, [col_index]] # as a Series. Index is moved to `.name.` Sets index to column name. # > > data.iloc[[row_index], [col_index]] # as a DataFrame (preserves original index and column name) # > > # > > # column name + row index # > > data["col_name"][row_index] # > > data.col_name[row_index] # > > data["col_name"].iloc[row_index] # > > # > > # column index + row name # > > data.iloc[:, [col_index]].loc["row_name"] # as a Series # > > data.iloc[:, [col_index]].loc[["row_name"]] # as a DataFrame # > > # > > # using masks # > > data[data.index == "row_name"].T[data.T.index == "col_name"].T # > > ~~~ # > > {: .language-python} # > > 4\. Access several columns: # > > ~~~ # > > # by name # > > data[["col1", "col2", "col3"]] # > > data.loc[:, ["col1", "col2", "col3"]] # > > # > > # by index # > > data.iloc[:, [col1_index, col2_index, col3_index]] # > > ~~~ # > > {: .language-python} # > > 5\. Access several rows # > > ~~~ # > > # by name # > > data.loc[["row1", "row2", "row3"]] # > > # > > # by index # > > data.iloc[[row1_index, row2_index, row3_index]] # > > ~~~ # > > {: .language-python} # > > 6\. Access a subset of specific rows and columns # > > ~~~ # > > # by names # > > data.loc[["row1", "row2", "row3"], ["col1", "col2", "col3"]] # > > # > > # by indices # > > data.iloc[[row1_index, row2_index, row3_index], [col1_index, col2_index, col3_index]] # > > # > > # column names + row indices # > > data[["col1", "col2", "col3"]].iloc[[row1_index, row2_index, row3_index]] # > > # > > # column indices + row names # > > data.iloc[:, [col1_index, col2_index, col3_index]].loc[["row1", "row2", "row3"]] # > > ~~~ # > > {: .language-python} # > > 7\. Access a subset of row and column ranges # > > ~~~ # > > # by name # > > data.loc["row1":"row2", "col1":"col2"] # > > # > > # by index # > > data.iloc[row1_index:row2_index, col1_index:col2_index] # > > # > > # column names + row indices # > > data.loc[:, "col1_name":"col2_name"].iloc[row1_index:row2_index] # > > # > > # column indices + row names # > > data.iloc[:, col1_index:col2_index].loc["row1":"row2"] # > > ~~~ # > > {: .language-python} # > {: .solution} # {: .challenge} # # > ## Exploring available methods using the `dir()` function # > # > Python includes a `dir()` function that can be used to display all of the available methods (functions) that are built into a data object. In Episode 4, we used some methods with a string. But we can see many more are available by using `dir()`: # > # > ~~~ # > my_string = 'Hello world!' # creation of a string object # > dir(my_string) # > ~~~ # > {: .language-python} # > # > This command returns: # > # > ~~~ # > ['__add__', # > ... # > '__subclasshook__', # > 'capitalize', # > 'casefold', # > 'center', # > ... # > 'upper', # > 'zfill'] # > ~~~ # > {: .language-python} # > # > You can use `help()` or <kbd>Shift</kbd>+<kbd>Tab</kbd> to get more information about what these methods do. # > # > Assume Pandas has been imported and the Gapminder GDP data for Europe has been loaded as `data`. Then, use `dir()` # > to find the function that prints out the median per-capita GDP across all European countries for each year that information is available. # > # > > ## Solution # > > Among many choices, `dir()` lists the `median()` function as a possibility. Thus, # > > ~~~ # > > data.median() # > > ~~~ # > > {: .language-python} # > {: .solution} # {: .challenge} # # # > ## Interpretation # > # > Poland's borders have been stable since 1945, # > but changed several times in the years before then. # > How would you handle this if you were creating a table of GDP per capita for Poland # > for the entire twentieth century? # {: .challenge} # # # [pandas-dataframe]: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html # [pandas-series]: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html # [numpy]: http://www.numpy.org/ # + [markdown] id="W0FPq4Hlxl1Z" # # + id="kb0GyFJ6xiCy"
colab/08_data_frames.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="n3y2gU1Nw-Ng" colab={"base_uri": "https://localhost:8080/"} outputId="f81047fb-7cc4-444c-9c37-b8cd13812706" pip install -U scikit-learn # + id="mub0ifexvqP4" colab={"base_uri": "https://localhost:8080/"} outputId="2d3c851e-0bf2-4682-9abc-e6493469bc66" import pandas as pd from pathlib import PurePath import numpy as np import data_construction as dc from sklearn import linear_model from sklearn.model_selection import TimeSeriesSplit from sklearn.metrics import mean_squared_error as mse from statsmodels.tsa.arima_model import ARIMA from statsmodels.tsa.stattools import adfuller import matplotlib.pyplot as plt from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from pandas.plotting import autocorrelation_plot # + [markdown] id="6HagO-2EAnDi" # Data Preparation # + id="ibsGav9yvwTj" # file clean_data = 'cleaned_full_data.csv' # import data df = pd.read_csv(clean_data, index_col=0) # interpolate and join test = dc.det_interp(df.iloc[:,1]) econ_interp = df.iloc[:,:-1].apply(dc.det_interp, axis=0) df = pd.concat([econ_interp, df.iloc[:,-1]], axis=1, join="outer") # perform time lags df['SVENY10_1'] = df['SVENY10'].shift(1) df['SVENY10_60'] = df['SVENY10'].shift(60) df_lag_1 = df.iloc[:,:-1].dropna().drop(['SVENY10'], axis=1) df_lag_60 = df.drop(['SVENY10_1', 'SVENY10'], axis=1).dropna() df = df.iloc[:,:-2] # test vs train tscv = TimeSeriesSplit(n_splits=5, test_size=60) # Taking on the results of yield into account df_arima = df.iloc[:, [-1]] df_arima_train = df_arima.iloc[df_arima.shape[0] - 500:-10, :] df_arima_test = df_arima.iloc[-10:, :] # + [markdown] id="5bVeCggUAqVj" # Performing Dicker Fuller test to identify stationarity of data # + colab={"base_uri": "https://localhost:8080/"} id="T9q3-KByGnKZ" outputId="b608fd51-90b4-4b9f-fde1-a6829bcd572d" result = adfuller(df_arima_train['SVENY10']) print('ADF Statistic: {}'.format(result[0])) print('p-value: {}'.format(result[1])) # + [markdown] id="4u5priGJA_1D" # Dicker Fuller test on differenced data # + colab={"base_uri": "https://localhost:8080/"} id="1mx5TMNy7ISP" outputId="4e6a5e2c-d3bf-4a23-82b4-04863b5fb1ce" # selecting d=1 result = adfuller(df_arima_train['SVENY10'].diff().dropna()) print('ADF Statistic: {}'.format(result[0])) print('p-value: {}'.format(result[1])) # + colab={"base_uri": "https://localhost:8080/", "height": 248} id="9V6Q7wJ_Hv9i" outputId="f0e1092c-5eda-46be-e3b8-20ba1c6c9308" fig, axes = plt.subplots(2) axes[0].plot(df_arima_train['SVENY10'].dropna()) axes[1].plot(df_arima_train['SVENY10'].diff().dropna()) axes[0].tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False) axes[1].tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False) plt.show() # + [markdown] id="LEsbchQHb69J" # The optimal level of difference is also the one with lower standard deviation # + colab={"base_uri": "https://localhost:8080/", "height": 248} id="LDQeOOYhaCtX" outputId="14a1a306-60cb-4a24-88a4-99778b48e08d" plt.plot(df_arima_train['SVENY10'].rolling(12).std()) plt.plot(df_arima_train['SVENY10'].diff(1).rolling(12).std()) plt.plot(df_arima_train['SVENY10'].diff(2).rolling(12).std()) plt.legend(['d=0', 'd=1', 'd=2']) plt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False) plt.show() # + [markdown] id="HYR1uNasBJI7" # Autocorrection graph to identify AR and MA terms # + colab={"base_uri": "https://localhost:8080/", "height": 809} id="pzn2YYFMTP79" outputId="cfd8a511-3542-4170-98fc-bce4efbe3f38" # p value = 1 plot_acf(df_arima_train['SVENY10'].diff().dropna(), lags=20) plot_pacf(df_arima_train['SVENY10'].diff().dropna(), lags=20) # + colab={"base_uri": "https://localhost:8080/"} id="f8733CvhPKXM" outputId="0d8385cc-4e07-4e99-a712-86bff89d4160" model = ARIMA(df_arima_train['SVENY10'], order=(1,1,0)) model_fit = model.fit(disp=0) print(model_fit.summary()) # + colab={"base_uri": "https://localhost:8080/", "height": 793} id="bBy6NKV2Whw7" outputId="12c411e9-7aff-4152-c4c6-9cc226077aa7" residuals = pd.DataFrame(model_fit.resid) residuals.plot() residuals.plot(kind='kde') residuals.describe() # + colab={"base_uri": "https://localhost:8080/", "height": 300} id="O9Ic6KgwWSpN" outputId="bf15cade-b942-4d15-d1b4-e59773b02c8c" autocorrelation_plot(residuals) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="kDxUaaaIbCBq" outputId="5ef1ec2a-9b35-49d3-a43a-74ac33cc0d43" model_fit.plot_predict(dynamic=False) plt.show() # + id="QvRGQSj5bZeC" fc, se, conf = model_fit.forecast(10, alpha=0.05) # + colab={"base_uri": "https://localhost:8080/", "height": 268} id="GQrmEWarbjLb" outputId="da2449c5-9c8e-4d16-9737-d516368f9e8d" fc_series = pd.Series(fc, index=df_arima_test.index) lower_series = pd.Series(conf[:, 0], index=df_arima_test.index) upper_series = pd.Series(conf[:, 1], index=df_arima_test.index) plt.figure() plt.plot(df_arima_train.iloc[-20:,:], label='training') plt.plot(df_arima_test, label='actual') plt.plot(fc_series, label='forecast') plt.fill_between(lower_series.index, lower_series, upper_series, color='k', alpha=.15) plt.title('Forecast vs Actuals') plt.legend(loc='upper left', fontsize=8) plt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False) plt.show()
notebooks/CS680_ARIMA_Project.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from sklearn import linear_model from sklearn.metrics import mean_absolute_error import os import numpy as np import xgboost train = np.load("./Inverter_1_2017-03-30/train.npy") test = np.load("./Inverter_1_2017-03-30/test.npy") train.shape , test.shape x_train , y_train = train[:,1:] , train[:,0].reshape((-1,1)) x_test , y_test = test[:,1:] , test[:,0].reshape((-1,1)) x_train.shape, y_train.shape, x_test.shape, y_test.shape lin_mod = linear_model.LinearRegression() lin_mod.fit(x_train,y_train) y_pred = lin_mod.predict(x_test) mean_absolute_error(y_test,y_pred) lin_mod = linear_model.Lasso(alpha=0.01) lin_mod.fit(x_train,y_train) y_pred = lin_mod.predict(x_test) mean_absolute_error(y_test,y_pred) lin_mod = xgboost.XGBRegressor() lin_mod.fit(x_train,y_train) y_pred = lin_mod.predict(x_test) mean_absolute_error(y_test,y_pred) # | Algorithm | Test Set MAE| # | ------------- | ------------- | # |Bonsai | 0.6228 # |Linear Regression | 0.655 # |Lasso Regression | 0.6425 # |XG Boost | 0.5965
Comparison-Results.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Exercise 10 # # # Capital Bikeshare data # ## Introduction # # - Capital Bikeshare dataset from Kaggle: [data](https://github.com/justmarkham/DAT8/blob/master/data/bikeshare.csv), [data dictionary](https://www.kaggle.com/c/bike-sharing-demand/data) # - Each observation represents the bikeshare rentals initiated during a given hour of a given day # %matplotlib inline import pandas as pd import numpy as np from sklearn.cross_validation import cross_val_score from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor, export_graphviz # read the data and set "datetime" as the index url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/bikeshare.csv' bikes = pd.read_csv(url, index_col='datetime', parse_dates=True) # "count" is a method, so it's best to rename that column bikes.rename(columns={'count':'total'}, inplace=True) # create "hour" as its own feature bikes['hour'] = bikes.index.hour bikes.head() bikes.tail() # - **hour** ranges from 0 (midnight) through 23 (11pm) # - **workingday** is either 0 (weekend or holiday) or 1 (non-holiday weekday) # # Exercice 13.1 # # Run these two `groupby` statements and figure out what they tell you about the data. # mean rentals for each value of "workingday" bikes.groupby('workingday').total.mean() # mean rentals for each value of "hour" bikes.groupby('hour').total.mean() # # Exercice 13.2 # # Run this plotting code, and make sure you understand the output. Then, separate this plot into two separate plots conditioned on "workingday". (In other words, one plot should display the hourly trend for "workingday=0", and the other should display the hourly trend for "workingday=1".) # mean rentals for each value of "hour" bikes.groupby('hour').total.mean().plot() # Plot for workingday == 0 and workingday == 1 # hourly rental trend for "workingday=0" bikes[bikes.workingday==0].groupby('hour').total.mean().plot() # hourly rental trend for "workingday=1" bikes[bikes.workingday==1].groupby('hour').total.mean().plot() # combine the two plots bikes.groupby(['hour', 'workingday']).total.mean().unstack().plot() # Write about your findings # # Exercice 13.3 # # Fit a linear regression model to the entire dataset, using "total" as the response and "hour" and "workingday" as the only features. Then, print the coefficients and interpret them. What are the limitations of linear regression in this instance? # create X and y feature_cols = ['hour', 'workingday'] X = bikes[feature_cols] y = bikes.total # fit a linear regression model and print coefficients linreg = LinearRegression() linreg.fit(X, y) linreg.coef_ # # Exercice 13.4 # # Use 10-fold cross-validation to calculate the RMSE for the linear regression model. # save the 10 MSE scores output by cross_val_score scores = cross_val_score(linreg, X, y, cv=10, scoring='mean_squared_error') # convert MSE to RMSE, and then calculate the mean of the 10 RMSE scores np.mean(np.sqrt(-scores)) # # Exercice 13.5 # # Use 10-fold cross-validation to evaluate a decision tree model with those same features (fit to any "max_depth" you choose). # evaluate a decision tree model with "max_depth=7" treereg = DecisionTreeRegressor(max_depth=7, random_state=1) scores = cross_val_score(treereg, X, y, cv=10, scoring='mean_squared_error') np.mean(np.sqrt(-scores)) # # Exercice 13.6 (2 points) # # Fit a decision tree model to the entire dataset using "max_depth=3", and create a tree diagram using Graphviz. Then, figure out what each leaf represents. What did the decision tree learn that a linear regression model could not learn? # fit a decision tree model with "max_depth=3" treereg = DecisionTreeRegressor(max_depth=3, random_state=1) treereg.fit(X, y) # + # create a Graphviz file export_graphviz(treereg, out_file='tree_bikeshare.dot', feature_names=feature_cols) # At the command line, run this to convert to PNG: # dot -Tpng tree_bikeshare.dot -o tree_bikeshare.png # - # ![Tree for bikeshare data](https://github.com/justmarkham/DAT8/raw/226791169b1cc6df8e8845c12e34e748d5ffaa85/notebooks/images/tree_bikeshare.png)
exercises/13_bikeshare_exercise_solution.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <a href="https://qworld.net" target="_blank" align="left"><img src="../qworld/images/header.jpg" align="left"></a> # _prepared by <NAME>_ # Qiskit is an open-source SDK for working with quantum computers at the level of pulses, circuits, and application modules and it has been developed by IBM. # # To run quantum program, we need to either install qiskit library locally in our computer, or run the circuit in the cloud. # # In this section, we will be showing how to install qiskit locally in your computer. # # # Qiskit Installation # Qiskit supports Python 3.6 or later. However, both Python and Qiskit are evolving ecosystems, and sometimes when new releases occur in one or the other, there can be problems with compatibility. # # Firstly, [<b>Anaconda</b>]("https://www.youtube.com/watch?v=5mDYijMfSzs") has to be installed in your local pc as it is a cross-platform Python distribution for scientific computing and among various other features, jupyter is for interacting with Qiskit. # Qiskit is tested and supported on the following 64-bit systems: # # * Ubuntu 16.04 or later # # * macOS 10.12.6 or later # # * Windows 7 or later # # We recommend using Python virtual environments to cleanly separate Qiskit from other applications and improve your experience. # # The simplest way to use environments is by using the ```conda``` command, included with Anaconda. A Conda environment allows you to specify a specific version of Python and set of libraries. Open a terminal window in the directory where you want to work. # # Create a minimal environment with only Python installed in it. # if you're using Windows: # # - Install Anaconda # - Search for Anaconda Prompt # - Open Anaconda Prompt # # Use the following commands # ```conda create -n name_of_my_env python=3``` # <br><br> # ```activate name_of_my_env``` # Next, install the Qiskit package, which includes Terra, Aer, Ignis, and Aqua. # # ```pip install qiskit``` # If the packages installed correctly, you can run conda list to see the active packages in your virtual environment. # # # After you’ve installed and verified the Qiskit packages you want to use, import them into your environment with Python to begin working. # # # <b>```import qiskit```</b>
Notebooks/QC_2_Qiskit_Installation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## High and Low Pass Filters # # Now, you might be wondering, what makes filters high and low-pass; why is a Sobel filter high-pass and a Gaussian filter low-pass? # # Well, you can actually visualize the frequencies that these filters block out by taking a look at their fourier transforms. The frequency components of any image can be displayed after doing a Fourier Transform (FT). An FT looks at the components of an image (edges that are high-frequency, and areas of smooth color as low-frequency), and plots the frequencies that occur as points in spectrum. So, let's treat our filters as small images, and display them in the frequency domain! # + import numpy as np import matplotlib.pyplot as plt import cv2 # %matplotlib inline # Define gaussian, sobel, and laplacian (edge) filters gaussian = (1/9)*np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) sobel_x= np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) sobel_y= np.array([[-1,-2,-1], [0, 0, 0], [1, 2, 1]]) # laplacian, edge filter laplacian=np.array([[0, 1, 0], [1,-4, 1], [0, 1, 0]]) filters = [gaussian, sobel_x, sobel_y, laplacian] filter_name = ['gaussian','sobel_x', \ 'sobel_y', 'laplacian'] # perform a fast fourier transform on each filter # and create a scaled, frequency transform image f_filters = [np.fft.fft2(x) for x in filters] fshift = [np.fft.fftshift(y) for y in f_filters] frequency_tx = [np.log(np.abs(z)+1) for z in fshift] # display 4 filters for i in range(len(filters)): plt.subplot(2,2,i+1),plt.imshow(frequency_tx[i],cmap = 'gray') plt.title(filter_name[i]), plt.xticks([]), plt.yticks([]) plt.show(); # - # Areas of white or light gray, allow that part of the frequency spectrum through! Areas of black mean that part of the spectrum is blocked out of the image. # # Recall that the low frequencies in the frequency spectrum are at the center of the frequency transform image, and high frequencies are at the edges. You should see that the Gaussian filter allows only low-pass frequencies through, which is the center of the frequency transformed image. The sobel filters block out frequencies of a certain orientation and a laplace (all edge, regardless of orientation) filter, should block out low-frequencies! # # You are encouraged to load in an image, apply a filter to it using `filter2d` then visualize what the fourier transform of that image looks like before and after a filter is applied. ## TODO: load in an image, and filter it using a kernel of your choice ## apply a fourier transform to the original *and* filtered images and compare them
Convolutional-Filters-and-Edges/Fourier-Transforms-and-Filters.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Theoratical Generation of Data # - Strain Life (Morrow equation): # $$ # \frac{\Delta \epsilon}{2} = \frac{\sigma'_f}{E}(2N_f)^b + \epsilon'_f(2N_f)^c # $$ # - Reversal Stress Ratio: # $$ # \frac{\Delta \sigma}{2} = \sigma_{max} = \sigma_f'(2N_f)^b # $$ # - SWT(Smith,Watson and Topper fatigue damage parameter): # $$ # SWT = \sigma_{max}\frac{\Delta\epsilon}{2} = \frac{(\sigma_f'^2)(2N_f)^{2b}}{E} + \sigma_f'\epsilon_f'(2N_f)^{b+c} # $$ # where,<br> # $\sigma^*_f$: fatigue strenght coefficient,<br> # $b$: fatigue strength exponent,<br> # $\epsilon^*_f$: fatigue ductility coefficient,<br> # $b$: fatigue ductility exponent and<br> # $E$: Young modulus<br> # # # The values of the constants for S355 Mild Steel are: # # |$E\\ GPa$|$\sigma_f' \\ MPa$|$b$|$\epsilon_f'$|c| # |----|----|----|----|----| # |211.60|952.20|-0.0890|0.7371|-0.6640| # + import numpy as np import matplotlib.pyplot as plt def generate_data( Nf=np.linspace(10,10000000,10000), E = 211600, sigma_dash = 952.20, b = -0.0890, epsilon_dash = 0.7371, c = -0.6640 ): ''' generate_data(Nf,E,sigma_dash,b,epsilon_dash,c)-> SWT,strain,stress,Nf (default for S355) ''' strain = (sigma_dash/E)*((2*Nf)**b) + epsilon_dash*((2*Nf)**c) stress = sigma_dash*((2*Nf)**b) SWT = strain*stress return SWT,strain,stress,Nf Nf = 10**np.linspace(1.7,7,50) SWT,strain,stress,Nf = generate_data(Nf) # Experimental Data Exp_strain = np.array([1.00,0.50,2.00,0.40,0.30,0.35,0.30,0.40,1.00,2.00])*(5e-3) Exp_stress = np.array([817.39,669.54,775.47,615.40,536.34,581.51,646.56,661.21,663.57,768.21])-300 Exp_Nf = np.array([4805,16175,336,29501,861304,278243,191940,64244,2009,5420]) plt.figure(figsize=(18,18)) plt.subplot(2,2,1) plt.ylabel('SWT') plt.xlabel('Nf') plt.xscale('log') plt.yscale('log') plt.plot(Nf,SWT,'-') plt.plot(Exp_Nf,Exp_strain*Exp_stress,'r.') plt.grid() plt.subplot(2,2,2) plt.ylabel('\u0394 \u03B5 /2') plt.xlabel('Nf') plt.xscale('log') plt.yscale('log') plt.plot(Exp_Nf,Exp_strain,'r.') plt.plot(Nf,strain,'-') plt.grid() plt.subplot(2,2,3) plt.ylabel('stress') plt.xlabel('Nf') plt.xscale('log') plt.plot(Nf,stress) plt.plot(Exp_Nf,Exp_stress,'r.') plt.grid() plt.subplot(2,2,4) plt.plot(strain,stress) plt.plot(Exp_strain,Exp_stress,'r.') plt.grid() # - # # The Model # --- # #### General information on Weibul Distribution # --- # If $X$ is a random variable denoting the _time to failure_, the __Weibull distribution__ gives a distribution for which the _failure rate_ is proportional to a power of time. # # $$ # f_X(x) = # \frac{\beta}{\delta}(\frac{x-\lambda}{\delta})^{\beta-1}e^{-(\frac{x-\lambda}{\delta})^\beta} # $$ # $$ # F_X(x;\lambda,\delta,\sigma) = 1-e^{-({\frac{x-\lambda}{\delta}})^\beta} # $$ # # where $\beta > 0$ is the __shape parameter__, # # $\delta > 0$ is the __scale parameter__, # # $\lambda > x$ is the __location parameter__ (the minimum value of X). # # Percentile points, # # $$ # x_p = \lambda + \delta(-log(1-p))^{\frac{1}{\beta}} # $$ # where $0\leq p\leq 1$ # # __Important Properties of Weibull Distribution__ # # - Stable with respect to location and scale # $$ # X \sim W(\lambda,\delta,\beta) \iff \frac{X-a}{b} \sim W(\frac{\lambda-a}{b},\frac{\delta}{b},\beta) # $$ # # - It is stable with respect to Minimum Operations.i.e., if $X_1,X_2,X_3,.....X_m$ are independent and identical distribution,then # $$ # X_i\sim W(\lambda,\delta,\beta) \iff min(X_1,X_2,....,X_m) \sim W(\lambda,\delta m^{\frac{1}{\beta}},\beta) # $$ # if a set of independent and identical distribution is weibull then its minimum is also a Weibull Random Variable # --- # #### Relevant Variable involved for modeling: # --- # $P$:Probability of fatigue faliure<br> # $N$:Number of stress cycles to failure<br> # $N_0$:Threshold value of N (min lifetime)<br> # $SWT$:Smith,Watson and Topper fatigue damage parameter<br> # $SWT_0$:Endurance limit<br> # # Putting Related variables together we have three varaibles(based on II Theorem)<br> # $$ # \frac{N}{N_0},\frac{SWT}{SWT_0},P \\ # P = q(\frac{N}{N_0},\frac{SWT}{SWT_0}) # $$ # where $q()$ is a function we are to determine<br> # so P can be any monotone function of $\frac{N}{N_0},\frac{SWT}{SWT_0}$ , as $h(\frac{N}{N_0})$ $\&$ $g(\frac{SWT}{SWT_0})$ # # We denote them as # $$ # N^* = h(\frac{N}{N_0}) \\ # SWT^* = g(\frac{SWT}{SWT_0}) # $$ # # --- # #### Justification of Weibull for S-N fields # --- # Considerations: # # - __Weakest Link__: Fatigue lifetime of a longitudinal element is the minimum of its constituting particles.Thus we need minimum model for a longitudinal element $L = ml$ # # - __Stability__: The distribution function must hold for different lengths. # # - __Limit Behaviour__: Need Asymptotic family of Distribution # # - __Limited Range__: $N^*$ & $SWT^*$ has finite lower bound,coincide with theoretical end of CDF # $$ # N\geq N_0 \\ # SWT \geq SWT_0 # $$ # - __Compatibility__: $$E(N^*;SWT^*) = F(SWT^*;N^*)$$ i.e., Distribution of $N^*$ can be determined based on given $SWT^*$ and similarly $SWT^*$ from $N^*$. # # ___All these are Statisfied by Weibull Distribution___ # # $$E(N^*;SWT^*) = F(SWT^*;N^*)$$ # becomes # $$ # [\frac{SWT^*-\lambda(N^*)}{\delta(N^*)}] ^{\beta(N^*)} = [\frac{N^*-\lambda(SWT^*)}{\delta(SWT^*)}] ^{\beta(SWT^*)} # $$ # # Best fitted Solution: # $$ # \lambda(N^*) = \frac{\lambda}{N^* - B} \\ # \delta(N^*) = \frac{\delta}{N^* - B} \\ # \beta(N^*) = \beta # $$ # and # # # $$ # \lambda(SWT^*) = \frac{\lambda}{SWT^* - C} \\ # \delta(SWT^*) = \frac{\delta}{SWT^* - C} \\ # \beta(SWT^*) = \beta # $$ # # results in, # $$ # E[N^*;SWT^*] = F[SWT^*;N^*] \\ \\ # = 1 - exp\lbrace -(\frac{(N^*-B)(SWT^*-C)-\lambda}{\delta})^{\beta}\} # $$ # # since $SWT^* \longrightarrow \infty$ a lower end for $N^* = h(\frac{N}{N_0)}) = h(1)$ must exists such that $B = h(1)$,<br> # similarly for $N^* \longrightarrow \infty$, $C = g(1)$ # # The percentile curve is constant. # $$ # \frac{N^*SWT^* - \lambda}{\delta} = constant # $$ # # - The Zero-percentile curve represents the minimum possible $N_f$ for different values of $SWT$ and is a hyperbola # As $log$ is used for $N_f$ and $SWT$ we choose, # $$ # h(x)=g(x) = log(x) # $$ # # therefore, # $$ # N^* = log(\frac{N}{N_0}) \\ SWT^* = log(\frac{SWT}{SWT_0}) \\ # $$ # # $B = C = log(1) = 0$ # $$E(N^*;SWT^*) = F(SWT^*;N^*) \\ # = 1 - exp\{-(\frac{N^*SWT^*}{\delta})^{\beta} \} # $$ # # $p$-curves # $$ # log(\frac{SWT}{SWT^*}) = \frac{\lambda + \delta[-log(1-p)]^{\frac{1}{\beta}}}{log(\frac{N}{N_0})} # $$ # # Final Distribution # $$ # N^*SWT^* \sim W(\lambda,\delta,\beta) \\ # log(\frac{N}{N_0)})log(\frac{SWT}{SWT_0}) \sim W(\lambda,\delta,\beta) \\ # log(\frac{N}{N_0)})\sim W(\frac{\lambda}{log(\frac{SWT}{SWT_0}) },\frac{\delta}{log(\frac{SWT}{SWT_0}) },\beta) \\ # $$ # ---- # The values for this model are: # # |$logN_0$|$logSWT_0$|$\lambda$|$\delta$|$\beta$| # |----|----|----|----|----| # |-4.1079|-4.4317|53.8423|7.2698|3.6226| # # |$logN_0$|$log\epsilon_{a0}$|$\lambda$|$\delta$|$\beta$| # |----|----|----|----|----| # |-3.2593|-9.1053|36.6676|5.8941|4.6952| # # # + def getMoments(X): n = X.size M0 = (1/n)*(X.sum()) sum1 = 0 for i in range(n): sum1 += i*X[i] M1 = (1/((n)*(n-1)))*sum1 sum2 = 0 for i in range(n): sum2 += i*(i-1)*X[i] M2 = (1/(n*(n-1)*(n-2)))*sum2 return M0,M1,M2 def f(x,C): return (2**x)*(C - 3) + (3**x) - (C-2) def f_dash(x,C): return math.log(2)*(2**x)*(C - 3) - math.log(3)*(3**x) def newton_approx(C,f,f_dash,x=-1,iteration=1000): for _ in range(iteration): x = x - (f(x,C)/f_dash(x,C)) #print(x) return x def getpara(M0,M1,M2,newt_init,newt_iterations): shape = -1/ newton_approx((3*M2 - M0)/(2*M1 - M0),f,f_dash,x = newt_init,iteration = newt_iterations) scale = (2*M1 - M0)/((1 - 2**(-(1/shape)))*math.gamma(1+(1/shape))) loc = M0 - scale*(math.gamma(1+(1/shape))) return loc,scale,shape def PWM(X,newt_init=-0.1,newt_iterations = 100): return getpara(*getMoments(X),newt_init,newt_iterations) # + import math class Weibull: ''' w = Weibull(shape:beta,scale:theta,position:lambda) ''' def __init__(self,shape,scale,loc,x): self.shape = shape self.scale = scale self.loc = loc self.x = x _,self.bins = np.histogram(self.x,100,density=True) def pdf(self): x = self.bins shape = self.shape scale = self.scale loc = self.loc return ((shape/scale)*((x-loc)/scale)**(shape-1))*(np.exp(-((x-loc)/scale)**shape)) def cdf(self): x = self.bins shape = self.shape scale = self.scale loc = self.loc return 1- np.exp(-((x-loc)/scale)**shape) def failure_rate(self): x = self.x shape = self.shape scale = self.scale return (shape/scale)*((x/scale)**(shape-1)) def E_x(self): shape = self.shape scale = self.scale return np.real(scale*(gamma(1+1/shape))) def var_x(self): shape = self.shape scale = self.scale return (scale**2)*(gamma(1+(2/shape))-((gamma(1+(1/shape)))**2)) def plot_pdf(self): plt.plot(self.bins,self.pdf()) plt.grid() def plot_cdf(self): plt.plot(self.bins,self.cdf()) plt.grid() def plot_fr(self): plt.plot(self.bins,self.failure_rate()) plt.grid() def plot_hist(self): plt.hist(self.x) plt.grid() def get_xp(self,F_x): return np.real(self.loc+(self.scale)*(-(math.log(1-F_x))**(1/self.shape))) logSWT0 = -4.4317 logN01 = -4.1079 loc1 = 53.8423+9 scale1 = 7.2698 shape1 = 3.6226 X1 = (np.log(Nf) - logN01)*(np.log(SWT) - logSWT0) print('predicted values:',PWM(np.sort(X1))) print('values in paper:',loc1,scale1,shape1) #loc1,scale1,shape1 = PWM(np.sort(X1)) w1 = Weibull(shape1,scale1,loc1,X1) xp101 = w1.get_xp(0.001) xp105 = w1.get_xp(0.005) xp150 = w1.get_xp(0.050) xp195 = w1.get_xp(0.095) xp199 = w1.get_xp(0.099) pSWT01 = np.exp(logSWT0 + (xp101/(np.log(Nf)-logN01))) pSWT05 = np.exp(logSWT0 + (xp105/(np.log(Nf)-logN01))) pSWT50 = np.exp(logSWT0 + (xp150/(np.log(Nf)-logN01))) pSWT95 = np.exp(logSWT0 + (xp195/(np.log(Nf)-logN01))) pSWT99 = np.exp(logSWT0 + (xp199/(np.log(Nf)-logN01))) plt.figure(figsize=(12,18)) plt.subplot(2,1,1) plt.title("p-SWT-N") plt.xlabel("Nf") plt.ylabel("SWT") plt.xscale('log') plt.yscale('log') # percentile curves plt.plot(Nf,pSWT01,label="p=1%") plt.plot(Nf,pSWT05,label="p=5%") plt.plot(Nf,pSWT50,label="p=50%") plt.plot(Nf,pSWT95,label="p=95%") plt.plot(Nf,pSWT99,label="p=99%") # theoretical data plt.plot(Nf,SWT,'b.',label="Postulated Data") # Experimental Data plt.plot(Exp_Nf,Exp_strain*Exp_stress,'r^') plt.grid() plt.legend() # plt.savefig("images/p_s_n_model.png") # Strain p-E_a-N logEa0 = -9.1053 logN02 = -3.2593 loc2 = 36.6676+7 scale2 = 5.8941 shape2 = 4.6952 X2 = (np.log(Nf) - logN02)*(np.log(strain) - logEa0) print('predicted values(p-Ea-Nf):',PWM(np.sort(X2))) print('values in paper(p-Ea-Nf):',loc2,scale2,shape2) w2 = Weibull(shape2,scale2,loc2,X2) xp201 = w2.get_xp(0.001) xp205 = w2.get_xp(0.005) xp250 = w2.get_xp(0.050) xp295 = w2.get_xp(0.095) xp299 = w2.get_xp(0.099) pEa01 = np.exp(logEa0 + (xp201/(np.log(Nf)-logN02))) pEa05 = np.exp(logEa0 + (xp205/(np.log(Nf)-logN02))) pEa50 = np.exp(logEa0 + (xp250/(np.log(Nf)-logN02))) pEa95 = np.exp(logEa0 + (xp295/(np.log(Nf)-logN02))) pEa99 = np.exp(logEa0 + (xp299/(np.log(Nf)-logN02))) plt.subplot(2,1,2) plt.title("p-Ea-N") plt.xlabel("Nf") plt.ylabel("Ea") plt.xscale('log') plt.yscale('log') # percentile curves plt.plot(Nf,pEa01,label="p=1%") plt.plot(Nf,pEa05,label="p=5%") plt.plot(Nf,pEa50,label="p=50%") plt.plot(Nf,pEa95,label="p=95%") plt.plot(Nf,pEa99,label="p=99%") # theoretical data plt.plot(Nf,strain,'b.',label="Postulated Data") # Experimental Data plt.plot(Exp_Nf,Exp_strain,'r^') plt.grid() plt.legend() plt.savefig("images/model.png") # - # ### p-Nf given SWT # $$ # N^*SWT^* \sim W(\lambda,\delta,\beta) \\ # log(\frac{N}{N_0)})log(\frac{SWT}{SWT_0}) \sim W(\lambda,\delta,\beta) \\ # log(\frac{N}{N_0)})\sim W(\frac{\lambda}{log(\frac{SWT}{SWT_0}) },\frac{\delta}{log(\frac{SWT}{SWT_0}) },\beta) \\ # log(\frac{N}{N_0)}) = x_p \\ # log(N_f) = x_p + log(N_0) \\ # N_f = e^{x_p + log(N_0) } # $$ # ## Determining the fatigue crack propogation curves # # $$ # \frac{\rho^*}{N_f}=\frac{da}{dN} = C\Delta K^m # $$ # $\rho^* = 5.5\mu m$ # - Determining $p$-$\frac{da}{dN}$-$\Delta K$ curves: # $$ # log(\frac{N}{N_0)})\sim W(\frac{\lambda}{log(\frac{SWT}{SWT_0}) },\frac{\delta}{log(\frac{SWT}{SWT_0}) },\beta) \\ # $$ # # #### Generating Crack Propogation value: # # | | $C$ | $m$ | # |-----|----------------|-------| # |R=0.0|$7.195x10^{-15}$|3.499| # |R=0.5|$6.281x10^{-15}$|3.555| # |R=0.7|$2.037x10^{-13}$|3.003| # # + import math # coping values of p-SWT-N curve # determing p-Nf for a particular SWT # say SWT = 9 def plt_pNf(SWT): logSWT0 = -4.4317 lgSWT_SWT0 = math.log(SWT) - logSWT0 logN01 = -4.1079 loc3 = (53.8423+9)/lgSWT_SWT0 scale3 = (7.2698)/lgSWT_SWT0 shape1 = 3.6226 #print(loc3,scale3,shape1) # X3 Weibull random variable (Nf) given SWT = 9 X3 = (np.random.weibull(shape1,1000)*scale3) + loc3 _,bins = np.histogram(X3,100,density=True) pdf = ((shape1/scale3)*((bins-loc3)/scale3)**(shape1-1))*(np.exp(-((bins-loc3)/scale3)**shape1)) plt.xlabel("Nf") plt.title("Histogram with PDF curve of Nf for SWT ="+str(SWT)) h,_,_ = plt.hist(np.exp(X3+logN01),label='histograph') plt.plot(np.exp(bins+logN01),pdf*(h.max()*(0.65)),'r-',label='PDF',linewidth="2") plt.grid() plt.figure(figsize=(12,12)) plt.subplot(2,2,1) plt_pNf(10) plt.subplot(2,2,2) plt_pNf(50) plt.subplot(2,2,3) plt_pNf(150) plt.subplot(2,2,4) plt_pNf(200) plt.savefig("images/nfswtpdf.png") # + # Crack propogation data logN01 = -4.1079 C0 = 7.195e-15 m0 = 3.499 delta_k = np.linspace(250,600,50) da_dN0 = C0*(delta_k**m0) plt.figure(figsize=(10,6)) plt.ylabel('da/dN') plt.yscale('log') plt.xlabel('\u0394 K') plt.xscale('log') #plt.plot(delta_k,da_dN0,'r.',label='Theoratical data') #plt.title('Fatigue crack propagation data of S355 steel for distinct stress ratios') # percentile crack propogation SWT_a = 30 lgSWT_SWT0_a = math.log(SWT_a) - logSWT0 logSWT0 = -4.4317 shape1 = 3.6226 logN01 = -4.1079 loc3_a = (53.8423+9)/lgSWT_SWT0_a scale3_a = (7.2698)/lgSWT_SWT0_a def get_xp_Nf_a(p,loc=loc3_a,shape=shape1,scale=scale3_a): return np.real(loc+(scale)*(-(math.log(1-p))**(1/shape))) SWT_b = 9000 points = [230,600] lgSWT_SWT0_b = math.log(SWT_b) - logSWT0 logSWT0 = -4.4317 shape1 = 3.6226 logN01 = -4.1079 loc3_b = (53.8423+9)/lgSWT_SWT0_b scale3_b = (7.2698)/lgSWT_SWT0_b def get_xp_Nf_b(p,loc=loc3_b,shape=shape1,scale=scale3_b): return np.real(loc+(scale)*(-(math.log(1-p))**(1/shape))) Nf01_a = np.exp(get_xp_Nf_a(0.001) + logN01) Nf01_b = np.exp(get_xp_Nf_b(0.001) + logN01) Nf05_a = np.exp(get_xp_Nf_a(0.005) + logN01) Nf05_b = np.exp(get_xp_Nf_b(0.005) + logN01) Nf50_a = np.exp(get_xp_Nf_a(0.050) + logN01) Nf50_b = np.exp(get_xp_Nf_b(0.050) + logN01) Nf95_a = np.exp(get_xp_Nf_a(0.095) + logN01) Nf95_b = np.exp(get_xp_Nf_b(0.095) + logN01) Nf99_a = np.exp(get_xp_Nf_a(0.099) + logN01) Nf99_b = np.exp(get_xp_Nf_b(0.099) + logN01) rho = 5.5e-5 plt.plot(points,[rho/Nf50_a,rho/Nf50_b],'--',label="p-da/dN-K at p=50%") plt.plot(points,[rho/Nf01_a,rho/Nf01_b],label="p-da/dN-K at p=1%") plt.plot(points,[rho/Nf99_a,rho/Nf99_b],label="p-da/dN-K at p=99%") plt.grid() plt.legend() # - print('predicted values:',PWM(np.sort(X1))) print('values in paper:',loc1,scale1,shape1) A=PWM(np.sort(X1)) B=loc1,scale1,shape1 A B # + # plt.figure(figsize=(15,12)) plt.title("Weibull Parameters proposed vs predicted p-SWT-N") plt.scatter(np.arange(0,3),A,c="r",label="predicted values") plt.scatter(np.arange(0,3),B,c="g",label="Values proposed in paper") plt.ylabel('Value') plt.xlabel('0=Location,1=Scale,2=Shape of Weibull Dist') plt.legend() plt.grid() plt.savefig("images/PWMPlotswt.png") # - print("Predicted (Location, Scale,Shape) = " , A) print("Proposed in Paper(Location, Scale, Shape) = ", B) # + A=PWM(np.sort(X2)) B=loc2,scale2,shape2 # plt.figure(figsize=(15,12)) plt.title("Weibull Parameters proposed vs predicted p-Ea-N") plt.scatter(np.arange(0,3),A,c="c",label="predicted values") plt.scatter(np.arange(0,3),B,c="y",label="Values proposed in paper") plt.ylabel('Value') plt.xlabel('0=Location,1=Scale,2=Shape of Weibull Dist') plt.legend() plt.grid() plt.savefig("images/PWMPlotstrain.png") print("Predicted (Location, Scale,Shape) = " , A) print("Proposed in Paper(Location, Scale, Shape) = ", B) # - Nf stress,SWT,strain Nf.size,SWT.size # + plt.subplot(2,2,1) plt.plot(np.log(SWT),np.log(Nf),'.') def initial_est(x1,x2,x3,y1,y2,y3): c = (x2*(x3-x1)*(y1-y2) - x3*(x2-x1)*(y1-y3)) / ((x3-x1)*(y1-y2)-(x2-x1)*(y1-y3)) b = ((y1-y2)*(x2-c)*(x1-c))/(x2-x1) a = y1 - (b/(x1-c)) return a,b,c para = [] for i in range(Nf.size): for j in range(Nf.size): for k in range(Nf.size): if (i!= j and j!=k and i!=k): logN0,K,logSWT0 = initial_est(np.log(SWT[i]),np.log(SWT[j]),np.log(SWT[k]),np.log(Nf[i]),np.log(Nf[j]),np.log(Nf[k])) para.append(np.array([logN0,K,logSWT0])) print('logN0',np.mean(np.array(para)[:,0])) print('logSWT0',np.mean(np.array(para)[:,2])) logN0 = np.mean(np.array(para)[:,0]) K = np.mean(np.array(para)[:,1]) logSWT0 = np.mean(np.array(para)[:,2]) point = np.array([-1.5,4]) val = logN0 + K/(point-logSWT0) plt.plot(point,val) # + Nf_logged=np.log(Nf) swt_logged=np.log(SWT) # plt.figure(figsize=(20,20)) plt.subplot(2,2,1) # ploting the distribution plt.plot(swt_logged,Nf_logged,'.') # determine the initial estimation def initial_est(Nf_logged,stress_logged): x1 = np.mean(stress_logged[0:16]) x2 = np.mean(stress_logged[16:32]) x3 = np.mean(stress_logged[32:48]) y1 = np.mean(Nf_logged[0:16]) y2 = np.mean(Nf_logged[16:32]) y3 = np.mean(Nf_logged[32:48]) c = (x2*(x3-x1)*(y1-y2) - x3*(x2-x1)*(y1-y3)) / ((x3-x1)*(y1-y2)-(x2-x1)*(y1-y3)) b = ((y1-y2)*(x2-c)*(x1-c))/(x2-x1) a = y1 - (b/(x1-c)) return a,b,c int_a,int_b,int_c = initial_est(Nf_logged,swt_logged) # plot intial estimation int_points = np.array([-0.4,-0.05]) # start and end points based on graph of experimental values int_val = int_a + (int_b/(int_points - int_c)) # values corresponind to that points based on initial parameters plt.plot(int_points,int_val,label="initial estimation") plt.grid() print('initial estimation of parameters :',int_a,int_b,int_c) # Better the estimation with gradient Descent # Cost loss function def cal_cost(a,b,c,X,Y): cost = (Y - a - (b/(X - c)))**2 return np.mean(cost)/2 def predict(a,b,c,X,Y,alpha): G_a = (-2)*(Y - a - (b/(X-c))) G_b = (-2)*(Y - a - (b/(X-c)))*(1/X-c) G_c = (-2)*(Y - a - (b/(X-c)))*(b/((X-c)**2)) a_new = a - (alpha*(np.mean(G_a))) b_new = b - (alpha*(np.mean(G_b))) c_new = c - (alpha*(np.mean(G_c))) #print(np.mean(G_a),np.mean(G_b),np.mean(G_c)) return a_new,b_new,c_new def gradient_desc(a,b,c,X,Y,alpha= 0.001,iterations=3000): cost_history = np.zeros(iterations) para_history = np.zeros((iterations,3)) for i in range(iterations): para_history[i,:] = np.array([a,b,c]) a,b,c = predict(a,b,c,X,Y,alpha) cost_history[i] = cal_cost(a,b,c,X,Y) #print(m,c) return [a,b,c],para_history,cost_history pred=gradient_desc(int_a,int_b,int_c,Nf_logged,swt_logged) # - pred[0] # plt.figure(figsize=(15,12)) plt.title("Cost vs Iteration Nf0 and SWT0") plt.xlabel("Iterations") plt.ylabel("Cost Value") plt.grid() plt.plot(pred[2],label="At alpha = 0.001") plt.legend() plt.savefig("images/costviterswt.png") # The values for this model are: # # |$logN_0$|$logSWT_0$|$\lambda$|$\delta$|$\beta$| # |----|----|----|----|----| # |-4.1079|-4.4317|53.8423|7.2698|3.6226| # + Nf_logged=np.log(Nf) strain_logged=np.log(strain/2) # plt.figure(figsize=(20,20)) plt.subplot(2,2,1) # ploting the distribution plt.plot(strain_logged,Nf_logged,'.') # determine the initial estimation def initial_est(Nf_logged,stress_logged): x1 = np.mean(stress_logged[0:16]) x2 = np.mean(stress_logged[16:32]) x3 = np.mean(stress_logged[32:48]) y1 = np.mean(Nf_logged[0:16]) y2 = np.mean(Nf_logged[16:32]) y3 = np.mean(Nf_logged[32:48]) c = (x2*(x3-x1)*(y1-y2) - x3*(x2-x1)*(y1-y3)) / ((x3-x1)*(y1-y2)-(x2-x1)*(y1-y3)) b = ((y1-y2)*(x2-c)*(x1-c))/(x2-x1) a = y1 - (b/(x1-c)) return a,b,c int_a,int_b,int_c = initial_est(Nf_logged,strain_logged) # plot intial estimation int_points = np.array([-0.4,-0.05]) # start and end points based on graph of experimental values int_val = int_a + (int_b/(int_points - int_c)) # values corresponind to that points based on initial parameters plt.plot(int_points,int_val,label="initial estimation") plt.grid() print('initial estimation of parameters :',int_a,int_b,int_c) # Better the estimation with gradient Descent # Cost loss function def cal_cost(a,b,c,X,Y): cost = (Y - a - (b/(X - c)))**2 return np.mean(cost)/2 def predict(a,b,c,X,Y,alpha): G_a = (-2)*(Y - a - (b/(X-c))) G_b = (-2)*(Y - a - (b/(X-c)))*(1/X-c) G_c = (-2)*(Y - a - (b/(X-c)))*(b/((X-c)**2)) a_new = a - (alpha*(np.mean(G_a))) b_new = b - (alpha*(np.mean(G_b))) c_new = c - (alpha*(np.mean(G_c))) #print(np.mean(G_a),np.mean(G_b),np.mean(G_c)) return a_new,b_new,c_new def gradient_desc(a,b,c,X,Y,alpha= 0.0003,iterations=1050): cost_history = np.zeros(iterations) para_history = np.zeros((iterations,3)) for i in range(iterations): para_history[i,:] = np.array([a,b,c]) a,b,c = predict(a,b,c,X,Y,alpha) cost_history[i] = cal_cost(a,b,c,X,Y) #print(m,c) return [a,b,c],para_history,cost_history pred=gradient_desc(int_a,int_b,int_c,Nf_logged,strain_logged) # - pred[0] # |$logN_0$|$log\epsilon_{a0}$|$\lambda$|$\delta$|$\beta$| # |----|----|----|----|----| # |-3.2593|-9.1053|36.6676|5.8941|4.6952| # plt.figure(figsize=(15,12)) plt.title("Cost vs Iteration Nf0 and Ea0 ") plt.xlabel("Iterations") plt.ylabel("Cost Value") plt.grid() plt.plot(pred[2],label="At alpha = 0.001") plt.legend() plt.savefig("images/costviterEa.png") # + constlogN0=-3.2593 constlogEa0=-9.1053 predlogN0=-3.2169137446018166 predlogEa0=-9.12850244974238 A=constlogN0,constlogEa0 B=predlogN0,predlogEa0 # plt.figure(figsize=(15,12)) plt.title("Strain-Life Field Parameters proposed vs predicted ") plt.scatter(np.arange(0,2),A,c="c",label="predicted values") plt.scatter(np.arange(0,2),B,c="y",label="Values proposed in paper") plt.ylabel('Value') plt.xlabel('0=LogN0,1=LogEa0') plt.legend() plt.grid() plt.savefig("images/StrainLifePropvPred.png") # + constlogN0swt=-4.1079 constlogSWT=-4.4317 predlogN0swt=-3.8413545070878463 predlogSWT=-4.383809373097227 A=constlogN0swt,constlogSWT B=predlogN0swt,predlogSWT # plt.figure(figsize=(15,12)) plt.title("SWT-Life Field Parameters proposed in paper vs predicted ") plt.scatter(np.arange(0,2),A,c="r",label="predicted values") plt.scatter(np.arange(0,2),B,c="b",label="Values proposed in paper") plt.ylabel('Value') plt.xlabel('0=LogN0,1=LogSWT0') plt.legend() plt.grid() plt.savefig("images/SWTLifePropvPred.png") # -
.ipynb_checkpoints/special_assignment_1-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### download the dogs and cats data set and unzip it # # URL: https://www.microsoft.com/en-us/download/details.aspx?id=54765 # # You will run this to create the following folder structure: # # # ``` # test # dog # cat # train # dog # cat # ``` # # Resize to whatever is the preferred new size # + # read some pics and show import cv2 import glob from matplotlib import pyplot as plt from matplotlib.image import imread import random import os import shutil # %matplotlib inline # + image_dir='PetImages' dogs = glob.glob(image_dir + '/Dog/*.jpg') cats = glob.glob(image_dir + '/Cat/*.jpg') print('dogs image count:', len(dogs)) print('cats image count:', len(cats)) # - def show_image(imgs): for i in range(9): # define subplot plt.subplot(330 + 1 + i) # define filename filename = imgs[i] # load image pixels image = imread(filename) # plot raw pixel data plt.xticks([]) plt.yticks([]) plt.imshow(image) # show the figure plt.show() show_image(dogs) show_image(cats) # + # make a dir of train/cat:dog/image.jpg and test/cat|dog/image.jpg if not already exists def make_dir(dir_name): os.makedirs(dir_name, exist_ok=True) def delete_dir_content(dir_name): flist = glob.glob(dir_name + '/*.jpg') for f in flist: os.remove(f) def copy_to_dir(list , dir_name): print('copying to:',dir_name) for f in list: shutil.copy2(f , dir_name) def resize_image(flist , isize): for filename in flist: img = cv2.imread(filename) if not img is None: img2 = cv2.resize(img,(isize,isize),interpolation=cv2.INTER_AREA) cv2.imwrite(filename , img2) img = cv2.imread(filename) h , w , c = img.shape if not (h == isize and w == isize) : print('error cannot resize:', filename) else: os.remove(filename) make_dir('train/dog') make_dir('train/cat') make_dir('test/dog') make_dir('test/cat') # delete the contents delete_flag = True if delete_flag: delete_dir_content('train/dog') delete_dir_content('train/cat') delete_dir_content('test/dog') delete_dir_content('test/cat') # train vs test test_ratio = 0.25 image_size = 224 test_size = int( test_ratio * len(dogs)) # copy random cat/dog files to train and test test_dogs = random.sample(dogs, test_size) test_cats = random.sample(cats, test_size) copy_to_dir(test_dogs , 'test/dog/') copy_to_dir(test_cats , 'test/cat/') train_dogs = [n for n in dogs if n not in test_dogs] train_cats = [n for n in cats if n not in test_cats] copy_to_dir(train_dogs , 'train/dog/') copy_to_dir(train_cats , 'train/cat/') test_list = glob.glob('test/*/*.jpg') train_list = glob.glob('train/*/*.jpg') print('image size:',image_size) print('resizing test...') resize_image(test_list , image_size) print('resizing train...') resize_image(train_list , image_size) # show size test_dog_list = glob.glob('test/dog/*.jpg') test_cat_list = glob.glob('test/cat/*.jpg') train_dog_list = glob.glob('train/dog/*.jpg') train_cat_list = glob.glob('train/cat/*.jpg') print('dog test size:', len(test_dog_list)) print('cat test size:', len(test_cat_list)) print('dog train size:', len(train_dog_list)) print('cat train size:', len(train_cat_list)) # -
catdog/data_prep.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # STAT 453: Deep Learning (Spring 2021) # Instructor: <NAME> (<EMAIL>) # # Course website: http://pages.stat.wisc.edu/~sraschka/teaching/stat453-ss2021/ # GitHub repository: https://github.com/rasbt/stat453-deep-learning-ss21 # # --- # %load_ext watermark # %watermark -a '<NAME>' -v -p torch # # MLP With Different Loss Functions # ## Imports import matplotlib.pyplot as plt import pandas as pd import torch # %matplotlib inline import time import numpy as np from torchvision import datasets from torchvision import transforms from torch.utils.data import DataLoader import torch.nn.functional as F import torch # ## Settings and Dataset # + ########################## ### SETTINGS ########################## RANDOM_SEED = 1 BATCH_SIZE = 100 NUM_EPOCHS = 100 DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') ########################## ### MNIST DATASET ########################## # Note transforms.ToTensor() scales input images # to 0-1 range train_dataset = datasets.MNIST(root='data', train=True, transform=transforms.ToTensor(), download=True) test_dataset = datasets.MNIST(root='data', train=False, transform=transforms.ToTensor()) train_loader = DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True) test_loader = DataLoader(dataset=test_dataset, batch_size=BATCH_SIZE, shuffle=False) # Checking the dataset for images, labels in train_loader: print('Image batch dimensions:', images.shape) print('Image label dimensions:', labels.shape) break # - # ## Model # + class MLP(torch.nn.Module): def __init__(self, num_features, num_hidden, num_classes): super().__init__() self.num_classes = num_classes ### 1st hidden layer self.linear_1 = torch.nn.Linear(num_features, num_hidden) self.linear_1.weight.detach().normal_(0.0, 0.1) self.linear_1.bias.detach().zero_() ### Output layer self.linear_out = torch.nn.Linear(num_hidden, num_classes) self.linear_out.weight.detach().normal_(0.0, 0.1) self.linear_out.bias.detach().zero_() def forward(self, x): out = self.linear_1(x) out = torch.sigmoid(out) logits = self.linear_out(out) #probas = torch.softmax(logits, dim=1) return logits#, probas ################################# ### Model Initialization ################################# torch.manual_seed(RANDOM_SEED) model = MLP(num_features=28*28, num_hidden=100, num_classes=10) model = model.to(DEVICE) optimizer = torch.optim.SGD(model.parameters(), lr=0.1) ################################# ### Training ################################# def compute_loss(net, data_loader): curr_loss = 0. with torch.no_grad(): for cnt, (features, targets) in enumerate(data_loader): features = features.view(-1, 28*28).to(DEVICE) targets = targets.to(DEVICE) logits = net(features) loss = F.cross_entropy(logits, targets) curr_loss += loss return float(curr_loss)/cnt start_time = time.time() minibatch_cost = [] epoch_cost = [] for epoch in range(NUM_EPOCHS): model.train() for batch_idx, (features, targets) in enumerate(train_loader): features = features.view(-1, 28*28).to(DEVICE) targets = targets.to(DEVICE) ### FORWARD AND BACK PROP logits = model(features) cost = F.cross_entropy(logits, targets) optimizer.zero_grad() cost.backward() ### UPDATE MODEL PARAMETERS optimizer.step() ### LOGGING minibatch_cost.append(cost.item()) if not batch_idx % 50: print ('Epoch: %03d/%03d | Batch %03d/%03d | Cost: %.4f' %(epoch+1, NUM_EPOCHS, batch_idx, len(train_loader), cost.item())) cost = compute_loss(model, train_loader) epoch_cost.append(cost) print('Epoch: %03d/%03d Train Cost: %.4f' % ( epoch+1, NUM_EPOCHS, cost)) print('Time elapsed: %.2f min' % ((time.time() - start_time)/60)) print('Total Training Time: %.2f min' % ((time.time() - start_time)/60)) # + plt.plot(range(len(minibatch_cost)), minibatch_cost) plt.ylabel('Cross Entropy') plt.xlabel('Minibatch') plt.show() plt.plot(range(len(epoch_cost)), epoch_cost) plt.ylabel('Cross Entropy') plt.xlabel('Epoch') plt.show() # + def compute_accuracy(net, data_loader): correct_pred, num_examples = 0, 0 with torch.no_grad(): for features, targets in data_loader: features = features.view(-1, 28*28).to(DEVICE) targets = targets.to(DEVICE) logits = net.forward(features) predicted_labels = torch.argmax(logits, 1) num_examples += targets.size(0) correct_pred += (predicted_labels == targets).sum() return correct_pred.float()/num_examples * 100 print('Training Accuracy: %.2f' % compute_accuracy(model, train_loader)) print('Test Accuracy: %.2f' % compute_accuracy(model, test_loader))
L09/code/mlp-pytorch_softmax-crossentr.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="MpSRZmco14dZ" colab_type="code" colab={} import pandas as pd import numpy as np import matplotlib as plt import seaborn as sns # + id="JEDnSr-X2iFN" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="dd808646-24db-43c7-b233-50b61829ddd3" executionInfo={"status": "ok", "timestamp": 1583230600083, "user_tz": -60, "elapsed": 579, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} # cd "/content/drive/My Drive/Colab Notebooks/dw_matrix/matrix_two/dw_matrix_car" # + id="LASjyK6D3SGg" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="643d2dd2-016c-4ed3-95c6-c7561c7e66f8" executionInfo={"status": "ok", "timestamp": 1583230242371, "user_tz": -60, "elapsed": 2131, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} # ls # + id="VVW5SYqR4EWf" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="f3be63a7-d363-4bb2-86d5-44a7e391bffd" executionInfo={"status": "ok", "timestamp": 1583230609524, "user_tz": -60, "elapsed": 2717, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} df = pd.read_hdf('data/car.h5') df.shape # + id="a8JCgQKZ4Zqa" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 290} outputId="023a9ccd-8a98-4530-a555-95d9ae19e368" executionInfo={"status": "ok", "timestamp": 1583230550090, "user_tz": -60, "elapsed": 6208, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} # !pip install --upgrade tables # + id="Bucq9tcP5OeG" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="a377a59f-f8d0-4128-f8f0-318339074c7f" executionInfo={"status": "ok", "timestamp": 1583230673935, "user_tz": -60, "elapsed": 603, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} df.columns.values # + id="c4p2gM4r5q4u" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 282} outputId="26fce888-bf91-4746-ac83-d4d5d30dac6d" executionInfo={"status": "ok", "timestamp": 1583230806114, "user_tz": -60, "elapsed": 824, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} df['price_value'].hist(bins=100) # + id="aK2DmNUd6FQ9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 168} outputId="cf7afcb3-9da4-446e-8313-44a0f03099a8" executionInfo={"status": "ok", "timestamp": 1583230876846, "user_tz": -60, "elapsed": 526, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} df['price_value'].describe() # + id="ShsSWVpz6fpY" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 302} outputId="e782bd92-0b7c-4083-ad1f-4834b3b92348" executionInfo={"status": "ok", "timestamp": 1583231018408, "user_tz": -60, "elapsed": 616, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} df['param_marka-pojazdu'].unique() # + id="h8A0s8y57CL2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 235} outputId="7bce26ef-c222-4eaa-8bee-562ab06c3cbf" executionInfo={"status": "ok", "timestamp": 1583233368480, "user_tz": -60, "elapsed": 569, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} df.groupby('param_marka-pojazdu')['price_value'].mean() # + id="O9hHTqsI7hKk" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 484} outputId="3eb51152-b8ec-44d1-9bf4-acb0aeb138d8" executionInfo={"status": "ok", "timestamp": 1583233477045, "user_tz": -60, "elapsed": 2210, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} ( df .groupby('param_marka-pojazdu')['price_value'] .agg([np.mean, np.median, np.size]) .sort_values(by='size', ascending=False) .head(50) ).plot(kind='bar', figsize=(15,5), subplots=True) # + id="fEEGOLORDCJn" colab_type="code" colab={} def group_and_barplot(feat_groupby, feat_agg='price_value', agg_funcs=[np.mean, np.median, np.size], feat_sort='mean', top=50, subplots=True): return ( df .groupby(feat_groupby)[feat_agg] .agg(agg_funcs) .sort_values(by=feat_sort, ascending=False) .head(top) ).plot(kind='bar', figsize=(15,5), subplots=subplots) # + id="71iQVfHgGJ8O" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 484} outputId="d0c99caf-637d-425f-b61a-26dfeae3d74a" executionInfo={"status": "ok", "timestamp": 1583234240838, "user_tz": -60, "elapsed": 2018, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} group_and_barplot('param_marka-pojazdu') # + id="vEOs7JH7HUkN" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 504} outputId="755ab301-ce95-4ad6-e25f-6bdc6ed290b6" executionInfo={"status": "ok", "timestamp": 1583234372814, "user_tz": -60, "elapsed": 1335, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} group_and_barplot('param_country-of-origin') # + id="E0R4tyN7H09I" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 504} outputId="4ac3ebba-00da-465e-ba1d-af5a8696f010" executionInfo={"status": "ok", "timestamp": 1583234551428, "user_tz": -60, "elapsed": 1844, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} group_and_barplot('param_kraj-pochodzenia', feat_sort='size') # + id="ul00Xq9TIHtP" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 458} outputId="e1e5ac00-c743-47d5-a0c5-19b592842480" executionInfo={"status": "ok", "timestamp": 1583234730021, "user_tz": -60, "elapsed": 1405, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "03418938068928588506"}} group_and_barplot('param_color', feat_sort='mean') # + id="3D8h0vURJMJR" colab_type="code" colab={}
day2_visualization.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: opti env # language: python # name: opti # --- # # Process Results # Process data from DCOPF and MPPDC models. # # ## Import packages # + import os import re import pickle import numpy as np import pandas as pd # - # ## Declare paths to files # + # Identifier used to update paths depending on the number of scenarios investigated number_of_scenarios = '100_scenarios' # Core data directory data_dir = os.path.join(os.path.curdir, os.path.pardir, os.path.pardir, 'data') # Operating scenario data operating_scenarios_dir = os.path.join(os.path.curdir, os.path.pardir, '1_create_scenarios') # Model output directory parameter_selector_dir = os.path.join(os.path.curdir, os.path.pardir, '2_parameter_selector', 'output', number_of_scenarios) # Output directory output_dir = os.path.join(os.path.curdir, 'output', number_of_scenarios) # - # ## Import data # + # NOTE: SRMCs were adjusted for generators and node reindexed in the parameter_selector notebook. # Therefore data should be loaded from the parameter_selector output folder # Generator data with open(os.path.join(parameter_selector_dir, 'df_g.pickle'), 'rb') as f: df_g = pickle.load(f) # Node data with open(os.path.join(parameter_selector_dir, 'df_n.pickle'), 'rb') as f: df_n = pickle.load(f) # Scenario data with open(os.path.join(parameter_selector_dir, 'df_scenarios.pickle'), 'rb') as f: df_scenarios = pickle.load(f) # DCOPF results for BAU scenario - (baseline=0, permit price=0) with open(os.path.join(parameter_selector_dir, 'DCOPF-FIXED_PARAMETERS-PERMIT_PRICE_0-BASELINE_0.pickle'), 'rb') as f: df_dcopf = pickle.load(f) # MPPDC results for BAU scenario - (baseline=0, permit price=0) with open(os.path.join(parameter_selector_dir, 'MPPDC-FIXED_PARAMETERS-BASELINE_0-PERMIT_PRICE_0.pickle'), 'rb') as g: df_mppdc = pickle.load(g) # Function used to collate DataFrames for different modelling scenarios def collate_data(filename_contains): """Collate data for different scenarios into a single DataFrame Parameters ---------- filename_contains : str Partial filename used to filter files in parameter_selector output directory Returns ------- df_o : pandas DataFrame Collated results for specified model type """ # Filtered files files = [os.path.join(parameter_selector_dir, f) for f in os.listdir(os.path.join(parameter_selector_dir)) if filename_contains in f] # Container for inidividual scenarios dfs = [] # Loop through files and load results objects for f in files: # Load results with open(f, 'rb') as g: df = pickle.load(g) # Filter column names filtered_columns = [i for i in df.columns if i not in ['Gap', 'Status', 'Message', 'Problem', 'Objective', 'Constraint']] # Filter DataFrame df_filtered = df.loc[df.index.str.contains(r'\.P\[|\.H\[|\.vang\[|\.lambda_var\[|phi'), filtered_columns] # Append to container which will later be concatenated dfs.append(df_filtered) # Concatenate results df_o = pd.concat(dfs) return df_o # - # ## Compare DCOPF and MPPDC models # Compare primal variables between DCOPF and MPPDC models. # + def compare_primal_variables(df_dcopf, df_mppdc): """Verify that MPPDC and DCOPF results match Parameters ---------- df_dcopf : pandas DataFrame DataFrame containing results for DCOPF model df_mppdc : pandas DataFrame DataFrame containing results for MPPDC model Returns ------- df_max_difference : pandas DataFrame Max difference across all scenarios for each primal variable """ # Process DCOPF DataFrame # ----------------------- df_dcopf = df_dcopf.reset_index() df_dcopf = df_dcopf[df_dcopf['index'].str.contains(r'\.P\[|\.H\[|\.vang\[')] # Extract values for primal variables df_dcopf['Value'] = df_dcopf.apply(lambda x: x['Variable']['Value'], axis=1) # Extract scenario ID df_dcopf['SCENARIO_ID'] = df_dcopf['SCENARIO_ID'].astype(int) # Extract variable names and indices df_dcopf['variable_index_1'] = df_dcopf['index'].str.extract(r'\.(.+)\[') df_dcopf['variable_index_2'] = df_dcopf['index'].str.extract(r'\.[A-Za-z]+\[(.+)\]$') # Reset index df_dcopf = df_dcopf.set_index(['SCENARIO_ID', 'variable_index_1', 'variable_index_2'])['Value'] # Process MPPDC DataFrame # ----------------------- df_mppdc = df_mppdc.reset_index() # Extract values for primal variables df_mppdc = df_mppdc[df_mppdc['index'].str.contains(r'\.P\[|\.H\[|\.vang\[')] df_mppdc['Value'] = df_mppdc.apply(lambda x: x['Variable']['Value'], axis=1) # Extract scenario ID df_mppdc['SCENARIO_ID'] = df_mppdc['index'].str.extract(r'\[(\d+)\]\.') df_mppdc['SCENARIO_ID'] = df_mppdc['SCENARIO_ID'].astype(int) # Extract variable names and indices df_mppdc['variable_index_1'] = df_mppdc['index'].str.extract(r'\.(.+)\[') df_mppdc['variable_index_2'] = df_mppdc['index'].str.extract(r'\.[A-Za-z]+\[(.+)\]$') # Reset index df_mppdc = df_mppdc.set_index(['SCENARIO_ID', 'variable_index_1', 'variable_index_2'])['Value'] # Max difference across all time intervals and primal variables df_max_difference = (df_dcopf.subtract(df_mppdc) .reset_index() .groupby(['variable_index_1'])['Value'] .apply(lambda x: x.abs().max())) return df_max_difference # Find max difference in primal variables between DCOPF and MPPDC models over all scenarios compare_primal_variables(df_dcopf, df_mppdc) # - # Note that voltage angles and HVDC flows do not correspond exactly, but power output and prices do. This is likely due to the introduction of an additional degree of freedom when adding HVDC links into the network analysis. Having HVDC links allows power to flow over either the HVDC or AC networks. So long as branch flows are within limits for constrained links, different combinations of these flows may be possible. This results in different intra-zonal flows (hence different voltage angles), but net inter-zonal flows are the same as the DCOPF case. # # These differences are likely due to the way in which the solver approaches a solution; different feasible HVDC and intra-zonal AC flows yield the same least-cost dispatch. Consequently, DCOPF and MPPDC output corresponds, but HVDC flows and node voltage angles (which relate to AC power flows) do not. As an additional check average and nodal prices are compared between the DCOPF and MPPDC models. # + def get_dcopf_average_price(df, variable_name_contains): "Find average price for DCOPF BAU scenario" df_tmp = df.reset_index().copy() # Filter price records df_tmp = df_tmp[df_tmp['index'].str.contains(r'\.{0}\['.format(variable_name_contains))] # Extract values df_tmp['Value'] = df_tmp.apply(lambda x: x['Constraint']['Dual'], axis=1) # Extract node and scenario IDs df_tmp['NODE_ID'] = df_tmp['index'].str.extract(r'\.{0}\[(\d+)\]'.format(variable_name_contains)).astype(int) df_tmp['SCENARIO_ID'] = df_tmp['SCENARIO_ID'].astype(int) # Merge demand for each node and scenario df_demand = df_scenarios.loc[:, ('demand')].T df_demand.index = df_demand.index.astype(int) df_demand = df_demand.reset_index().melt(id_vars=['NODE_ID']).rename(columns={'value': 'demand'}) df_demand['closest_centroid'] = df_demand['closest_centroid'].astype(int) df_tmp = pd.merge(df_tmp, df_demand, left_on=['SCENARIO_ID', 'NODE_ID'], right_on=['closest_centroid', 'NODE_ID']) # Merge duration information for each scenario df_duration = df_scenarios.loc[:, ('hours', 'duration')].to_frame() df_duration.columns = df_duration.columns.droplevel() df_tmp = pd.merge(df_tmp, df_duration, left_on='SCENARIO_ID', right_index=True) # Compute total revenue and total energy demand total_revenue = df_tmp.apply(lambda x: x['Value'] * x['demand'] * x['duration'], axis=1).sum() total_demand = df_tmp.apply(lambda x: x['demand'] * x['duration'], axis=1).sum() # Find average price (national) average_price = total_revenue / total_demand return average_price dcopf_average_price = get_dcopf_average_price(df_dcopf, 'POWER_BALANCE') mppdc_average_price = df_mppdc['AVERAGE_PRICE'].unique()[0] # Save BAU average price - useful when constructing plots with open(os.path.join(output_dir, 'mppdc_bau_average_price.pickle'), 'wb') as f: pickle.dump(mppdc_average_price, f) print('Absolute difference between DCOPF and MPPDC average prices: {0} [$/MWh]'.format(abs(dcopf_average_price - mppdc_average_price))) # - # Compare nodal prices between DCOPF and MPPDC models. # + def compare_nodal_prices(df_dcopf, df_mppdc): """Find max absolute difference in nodal prices between DCOPF and MPPDC models Parameters ---------- df_dcopf : pandas DataFrame Results from DCOPF model df_mppdc : pandas DataFrame Results from MPPDC model Returns ------- max_price_difference : float Maximum difference between nodal prices for DCOPF and MPPDC models over all nodes and scenarios """ # DCOPF model # ----------- df_tmp_1 = df_dcopf.reset_index().copy() # Filter price records df_tmp_1 = df_tmp_1[df_tmp_1['index'].str.contains(r'\.POWER_BALANCE\[')] # Extract values df_tmp_1['Value'] = df_tmp_1.apply(lambda x: x['Constraint']['Dual'], axis=1) # Extract node and scenario IDs df_tmp_1['NODE_ID'] = df_tmp_1['index'].str.extract(r'\.POWER_BALANCE\[(\d+)\]').astype(int) df_tmp_1['SCENARIO_ID'] = df_tmp_1['SCENARIO_ID'].astype(int) # Prices at each node for each scenario df_dcopf_prices = df_tmp_1.set_index(['SCENARIO_ID', 'NODE_ID'])['Value'] # MPPDC model # ----------- df_tmp_2 = df_mppdc.reset_index().copy() # Filter price records df_tmp_2 = df_tmp_2[df_tmp_2['index'].str.contains(r'\.lambda_var\[')] # Extract values df_tmp_2['Value'] = df_tmp_2.apply(lambda x: x['Variable']['Value'], axis=1) # Extract node and scenario IDs df_tmp_2['NODE_ID'] = df_tmp_2['index'].str.extract(r'\.lambda_var\[(\d+)\]').astype(int) df_tmp_2['SCENARIO_ID'] = df_tmp_2['index'].str.extract(r'LL_DUAL\[(\d+)\]').astype(int) # Prices at each node for each scenario df_mppdc_prices = df_tmp_2.set_index(['SCENARIO_ID', 'NODE_ID'])['Value'] # Compute difference between models # --------------------------------- max_price_difference = df_dcopf_prices.subtract(df_mppdc_prices).abs().max() print('Maximum difference between nodal prices over all nodes and scenarios: {0}'.format(max_price_difference)) return max_price_difference # Find max nodal price difference between DCOPF and MPPDC models compare_nodal_prices(df_dcopf=df_dcopf, df_mppdc=df_mppdc) # - # Close correspondence of price and output results between MPPDC and DCOPF representations suggests that the MPPDC has been formulated correctly. # ## Organise data for plotting # Using collated model results data, find: # 1. emissions intensity baselines that target average wholesale prices for different permit price scenarios; # 2. scheme revenue that corresponds with price targeting baselines and permit price scenarios; # 3. average regional and national prices under a REP scheme with different average wholesale price targets; # 4. average regional and national prices under a carbon tax. # # # ### Price targeting baselines for different average price targets and fixed permit prices # Collated data. # Price targeting baseline results - unprocessed df_price_targeting_baseline = collate_data('MPPDC-FIND_PRICE_TARGETING_BASELINE') # #### Baselines for different average price targets # + # Price targeting baseline as a function of permit price df_baseline_vs_permit_price = df_price_targeting_baseline.groupby(['FIXED_TAU', 'TARGET_PRICE_BAU_MULTIPLE']).apply(lambda x: x.loc['phi', 'Variable']['Value']).unstack() with open(os.path.join(output_dir, 'df_baseline_vs_permit_price.pickle'), 'wb') as f: pickle.dump(df_baseline_vs_permit_price, f) # - # #### Scheme revenue for different average price targets # + def get_revenue(group): "Get scheme revenue for each permit price - price target scenario" # Get baseline for each group baseline = group.loc['phi', 'Variable']['Value'] # Filter power output records group = group[group.index.str.contains(r'LL_PRIM\[\d+\].P\[')].copy() # Extract DUID - used to merge generator information group['DUID'] = group.apply(lambda x: re.findall(r'P\[(.+)\]', x.name)[0], axis=1) # Extract scenario ID - used to get duration of scenario group['SCENARIO_ID'] = group.apply(lambda x: re.findall(r'LL_PRIM\[(\d+)\]', x.name)[0], axis=1) # Duration of each scenario [hours] scenario_id = int(group['SCENARIO_ID'].unique()[0]) scenario_duration = df_scenarios.loc[scenario_id, ('hours', 'duration')] # Generator power output group['Value'] = group.apply(lambda x: x['Variable']['Value'], axis=1) # Merge SRMCs and emissions intensities group = pd.merge(group, df_g[['SRMC_2016-17', 'EMISSIONS']], how='left', left_on='DUID', right_index=True) # Compute revenue SUM ((emissions_intensity - baseline) * power_output * duration) revenue = group['EMISSIONS'].subtract(baseline).mul(group['Value']).mul(group['FIXED_TAU']).mul(scenario_duration).sum() / 8760 return revenue # Get revenue for each permit price and wholesale average price target scenario df_baseline_vs_revenue = df_price_targeting_baseline.groupby(['FIXED_TAU', 'TARGET_PRICE_BAU_MULTIPLE']).apply(get_revenue).unstack() with open(os.path.join(output_dir, 'df_baseline_vs_revenue.pickle'), 'wb') as f: pickle.dump(df_baseline_vs_revenue, f) # - # #### Regional and national average wholesale electricity prices for different average price targets # + def get_average_prices(group): "Compute regional and national average wholesale prices" # Filter price records group = group[group.index.str.contains(r'\.lambda_var\[')].reset_index().copy() # Extract nodal prices group['Value'] = group.apply(lambda x: x['Variable']['Value'], axis=1) # Extract node and scenario IDs group['NODE_ID'] = group['index'].str.extract(r'lambda_var\[(\d+)\]')[0].astype(int) group['SCENARIO_ID'] = group['index'].str.extract(r'LL_DUAL\[(\d+)\]')[0].astype(int) # Scenario Demand df_demand = df_scenarios.loc[:, ('demand')].reset_index().melt(id_vars=['closest_centroid']) df_demand['NODE_ID'] = df_demand['NODE_ID'].astype(int) df_demand = df_demand.rename(columns={'value': 'demand'}) group = pd.merge(group, df_demand, how='left', left_on=['NODE_ID', 'SCENARIO_ID'], right_on=['NODE_ID', 'closest_centroid']) # Scenario duration df_duration = df_scenarios.loc[:, ('hours', 'duration')].to_frame() df_duration.columns = df_duration.columns.droplevel() group = pd.merge(group, df_duration, how='left', left_on='SCENARIO_ID', right_index=True) # NEM regions group = pd.merge(group, df_n[['NEM_REGION']], how='left', left_on='NODE_ID', right_index=True) # Compute node energy demand [MWh] group['total_demand'] = group['demand'].mul(group['duration']) # Compute node revenue [$] group['total_revenue'] = group['total_demand'].mul(group['Value']) # National average price national_average_price = group['total_revenue'].sum() / group['total_demand'].sum() # Regional averages df_average_prices = group.groupby('NEM_REGION')[['total_demand', 'total_revenue']].sum().apply(lambda x: x['total_revenue'] / x['total_demand'], axis=1) df_average_prices.loc['NATIONAL'] = national_average_price return df_average_prices # REP Scheme average prices df_rep_average_prices = df_price_targeting_baseline.groupby(['FIXED_TAU', 'TARGET_PRICE_BAU_MULTIPLE']).apply(get_average_prices) with open(os.path.join(output_dir, 'df_rep_average_prices.pickle'), 'wb') as f: pickle.dump(df_rep_average_prices, f) # - # ### Average prices under a carbon tax # Collate data # Carbon tax scenario results df_carbon_tax = collate_data('MPPDC-FIXED_PARAMETERS-BASELINE_0') # #### Average prices under carbon tax # + # Average regional and national prices under a carbon tax df_carbon_tax_average_prices = df_carbon_tax.groupby(['FIXED_TAU', 'TARGET_PRICE_BAU_MULTIPLE']).apply(get_average_prices) with open(os.path.join(output_dir, 'df_carbon_tax_average_prices.pickle'), 'wb') as f: pickle.dump(df_carbon_tax_average_prices, f) # - # #### Average system emissions intensity for different permit prices # Average system emissions intensity is invariant to the emissions intensity baseline (the emissions intensity baseline doesn't affect the relative costs of generators). Therefore the emissions outcomes will be the same for the REP and carbon tax scenarios when permit prices are fixed. # # **Note: this equivalence in outcomes assumes that demand is perfectly inelastic.** # + def get_average_emissions_intensity(group): "Get average emissions intensity for each permit price scenario" # Reset index df_tmp = group.reset_index() df_tmp = df_tmp[df_tmp['index'].str.contains(r'\.P\[')].copy() # Extract generator IDs df_tmp['DUID'] = df_tmp['index'].str.extract(r'\.P\[(.+)\]') # Extract and format scenario IDs df_tmp['SCENARIO_ID'] = df_tmp['index'].str.extract(r'LL_PRIM\[(.+)\]\.') df_tmp['SCENARIO_ID'] = df_tmp['SCENARIO_ID'].astype(int) # Extract power output values df_tmp['value'] = df_tmp.apply(lambda x: x['Variable']['Value'], axis=1) # Duration of each scenario df_duration = df_scenarios.loc[:, ('hours', 'duration')].to_frame() df_duration.columns = df_duration.columns.droplevel(0) # Merge scenario duration information df_tmp = pd.merge(df_tmp, df_duration, how='left', left_on='SCENARIO_ID', right_index=True) # Merge emissions intensity information df_tmp = pd.merge(df_tmp, df_g[['EMISSIONS']], how='left', left_on='DUID', right_index=True) # Total emissions [tCO2] total_emissions = df_tmp['value'].mul(df_tmp['duration']).mul(df_tmp['EMISSIONS']).sum() # Total demand [MWh] total_demand = df_scenarios.loc[:, ('demand')].sum(axis=1).mul(df_duration['duration']).sum() # Average emissions intensity average_emissions_intensity = total_emissions / total_demand return average_emissions_intensity # Average emissions intensity for different permit price scenarios df_average_emissions_intensities = df_carbon_tax.groupby('FIXED_TAU').apply(get_average_emissions_intensity) with open(os.path.join(output_dir, 'df_average_emissions_intensities.pickle'), 'wb') as f: pickle.dump(df_average_emissions_intensities, f)
src/3_process_results/process-results.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="nCc3XZEyG3XV" # Lambda School Data Science # # *Unit 2, Sprint 3, Module 2* # # --- # # # # Permutation & Boosting # # You will use your portfolio project dataset for all assignments this sprint. # # ## Assignment # # Complete these tasks for your project, and document your work. # # - [ ] If you haven't completed assignment #1, please do so first. # - [ ] Continue to clean and explore your data. Make exploratory visualizations. # - [ ] Fit a model. Does it beat your baseline? # - [ ] Try xgboost. # - [ ] Get your model's permutation importances. # # You should try to complete an initial model today, because the rest of the week, we're making model interpretation visualizations. # # But, if you aren't ready to try xgboost and permutation importances with your dataset today, that's okay. You can practice with another dataset instead. You may choose any dataset you've worked with previously. # # The data subdirectory includes the Titanic dataset for classification and the NYC apartments dataset for regression. You may want to choose one of these datasets, because example solutions will be available for each. # # # ## Reading # # Top recommendations in _**bold italic:**_ # # #### Permutation Importances # - _**[Kaggle / <NAME>: Machine Learning Explainability](https://www.kaggle.com/dansbecker/permutation-importance)**_ # - [<NAME>: Interpretable Machine Learning](https://christophm.github.io/interpretable-ml-book/feature-importance.html) # # #### (Default) Feature Importances # - [<NAME>: Selecting good features, Part 3, Random Forests](https://blog.datadive.net/selecting-good-features-part-iii-random-forests/) # - [<NAME>, et al: Beware Default Random Forest Importances](https://explained.ai/rf-importance/index.html) # # #### Gradient Boosting # - [A Gentle Introduction to the Gradient Boosting Algorithm for Machine Learning](https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/) # - _**[A Kaggle Master Explains Gradient Boosting](http://blog.kaggle.com/2017/01/23/a-kaggle-master-explains-gradient-boosting/)**_ # - [_An Introduction to Statistical Learning_](http://www-bcf.usc.edu/~gareth/ISL/ISLR%20Seventh%20Printing.pdf) Chapter 8 # - [Gradient Boosting Explained](http://arogozhnikov.github.io/2016/06/24/gradient_boosting_explained.html) # - _**[Boosting](https://www.youtube.com/watch?v=GM3CDQfQ4sw) (2.5 minute video)**_ # + ## As my sets are not yet ready for use on this assignment, I'm pulling in the SalesDF from Unit2 s1-m3, ## as it will provide practice with regression. # + # %%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/' # !pip install category_encoders==2.* # !pip install eli5 # If you're working locally: else: DATA_PATH = '../data/' # - conda list import matplotlib.pyplot # + import pandas as pd import numpy as np import category_encoders as ce # import matplotlib.pyplot as plt import eli5 from sklearn.model_selection import train_test_split from sklearn.impute import SimpleImputer from sklearn.ensemble import RandomForestRegressor from sklearn.pipeline import make_pipeline from sklearn.metrics import mean_absolute_error as meanAbErr from sklearn.metrics import mean_squared_error as meanSqErr from eli5.sklearn import PermutationImportance from xgboost import XGBRegressor # - # Import df = pd.read_csv(DATA_PATH+'condos/NYC_Citywide_Rolling_Calendar_Sales.csv') # + ## REAL TALK HERE: ## Doing a fair amount of copy/paste from 2-1-3 just to get going on today's assignment! # + # Change column names: replace spaces with underscores df.columns = [col.replace(' ', '_') for col in df] # SALE_PRICE was read as strings. # Remove symbols, convert to integer df['SALE_PRICE'] = ( df['SALE_PRICE'] .str.replace('$','') .str.replace('-','') .str.replace(',','') .astype(int) ) df['BOROUGH'] = df['BOROUGH'].astype(str) top10 = df['NEIGHBORHOOD'].value_counts()[:10].index df.loc[~df['NEIGHBORHOOD'].isin(top10), 'NEIGHBORHOOD'] = 'OTHER' df['YEAR_BUILT'] = df['YEAR_BUILT'].ffill().astype(int) df['SALE_DATE'] = pd.to_datetime(df['SALE_DATE']) # - df['SALE_DATE'].describe() train = df[df['SALE_DATE'] < pd.datetime(2019, 4, 1)] test = df[df['SALE_DATE'] >= pd.datetime(2019, 4, 1)] assert(len(train) + len(test) == len(df)) # + target = 'SALE_PRICE' badObjCols = ['TAX_CLASS_AT_PRESENT', 'BUILDING_CLASS_AT_PRESENT', 'ADDRESS', 'APARTMENT_NUMBER', 'LAND_SQUARE_FEET', 'BUILDING_CLASS_AT_TIME_OF_SALE', 'SALE_DATE', 'EASE-MENT'] features = train.columns.drop([target] + badObjCols) # - features train, val = train_test_split(train, train_size=0.8, test_size=0.2, random_state=55) # + X_train = train[features] X_val = val[features] X_test = test[features] y_train = train[target] y_val = val[target] y_test = test[target] # - y_baseline = [y_test.mean()] * len(y_test) pipeline = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(strategy='mean'), RandomForestRegressor(n_estimators=100, random_state=55, n_jobs=-2) ) pipeline.fit(X_train, y_train) # + y_val_pred = pipeline.predict(X_val) y_test_pred = pipeline.predict(X_test) val_mae = meanAbErr(y_val, y_val_pred) val_mse = meanSqErr(y_val, y_val_pred) val_rmse = val_mse**.5 test_mae = meanAbErr(y_test, y_test_pred) test_mse = meanSqErr(y_test, y_test_pred) test_rmse = test_mse**.5 print(f'Validation Absolute Err: ${val_mae:,.0f}\nSqRt of MeanSqErr: ${val_rmse:,.0f}\n') print(f'Test Absolute Err: ${test_mae:,.0f}\nSqRt of MeanSqErr: ${test_rmse:,.0f}\n') # + # Get feature importances rf = pipeline.named_steps['randomforestregressor'] importances = pd.Series(rf.feature_importances_, X_train.columns) n = len(features) plt.figure(figsize=(10,n/2)) plt.title(f'Top {n} features') importances.sort_values()[-n:].plot.barh(color='grey'); # + transformers = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(strategy='mean') ) X_train_transformed = transformers.fit_transform(X_train) X_val_transformed = transformers.transform(X_val) model = RandomForestRegressor(n_estimators=100, random_state=55, n_jobs=-2) model.fit(X_train_transformed, y_train) # + permuter = PermutationImportance( model, n_iter=5, random_state=55 ) permuter.fit(X_val_transformed, y_val) # - feature_names = X_val.columns.tolist() pd.Series(permuter.feature_importances_, feature_names).sort_values(ascending=False) # + feature_names = X_val.columns.tolist() eli5.show_weights( permuter, top=None, # show permutation importances for all features feature_names=feature_names ) # - minimum_importance = 0.001 mask = permuter.feature_importances_ > minimum_importance features_masked = X_train.columns[mask] X_train_masked = X_train[features_masked] # + X_val_masked = X_val[features_masked] X_test_masked = X_test[features_masked] pipeline2 = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(strategy='median'), RandomForestRegressor(n_estimators=100, random_state=55, n_jobs=-2) ) # Fit on train, score on val pipeline2.fit(X_train_masked, y_train) # + y_val_pred = pipeline2.predict(X_val_masked) y_test_pred = pipeline2.predict(X_test_masked) val_mae = meanAbErr(y_val, y_val_pred) val_mse = meanSqErr(y_val, y_val_pred) val_rmse = val_mse**.5 test_mae = meanAbErr(y_test, y_test_pred) test_mse = meanSqErr(y_test, y_test_pred) test_rmse = test_mse**.5 print(f'Validation Absolute Err: ${val_mae:,.0f}\nSqRt of MeanSqErr: ${val_rmse:,.0f}\n') print(f'Test Absolute Err: ${test_mae:,.0f}\nSqRt of MeanSqErr: ${test_rmse:,.0f}\n') # + pipeline3 = make_pipeline( ce.OrdinalEncoder(), XGBRegressor(objective='reg:squarederror', n_estimators=100, random_state=55, n_jobs=-2) ) pipeline3.fit(X_train, y_train) # + y_val_pred = pipeline3.predict(X_val) y_test_pred = pipeline3.predict(X_test) val_mae = meanAbErr(y_val, y_val_pred) val_mse = meanSqErr(y_val, y_val_pred) val_rmse = val_mse**.5 test_mae = meanAbErr(y_test, y_test_pred) test_mse = meanSqErr(y_test, y_test_pred) test_rmse = test_mse**.5 print(f'Validation Absolute Err: ${val_mae:,.0f}\nSqRt of MeanSqErr: ${val_rmse:,.0f}\n') print(f'Test Absolute Err: ${test_mae:,.0f}\nSqRt of MeanSqErr: ${test_rmse:,.0f}\n') # + encoder = ce.OrdinalEncoder() X_train_encoded = encoder.fit_transform(X_train) X_val_encoded = encoder.transform(X_val) model = XGBRegressor( objective='reg:squarederror', n_estimators=1000, # <= 1000 trees, depends on early stopping max_depth=7, # try deeper trees because of high cardinality categoricals learning_rate=0.5, # try higher learning rate n_jobs=-2 ) eval_set = [(X_train_encoded, y_train), (X_val_encoded, y_val)] model.fit(X_train_encoded, y_train, eval_set=eval_set, eval_metric='merror', early_stopping_rounds=50)
module2/assignment_applied_modeling_2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 35 # language: python # name: python35 # --- import eeconvert import ee import geopandas as gpd ee.Initialize() fc = ee.FeatureCollection("USDOS/LSIB_SIMPLE/2017"); fcEu = fc.filter(ee.Filter.eq("wld_rgn","Europe")) fcTest = fcEu.filter(ee.Filter.inList("country_co",["PO","NL"])) gdf =eeconvert.fcToGdf(fcTest)
examples/sample.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Notebook Purpose # # Analyze feature map regularization results for ismrm paper. Previously tuned parameters, i.e. see `20201121_results_fm_regularizn_quant_across_trials.ipynb` # # ### Note # - Currently, fm_reg is run in the new pytorch environment, but fastmri results for ismrm were made in the old pytorch environment. hence need to port fm_reg over into old environment # + import os, sys from os import listdir from os.path import isfile, join import numpy as np import pandas as pd import json import torch from matplotlib import pyplot as plt import matplotlib.patches as patches import matplotlib.gridspec as gridspec from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes sys.path.append('/home/vanveen/ConvDecoder/') from utils.data_io import load_h5 from utils.evaluate import calc_metrics, norm_imgs from utils.transform import fft_2d, ifft_2d, root_sum_squares, \ crop_center # + display_rows = 10#len(df) pd.set_option('display.max_rows', display_rows) def agg_sort_df(df_in): ''' given df, aggregate trial_ids across means for different file_ids sort df rows by the highest ssim_dc ''' try: agg_fns = {'ssim_dc': 'mean', 'psnr_dc': 'mean', 'ssim_est':'mean', 'psnr_est':'mean', \ 'alpha_fm': 'first', 'num_iter': 'first', 'iter_start_fm_loss': 'first', \ 'weight_method': 'first', 'downsamp_method':'first'} df = df_in.groupby(df_in['trial_id']).aggregate(agg_fns).reset_index() except: agg_fns = {'ssim_dc': 'mean', 'psnr_dc': 'mean', 'ssim_est':'mean', 'psnr_est':'mean', \ 'alpha_fm': 'first', 'num_iter': 'first', \ 'weight_method': 'first', 'downsamp_method':'first'} df = df_in.groupby(df_in['trial_id']).aggregate(agg_fns).reset_index() df = df.sort_values(by='ssim_dc', ascending=False) return df def load_gt(file_id): _, ksp_orig = load_h5(file_id) ksp_orig = torch.from_numpy(ksp_orig) return crop_center(root_sum_squares(ifft_2d(ksp_orig)), 320, 320) def plot_list(arr_list, clim=(0, .1)): NUM_COLS = len(arr_list) title_list = ['gt', 'dd+'] fig = plt.figure(figsize=(20,20)) for idx in range(NUM_COLS): ax = fig.add_subplot(1,NUM_COLS,idx+1) ax.imshow(arr_list[idx], cmap='gray', clim=clim) ax.set_title(title_list[idx], fontsize=20) ax.axis('off') def compute_scores(path, trial_id=None): NUM_METRICS = 4 NUM_SAMPS = len(file_id_list) NUM_VARS = 2 # gt, dc metric_list = np.empty((NUM_SAMPS, NUM_METRICS)) im_list = np.empty((NUM_SAMPS, NUM_VARS, 320, 320)) for idx, file_id in enumerate(file_id_list): if trial_id: fn_base = '{}{}_{}'.format(path, trial_id, file_id) else: fn_base = '{}{}'.format(path, file_id) img_gt = np.array(load_gt(file_id)).astype('float32') img_dc = np.load('{}_dc.npy'.format(fn_base)).astype('float32') img_gt, img_dc = norm_imgs(img_gt, img_dc) metric_list[idx] = calc_metrics(img_gt, img_dc) im_list[idx] = [img_gt, img_dc] return metric_list, im_list # + path_fm = '/bmrNAS/people/dvv/out_fastmri/expmt_fm_loss/' path_fm_8 = '/bmrNAS/people/dvv/out_fastmri/expmt_fm_loss/accel_8x/' path_tb = path_fm + 'trials_best/' path_6 = '/bmrNAS/people/dvv/out_fastmri/ismrm/model6/' # n = 5 or n = 11 prototyping test set file_id_list = ['1000273', '1000325', '1000464', \ '1000537', '1000818', '1001140', '1001219', \ '1001338', '1001598', '1001533', '1001798'] # file_id_list = file_id_list + ['1000000', '1000007', '1000017', '1000026', '1000031', # '1000033', '1000041', '1000052', '1000071', '1000073', # '1000107', '1000108', '1000114', '1000126', '1000153', # '1000178', '1000182', '1000190', '1000196', '1000201', # '1000206', '1000229', '1000243', '1000247', '1000254', # '1000263', '1000264', '1000267'] # - # ### which dd+ model to compare # # trial description # - environment: pt==1.7 is new, pt==1.5 is old # - returns: loss_ksp (old bug?) or loss_total # - thus (environment, returns) # # trials # - 0000_10k: (new, ---) w alpha_fm=0 # - autybby9: (new, loss_ksp) w alpha_fm non-zero # - dkrrw7xv: (new, loss_total) # - path_6: (old, ---) w alpha_fm=0 # - tried accel_8x, and it was dogshit # ### get quant results # + metric_list_bl, im_list_bl = compute_scores(path_tb, '0000_10k') metric_list_fm, im_list_fm = compute_scores(path_tb, 'autybby9') print(np.mean(metric_list_bl, axis=0)) print(np.mean(metric_list_fm, axis=0)) # - IDX_OI = 1 metric_list_bl[IDX_OI], metric_list_fm[IDX_OI] # w n=11 # # [ 0.62201909 0.94783812 0.75140817 31.86894458] # [ 0.63941339 0.94933482 0.7619884 32.04480433] # # w n=39 # # [ 0.64683873 0.94417609 0.74882881 31.6465128 ] # [ 0.64759432 0.94441593 0.75076202 31.6559696 ] # + win_board = np.empty((metric_list_fm.shape), dtype='uint8') delta_board = np.empty((metric_list_fm.shape)) NUM_SAMPS = len(metric_list_fm) for idx in range(NUM_SAMPS): scores_bl = metric_list_bl[idx] scores_fm = metric_list_fm[idx] scores_delta = scores_fm - scores_bl win_board[idx] = [1 if s>=0 else 0 for s in scores_delta] delta_board[idx] = np.abs(scores_delta) # win percentage on each metric win_perc = np.sum(win_board, axis=0) / NUM_SAMPS # absolute difference: mean and std delta_mu = np.mean(delta_board, axis=0) delta_std = np.std(delta_board, axis=0) print(win_perc) print('') print(delta_mu) print(delta_std) # - # w n=11 # # [0.81818182 0.72727273 0.72727273 0.81818182] # # [0.02318087 0.00300031 0.01294956 0.23042601] # [0.01423445 0.0015726 0.01886346 0.14056513] # # w n=39 # # [0.56410256 0.56410256 0.51282051 0.53846154] # # [0.02013492 0.00321181 0.00897205 0.22053075] # [0.01647661 0.00198981 0.01166183 0.1796695 ] IDX_OI = 1 FILE_ID_OI = file_id_list[IDX_OI] print(FILE_ID_OI) def plot_list(arr_list, clim=(0,.1), bbox=None, display_scores=True, inset=True): ''' given list of arrays arr_list, plot ''' NUM_COLS = len(arr_list) title_list = ['GT', 'lam=0', 'lam=.001'] im_gt = arr_list[0] fig = plt.figure(figsize=(20,20)) plt.tight_layout() gs = gridspec.GridSpec(1,3) gs.update(wspace=0, hspace=0) for idx in range(NUM_COLS): ax = plt.subplot(gs[idx]) im = arr_list[idx] if bbox: y0, x0, size = dict_inset_bbox[FILE_ID_OI]['bbox'] rect = patches.Rectangle((y0,x0),size,size,linewidth=2,edgecolor='g',facecolor='none') ax.add_patch(rect) if display_scores: if idx == 0: textstr_1, textstr_2 = 'VIF', 'SSIM' elif idx == 1: textstr_1, textstr_2 = '0.53', '0.70' elif idx == 2: textstr_1, textstr_2 = '0.56', '0.76' ax.text(0.86, 0.11, textstr_1, transform=ax.transAxes, fontsize=21, verticalalignment='top', color='cyan') ax.text(0.86, 0.055, textstr_2, transform=ax.transAxes, fontsize=21, verticalalignment='top', color='yellow') ax.imshow(im, cmap='gray', clim=clim, aspect=1) if inset: axins = zoomed_inset_axes(ax, zoom=2, loc=1) EXTENT = 256 axins.imshow(im, cmap='gray', clim=clim, extent=[0,EXTENT,0,EXTENT]) # origin for inset is lower left x0, y0, size = dict_inset_bbox[FILE_ID_OI]['inset'] axins.set_anchor('NE')#, axins.axis('off') axins.set_xlim(x0, x0+size) # axes origin at upper left axins.set_ylim(y0, y0+size) plt.xticks(visible=False), plt.yticks(visible=False) plt.tick_params(axis='both', which='both', bottom=False, top=False, labelbottom=False) plt.rcParams["axes.edgecolor"] = 'green' plt.rcParams["axes.linewidth"] = 3 ax.set_title(title_list[idx], fontsize=20) ax.axis('off') # + dict_inset_bbox = {'1000325': {'bbox': (207, 158, 73), 'inset': (165, 70, 60)}} IDX_OI = 1 im_list_oi = [np.flip(im_list_fm[IDX_OI][0], 0), np.flip(im_list_bl[IDX_OI][1], 0), np.flip(im_list_fm[IDX_OI][1], 0)] plot_list(im_list_oi, bbox=True)
ipynb/ismrm/20201210_ismrm_fm_reg_expmts.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + active="" # ~~~~~~~~~~~<NAME> ID: 305229627*~~~~~~~~~~ # # First block is for loadin the Iris flower data set and relevant modules # + # import load_iris function from datasets module from sklearn.datasets import load_iris from sklearn.metrics import accuracy_score,classification_report,confusion_matrix from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression #Yellowbrick: Machine Learning Visualization from yellowbrick.classifier import ClassificationReport import matplotlib.pyplot as plt # save "bunch" object containing iris dataset and its attributes iris = load_iris() # store feature matrix in "X" X = iris.data # store response vector in "y" y = iris.target # - # print the shapes of X and y print(X.shape) print(y.shape) # + # ~~~~~~~~~~~*Logistic regression Classifier*~~~~~~~~~~ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=4) logreg = LogisticRegression() logreg.fit(X_train, y_train) pred_logreg = logreg.predict(X_test) # compare actual response values (y_test) with predicted response values (y_pred) print("LogisticRegression accuracy score : ",accuracy_score(y_test, pred_logreg)) print(confusion_matrix(y_test, pred_logreg)) print(classification_report(y_test, pred_logreg)) # - # ~~~~~~~~~~~*Logistic regression visual plot*~~~~~~~~~~ visualizer = ClassificationReport(logreg, classes=['setosa', ' versicolor','virginica']) visualizer.fit(X_train, y_train) # Fit the training data to the visualizer visualizer.score(X_test, y_test) # Evaluate the model on the test data g_logreg = visualizer.show() # + # ~~~~~~~~~~~*K-Neighbors Classifier*~~~~~~~~~~ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=4) #try K=1 through K=25 and record testing accuracy k_optimum=1 previous_accuracy=0 k_range = list(range(1, 26)) scores = [] for k in k_range: knn = KNeighborsClassifier(n_neighbors=k) knn.fit(X_train, y_train) y_pred = knn.predict(X_test) scores.append(metrics.accuracy_score(y_test, y_pred)) if metrics.accuracy_score(y_test, y_pred)>previous_accuracy: k_optimum=k previous_accuracy=metrics.accuracy_score(y_test, y_pred) # allow plots to appear within the notebook # %matplotlib inline # plot the relationship between K and testing accuracy plt.plot(k_range, scores) plt.xlabel('Value of K for KNN') plt.ylabel('Testing Accuracy') print("The optimum K for this data set is k =",k_optimum) # - # evaluate the best KNN option accuracy X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=4) print (k_optimum) knn = KNeighborsClassifier(n_neighbors=k_optimum) knn.fit(X_train, y_train) y_pred = knn.predict(X_test) print("KNeighbors accuracy score : ", accuracy_score(y_test, y_pred)) print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred)) # ~~~~~~~~~~~*K-Neighbors Classifier visual plot*~~~~~~~~~~ # Instantiate the classification model and visualizer visualizer = ClassificationReport(knn, classes=['setosa', ' versicolor','virginica']) visualizer.fit(X_train, y_train) # Fit the training data to the visualizer visualizer.score(X_test, y_test) # Evaluate the model on the test data g_KNN = visualizer.poof() # Draw/show/poof the data # This data set is arranged in a table and allows easy access to the information stored in it. # Through Machine learning library SKlearn, it is relatively easy to analyze the information and predict results at a fairly accurate level. # In this project I focused on two types of machine learning, from the SKlearn library: # 1) Logistic Regression # 2) K Neighbors classifier-KNN # # I choosed to Splite the dataset into two pieces: a training set-60 % and a testing set-40 %. # The random state was set to a fixed value - 4, in order to get a fixed result for the same parameters each time I run the program. # # Logistic Regression: # accuracy score : 96.67% # # K Neighbors classifier: # For KNN algorithm, I test the prediction accuracy for diffrent value K - neighbors, in order to find the optimum K value. # After tuning the K value I got quite accurate prediction accuracy of 98.3%. # # For both algorithm the prediction for the Setosa Iris flower was 100% accurate # # + active="" # # -
Iris-flower-data-set-classifier.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Advanced Algorithmic Trading DT - V4 # # ### Updates from Last Version # - Fixed Train/Test split # - Fixed R-Squared calculation for linear model # - Do for: # - Random Forest # - Bagging # - Boosting # - Linear Regression # # # - Grid Search for best model # # #### Import Packages # + import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns import math import datetime import gc from sklearn.ensemble import (BaggingRegressor, RandomForestRegressor, AdaBoostRegressor) from sklearn.model_selection import ParameterGrid from sklearn.tree import DecisionTreeRegressor from sklearn import linear_model from sklearn.linear_model import LinearRegression from sklearn.linear_model import BayesianRidge from sklearn.metrics import mean_squared_error from technical_indicators import * # import all function from sklearn.model_selection import TimeSeriesSplit from sklearn.model_selection import train_test_split #import parfit as pf from sklearn.metrics import r2_score from sklearn.preprocessing import scale from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.cross_decomposition import PLSRegression # - # #### Set Parameters # Set the random seed, number of estimators and the "step factor" used to plot the graph of MSE for each method random_state = 42 # Seed n_jobs = -1 # -1 --> all Processors # Parallelisation factor for bagging, random forests (controls the number of processor cores used) n_estimators = 200 # total number of estimators ot use in the MSE graph step_factor = 10 # controls cranularity of calculation by stepping through the number of estimators axis_step = int(n_estimators / step_factor) # 1000/10 = 100 separate calculations will be performed for each of the 3 ensebmle methods # #### Read in Data via GitHub URL url = "https://raw.githubusercontent.com/meenmo/Stat479_Project/master/Data/IBM.csv" df_ORIGINAL = pd.read_csv(url) # *** # ## Clean Data & Create Technical Indicator Variables # # - Create Deep copy of dataframe # - Use Adjusted Close Data # - Drop Close # - Rename "Adj. Close" as "Close" # - Create Lagged Features # - Drop NaN # - Create Technical Indicator Variables # - Drop NaN # - Re-set index as Date # + df_features = df_ORIGINAL.copy(deep=True) # Create Deep df_features.drop(['Close'], axis = 1, inplace = True) # drop close column df_features.columns = ['Date', 'High', 'Low', 'Open', 'Volume', 'Close'] # Close is actually Adj. Close df_features['Date'] = pd.to_datetime(df_features['Date']) #df_features.head() # sanity check """ Creates Lagged Returns - given OHLCV dataframe - numer of lagged days """ def create_lag_features(df, lag_days): df_ret = df.copy() # iterate through the lag days to generate lag values up to lag_days + 1 for i in range(1,lag_days + 2): df_lag = df_ret[['Date', 'Close']].copy() # generate dataframe to shift index by i day. df_lag['Date'] = df_lag['Date'].shift(-i) df_lag.columns = ['Date', 'value_lag' + str(i)] # combine the valuelag df_ret = pd.merge(df_ret, df_lag, how = 'left', left_on = ['Date'], right_on = ['Date']) #frees memory del df_lag # calculate today's percentage lag df_ret['Today'] = (df_ret['Close'] - df_ret['value_lag1'])/(df_ret['value_lag1']) * 100.0 # calculate percentage lag for i in range(1, lag_days + 1): df_ret['lag' + str(i)] = (df_ret['value_lag'+ str(i)] - df_ret['value_lag'+ str(i+1)])/(df_ret['value_lag'+str(i+1)]) * 100.0 # drop unneeded columns which are value_lags for i in range(1, lag_days + 2): df_ret.drop(['value_lag' + str(i)], axis = 1, inplace = True) return df_ret ### Run Function df_features = create_lag_features(df_features, 5) # 5 lag features #df_features.head(7) # drop earlier data with missing lag features df_features.dropna(inplace=True) # reset index df_features.reset_index(drop = True, inplace = True) #### GENERATE TECHNICAL INDICATORS FEATURES df_features = standard_deviation(df_features, 14) df_features = relative_strength_index(df_features, 14) # periods df_features = average_directional_movement_index(df_features, 14, 13) # n, n_ADX df_features = moving_average(df_features, 21) # periods df_features = exponential_moving_average(df_features, 21) # periods df_features = momentum(df_features, 14) # df_features = average_true_range(df_features, 14) df_features = bollinger_bands(df_features, 21) df_features = ppsr(df_features) df_features = stochastic_oscillator_k(df_features) df_features = stochastic_oscillator_d(df_features, 14) df_features = trix(df_features, 14) df_features = macd(df_features, 26, 12) df_features = mass_index(df_features) df_features = vortex_indicator(df_features, 14) df_features = kst_oscillator(df_features, 10, 10, 10, 15, 10, 15, 20, 30) df_features = true_strength_index(df_features, 25, 13) #df_features = accumulation_distribution(df_features, 14) # Causes Problems, apparently df_features = chaikin_oscillator(df_features) df_features = money_flow_index(df_features, 14) df_features = on_balance_volume(df_features, 14) df_features = force_index(df_features, 14) df_features = ease_of_movement(df_features, 14) df_features = commodity_channel_index(df_features, 14) df_features = keltner_channel(df_features, 14) df_features = ultimate_oscillator(df_features) df_features = donchian_channel(df_features, 14) #drop earlier data with missing lag features df_features.dropna(inplace=True) df_features = df_features.reset_index(drop = True) ########################################################################################### # Store Variables now for plots later daily_index = df_features.index daily_returns = df_features["Today"] daily_price = df_features["Close"] # Re-set "Date" as the index df_features = df_features.set_index('Date') ### Sanity Check df_features.head(10) # - # ## Standardize Data & Create X & y # # - Drop all data used to create technical indicators (this is done in the book) # - Then Standardize, necessary for PLS # - Run PLS # - Select Appropriate number of components # - Create X & y # # NOTE: some technical indicators use Present data, but for simplicity, just ignore this # + ### Standardize Data ########################################################################################## # Drop Columns list_of_columns_to_exclude = ["High", "Low", "Open", "Volume","Close", "Today"] X_temp_standardized = df_features.copy(deep=True) X_temp_standardized.drop(list_of_columns_to_exclude, axis = 1, inplace = True) # drop columns # Standardize X_temp_standardized dates = X_temp_standardized.index # get dates to set as index after data is standardized names = X_temp_standardized.columns # Get column names first X_temp_standardized = StandardScaler().fit_transform(X_temp_standardized) # Convert to DataFrame X_temp_standardized = pd.DataFrame(X_temp_standardized, columns=names, index=dates) X = X_temp_standardized ### Get y ########################################################################################## y_temp = pd.DataFrame(df_features["Today"], index=X.index) # can only standardize a dataframe y = StandardScaler().fit_transform(y_temp) # Standardize, cause we did it for our original variables y = pd.DataFrame(y, index=X.index, columns=["Today"]) # convert back to dataframe y = y["Today"] # now re-get y as a Pandas Series ### Sanity Check print("Shape of X: ", X.shape) print("Shape of y: ", y.shape) # Check Types print(type(X)) # Needs to be <class 'pandas.core.frame.DataFrame'> print(type(y)) # Needs ro be <class 'pandas.core.series.Series'> # - # #### Split: Train & Validatte / Test # # - Train & Validate: < '2018-01-01' # - Test: >= '2018-01-01' # + X_train_all = X.loc[(X.index < '2018-01-01')] y_train_all = y[X_train_all.index] # # creates all test data which is all after January 2018 X_test = X.loc[(X.index >= '2018-01-01'),:] y_test = y[X_test.index] ### Sanity Check print("Shape of X_train_all: ", X_train_all.shape) print("Shape of y_train_all: ", y_train_all.shape) print("Shape of X_test: ", X_test.shape) print("Shape of y_test: ", y_test.shape) # - # ## Time Series Train Test Split ---- # # ### Random Forest # + """ Execute Random Forest for differnt number of Time Series Splits """ def Call_Random_Forest(numSplits): ### Prepare Random Forest ############################################################################## # Initialize Random Forest Instance rf = RandomForestRegressor(n_estimators=150, n_jobs=-1, random_state=123, max_features="sqrt", min_samples_split=4, max_depth=30, min_samples_leaf=1) rf_mse = [] # MSE rf_r2 = [] # R2 ### Time Series Split ############################################################################## splits = TimeSeriesSplit(n_splits=numSplits) # 3 splits splitCount = 0 # dummy count var to track current split num in print statements for train_index, test_index in splits.split(X_train_all): splitCount += 1 # Train Split X_train = X_train_all.iloc[train_index,:] y_train = y[X_train.index] # Validate Split X_val = X_train_all.iloc[test_index,:] y_val = y[X_val.index] # # Print Statements # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") # print("Split: ", splitCount) # print('Observations: ', (X_train.shape[0] + X_val.shape[0])) # #print('Cutoff date, or first date in validation data: ', X_val.iloc[0,0]) # print('Training Observations: ', (X_train.shape[0])) # print('Testing Observations: ', (X_val.shape[0])) # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") ### Run Random Forest rf.fit(X_train, y_train) prediction = rf.predict(X_val) mse = mean_squared_error(y_val, prediction) r2 = r2_score(y_val, prediction) rf_mse.append(mse) rf_r2.append(r2) # print("rf_mse: ", rf_mse) # print("rf_r2: ", rf_r2) ### Time Series Split ############################################################################## # Plot the chart of MSE versus number of estimators plt.figure(figsize=(12, 7)) plt.title('Random Forest - MSE & R-Squared') ### MSE plt.plot(list(range(1,splitCount+1)), rf_mse, 'b-', color="blue", label='MSE') plt.plot(list(range(1,splitCount+1)), rf_r2, 'b-', color="green", label='R-Squared') plt.plot(list(range(1,splitCount+1)), np.array([0] * splitCount), 'b-', color="red", label='Zero') plt.legend(loc='upper right') plt.xlabel('Train/Test Split Number') plt.ylabel('Mean Squared Error & R-Squared') plt.show() print("rf_r2: ", rf_r2) #print(rf.feature_importances_) print("Mean r2: ", np.mean(rf_r2)) ############ Call_Random_Forest(20) # - # ### Bagging # + """ Execute Bagging for differnt number of Time Series Splits """ def Call_Bagging(numSplits): ### Prepare Bagging ############################################################################## # Initialize Bagging Instance bagging = BaggingRegressor(n_estimators=150, n_jobs=-1, random_state=123) bagging_mse = [] # MSE bagging_r2 = [] # R2 ### Time Series Split ############################################################################## splits = TimeSeriesSplit(n_splits=numSplits) # 3 splits splitCount = 0 # dummy count var to track current split num in print statements for train_index, test_index in splits.split(X_train_all): splitCount += 1 # Train Split X_train = X_train_all.iloc[train_index,:] y_train = y[X_train.index] # Validate Split X_val = X_train_all.iloc[test_index,:] y_val = y[X_val.index] # # Print Statements # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") # print("Split: ", splitCount) # print('Observations: ', (X_train.shape[0] + X_test.shape[0])) # #print('Cutoff date, or first date in validation data: ', X_val.iloc[0,0]) # print('Training Observations: ', (X_train.shape[0])) # print('Testing Observations: ', (X_test.shape[0])) # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") ### Run Random Forest bagging.fit(X_train, y_train) prediction = bagging.predict(X_val) mse = mean_squared_error(y_val, prediction) r2 = r2_score(y_val, prediction) bagging_mse.append(mse) bagging_r2.append(r2) ### Time Series Split ############################################################################## # Plot the chart of MSE versus number of estimators plt.figure(figsize=(12, 7)) plt.title('Bagging - MSE & R-Squared') ### MSE plt.plot(list(range(1,splitCount+1)), bagging_mse, 'b-', color="blue", label='MSE') plt.plot(list(range(1,splitCount+1)), bagging_r2, 'b-', color="green", label='R-Squared') plt.plot(list(range(1,splitCount+1)), np.array([0] * splitCount), 'b-', color="red", label='Zero') plt.legend(loc='upper right') plt.xlabel('Train/Test Split Number') plt.ylabel('Mean Squared Error & R-Squared') plt.show() print("bagging_r2: ", bagging_r2) # - # ### Boosting # + """ Execute Random Forest for differnt number of Time Series Splits """ def Call_Boosting(numSplits): ### Prepare Boosting ############################################################################## # Initialize Boosting Instance boosting = AdaBoostRegressor(DecisionTreeRegressor(), n_estimators=150, random_state=123,learning_rate=0.01) boosting_mse = [] # MSE boosting_r2 = [] # R2 ### Time Series Split ############################################################################## splits = TimeSeriesSplit(n_splits=numSplits) # 3 splits splitCount = 0 # dummy count var to track current split num in print statements for train_index, test_index in splits.split(X_train_all): splitCount += 1 # Train Split X_train = X_train_all.iloc[train_index,:] y_train = y[X_train.index] # Validate Split X_val = X_train_all.iloc[test_index,:] y_val = y[X_val.index] # # Print Statements # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") # print("Split: ", splitCount) # print('Observations: ', (X_train.shape[0] + X_test.shape[0])) # #print('Cutoff date, or first date in validation data: ', X_val.iloc[0,0]) # print('Training Observations: ', (X_train.shape[0])) # print('Testing Observations: ', (X_test.shape[0])) # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") ### Run Random Forest boosting.fit(X_train, y_train) prediction = boosting.predict(X_val) mse = mean_squared_error(y_val, prediction) r2 = r2_score(y_val, prediction) boosting_mse.append(mse) boosting_r2.append(r2) ### Time Series Split ############################################################################## # Plot the chart of MSE versus number of estimators plt.figure(figsize=(12, 7)) plt.title('Boosting - MSE & R-Squared') ### MSE plt.plot(list(range(1,splitCount+1)), boosting_mse, 'b-', color="blue", label='MSE') plt.plot(list(range(1,splitCount+1)), boosting_r2, 'b-', color="green", label='R-Squared') plt.plot(list(range(1,splitCount+1)), np.array([0] * splitCount), 'b-', color="red", label='Zero') plt.legend(loc='upper right') plt.xlabel('Train/Test Split Number') plt.ylabel('Mean Squared Error & R-Squared') plt.show() print("boosting_r2: ", boosting_r2) # - # ### Linear Regression # # + """ Execute Linear Regression for different number of Time Series Splits """ def Call_Linear(numSplits): ### Prepare Random Forest ############################################################################## # Initialize Random Forest Instance linear = LinearRegression(n_jobs=-1, normalize=True, fit_intercept=False) # if we don't fit the intercept we get a better prediction linear_mse = [] # MSE linear_r2 = [] # R2 ### Time Series Split ############################################################################## splits = TimeSeriesSplit(n_splits=numSplits) # 3 splits splitCount = 0 # dummy count var to track current split num in print statements for train_index, test_index in splits.split(X_train_all): splitCount += 1 # Train Split X_train = X_train_all.iloc[train_index,:] y_train = y[X_train.index] # Validate Split X_val = X_train_all.iloc[test_index,:] y_val = y[X_val.index] ################# # # Print Statements # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") # print("Split: ", splitCount) # print('Observations: ', (X_train.shape[0] + X_test.shape[0])) # #print('Cutoff date, or first date in validation data: ', X_val.iloc[0,0]) # print('Training Observations: ', (X_train.shape[0])) # print('Testing Observations: ', (X_test.shape[0])) # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") ### Run Random Forest linear.fit(X_train, y_train) prediction = linear.predict(X_val) mse = mean_squared_error(y_val, prediction) r2 = r2_score(y_val, prediction) r2 = np.corrcoef(y_val, prediction)[0, 1] r2 = r2*r2 # square of correlation coefficient --> R-squared linear_mse.append(mse) linear_r2.append(r2) ### Time Series Split ############################################################################## # Plot the chart of MSE versus number of estimators plt.figure(figsize=(12, 7)) plt.title('Linear Regression - MSE & R-Squared') ### MSE plt.plot(list(range(1,splitCount+1)), linear_mse, 'b-', color="blue", label='MSE') plt.plot(list(range(1,splitCount+1)), linear_r2, 'b-', color="green", label='R-Squared') plt.plot(list(range(1,splitCount+1)), np.array([0] * splitCount), 'b-', color="red", label='Zero') plt.legend(loc='upper right') plt.xlabel('Train/Test Split Number') plt.ylabel('Mean Squared Error & R-Squared') plt.show() #print("linear_r2: ", linear_r2) # - # ### Misc. Graphs ---- Price, Returns & Cumulative Returns # + # figure dimenstions length = 15 height = 5 ### Prices plt.figure(figsize=(length, height)) plt.title('IBM Adj Close Price Graph') plt.plot(daily_index, daily_price, 'b-', color="blue", label='Prices') plt.legend(loc='upper right') plt.xlabel('Days') plt.ylabel('Prices') plt.show() ### Returns plt.figure(figsize=(length, height)) plt.title('IBM Daily Returns') plt.plot(daily_index, daily_returns, 'b-', color="blue", label='Returns') plt.legend(loc='upper right') plt.xlabel('Days') plt.ylabel('Returns') plt.show() ### Cumulative Returns plt.figure(figsize=(length, height)) plt.title('IBM Cumulative Returns') cumulative_returns = daily_returns.cumsum() plt.plot(daily_index, cumulative_returns, 'b-', color="green", label='Cumulative Returns') plt.legend(loc='upper right') plt.xlabel('Days') plt.ylabel('Cumulative Return') plt.show() # - # ### First - A Note on R-Squared # # ##### What Does A Negative R Squared Value Mean? # # - What does R-squared tell us? # - It tells us whether a horizonal line through the vertical mean of the data is a better predictor # - For a Linear Regression # - R-squared is just the coreelation coefficient squared # - R-squared can't be negative, becasue at 0, it becomes the horizontal line # - For All other Model # - For practical purposes, the lowest R2 you can get is zero, but only because the assumption is that if your regression line is not better than using the mean, then you will just use the mean value. # - However if your regression line is worse than using the mean value, the r squared value that you calculate will be negative. # - Note that the reason R2 can't be negative in the linear regression case is just due to chance and how linear regression is contructed # # ##### Note # - In our R2 computation for the linear model, we're still getting a negative R2, not sure why #Call_Random_Forest(20) Call_Bagging(20) # Call_Boosting(20) # takes forever to run Call_Linear(100) # + for param1 for param2 for param 3 call random forestt # + """ Execute Random Forest for differnt number of Time Series Splits """ def Call_Random_Forest_Grid_Search(numSplits, minSamplesSplit, maxDepth, minSamplesLeaf): ### Prepare Random Forest ############################################################################## # Initialize Random Forest Instance rf = RandomForestRegressor(n_estimators=150, n_jobs=-1, random_state=123, max_features="sqrt", min_samples_split=minSamplesSplit, max_depth=maxDepth, min_samples_leaf=minSamplesLeaf) rf_mse = [] # MSE rf_r2 = [] # R2 ### Time Series Split ############################################################################## splits = TimeSeriesSplit(n_splits=numSplits) # 3 splits splitCount = 0 # dummy count var to track current split num in print statements for train_index, test_index in splits.split(X_train_all): splitCount += 1 # Train Split X_train = X_train_all.iloc[train_index,:] y_train = y[X_train.index] # Validate Split X_val = X_train_all.iloc[test_index,:] y_val = y[X_val.index] # # Print Statements # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") # print("Split: ", splitCount) # print('Observations: ', (X_train.shape[0] + X_val.shape[0])) # #print('Cutoff date, or first date in validation data: ', X_val.iloc[0,0]) # print('Training Observations: ', (X_train.shape[0])) # print('Testing Observations: ', (X_val.shape[0])) # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") ### Run Random Forest rf.fit(X_train, y_train) prediction = rf.predict(X_val) mse = mean_squared_error(y_val, prediction) r2 = r2_score(y_val, prediction) rf_mse.append(mse) rf_r2.append(r2) # print("rf_mse: ", rf_mse) # print("rf_r2: ", rf_r2) # ### Time Series Split Plot # ############################################################################## # # Plot the chart of MSE versus number of estimators # plt.figure(figsize=(12, 7)) # plt.title('Random Forest - MSE & R-Squared') # ### MSE # plt.plot(list(range(1,splitCount+1)), rf_mse, 'b-', color="blue", label='MSE') # plt.plot(list(range(1,splitCount+1)), rf_r2, 'b-', color="green", label='R-Squared') # plt.plot(list(range(1,splitCount+1)), np.array([0] * splitCount), 'b-', color="red", label='Zero') # plt.legend(loc='upper right') # plt.xlabel('Train/Test Split Number') # plt.ylabel('Mean Squared Error & R-Squared') # plt.show() #print("rf_r2: ", rf_r2) #print(rf.feature_importances_) #print("Mean r2: ", np.mean(rf_r2)) return np.mean(rf_r2) ############ #Call_Random_Forest(10) # + # Call_Random_Forest_Grid_Search(numSplits, minSamplesSplit, maxDepth, minSamplesLeaf) minSamplesSplit_list = [2,5,10,15,20] maxDepth_list = [15,20,25] minSamplesLeaf_list = [2,5,10] best_model_parameters = [0,0,0] max_r2 = -100 count = 0 # Loop over all possible parameters for minSamplesSplit in minSamplesSplit_list: for maxDepth in maxDepth_list: for minSamplesLeaf in minSamplesLeaf_list: count += 1 temp_mean_r2 = Call_Random_Forest_Grid_Search(20, minSamplesSplit, maxDepth, minSamplesLeaf) # Call Random Forest Train/Validation print("temp_mean ", count, ": ", temp_mean_r2) if temp_mean_r2 > max_r2: max_r2 = temp_mean_r2 # store new max best_model_parameters[0] = minSamplesSplit best_model_parameters[1] = maxDepth best_model_parameters[2] = minSamplesLeaf print("Best R2: ", max_r2) # - best_model_parameters # + minSamplesSplit_list = [4,5,6] maxDepth_list = [25,30,35] minSamplesLeaf_list = [1,2,3] best_model_parameters = [0,0,0] max_r2 = -100 count = 0 # Loop over all possible parameters for minSamplesSplit in minSamplesSplit_list: for maxDepth in maxDepth_list: for minSamplesLeaf in minSamplesLeaf_list: count += 1 temp_mean_r2 = Call_Random_Forest_Grid_Search(20, minSamplesSplit, maxDepth, minSamplesLeaf) # Call Random Forest Train/Validation print("temp_mean ", count, ": ", temp_mean_r2) if temp_mean_r2 > max_r2: max_r2 = temp_mean_r2 # store new max best_model_parameters[0] = minSamplesSplit best_model_parameters[1] = maxDepth best_model_parameters[2] = minSamplesLeaf print("Best R2: ", max_r2) # - best_model_parameters # + minSamplesSplit_list = [2,3,4] maxDepth_list = [29,30,31] minSamplesLeaf_list = [1,2] best_model_parameters = [0,0,0] max_r2 = -100 count = 0 # Loop over all possible parameters for minSamplesSplit in minSamplesSplit_list: for maxDepth in maxDepth_list: for minSamplesLeaf in minSamplesLeaf_list: count += 1 temp_mean_r2 = Call_Random_Forest_Grid_Search(20, minSamplesSplit, maxDepth, minSamplesLeaf) # Call Random Forest Train/Validation print("temp_mean ", count, ": ", temp_mean_r2) if temp_mean_r2 > max_r2: max_r2 = temp_mean_r2 # store new max best_model_parameters[0] = minSamplesSplit best_model_parameters[1] = maxDepth best_model_parameters[2] = minSamplesLeaf print("Best R2: ", max_r2) print(best_model_parameters) # - # # Best Model: Random Forest # # ##### According to Grid Search, our best model is: # - [4, 30, 1] # - minSamplesSplit = 4 # - maxDepth = 30 # - minSamplesLeaf = 1
Code/Model 1 (regression trees)/AAT-DT_v4.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ![images.jfif](attachment:images.jfif) # # The numpy.random package # # <font color=steelblue>The</font> <font color=lime>n</font><font color=coral>u</font><font color=crimson>m</font><font color=blue>p</font><font color=purple>y</font>.<font color=orange>r</font><font color=aqua>a</font><font color=chartreuse>n</font><font color=fuchsia>d</font><font color=gold>o</font><font color=indigo>m</font> <font color=steelblue>package</font><h1> # *I would just like to begin by apologizing for the lack of color or enhances formatting in the following project. I put quite a bit of time into colorising and centering the above title, only to find out (after a myriad of attemted fixes) that Github will not display colored text in Jupyter, nor does it support formatting, such as centering text etc. As a result the following paper is slightly less aesthetically pleasing than I would have liked. If you would like a sample of how it could have looked, I have included the original code for the title in the README file, if you care to run it on another notebook as markdown text. # ## What is the numpy.random package? # # # - Numpy.random is a library of functions that can be used to generate arrays of pseudo-random numbers under a variety of different key parameters. # - These parameters can include specifications of range, division of parts, the amount of numbers generated within each array, the shape and number of arrays generated & variables regarding the probability distribution of the function itself. # # # Simple Random Data # ![random_data_watermark.576078a4008d.jpg](attachment:random_data_watermark.576078a4008d.jpg) # ## Integers # ![Negative-Integers-1.jpg](attachment:Negative-Integers-1.jpg) # #### parameters: # - low : int or array-like of ints # - high : int or array-like of ints, optional # - size : int or tuple of ints, optional # - dtype : dtype, optional # - endpoint : bool, optional # # #### returns # - out : int or ndarray of ints # # First we import the required libraries: import numpy as np import matplotlib.pyplot as plt import seaborn as sns # And then we create a shorthand value name for 'np.random.default_rng()', so that we don't have to type that in every time. rng = np.random.default_rng() # #### high # - For some reason, the first value to be set in the function is the high value (Even though above 'low' is mentioned first). If there is only one value entered as below, the default lowest point in the range is 0, with the entered value being the highest (exclusive). This means that the numbers generated will be integers between 0 and (x-1), with x being the number entered. This is due to the manner in which computers deal with integers and tally values starting from 0 rather than 1. rng.integers(7) # #### low # - if a second value is entered, the order of values becomes as such: (low, high). Here we can see that the lowest range is now changed from the default '0' to the first value in the brackets. rng.integers(-15, 7) # #### Size # - Next we can specify the size of the array. This in itself comes with it's own range of parameters that allow us to determine the nature of the output in further detail. # # -In this next piece of code we can see that we have the same first two parameters, but have now generated an array of 10 outcomes. rng.integers(-15, 7, 10) # - You can specify size without setting low value by using 'size='. You will be required to set at least one positional arguement before this will work, however. rng.integers(5, size=10) # -Another value recieves an error message. # # *(I have included an image of this outcome instead of including the actual code, as otherwise it disrupts the comtinuity of the 'Restart and Run All' action. # ![image.png](attachment:image.png) # -However if we now enclose the size parameter in brackets, we can see that we can now create 10 arrays, each containing 2 outcomes. # - (low, high, (No. of Arrays, No. of outcomes in each array)) rng.integers(-15, 7, (10, 2)) # - A third value adds another dimension to the arrays. m = rng.integers(-15, 7, (10, 2, 7)) m # - And as you can see, adding more values to the size parameter just keeps adding dimensions to the way the arrays are generated. rng.integers(-15, 7, (10, 2, 7, 4)) # #### Square Brackets: # - These allow you to give several sepperate values for a given parameter, and to generate an outcome for each. # # - Here we can see we have set three different high values, and have generated an outcome for each: rng.integers(1, [7, 10, 2]) # - Or we can do the same for the low parameter: rng.integers([0, 50, 95], 100) # #### Default distribution: # - The default distribution of these simple data functions is essentially the uniform distribution. We can test this by running the function through a large data set and visualizing the distribution through a histogram. a = rng.integers(1000, size=10000000) plt.hist(a) # - Here we can see the distrinution of probability is uniformly spread out accross the parameters. # - So what if we changed the default distribution? b = rng.normal(1000, size=10000000) b plt.hist(b) # - Here we see the probability distribution has been changed. Now instead of uniform distribution, it is more likely for a number to fall closer to 1000 than the outer boundaries of the ranges of the array. # ## Random # ![1_t_G1kZwKv0p2arQCgYG7IQ.gif](attachment:1_t_G1kZwKv0p2arQCgYG7IQ.gif) # - .ramdom generates floating point numbers between the 'half-open interval', which means between [0.0, 1.0]. # #### parameters: # - size : int or tuple of ints, optional # - dtype : dtype, optional # - out : ndarray, optional # # #### returns: # - out : float or ndarray of floats # The command on its own will simply generate a single float: rng.random() # If given a value, it will produce that many floats. rng.random(5) # Another value withing an extra set of brackets adds anothher dimension to the output. You may keep adding dimensions. rng.random((5, 4)) # You may keep adding dimensions. rng.random((5, 4, 3)) # In order to change the boundaries of the range, one can use the following method: # # x * rng.random() - y # # (Where 0 to x is the size of the range, and y is the amount you would like to move the starting point of the range by from 0 (ie: x = 30 y= 15 would result in the range being from -15 to 15)) # Example: 30 * rng.random(30) - 15 # Floating point numbers are good for generating more precise outcomes than those produced by the integer rng. # #### Distribution: c = rng.random(10000000) c plt.hist(c) # Again, we can see that the distribution is uniform across the range. # ## Choice: # ![download.jfif](attachment:download.jfif) # This rng generates a number or array of numbers from a speciific array/data set that is manually input by the user. For example if you wanted a function that would pick a number between 1 and ten, but you didn't want it to pick any even numbers, you could input the array fom which it may chose a number as: (0,1,3,5,7,9). # #### Parameters: # - a : {array_like, int} # - size : {int, tuple[int]}, optional # - replace : bool, optional # - p : 1-D array_like, optional # - axis : int, optional # - shuffle : bool, optional # # #### Returns: # - samples : single item or ndarray # # If given only one parametre, will generate a random integer based on np.arrange(x), which basically will give a list of integers from 0 to x. # #### a rng.choice(5) # #### size # Given two parameters, it will generate a given number of integers from the same set. rng.choice(5, 3) # However if you enclose the initial set of parameters in brackets, you can specify the array's elements. rng.choice((1,3,5), 3) # #### replace # The replace option decides whether an element is replaced in the array after it has been chosen initially. For instance: # - An example of 'replace=false' would be if you have a deck of cards, and you pick one card, it would be from a data set of 52 cards. However, if you then go on to pick another card from the same deck, you cannot pick the same card again, as that card has already been removed from the deck, and thus you are picking from a data set of 51 elements, none of which could possibly be the one chosen before. # - An example of 'replace=true' would be picking a card from a deck, but then putting it back, reshuffling the deck, and chosing another card. All 52 cards are possible each time. rng.choice(5, 5, replace=False) # Above we can see each element only appears once. # Since the default is replace=true, we do not have to enter it for it to apply. # Below you can see the same number can appear repeatedly in the output. rng.choice(5, 5) # P: # We may also define the probability of each element of the given array to occur: # (If not given, uniform distribution applies) e = rng.choice(10, 100, p=[0.1, 0, 0.1, 0.3, 0, 0.1, 0, 0.2, 0.2, 0]) e # Here shows the probability distribution of 'e' in a histogram. plt.hist(e) # Any array can be given, including words or any other elements: d = ['Donald', 'Joeseph', 'Kanye', 'Vladimir'] f = rng.choice(d, 100000, p=[0.1, 0.1, 0.3, 0.5]) plt.hist(f) # ## bytes # ![yellow-popsicle-bite-blue-background-98702661.jpg](attachment:yellow-popsicle-bite-blue-background-98702661.jpg) # #### parameters: # - length : int - Number of random bytes # # Will randomly generate a number of bytes. The number of bytes generated will be between 0 and the value entered. The bytes themselves will be random. rng.bytes(5) # Generating random bytes is useful for encryption and salting passwords. # # Permutations # ![download.png](attachment:download.png) # [1] Cambridge Dictionary: https://dictionary.cambridge.org/dictionary/english/permutation # # "Any of the various ways in which a set of things can be ordered." # There are two functions with which one can generate permutations of a given array in numpy: # - Shuffle # - Permutation # Both are very similar in terms of outcome, however the manner in which they generate the outcome is different. # # [2] programmersought.com: https://programmersought.com/article/32541516928/ # # "Differences: # # -Shuffle directly operates on the original array, changing the order of the original array, no return value # # -Permutation does not directly operate on the original array, but returns a new array of scrambled orders, without changing the original array" # Here is a given array: arr = np.arange(10) arr # #### Permutation # - Here we can see that the permutation funtion has reshuffled the elements of the array: arr = np.arange(10) rng.permutation(arr) # - However when we show 'arr' again it remains intact in it's original order. arr # #### Shuffle # - Here we see a similar outcome regarding the reshuffling: rng.shuffle(arr) arr # -However when we check for the state of 'arr' we can see that the array (arr) has been changed, and is no longer what it was originally. The original array value no longer exists to be recalled upon. arr # - The implications of losing the original array value may have certain repercussions depending on the nature of the code and the need to refer back to the original array. # -The Shuffle function tends to perform noticeably faster when applied to very large arrays, and may therefore be the prefered choice when speed is a deciding factor. # [3] programmersought.com: https://programmersought.com/article/4415574540/ # # ![3fea1c0818626a07c2c89bab010713bb.png](attachment:3fea1c0818626a07c2c89bab010713bb.png) # # Distributions # - There are 36 different probability distributions in numpy. # - Each serves to emulate different scenarios of probability. # - Here I will discuss a few examples of the different distributions and how they can be used to simulate real life situtions, and thus give us further insight into the nature of specific scenarios. # ## Types of distribution: # - Certain distributions share features, so we divide them into types. # - Dicrete # - Continuous # # ### Discrete: # - Distributions in which there are a finite number of outcomes. # - A few examples here would be rolling a dice or picking a card. # # ### Continuous: # - Distriutions where there are infinite outcomes. # - Examples here would be recording time and distance in a race. # # [4]: 365 Data Science: Probability: Types of distributions:Binomial distribution: https://www.youtube.com/watch?v=b9a27XN_6tg # ## Other useful terms: # - Empirical Distributions: # "An empirical distribution is one for which each possible event is assigned a probability." # # [5] Empirical Distributions: https://www.unf.edu/~cwinton/html/cop4300/s09/class.notes/DiscreteDist.pdf # # -Bernoulli event: # "A Bernoulli event is one for which the probability the event occurs is p and the probability the event does not occur is 1-p; i.e., the event is has two possible outcomes (usually viewed as success or failure) occurring with probability p and 1-p, respectively." [5] # # Discrete distributions: # - Here we will discuss some of the most commonly used discrete distributions, and how they are used in real life. # # ## Uniform: # ![unnamed.gif](attachment:unnamed.gif) # [8] # Distributions for assigning random values http://resources.esri.com/help/9.3/arcgisengine/java/gp_toolref/process_simulations_sensitivity_analysis_and_error_analysis_modeling/distributions_for_assigning_random_values.htm # - Some events, such as flipping a coin or roling a dice have a set of equally likely outcomes. # - We call these outcomes 'Equiprobable'. # - The distribution of these outomes is thus described as Uniform. # - We saw this distribution earlier in the paper as the default distribution of the simple random data functions. f = rng.uniform(-100,100,1000000) f plt.hist(f) # # Binomial: # ![kiVGG.gif](attachment:kiVGG.gif) # [9] Why is a binomial distribution bell-shaped? https://stats.stackexchange.com/questions/176425/why-is-a-binomial-distribution-bell-shaped # - "The Bernoulli distribution represents the success or failure of a single Bernoulli trial" # - ie: Likelihood of coing flip is even distribution = 0.5/0.5, but the likelihood of rolling a six on a die would be 0.17 success/0.83 failure. # - "The Binomial Distribution represents the number of successes and failures in n number of independent Bernoulli trials for some given value of n." [5] # - It is basically a probability of probabilities, ie: the success rate or the likeliehood of a specific set of outcomes occuring vs other possible outcomes. # - It is useful when deling with uncertainty regarding a long run frequency. # # [6] # 3Blue1Brown: Binomial distributions | Probabilities of probabilities, part 1 https://www.youtube.com/watch?v=8idr1WZ1A7Q # - An example of this would be if a car manufacturer has a 0.13 percent chance of producing a faulty model, the binomial distribution would describe the most likely number of cars that would be faulty if the manufacturer made 10,000 cars. It doesn't guarantee the outcome will be 1300, but it tells you the probability of that outcome. It will also tell you the probability of the number being higher or lower. # - Basically the distibution will run a number of bernoulli trialls and return a success rate for a given outcome. n, p = 10000, .13 g = rng.binomial(n, p, 1000000) g plt.hist(g) # [7] Binomial distribution: https://en.wikipedia.org/wiki/Binomial_distribution # # [8] Binomial Distribution https://mathworld.wolfram.com/BinomialDistribution.html # # Poisson: # ![%D0%9F%D0%BE%D0%B8%D1%81%D0%BE%D0%BD%D0%BE%D0%B21.png](attachment:%D0%9F%D0%BE%D0%B8%D1%81%D0%BE%D0%BD%D0%BE%D0%B21.png) # [9] File:Поисонов1.png https://commons.wikimedia.org/wiki/File:%D0%9F%D0%BE%D0%B8%D1%81%D0%BE%D0%BD%D0%BE%D0%B21.png # - Deals with a number of events occuring in a given timeframe, provided we have an expected outcome. # - Example would be if a bank teller usually gets 4 customers in an hour, what is the distribution of likelihood regarding the number of customers he will get on any given hour? # - It is similar in many ways to the binomial distribution, however it always starts from 0 and has no upper limit to the outcomes. It deals with continuos events rather than discrete events ie: with binomial you have a certain number of attempts, each with a given probability for success, with poisson you essentially have an infinite number of attempts with a given average outcome, with infinitesimal chance for success. # [10} Difference between Poisson and Binomial distributions: https://math.stackexchange.com/questions/1050184/difference-between-poisson-and-binomial-distributions h = rng.poisson(10, 10000000) h plt.hist(h) # - The rate of events occuring is constant, and each event is ineffected by the subsequent event. # - Can be used to determine likelihood of certain events, such as someone scoring x amount of goals in a match based on their average scores over the season. # # Continuous Distributions: # - Here we willl discuss some continuos distributions and their uses in real life. # ## Normal # ![1200px-Normal_Distribution_PDF.svg.png](attachment:1200px-Normal_Distribution_PDF.svg.png) # [11] https://en.wikipedia.org/wiki/Normal_distribution # - Also called Gaussian distribuion. # - Often called the 'Bell Curve' distribution due to it's characteristic shape. # - The normal distribution occurs frequently in nature. # - For example, it could describe the size of mature blue whales and the likelihood of finding one of a particular size. i, j = 150, 50 k = rng.normal(i, j, 1000000) k sns.distplot(k) # ## Standard T: # ![main-qimg-db91d75fe597b7d466a3dc8d98f25371.png](attachment:main-qimg-db91d75fe597b7d466a3dc8d98f25371.png) # [12] https://www.quora.com/In-simple-terms-how-are-normal-z-distribution-and-student-t-distribution-related-How-do-they-differ # - Also known commonly as 'Student's T' distribution. # - Similar in shape and nature to the normal distribution, the Student's T distribution has more instances in the outlier areas of its distribution. # - Used instead of normaal distribution when info is limited/sample size is small. # - It is designed to calculate inferences through small samples with an unkown popuation variance, ie: one can calculate the quality of a larger sample based on a limited sample. # - Like the normal distribution, it has many real life applications, such as calculating . # - "The t test provides a way to test whether the sample mean (that is the mean calculated from the data) is a good estimate of the true mean." # - An example here would be similar to the normal distributin example regarding the average whale size, but in this case it could be based on the past 16 sightings only. Due to the limited data, this is a way of using those 16 sightings to most efficiently represent a much bigger part of the population of whales, given we have a previous mean or projected mean to compare deviation, ie: 10 years ago the average size was 150. # # [13] https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.standard_t.html#numpy.random.Generator.standard_t # # [14] # 365 Data Science: Student's T Distribution: https://www.youtube.com/watch?v=32CuxWdOlow # # # So let's take the above example and apply it. Here we have 15 values, (so our degrees of freedom is that number -1 = 15), We also calculate the mean of the 16 values. l = np.array([150, 139, 157, 153, 135, 160, 146, 149, 148, 151, 149, 143, 158, 150, 147, 154]) m = rng.standard_t(15, size=100000) np.mean(l) t = (np.mean(l)-150)/(l.std(ddof=1)/np.sqrt(len(l))) h = plt.hist(m, bins=100, density=True) np.sum(m<t) / float(len(m)) t # -The t value is the calculated difference between the previousstudy and the new one. This difference is compared against the 'null hypothesis', which is used in statistis as a ground zero, or a control, with which we can measure the likelihood of there being no difference in the results of the two studies. The closer t is to 0 the more likely there isn't a significant difference. # - The t value is generated from a single sample of the entire population. Repeated random samples would garner slightly different results. # - How different you expect the t value to be due to random sampling error (an expected variation in statistics) can be represented as above in a t-distribution. # - p is the probability value of the results deviating from the null hypothesis. # # [15] https://blog.minitab.com/blog/statistics-and-quality-data-analysis/what-are-t-values-and-p-values-in-statistics # # Seeds and generating Pseudorandom Numbers: # - Numbers are not actually generated randomly by computers. There still has to be a process in place that generates these numbers, albeit in a manner that simulates randomness. # - One way of doing this would be to take the numbers after pi. Since these nubers never repeat periodically, you could just pick a point somewhere along that sequence of numbers, and every time you required a random number you could just call out the next digit. To an outside observer this wouold be the same as if you were generating random numbers, however if they were to have access to the sequence from which you were pulling numbers they would be able to predict the outcome each time. That information regarding how the numbers are being generated is called the 'seed'. # - Another example of a basis of a seed generator would be stopping a clock at the moment a program begins and using the digits as the seed. # - Other seed generate a number at the beginning of a program, let's say, when you import numpy, and then base all of their following outcomes on that original seed. # - This number is overwritten upon starting the program so as to garner new results, however if you speify that you would like the seed to remain the same, you can revert back to the exact state you program was in before you generated a list of outcomes and then proceed to generate the exact same outcomes again. # - Basically, the seed is a number used to initialize a psedorandom numnber generator, and knowing this seed gives you functional control over the outcomes. # - The pseudorandom number generator will generate numbers based on the seed using a set probability distribution. # - A good random seed is crucial in the field of cyber-security & encryption. # - If the same random key is shared deliberately, it becomes a 'secret key', allowing two or more systems to generate matching sequences of non-repeating numbers. This can be used to synchronize remote systems such as GPS satelites and recievers. # # # Permuted Congruential Generator(PCG64) vs Mersenne Twister (mt19937) # - In recent months the recomended generator in numpy has changed from mt19937 to PCG64. # - According to numpy's own documentation: " It is statistically high quality, full-featured, and fast on most platforms, but somewhat slow when compiled for 32-bit processes." # - mt19937 apparently fails in some statistical tests, and thus is only recomended to be ued to generate old results. # - There are two other genrators mentioned as well: # - Philox - Slow but high quality. # -SFC64 - Fast and high quality, but lacks jumpability. # # [16] https://numpy.org/doc/stable/reference/random/performance.html
numpy.random.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # --- # ![](images/spam-lord.png) # --- # Harvesting emails and phone numbers # --- # # Here's your chance to be a SpamLord! Yes, you too can build regexes to help spread evil throughout the galaxy! # # More specifically, your goal in this assignment is to write regular expressions that extract phone numbers and regular expressions that extract email addresses. # # To start with a trivial example, given # # <EMAIL> # # your job is to return # # <EMAIL> # # # ![](https://imgs.xkcd.com/comics/hacking.png) # # But you also need to deal with more complex examples created by people trying to shield their addresses, such as the following types of examples that I'm sure you've all seen: # # bspiering(at)usfca.edu # bspiering at usfca dot edu # # You should even handle examples that look like the following: # # <script type="text/javascript">obfuscate('usfca.edu','bspiering')</script> # # For all of the above you should return the corresponding email address # # <EMAIL> # # as appropriate. # Similarly, for phone numbers, you need to handle examples like the following: # # TEL +1-415-805-1888 # Phone: (415) 805-1888 # Tel (+1): 415-805-1888 # <a href="contact.html">TEL</a> +1&thinsp;415&thinsp;805&thinsp;1888 # # all of which should return the following canonical form: # # 415-805-1888 # # (you can assume all phone numbers we give you will be inside North America). # In order to make it easier for you to do this, we will be giving you some data to test your code on, what is technically called a *development test set*. This is a document with some emails and phone numbers, together with the correct answers, so that you can make sure your code extracts all and only the right information. However, because you want to be sure your code *generalizes* well, you should be creative in looking at the web and thinking of different types of ways of encoding emails and phone numbers, and not just rely on the methods we've listed here. # # **You won't have to deal with:** really difficult examples like images of any kind, or examples that require parsing names into first/last like: # # "first name"@<EMAIL> # # or difficult examples like: # # To send me email, try the simplest address that makes sense. # ---- # Where can I find the starter code? # ---- # # You will find starter code in the github repository. # By default, if you execute: run spam_lord.py data/dev/ data/devGOLD whos # --- # # You can also run the code at the command line: # # + language="bash" # python spam_lord.py data/dev/ data/devGOLD # - # ---- # It will run your code on the files contained in data/dev/ and compare the results of a simple regular expression against the correct results. The results will look something like this: # # True Positives (4): # set([('mike', 'e', '<EMAIL>'), # ('nass', 'e', '<EMAIL>'), # ('shoham', 'e', '<EMAIL>'), # ('thm', 'e', '<EMAIL>')]) # False Positives (1): # set([('psyoung', 'e', '<EMAIL>')]) # False Negatives (113): # set([('ashishg', 'e', '<EMAIL>'), # ('ashishg', 'e', '<EMAIL>'), # ('ashishg', 'p', '650-723-1614'), # ... # # The true positive section displays e-mails and phone numbers which the starter code correctly matches. # # The false positive section displays e-mails which the starter code regular expressions match but which are not correct # # The false negative section displays e-mails and phone numbers which the starter code did not match, but which do exist in the html files. # # Your goal, then, is to reduce the number of false positives and negatives to zero. # ---- # Check for Understanding # ----- # <br> # <details><summary> # Why do you not care about true negatives? # </summary> # There are too many TN. It is all the text that is not a phone number or email! # </details> # Where should I write my Python code? # ---- # # The function # ```python # def process_file(name, f): # ``` # has been flagged for you with the universal "TODO" marker. This function takes in a file object (or any iterable of strings) and returns a list of tuples representing e-mails or phone numbers found in that file. Specifically the tuple has the format: # # (filename, type, value) # # where type is either 'e', for e-mail, or 'p' for phone number, and value is just the actual e-mail or phone number. # What format should the final phone numbers and e-mail have? # --- # # The canonical forms expected are: # # <EMAIL> # 415-555-1234 # # The case of the e-mails you find should not matter because the starter code will lowercase your matched e-mails before comparing them against the gold set # ---- # Hints # ----- # # - Look at the raw data in `./data/dev/`. They are saved webpages. # - Look at the correct answers in `./data/devGOLD` # - Be careful about online Python regex checkers. They tend to use Python 2 which is different. # - Start with phone numbers then tackle emails. # - It is possible to get to 💯 # --- # When my regex works on first try # ---- # # ![](http://tclhost.com/vngeKjr.gif) # # [Source](http://thecodinglove.com/post/128186083300/when-my-regex-works-on-first-try) # <br> # <br>
02_regex/lab_spamlord/exercises_spamlord.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="auzlUi26MZ8M" # # Dataset download # In this section the dataset is downloaded from *Kaggle*, unzipped and well formatted. # + id="a0zv87IvWTTu" import pandas as pd import numpy as np import matplotlib.pyplot as plt import json import os from tqdm import tqdm, tqdm_notebook import random import tensorflow as tf from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import * from tensorflow.keras.optimizers import * from tensorflow.keras.applications import * from tensorflow.keras.callbacks import * from tensorflow.keras.initializers import * from tensorflow.keras.preprocessing.image import ImageDataGenerator from numpy.random import seed seed(42) tf.random.set_seed(42) # + colab={"base_uri": "https://localhost:8080/", "height": 73, "resources": {"http://localhost:8080/nbextensions/google.colab/files.js": {"data": "<KEY>", "headers": [["content-type", "application/javascript"]], "ok": true, "status": 200, "status_text": ""}}} executionInfo={"elapsed": 17032, "status": "ok", "timestamp": 1639550255538, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}, "user_tz": -60} id="1tlmQfg92Cdr" outputId="05f56191-ccc7-4f23-94f5-0e10207f7dcd" # ! pip install -q kaggle from google.colab import files _ = files.upload() # ! mkdir -p ~/.kaggle # ! cp kaggle.json ~/.kaggle/ # ! chmod 600 ~/.kaggle/kaggle.json # + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 84647, "status": "ok", "timestamp": 1639550342457, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}, "user_tz": -60} id="eWb-0qkK1vnR" outputId="95959580-ab91-4773-d8f3-939a6bfe280d" # ! kaggle datasets download -d ikarus777/best-artworks-of-all-time # ! unzip best-artworks-of-all-time.zip # + [markdown] id="QZ_qRXfZWdsY" # #Data preprocessing # + colab={"base_uri": "https://localhost:8080/", "height": 390} executionInfo={"elapsed": 249, "status": "ok", "timestamp": 1639550418338, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}, "user_tz": -60} id="IveSKkb5Nj7m" outputId="b401791c-efe7-4fcf-d4eb-59282839061e" artists = pd.read_csv('artists.csv') # Sort artists by number of paintings artists = artists.sort_values(by=['paintings'], ascending=False) # Create a dataframe with artists having more than 200 paintings artists_top = artists[artists['paintings'] >= 200].reset_index() artists_top = artists_top[['name', 'paintings']] artists_top['class_weight'] = artists_top.paintings.sum() / (artists_top.shape[0] * artists_top.paintings) #artists_top = artists_top.loc[artists_top['paintings'] >200] artists_top # + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 234, "status": "ok", "timestamp": 1639550420687, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}, "user_tz": -60} id="dsc16QepPiK-" outputId="380d7046-f103-4e33-8be3-3335e897b336" # Set class weights - assign higher weights to underrepresented classes class_weights = artists_top['class_weight'].to_dict() class_weights # + [markdown] id="mpSrOAB-NDst" # Next step is to solve a problem: the downloaded dataset present two directory containing the same paintings but they have different name. What we do in the next cells is to create a single directory called 'Albrecht_Durer' containing one copy of each painting, and then we delete all unuseful directories. # + id="neb7zCZFWsfj" updated_name = "Albrecht_Dürer".replace("_", " ") artists_top.iloc[4, 0] = updated_name images_dir = 'images/images' artists_dirs = os.listdir(images_dir) artists_top_name = artists_top['name'].str.replace(' ', '_').values # + id="tq-1RDnjMn9B" # ! mv '/content/images/images/Albrecht_Du╠Иrer' /content/images/images/Albrecht_Dürer # + id="Kc990ZOILu8b" # ! rm -R '/content/images/images/Albrecht_DuтХа├кrer' # ! rm -R '/content/resized' # + [markdown] id="yvMzxkQCQg_n" # #Data fetch # + id="Nx-EWVOWQimm" import pathlib import os IMAGE_DIR = '/content/images/' TRAIN_DIR = pathlib.Path(os.path.join(IMAGE_DIR, 'train')) TEST_DIR = pathlib.Path(os.path.join(IMAGE_DIR, 'test')) IMAGE_HEIGHT = 256 IMAGE_WIDTH = 256 BATCH_SIZE = 128 RANDOM_SEED = 42 VALIDATION_SPLIT = 0.10 # + id="ajmGZkuzzEBZ" import os import numpy as np import shutil rootdir= '/content/images/images' #path of the original folder classes = os.listdir(rootdir) for i, c in enumerate(classes, start=1): if c not in artists_top_name.tolist(): shutil.rmtree(rootdir + '/' + c) continue if not os.path.exists(rootdir + '/train/' + c): os.makedirs(rootdir + '/train/' + c) if not os.path.exists(rootdir + '/test/' + c): os.makedirs(rootdir + '/test/' + c) source = os.path.join(rootdir, c) allFileNames = os.listdir(source) np.random.shuffle(allFileNames) test_ratio = 0.10 train_FileNames, test_FileNames = np.split(np.array(allFileNames), [int(len(allFileNames)* (1 - test_ratio))]) train_FileNames = [source+'/'+ name for name in train_FileNames.tolist()] test_FileNames = [source+'/' + name for name in test_FileNames.tolist()] for name in train_FileNames: shutil.copy(name, rootdir +'/train/' + c) for name in test_FileNames: shutil.copy(name, rootdir +'/test/' + c) # + id="ok4kSh_j0MP2" # ! mv /content/images/images/train /content/images # ! mv /content/images/images/test /content/images # ! rm -r /content/images/images # + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 3262, "status": "ok", "timestamp": 1639550452886, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}, "user_tz": -60} id="tobnLNe30AxK" outputId="c5d82ca0-2636-4521-d4ea-e8721ff375c4" import tensorflow as tf training_images = tf.keras.preprocessing.image_dataset_from_directory( TRAIN_DIR, labels='inferred', label_mode='categorical', class_names=None, color_mode='rgb', batch_size=BATCH_SIZE, image_size=(IMAGE_HEIGHT, IMAGE_WIDTH), shuffle=True, seed=RANDOM_SEED, validation_split=VALIDATION_SPLIT, subset='training', interpolation='bilinear', follow_links=False ) val_images = tf.keras.preprocessing.image_dataset_from_directory( TRAIN_DIR, labels='inferred', label_mode='categorical', class_names=None, color_mode='rgb', batch_size=BATCH_SIZE, image_size=(IMAGE_HEIGHT, IMAGE_WIDTH), shuffle=True, seed=RANDOM_SEED, validation_split=VALIDATION_SPLIT, subset='validation', interpolation='bilinear', follow_links=False ) test_images = tf.keras.preprocessing.image_dataset_from_directory( TEST_DIR, labels='inferred', label_mode='categorical', class_names=None, color_mode='rgb', batch_size=BATCH_SIZE, image_size=(IMAGE_HEIGHT, IMAGE_WIDTH), shuffle=True, seed=RANDOM_SEED, interpolation='bilinear', follow_links=False ) # + id="Ndh6-EWL1wHK" NUM_CLASSES = len(training_images.class_names) # + [markdown] id="HtVmR4LCRDQP" # #Build model # + [markdown] id="l0b6BjeGE9A_" # Needed imports: # + id="TPan9Qq6RE8Q" import tensorflow as tf from tensorflow import keras as ks from tensorflow.keras import layers from tensorflow.keras.applications import VGG16 from tensorflow.keras import regularizers import pathlib import matplotlib.pyplot as plt import numpy as np # + [markdown] id="Shm2mhuaE8yZ" # Callback and data augmentation objects: # + id="w24ha15v0wnh" callbacks_list = [ ks.callbacks.EarlyStopping( monitor='val_accuracy', patience=5, ), ks.callbacks.ModelCheckpoint( filepath='checkpoint_vgg16.keras', monitor='val_loss', save_best_only=True, ) ] data_augmentation = ks.Sequential( [ layers.RandomFlip('horizontal'), layers.RandomRotation(0.1), layers.RandomZoom(0.2), layers.RandomHeight(0.1), layers.RandomWidth(0.1) ] ) # + [markdown] id="LZz11rX1FKNb" # ##### VGG16 class: # + id="HlmWAGHrFHQ-" class Vgg16: LOSS = 'categorical_crossentropy' def __init__(self, train=None, test=None, val=None, classes=11, epochs=10, callbacks_list=None, data_augmentation=None, class_weights=None): # set datasets self.training_set = train self.test_set = test self.val_set = val # model self.model = None # utils self.history = None self.classes = classes self.epochs = epochs self.callbacks_list = callbacks_list self.data_augmentation= data_augmentation self.vgg16dict = {} self.class_weights=class_weights """ ARCHITECTURE TO TEST """ def classic_vgg16(self): inputs = self.input() x = self.base_vgg16()(inputs) x = layers.Flatten(name='my_flatten')(x) x = layers.Dense(256, activation='relu', name='my_dense1')(x) x = layers.Dense(256, activation='relu', name='my_dense2')(x) outputs = layers.Dense(self.classes, activation='softmax', name='predictions')(x) self.model = ks.Model(inputs=inputs, outputs=outputs) def classic_vgg16_dropout(self): inputs = self.input() x = self.base_vgg16()(inputs) x = layers.Flatten(name='my_flatten')(x) x = layers.Dense(256, activation='relu', name='my_dense1')(x) x = layers.Dense(256, activation='relu', name='my_dense2')(x) x = layers.Dropout(0.5)(x) outputs = layers.Dense(self.classes, activation='softmax', name='predictions')(x) self.model = ks.Model(inputs=inputs, outputs=outputs) def vgg16_finetuned(self, num_of_blocks=1): inputs = self.input() x = self.fine_tuning(num_of_blocks=num_of_blocks)(inputs) x = layers.Flatten(name='my_flatten')(x) x = layers.Dense(256, activation='relu', name='my_dense1')(x) x = layers.Dense(256, activation='relu', name='my_dense2')(x) outputs = layers.Dense(self.classes, activation='softmax', name='predictions')(x) self.model = ks.Model(inputs=inputs, outputs=outputs) def vgg16_finetuned_dropout(self, num_of_blocks=1): inputs = self.input() x = self.fine_tuning(num_of_blocks=num_of_blocks)(inputs) x = layers.Flatten(name='my_flatten')(x) x = layers.Dense(256, activation='relu', name='my_dense1')(x) x = layers.Dense(256, activation='relu', name='my_dense2')(x) x = layers.Dropout(0.5)(x) outputs = layers.Dense(self.classes, activation='softmax', name='predictions')(x) self.model = ks.Model(inputs=inputs, outputs=outputs) def vgg16_finetuned_dropout_reg(self, num_of_blocks=1): inputs = self.input() x = self.fine_tuning(num_of_blocks=num_of_blocks)(inputs) x = layers.Flatten(name='my_flatten')(x) x = layers.Dense(256, activation='relu', name='my_dense1', kernel_regularizer=regularizers.l1_l2(0.002, 0.002))(x) x = layers.Dense(256, activation='relu', name='my_dense2', kernel_regularizer=regularizers.l1_l2(0.002, 0.002))(x) x = layers.Dropout(0.5)(x) outputs = layers.Dense(self.classes, activation='softmax', name='predictions')(x) self.model = ks.Model(inputs=inputs, outputs=outputs) """ NETWORK PIECE BY PIECE STRUCTURE BLOCK """ def input(self): inputs = ks.Input(shape=(256, 256, 3)) x = ks.applications.vgg16.preprocess_input(inputs) x = self.data_augmentation(x) x = layers.Rescaling(1. / 255)(x) return x def base_vgg16(self): res = VGG16( weights='imagenet', include_top=False, input_shape=((256, 256, 3)) ) res.trainable = False return res def fine_tuning(self, num_of_blocks=1): if num_of_blocks < 1: num_of_blocks = 1 res = self.base_vgg16() res.trainable = True set_trainable = False if num_of_blocks == 1: block_name = 'block5_conv3' else: block_name = 'block5_conv2' for layer in res.layers: if layer.name == block_name: set_trainable = True if set_trainable: layer.trainable = True else: layer.trainable = False return res """ UTILITIES """ def plot_model(self, model_name): ks.utils.plot_model(self.model, model_name, show_shapes=True) def plot_accuracy(self): acc = self.history.history['accuracy'] val_acc = self.history.history['val_accuracy'] plt.plot(range(1, len(acc) + 1), acc, 'r', label='Training Accuracy') plt.plot(range(1, len(acc) + 1), val_acc, 'g', label='Validation Accuracy') plt.title('Training and Validation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.plot() def plot_loss(self): loss = self.history.history['loss'] val_loss = self.history.history['val_loss'] plt.plot(range(1, len(loss) + 1), loss, 'r', label='Training Loss') plt.plot(range(1, len(loss) + 1), val_loss, 'g', label='Validation Loss') plt.title('Training and Validation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.plot() def summary(self): self.model.summary() """ COMPILE AND FIT """ def compile_and_fit(self, optimizer, activation=None, ga=False): self.model.compile( optimizer=optimizer, loss=self.LOSS, metrics=['accuracy'] ) if self.callbacks_list is None: self.history = self.model.fit( self.training_set, epochs=self.epochs, validation_data=self.val_set ) else: self.history = self.model.fit( self.training_set, epochs=self.epochs, validation_data=self.val_set, callbacks=self.callbacks_list, class_weight=self.class_weights ) def evaluate(self): test_loss, test_acc = self.model.evaluate(self.test_set) print(f"Test accuracy: {test_acc:.3f}") # + [markdown] id="6TuFRgXgFW2z" # #### Feature extraction: # + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 2767, "status": "ok", "timestamp": 1639499453136, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10977236443775929893"}, "user_tz": -60} id="EgF6QlX9FV2c" outputId="cb665b82-7254-4852-9779-9e7beb5e2748" vgg16 = Vgg16(train=training_images, val=val_images, test=test_images, classes=NUM_CLASSES, callbacks_list=callbacks_list, data_augmentation=data_augmentation, class_weights=class_weights, epochs=25) vgg16.classic_vgg16() vgg16.summary() # + [markdown] id="KTHeZI1yIyTh" # Show graph: # + id="ClVGCh31IyB9" vgg16.plot_model('vgg_feature_extraction.png') # + [markdown] id="a0TiA7mLIcp1" # Test using rmsprop as optimizer: # + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 858978, "status": "ok", "timestamp": 1639500314262, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10977236443775929893"}, "user_tz": -60} id="C2urk71iH9kf" outputId="adde3f28-b4c2-4b0c-8e73-bad5b5fa7e4c" vgg16.compile_and_fit(optimizer='rmsprop') # + [markdown] id="8lGaIiu4JAu4" # Plot the results: # + colab={"base_uri": "https://localhost:8080/", "height": 295} executionInfo={"elapsed": 776, "status": "ok", "timestamp": 1639500316981, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10977236443775929893"}, "user_tz": -60} id="9QmZV33eIwb1" outputId="7bd66bcf-3197-46d5-cccb-720be85dbdbb" vgg16.plot_accuracy() # + colab={"base_uri": "https://localhost:8080/", "height": 295} executionInfo={"elapsed": 6, "status": "ok", "timestamp": 1639500316982, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10977236443775929893"}, "user_tz": -60} id="D_v2iKdTI9hm" outputId="9265a12e-f41a-4ad8-c7f8-62b5d62c8616" vgg16.plot_loss() # + [markdown] id="UqBxE2d3JCtH" # Test on testset: # + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 23637, "status": "ok", "timestamp": 1639500340615, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10977236443775929893"}, "user_tz": -60} id="O1NAFfQZJOvj" outputId="0a494a74-3c19-4b67-eba9-7fce720262c8" vgg16.evaluate() # + [markdown] id="c-3AkF8kvol9" # ### Adding dropout # + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 2025, "status": "ok", "timestamp": 1639510406394, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}, "user_tz": -60} id="h3s7D5zAvqi4" outputId="9edfd4fc-cb5b-4e2e-da83-adaf582d442a" vgg16 = Vgg16(train=training_images, val=val_images, test=test_images, classes=NUM_CLASSES, callbacks_list=callbacks_list, data_augmentation=data_augmentation, class_weights=class_weights, epochs=60) vgg16.classic_vgg16_dropout() vgg16.summary() # + colab={"background_save": true, "base_uri": "https://localhost:8080/"} id="TEcmhffvvxGG" outputId="6a3bf529-463c-44d9-83fc-3c148dadb2bd" vgg16.compile_and_fit(optimizer='rmsprop') # + colab={"background_save": true} id="9eWphiyMv1OR" outputId="7bc13cb0-0812-488f-99d5-d8fa79143eba" vgg16.plot_accuracy() # + colab={"background_save": true} id="9BRpY9pIv3e2" outputId="05d5d9ea-4f2d-4434-8fd2-e4f65cfb2254" vgg16.plot_loss() # + id="3zHt7Ljyv4Nv" vgg16.evaluate() # + [markdown] id="TJvlhY-z2zVi" # ### Finetune one block without dropout # + colab={"base_uri": "https://localhost:8080/"} id="OZeBgakl25Gd" executionInfo={"status": "ok", "timestamp": 1639551656682, "user_tz": -60, "elapsed": 832, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="790da32d-8ede-44fb-d7a6-43d0d514e934" vgg16 = Vgg16(train=training_images, val=val_images, test=test_images, classes=NUM_CLASSES, callbacks_list=callbacks_list, data_augmentation=data_augmentation, class_weights=class_weights, epochs=60) vgg16.vgg16_finetuned(num_of_blocks=1) vgg16.summary() # + colab={"base_uri": "https://localhost:8080/"} id="oycgq_VS3I9-" executionInfo={"status": "ok", "timestamp": 1639552683528, "user_tz": -60, "elapsed": 1018408, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="9ef9a00e-beb4-45f8-d76d-642e6386cb1f" vgg16.compile_and_fit(optimizer='rmsprop') # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="44N6cNXv6lyy" executionInfo={"status": "ok", "timestamp": 1639552737275, "user_tz": -60, "elapsed": 424, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="a9722f3b-cb90-4176-cf97-33c46b5ff4a2" vgg16.plot_accuracy() # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="ua2YxW2W6o6T" executionInfo={"status": "ok", "timestamp": 1639552742271, "user_tz": -60, "elapsed": 676, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="c29aced5-d10c-4976-de7b-f8eca2c51e0b" vgg16.plot_loss() # + colab={"base_uri": "https://localhost:8080/"} id="ZREkKpaC6rzD" executionInfo={"status": "ok", "timestamp": 1639552786904, "user_tz": -60, "elapsed": 41465, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="ae789c99-fe88-46e2-c9a6-ad07a07fc8a1" vgg16.evaluate() # + [markdown] id="cALH3k6S_1rt" # Fine tune 1 layer + dropout # + colab={"base_uri": "https://localhost:8080/"} id="LJB3VkFC_36S" executionInfo={"status": "ok", "timestamp": 1639553788791, "user_tz": -60, "elapsed": 1654, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="b5ca4c79-87b5-4c23-ec1a-9186e6954069" vgg16 = Vgg16(train=training_images, val=val_images, test=test_images, classes=NUM_CLASSES, callbacks_list=callbacks_list, data_augmentation=data_augmentation, class_weights=class_weights, epochs=60) vgg16.vgg16_finetuned_dropout(num_of_blocks=1) vgg16.summary() # + colab={"base_uri": "https://localhost:8080/"} id="JqlmICNKAH-I" executionInfo={"status": "ok", "timestamp": 1639555660569, "user_tz": -60, "elapsed": 1850029, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="92f36875-83f5-4d95-ec85-b5d1651b4d39" vgg16.compile_and_fit(optimizer=ks.optimizers.Adam(learning_rate=0.0001)) # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="5yfBU5sqIeF2" executionInfo={"status": "ok", "timestamp": 1639555670276, "user_tz": -60, "elapsed": 1388, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="9c84a124-dbb7-46bc-919e-a4e4e2f40a10" vgg16.plot_accuracy() # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="RwgmFrWtIjeh" executionInfo={"status": "ok", "timestamp": 1639555685020, "user_tz": -60, "elapsed": 562, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="3a6cb0ad-f1c3-46fb-a441-db0bbe95e31e" vgg16.plot_loss() # + colab={"base_uri": "https://localhost:8080/"} id="CoV5-XGsInU-" executionInfo={"status": "ok", "timestamp": 1639555710029, "user_tz": -60, "elapsed": 10628, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="a9bdfe6b-8bcf-416e-d24f-ad0dfaa7df15" vgg16.evaluate() # + [markdown] id="-KxjEqGhJ9N5" # #### Two layers fined tuned # + colab={"base_uri": "https://localhost:8080/"} id="GCgjeUpJKKtM" executionInfo={"status": "ok", "timestamp": 1639556152376, "user_tz": -60, "elapsed": 1035, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="6d40fdb6-46c5-4c8b-b3da-66b76ba59642" vgg16 = Vgg16(train=training_images, val=val_images, test=test_images, classes=NUM_CLASSES, callbacks_list=callbacks_list, data_augmentation=data_augmentation, class_weights=class_weights, epochs=60) vgg16.vgg16_finetuned_dropout(num_of_blocks=2) vgg16.summary() # + colab={"base_uri": "https://localhost:8080/"} id="SXunD1vwKQhe" executionInfo={"status": "ok", "timestamp": 1639557720987, "user_tz": -60, "elapsed": 1562545, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="2d68deef-554d-4932-be6a-d79150bd5821" vgg16.compile_and_fit(optimizer=ks.optimizers.Adam(learning_rate=0.0001)) # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="ba9dXUPHQO4q" executionInfo={"status": "ok", "timestamp": 1639557747656, "user_tz": -60, "elapsed": 575, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="329e9894-05da-4f9e-b867-db2773fec30d" vgg16.plot_accuracy() # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="LxbSkdwYQRGl" executionInfo={"status": "ok", "timestamp": 1639557748103, "user_tz": -60, "elapsed": 450, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="29a6fe53-b39b-405d-9795-911d16ec3395" vgg16.plot_loss() # + colab={"base_uri": "https://localhost:8080/"} id="ra2lkp3pQSzP" executionInfo={"status": "ok", "timestamp": 1639557758651, "user_tz": -60, "elapsed": 10551, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="f1f37ef2-3374-4704-f175-6938b681ec45" vgg16.evaluate() # + [markdown] id="4fk83teoQUUB" # ### ADDING L1 L2 reg to previous network # + colab={"base_uri": "https://localhost:8080/"} id="1CvRB2YcQctS" executionInfo={"status": "ok", "timestamp": 1639558179889, "user_tz": -60, "elapsed": 1174, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="3a75234f-f6bd-41d4-c8b2-d62e7bfe81e8" vgg16 = Vgg16(train=training_images, val=val_images, test=test_images, classes=NUM_CLASSES, callbacks_list=callbacks_list, data_augmentation=data_augmentation, class_weights=class_weights, epochs=60) vgg16.vgg16_finetuned_dropout_reg(num_of_blocks=2) vgg16.summary() # + colab={"base_uri": "https://localhost:8080/"} id="AdGk7pvlQggV" executionInfo={"status": "ok", "timestamp": 1639559830261, "user_tz": -60, "elapsed": 1628781, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="717bd652-1218-4b47-bbaf-68a69ace04c5" vgg16.compile_and_fit(optimizer=ks.optimizers.Adam(learning_rate=0.0001)) # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="BGuYzvXsYc9j" executionInfo={"status": "ok", "timestamp": 1639559917007, "user_tz": -60, "elapsed": 1092, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="5ef0fbc9-3c61-4500-972f-e5ce0d701a7a" vgg16.plot_accuracy() # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="-6hnNL9hYvdd" executionInfo={"status": "ok", "timestamp": 1639559939457, "user_tz": -60, "elapsed": 1426, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="4a3e59eb-3815-4bb1-e4c3-9d571a0a96d9" vgg16.plot_loss() # + colab={"base_uri": "https://localhost:8080/"} id="kpUY1I0sYxuO" executionInfo={"status": "ok", "timestamp": 1639559946713, "user_tz": -60, "elapsed": 7259, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "11023693490829624613"}} outputId="a0e1cf64-0986-4b6a-ff95-743607e795a6" vgg16.evaluate() # + [markdown] id="x73lf8jNS8KA" # ## Fine tune 1 + drop + reg # + colab={"base_uri": "https://localhost:8080/"} id="eUUpRUWPTAFY" executionInfo={"status": "ok", "timestamp": 1639558471037, "user_tz": -60, "elapsed": 1848, "user": {"displayName": "GenisLusor", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhPcK7HE12RWvgK-l10F38IIrCT890H8XJDAe6L=s64", "userId": "10975385014877711908"}} outputId="a83ac688-9b62-487c-bb2f-92b5f4118d61" vgg16 = Vgg16(train=training_images, val=val_images, test=test_images, classes=NUM_CLASSES, callbacks_list=callbacks_list, data_augmentation=data_augmentation, class_weights=class_weights, epochs=60) vgg16.vgg16_finetuned_dropout_reg(num_of_blocks=1) vgg16.summary() # + colab={"base_uri": "https://localhost:8080/"} id="BDGHTCMzTIRF" executionInfo={"status": "ok", "timestamp": 1639559951688, "user_tz": -60, "elapsed": 1467138, "user": {"displayName": "GenisLusor", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhPcK7HE12RWvgK-l10F38IIrCT890H8XJDAe6L=s64", "userId": "10975385014877711908"}} outputId="c31bda19-54b6-4cce-ad5b-1a5c175097a6" vgg16.compile_and_fit(optimizer=ks.optimizers.Adam(learning_rate=0.0001)) # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="NKUhYX6fa0j5" executionInfo={"status": "ok", "timestamp": 1639560474582, "user_tz": -60, "elapsed": 1256, "user": {"displayName": "GenisLusor", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhPcK7HE12RWvgK-l10F38IIrCT890H8XJDAe6L=s64", "userId": "10975385014877711908"}} outputId="4a62a01f-2730-47b0-b66b-148751a5d0e0" vgg16.plot_accuracy() # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="L3nmCfXXa21g" executionInfo={"status": "ok", "timestamp": 1639560483557, "user_tz": -60, "elapsed": 1209, "user": {"displayName": "GenisLusor", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhPcK7HE12RWvgK-l10F38IIrCT890H8XJDAe6L=s64", "userId": "10975385014877711908"}} outputId="b79c752a-068e-451f-f028-2aad9d0f133f" vgg16.plot_loss() # + colab={"base_uri": "https://localhost:8080/"} id="Cbpc6F5ia5KB" executionInfo={"status": "ok", "timestamp": 1639560515887, "user_tz": -60, "elapsed": 26588, "user": {"displayName": "GenisLusor", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhPcK7HE12RWvgK-l10F38IIrCT890H8XJDAe6L=s64", "userId": "10975385014877711908"}} outputId="8950d11f-7ae9-4274-81e2-97494beaa63b" vgg16.evaluate()
2-vgg16.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + # ### %matplotlib inline import matplotlib.pyplot as plt import cv2 import os #cscpath = '/data/haarcascade_profileface.xml' cscpath = '/data/haarcascade_frontalface_default.xml' files = os.listdir("/data/images") print(files) filepath = '/data/images/' + files[5] #filepath = '/data/images/pic.jpg' print(filepath) faceCascade = cv2.CascadeClassifier(cscpath) image = cv2.imread(filepath) image = cv2.cvtColor(image, cv2.cv.CV_BGR2RGB) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=4, flags = cv2.cv.CV_HAAR_SCALE_IMAGE ) #print(faces) for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) plt.imshow(image) #print(image.shape) #plt.imshow(image) #plt.imshow(gray)
notebook/FaceDetection.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.9.7 ('base') # language: python # name: python3 # --- # # Getting Started # # Bambi requires a working Python interpreter (3.7+). We recommend installing Python and key numerical libraries using the [Anaconda Distribution](https://www.anaconda.com/products/individual), which has one-click installers available on all major platforms. # # Assuming a standard Python environment is installed on your machine (including pip), Bambi itself can be installed in one line using pip: # # pip install bambi # # Alternatively, if you want the bleeding edge version of the package, you can install from GitHub: # # pip install git+https://github.com/bambinos/bambi.git # ## Quickstart # # Suppose we have data for a typical within-subjects psychology experiment with 2 experimental conditions. Stimuli are nested within condition, and subjects are crossed with condition. We want to fit a model predicting reaction time (RT) from the common effect of condition, group specific intercepts for subjects, group specific condition slopes for students, and group specific intercepts for stimuli. Using Bambi we can fit this model and summarize its results as follows: # # ```python # import bambi as bmb # # # Assume we already have our data loaded as a pandas DataFrame # model = bmb.Model("rt ~ condition + (condition|subject) + (1|stimulus)", data) # results = model.fit(draws=5000, chains=2) # az.plot_trace(results) # az.summary(results) # ``` # ## User Guide # # ### Setup import arviz as az import bambi as bmb import numpy as np import pandas as pd az.style.use("arviz-darkgrid") # ### Creating a model # # Creating a new model in Bambi is simple: # + # Read in a tab-delimited file containing our data data = pd.read_table("data/my_data.txt", sep="\t") # Initialize the model model = bmb.Model("y ~ x + z", data) # Inspect model object model # - # Typically, we will initialize a Bambi ``Model`` by passing it a model formula and a pandas ``DataFrame``. Other arguments such as family, priors, and link are available. By default, it uses ``family="gaussian"`` which implies a linear regression with normal error. We get back a model that we can immediately fit by calling ``model.fit()``. # ### Data format # # As with most mixed effect modeling packages, Bambi expects data in "long" format--meaning that each row should reflects a single observation at the most fine-grained level of analysis. For example, given a model where students are nested into classrooms and classrooms are nested into schools, we would want data with the following kind of structure: # # <center> # # |student| gender | gpa | class | school # |:-----:|:------:|:------:|:------:| :------:| # 1 |F |3.4 | 1 |1 | # 2 |F |3.7 | 1 |1 | # 3 |M |2.2 | 1 |1 | # 4 |F |3.9 | 2 |1 | # 5 |M |3.6 | 2 |1 | # 6 |M |3.5 | 2 |1 | # 7 |F |2.8 | 3 |2 | # 8 |M |3.9 | 3 |2 | # 9 |F |4.0 | 3 |2 | # # </center> # ## Formula-based specification # # Models are specified in Bambi using a formula-based syntax similar to what one might find in R packages like lme4 or brms using the Python [formulae](https://github.com/bambinos/formulae) library. A couple of examples illustrate the breadth of models that can be easily specified in Bambi: data = pd.read_csv("data/rrr_long.csv") data.head(10) # Number of rows with missing values data.isna().any(axis=1).sum() # We pass ``dropna=True`` to tell Bambi to drop rows containing missing values. The number of rows dropped is different from the number of rows with missing values because Bambi only considers columns involved in the model. # Common (or fixed) effects only bmb.Model("value ~ condition + age + gender", data, dropna=True) # Common effects and group specific (or random) intercepts for subject bmb.Model("value ~ condition + age + gender + (1|uid)", data, dropna=True) # Multiple, complex group specific effects with both # group specific slopes and group specific intercepts bmb.Model("value ~ condition + age + gender + (1|uid) + (condition|study) + (condition|stimulus)", data, dropna=True) # Each of the above examples specifies a full model that can be fitted using PyMC3 by doing # # ```python # results = model.fit() # ``` # ### Coding of categorical variables # # When a categorical common effect with N levels is added to a model, by default, it is coded by N-1 dummy variables (i.e., reduced-rank coding). For example, suppose we write ``"y ~ condition + age + gender"``, where condition is a categorical variable with 4 levels, and age and gender are continuous variables. Then our model would contain an intercept term (added to the model by default, as in R), three dummy-coded variables (each contrasting the first level of ``condition`` with one of the subsequent levels), and continuous predictors for age and gender. Suppose, however, that we would rather use full-rank coding of conditions. If we explicitly remove the intercept --as in ``"y ~ 0 + condition + age + gender"``-- then we get the desired effect. Now, the intercept is no longer included, and condition will be coded using 4 dummy indicators, each one coding for the presence or absence of the respective condition without reference to the other conditions. # # Group specific effects are handled in a comparable way. When adding group specific intercepts, coding is always full-rank (e.g., when adding group specific intercepts for 100 schools, one gets 100 dummy-coded indicators coding each school separately, and not 99 indicators contrasting each school with the very first one). For group specific slopes, coding proceeds the same way as for common effects. The group specific effects specification ``"(condition|subject)"`` would add an intercept for each subject, plus N-1 condition slopes (each coded with respect to the first, omitted, level as the referent). If we instead specify ``"(0+condition|subject)"``, we get N condition slopes and no intercepts. # ### Fitting the model # # Once a model is fully specified, we need to run the PyMC3 sampler to generate parameter estimates. If we're using the one-line ``fit()`` interface, sampling will begin right away: model = bmb.Model("value ~ condition + age + gender + (1|uid)", data, dropna=True) results = model.fit() # The above code obtains 1,000 draws (the default value) and return them as an ``InferenceData`` instance (for more details, see the [ArviZ documentation](https://arviz-devs.github.io/arviz/schema/schema.html)). In this case, the `fit()` method accepts optional keyword arguments to pass onto PyMC3's ``sample()`` method, so any methods accepted by ``sample()`` can be specified here. We can also explicitly set the number of draws via the ``draws`` argument. For example, if we call ``fit(draws=2000, chains=2)``, the PyMC3 sampler will sample two chains in parallel, drawing 2,000 draws for each one. We could also specify starting parameter values, the step function to use, and so on (for full details, see the [PyMC3 documentation]( https://docs.pymc.io/api/inference.html#module-pymc3.sampling)). # # # Alternatively, we can build a model, but not fit it. model = bmb.Model("value ~ condition + age + gender + (1|uid)", data, dropna=True) model.build() # Building without sampling can be useful if we want to inspect the internal PyMC3 model before we start the (potentially long) sampling process. Once we're satisfied, and wish to run the sampler, we can then simply call ``model.fit()``, and the sampler will start running. Another good reason to build a model is to generate plot of the marginal priors using `model.plot_priors()`. model.plot_priors(); # ## Specifying priors # # # Bayesian inference requires one to specify prior probability distributions that represent the analyst's belief (in advance of seeing the data) about the likely values of the model parameters. In practice, analysts often lack sufficient information to formulate well-defined priors, and instead opt to use "weakly informative" priors that mainly serve to keep the model from exploring completely pathological parts of the parameter space (e.g., when defining a prior on the distribution of human heights, a value of 3,000 cms should be assigned a probability of exactly 0). # # By default, Bambi will intelligently generate weakly informative priors for all model terms, by loosely scaling them to the observed data. Currently, Bambi uses a methodology very similar to the one described in the documentation of the R package [`rstanarm`](https://mc-stan.org/rstanarm/articles/priors.html). While the default priors will behave well in most typical settings, there are many cases where an analyst will want to specify their own priors--and in general, when informative priors are available, it's a good idea to use them. # Fortunately, Bambi is built on top of PyMC3, which means that we can seamlessly use any of the over 40 ``Distribution`` classes defined in PyMC3. We can specify such priors in Bambi using the ``Prior`` class, which initializes with a ``name`` argument (which must map on exactly to the name of a valid PyMC3 ``Distribution``) followed by any of the parameters accepted by the corresponding ``distribution``. For example: # + # A Laplace prior with mean of 0 and scale of 10 my_favorite_prior = bmb.Prior("Laplace", mu=0, b=10) # Set the prior when adding a term to the model; more details on this below. priors = {"1|uid": my_favorite_prior} bmb.Model("value ~ condition + (1|uid)", data, priors=priors, dropna=True) # - # Priors specified using the ``Prior`` class can be nested to arbitrary depths--meaning, we can set any of a given prior's argument to point to another ``Prior`` instance. This is particularly useful when specifying hierarchical priors on group specific effects, where the individual group specific slopes or intercepts are constrained to share a common source distribution: subject_sd = bmb.Prior("HalfCauchy", beta=5) subject_prior = bmb.Prior("Normal", mu=0, sd=subject_sd) priors = {"1|uid": subject_prior} bmb.Model("value ~ condition + (1|uid)", data, priors=priors, dropna=True) # The above prior specification indicates that the individual subject intercepts are to be treated as if they are randomly sampled from the same underlying normal distribution, where the variance of that normal distribution is parameterized by a separate hyperprior (a half-cauchy with beta = 5). # It's important to note that explicitly setting priors by passing in ``Prior`` objects will disable Bambi's default behavior of scaling priors to the data in order to ensure that they remain weakly informative. This means that if you specify your own prior, you have to be sure not only to specify the distribution you want, but also any relevant scale parameters. For example, the 0.5 in ``Prior("Normal", mu=0, sd=0.5)`` will be specified on the scale of the data, not the bounded partial correlation scale that Bambi uses for default priors. This means that if your outcome variable has a mean value of 10,000 and a standard deviation of, say, 1,000, you could potentially have some problems getting the model to produce reasonable estimates, since from the perspective of the data, you're specifying an extremely strong prior. # ## Generalized linear mixed models # # Bambi supports the construction of mixed models with non-normal response distributions (i.e., generalized linear mixed models, or GLMMs). GLMMs are specified in the same way as LMMs, except that the user must specify the distribution to use for the response, and (optionally) the link function with which to transform the linear model prediction into the desired non-normal response. The easiest way to construct a GLMM is to simple set the ``family`` when creating the model: data = bmb.load_data("admissions") model = bmb.Model("admit ~ gre + gpa + rank", data, family="bernoulli") results = model.fit() # If no ``link`` argument is explicitly set (see below), the canonical link function (or an otherwise sensible default) will be used. The following table summarizes the currently available families and their associated links: # # <center> # # |Family name |Response distribution | Default link # |:------------- |:-------------------- |:------------- | # bernoulli | Bernoulli | logit | # beta | Beta | logit | # binomial | Binomial | logit | # gamma | Gamma | inverse | # gaussian | Normal | identity | # negativebinomial| NegativeBinomial | log | # poisson | Poisson | log | # t | StudentT | identity | # vonmises | VonMises | tan(x / 2) | # wald | InverseGaussian | inverse squared| # # </center> # ## Families # # Following the convention used in many R packages, the response distribution to use for a GLMM is specified in a ``Family`` class that indicates how the response variable is distributed, as well as the link function transforming the linear response to a non-linear one. Although the easiest way to specify a family is by name, using one of the options listed in the table above, users can also create and use their own family, providing enormous flexibility. In the following example, we show how the built-in Bernoulli family could be constructed on-the-fly: # + from scipy import special # Construct likelihood distribution ------------------------------ # This must use a valid PyMC3 distribution name. # 'parent' is the name of the variable that represents the mean of the distribution. # The mean of the Bernoulli family is given by 'p'. likelihood = bmb.Likelihood("Bernoulli", parent="p") # Set link function ---------------------------------------------- # There are two alternative approaches. # 1. Pass a name that is known by Bambi link = bmb.Link("logit") # 2. Build everything from scratch # link: A function that maps the response to the linear predictor # linkinv: A function that maps the linear predictor to the response # linkinv_backend: A function that maps the linear predictor to the response # that works with Aesara tensors. # bmb.math.sigmoid is a Aesara tensor function wrapped by PyMC3 and Bambi link = bmb.Link( "my_logit", link=special.expit, linkinv=special.logit, linkinv_backend=bmb.math.sigmoid ) # Construct the family ------------------------------------------- # Families are defined by a name, a Likelihood and a Link. family = bmb.Family("bernoulli", likelihood, link) # Now it's business as usual model = bmb.Model("admit ~ gre + gpa + rank", data, family=family) results = model.fit() # - # The above example produces results identical to simply setting ``family='bernoulli'``. # # One complication in specifying a custom ``Family`` is that one must pass both a link function and an inverse link function which must be able to operate over Aesara tensors rather than numpy arrays, so you'll probably need to rely on tensor operations provided in ``aesara.tensor`` (many of which are also wrapped by PyMC3) when defining a new link. # ## Results # # When a model is fitted, it returns a ``InferenceData`` object containing data related to the model and the posterior. This object can be passed to many functions in ArviZ to obtain numerical and visuals diagnostics and plot in general. # # # ## Plotting # # # To visualize a plot of the posterior estimates and sample traces for all parameters, simply pass the ``InferenceData`` object to the arviz function ``az._plot_trace``: az.plot_trace(results, compact=False); # More details on this plot are available in the [ArviZ documentation](https://arviz-devs.github.io/arviz/_modules/arviz/plots/traceplot.html). # # ## Summarizing # # If you prefer numerical summaries of the posterior estimates, you can use the ``az.summary()`` function from [ArviZ](https://arviz-devs.github.io/arviz/generated/arviz.summary.html#arviz.summary) which provides a pandas DataFrame with some key summary and diagnostics info on the model parameters, such as the 94% highest posterior density intervals: az.summary(results) # If you want to view summaries or plots for specific parameters, you can pass a list of its names: # show the names of all variables stored in the InferenceData object list(results.posterior.data_vars) # You can find detailed, worked examples of fitting Bambi models and working with the results in the example notebooks [here](bambi/examples.html). # # ## Accessing back-end objects # # Bambi is just a high-level interface to PyMC3. As such, Bambi internally stores virtually all objects generated by PyMC3, making it easy for users to retrieve, inspect, and modify those objects. For example, the ``Model`` class created by PyMC3 (as opposed to the Bambi class of the same name) is accessible from `model.backend.model`. type(model.backend.model) model.backend.model model.backend.model.observed_RVs model.backend.model.unobserved_RVs
docs/notebooks/getting_started.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # Python program to illustrate # the concept of locks # in multiprocessing import multiprocessing # function to withdraw from account def withdraw(balance, lock): for _ in range(2000): lock.acquire() balance.value = balance.value - 1 lock.release() # function to deposit to account def deposit(balance, lock): for _ in range(2000): lock.acquire() balance.value = balance.value + 1 lock.release() def perform_transactions(): # initial balance (in shared memory) balance = multiprocessing.Value('i', 500) # creating a lock object lock = multiprocessing.Lock() # creating new processes p1 = multiprocessing.Process(target=withdraw, args=(balance,lock)) p2 = multiprocessing.Process(target=deposit, args=(balance,lock)) # starting processes p1.start() p2.start() # wait until processes are finished p1.join() p2.join() # print final balance print("Final balance = {}".format(balance.value)) if __name__ == "__main__": for _ in range(10): # perform same transaction process 10 times perform_transactions() # -
Section 5/# 5.2 Stop processes from interfering with each other with locks.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import sqlite3 import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib import cm # %matplotlib inline db = 'chinook.db' def run_query(q): with sqlite3.connect(db) as conn: return pd.read_sql(q, conn) def run_command(c): with sqlite3.connect(db) as conn: conn.isolation_level = None conn.execute(c) def show_tables(): q = ''' SELECT name, type FROM sqlite_master WHERE type IN ("table","view"); ''' return run_query(q) show_tables() # - # # Find Newer Albums # + albums_to_purchase = ''' WITH usa_tracks_sold AS ( SELECT il.* FROM invoice_line il INNER JOIN invoice i on il.invoice_id = i.invoice_id INNER JOIN customer c on i.customer_id = c.customer_id WHERE c.country = "USA" ) SELECT g.name genre, count(uts.invoice_line_id) tracks_sold, cast(count(uts.invoice_line_id) AS FLOAT) / ( SELECT COUNT(*) from usa_tracks_sold ) percentage_sold FROM usa_tracks_sold uts INNER JOIN track t on t.track_id = uts.track_id INNER JOIN genre g on g.genre_id = t.genre_id GROUP BY 1 ORDER BY 2 DESC LIMIT 10; ''' run_query(albums_to_purchase) # + genre_sales_usa = run_query(albums_to_purchase) genre_sales_usa.set_index("genre", inplace=True, drop=True) genre_sales_usa["tracks_sold"].plot.barh( title="Top Selling Genres in the USA", xlim=(0, 625), colormap=plt.cm.Accent ) plt.ylabel('') for i, label in enumerate(list(genre_sales_usa.index)): score = genre_sales_usa.loc[label, "tracks_sold"] label = (genre_sales_usa.loc[label, "percentage_sold"] * 100 ).astype(int).astype(str) + "%" plt.annotate(str(label), (score + 10, i - 0.15)) plt.show() # - # Based on the sales of tracks across different genres in the USA, we should purchase the new albums by the following artists: # # - <NAME> (Punk) # - <NAME> (Blues) # - Meteor and the Girls (Pop) # # It's worth keeping in mind that combined, these three genres only make up only 17% of total sales, so we should be on the lookout for artists and albums from the 'rock' genre, which accounts for 53% of sales. # # Sales # + employee_sales_performance = ''' WITH customer_support_rep_sales AS ( SELECT i.customer_id, c.support_rep_id, SUM(i.total) total FROM invoice i INNER JOIN customer c ON i.customer_id = c.customer_id GROUP BY 1,2 ) SELECT e.first_name || " " || e.last_name employee, e.hire_date, SUM(csrs.total) total_sales FROM customer_support_rep_sales csrs INNER JOIN employee e ON e.employee_id = csrs.support_rep_id GROUP BY 1; ''' run_query(employee_sales_performance) # + employee_sales = run_query(employee_sales_performance) employee_sales.set_index("employee", drop=True, inplace=True) employee_sales.sort_values("total_sales", inplace=True) employee_sales.plot.barh( legend=False, title='Sales Breakdown by Employee', colormap=plt.cm.Accent ) plt.ylabel('') plt.show() # - # While there is a 20% difference in sales between Jane (the top employee) and Steve (the bottom employee), the difference roughly corresponds with the differences in their hiring dates. # # More Sales # + sales_by_country = ''' WITH country_or_other AS ( SELECT CASE WHEN ( SELECT count(*) FROM customer where country = c.country ) = 1 THEN "Other" ELSE c.country END AS country, c.customer_id, il.* FROM invoice_line il INNER JOIN invoice i ON i.invoice_id = il.invoice_id INNER JOIN customer c ON c.customer_id = i.customer_id ) SELECT country, customers, total_sales, average_order, customer_lifetime_value FROM ( SELECT country, count(distinct customer_id) customers, SUM(unit_price) total_sales, SUM(unit_price) / count(distinct customer_id) customer_lifetime_value, SUM(unit_price) / count(distinct invoice_id) average_order, CASE WHEN country = "Other" THEN 1 ELSE 0 END AS sort FROM country_or_other GROUP BY country ORDER BY sort ASC, total_sales DESC ); ''' run_query(sales_by_country) # - # # Visualizing Sales by Country # + country_metrics = run_query(sales_by_country) country_metrics.set_index("country", drop=True, inplace=True) colors = [plt.cm.Accent(i) for i in np.linspace(0, 1, country_metrics.shape[0])] fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(9, 10)) ax1, ax2, ax3, ax4 = axes.flatten() fig.subplots_adjust(hspace=.5, wspace=.3) # top left sales_breakdown = country_metrics["total_sales"].copy().rename('') sales_breakdown.plot.pie( ax=ax1, startangle=-90, counterclock=False, title='Sales Breakdown by Country,\nNumber of Customers', colormap=plt.cm.Accent, fontsize=8, wedgeprops={'linewidth':0} ) # top right cvd_cols = ["customers","total_sales"] custs_vs_dollars = country_metrics[cvd_cols].copy() custs_vs_dollars.index.name = '' for c in cvd_cols: custs_vs_dollars[c] /= custs_vs_dollars[c].sum() / 100 custs_vs_dollars.plot.bar( ax=ax2, colormap=plt.cm.Set1, title="Pct Customers vs Sales" ) ax2.tick_params(top="off", right="off", left="off", bottom="off") ax2.spines["top"].set_visible(False) ax2.spines["right"].set_visible(False) # bottom left avg_order = country_metrics["average_order"].copy() avg_order.index.name = '' difference_from_avg = avg_order * 100 / avg_order.mean() - 100 difference_from_avg.drop("Other", inplace=True) difference_from_avg.plot.bar( ax=ax3, color=colors, title="Average Order,\nPct Difference from Mean" ) ax3.tick_params(top="off", right="off", left="off", bottom="off") ax3.axhline(0, color='k') ax3.spines["top"].set_visible(False) ax3.spines["right"].set_visible(False) ax3.spines["bottom"].set_visible(False) # bottom right ltv = country_metrics["customer_lifetime_value"].copy() ltv.index.name = '' ltv.drop("Other",inplace=True) ltv.plot.bar( ax=ax4, color=colors, title="Customer Lifetime Value, Dollars" ) ax4.tick_params(top="off", right="off", left="off", bottom="off") ax4.spines["top"].set_visible(False) ax4.spines["right"].set_visible(False) plt.show() # - # Based on the data, there may be opportunity in the following countries: # # - Czech Republic # - United Kingdom # - India # # It's worth keeping in mind that because the amount of data from each of these countries is relatively low. Because of this, we should be cautious spending too much money on new marketing campaigns, as the sample size is not large enough to give us high confidence. A better approach would be to run small campaigns in these countries, collecting and analyzing the new customers to make sure that these trends hold with new customers. # # Albums vs Individual Tracks # + albums_vs_tracks = ''' WITH invoice_first_track AS ( SELECT il.invoice_id invoice_id, MIN(il.track_id) first_track_id FROM invoice_line il GROUP BY 1 ) SELECT album_purchase, COUNT(invoice_id) number_of_invoices, CAST(count(invoice_id) AS FLOAT) / ( SELECT COUNT(*) FROM invoice ) percent FROM ( SELECT ifs.*, CASE WHEN ( SELECT t.track_id FROM track t WHERE t.album_id = ( SELECT t2.album_id FROM track t2 WHERE t2.track_id = ifs.first_track_id ) EXCEPT SELECT il2.track_id FROM invoice_line il2 WHERE il2.invoice_id = ifs.invoice_id ) IS NULL AND ( SELECT il2.track_id FROM invoice_line il2 WHERE il2.invoice_id = ifs.invoice_id EXCEPT SELECT t.track_id FROM track t WHERE t.album_id = ( SELECT t2.album_id FROM track t2 WHERE t2.track_id = ifs.first_track_id ) ) IS NULL THEN "yes" ELSE "no" END AS "album_purchase" FROM invoice_first_track ifs ) GROUP BY album_purchase; ''' run_query(albums_vs_tracks) # - # Album purchases account for 18.6% of purchases. Based on this data, I would recommend against purchasing only select tracks from albums from record companies, since there is potential to lose one fifth of revenue.
org_data.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="5nBnlGtGPluR" # # **About the Project** # # In this project we will be using NLP to preprocess the text inside resume and segregate resumes based on domain. As this is a classification task, we will be using word embedding technique to transform raw text into numerical features. Based on these features final predictions will be performed. # + [markdown] id="1D75FxAUN0X_" # # **1. Loading and preprocessing the dataset** # + id="aHsfrefVQasE" # Importing libraries import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns import warnings import os # #!pip install tensorflow==2.1.0 # #!pip install keras==2.3.1 # %matplotlib inline #pd.set_option("display.max_rows", None,"display.max_columns", None) warnings.simplefilter(action='ignore') plt.style.use('seaborn') # + colab={"base_uri": "https://localhost:8080/"} id="uqSBUHbgQuM8" outputId="2d87ef87-7fcd-4025-b04f-1e6b232203b6" # Mounting google drive from google.colab import drive drive.mount('/content/drive') # + colab={"base_uri": "https://localhost:8080/"} id="pd1-3fEdQ4AU" outputId="37182a45-fd7b-4913-96b6-51c3fd36b85f" import zipfile zipPATH = '/content/drive/MyDrive/Colab Notebooks/Misc_Resume_Screening/archive_Resume_Screening.zip' if 'UpdatedResumeDataSet.csv' not in os.listdir('.'): with zipfile.ZipFile(zipPATH,"r") as z: print(f"Extracting content from archive_Resume_Screening.zip ......") z.extractall() print(f"Extracted to {os.getcwd()}") else: print("UpdatedResumeDataSet.csv already present") # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="CzvCbsWlRbQQ" outputId="88eb2480-a98c-4d73-e71f-941ad0ac0b64" df = pd.read_csv('UpdatedResumeDataSet.csv',encoding='utf-8') df.head() # + colab={"base_uri": "https://localhost:8080/"} id="KNNLoCu_TPjP" outputId="b3726a09-2a08-42fd-a083-c242a8c79b0c" df.info() # + colab={"base_uri": "https://localhost:8080/", "height": 175} id="dT7_v3lgUXC0" outputId="56237101-f6ef-448f-b6f7-1249b6fa466a" df.describe() # + colab={"base_uri": "https://localhost:8080/"} id="ojey91OhSDBp" outputId="f1c32bc6-5a3f-4360-9528-d9549e55993f" # Displaying content inside a resume print(df.loc[1,'Resume']) # + id="j5RIB4GMU-1D" import re def cleanResume(resumeText): resumeText = re.sub('http\S+\s*', ' ', resumeText) # remove URLs resumeText = re.sub('RT|cc', ' ', resumeText) # remove RT and cc resumeText = re.sub('#\S+', '', resumeText) # remove hashtags resumeText = re.sub('@\S+', ' ', resumeText) # remove mentions resumeText = re.sub('[%s]' % re.escape("""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""), ' ', resumeText) # remove punctuations resumeText = re.sub(r'[^\x00-\x7f]',r' ', resumeText) resumeText = re.sub('\d+', ' ', resumeText) # remove digits resumeText = re.sub('\s+', ' ', resumeText) # remove extra whitespace resumeText = resumeText.lower() return resumeText # + id="BoasiPRqgezL" df['cleaned_resume'] = df["Resume"].apply(cleanResume) # + colab={"base_uri": "https://localhost:8080/"} id="03HUvjJug--j" outputId="ec120eaa-0a3c-4cd0-83a1-32bc27e2e257" # Displaying content inside a resume print(df.loc[1,'cleaned_resume']) # + [markdown] id="B-PtLGLmF8-L" # # **2. Performing EDA** # + [markdown] id="JMXx6bIeGDdO" # ## **a) Checking Target Class Distribution** # + colab={"base_uri": "https://localhost:8080/", "height": 497} id="XOD5KywxVWLc" outputId="93bd9e43-d9cd-4bbe-c176-3c152757bbf2" plt.figure(figsize=(10,6)) df['Category'].value_counts().plot(kind="bar") plt.title("Resume Distribution") plt.show() # + [markdown] id="iYUvm8zp8_5P" # ## **b) Creating Wordcloud** # + colab={"base_uri": "https://localhost:8080/"} id="50s3_v4Zikfu" outputId="a7cc8923-e9a2-48f1-93ef-2301919cacf4" import nltk from nltk.corpus import stopwords import string from wordcloud import WordCloud from nltk.tokenize import word_tokenize nltk.download('stopwords') nltk.download('punkt') # + id="LuMNs2jSGrBX" def word_cloud(domain): sentences = df[df['Category']==domain]['cleaned_resume'].tolist() words = [] for sentence in sentences: word_tokens = word_tokenize(sentence) words = [word for word in word_tokens if word not in stopwords.words('english')] ''' wordfreqdist = nltk.FreqDist(words) mostcommon = wordfreqdist.most_common(50) print(mostcommon) ''' cleaned_text = " ".join(words) wc = WordCloud().generate(cleaned_text) plt.figure(figsize=(15,15)) plt.imshow(wc, interpolation='bilinear') plt.axis("off") plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 449} id="5DQst6SHITlo" outputId="6d306813-0671-4fae-f8b1-d1672ac6d4a4" word_cloud('Hadoop') # + [markdown] id="8ehQi8QYFVnS" # # **3. Data Preparation** # + [markdown] id="7g9CP0iNG8Kp" # ## **a) Train-Test Split** # + colab={"base_uri": "https://localhost:8080/"} id="jR184QN4Ub0n" outputId="384df8d6-56d0-46d9-ead5-752765ff3836" from sklearn.model_selection import train_test_split X = df['cleaned_resume'] y = df['Category'] X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=0, test_size=0.2, stratify=y) print("Train Shape :", X_train.shape) print("Test Shape :", X_test.shape) # + [markdown] id="yt_QL6jhHALe" # ## **b) Word Embedding** # + id="uTqUiWpLI2i6" colab={"base_uri": "https://localhost:8080/"} outputId="5fc0bdf8-19a2-428a-a658-35fd562161ae" from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.pipeline import Pipeline word_vectorizer = TfidfVectorizer( sublinear_tf=True, stop_words='english', max_features=1500) X_train_vec = word_vectorizer.fit_transform(X_train) X_test_vec = word_vectorizer.transform(X_test) print("Train vector :",X_train_vec.shape) print("Test vector :",X_test_vec.shape) # + [markdown] id="bUqs0SuQHH8Y" # # **4. Model Building and Evaluation** # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="76W2OfRhWfkG" outputId="9579e3e4-20b9-4f09-c248-6839f09cac23" from sklearn.multiclass import OneVsRestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import classification_report, confusion_matrix clf = KNeighborsClassifier() clf.fit(X_train_vec, y_train) prediction = clf.predict(X_test_vec) print('Accuracy of KNeighbors Classifier on training set: {:.2f}'.format(clf.score(X_train_vec, y_train))) print('Accuracy of KNeighbors Classifier on test set: {:.2f}'.format(clf.score(X_test_vec, y_test))) print("-----------------------------------------------------") print("Confusion Matrix: ") plt.figure(figsize=(9,9)) sns.heatmap(confusion_matrix(y_test,prediction),linewidths=.5,cmap="YlGnBu",annot=True,cbar=False,fmt='d',xticklabels=X.) plt.show() print("-----------------------------------------------------") print(f"\n Classification report: \n {classification_report(y_test, prediction)}") # + [markdown] id="ALeztHfzGJMY" # **Reference:** # # - <a href="https://thecleverprogrammer.com/2020/12/06/resume-screening-with-python/">Resume Segmentation</a> # - <a href="https://towardsdatascience.com/do-the-keywords-in-your-resume-aptly-represent-what-type-of-data-scientist-you-are-59134105ba0d">Resume Screening</a> # - <a href="https://thecleverprogrammer.com/2020/07/21/pipelines-in-machine-learning/">Pipelines</a> # - <a href="https://machinelearningmastery.com/types-of-classification-in-machine-learning/">Classification Techniques</a> # - <a href="https://machinelearningmastery.com/stacking-ensemble-machine-learning-with-python/">Stacking</a> #
Resume_Segmentation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:synthesized-timelags] # language: python # name: conda-env-synthesized-timelags-py # --- # # Timelag Maps # Compute all of the timelag maps here for all heating frequencies and observations and then save the maps. # + import os import sys import numpy as np import distributed import matplotlib.pyplot as plt import matplotlib.colors from sunpy.map import Map,GenericMap from astropy.coordinates import SkyCoord import astropy.units as u import synthesizAR from synthesizAR.instruments import InstrumentSDOAIA sys.path.append(os.path.join(os.environ['HOME'], 'projects/synthesized_timelag_maps/scripts/')) from aiacube import DistributedAIACube from timelags import AIATimeLags # %matplotlib inline # - channel_pairs = [(94,335), (94,171), (94,193), (94,131), (94,211), (335,131), (335,193), (335,211), (335,171), (211,131), (211,171), (211,193), (193,171), (193,131), (171,131),] timelag_bounds = (-6*u.hour,6*u.hour) channels = [94,131,171,193,211,335] read_template = '/storage-home/w/wtb2/data/timelag_synthesis_v2/{}/nei/SDO_AIA/{}/map_t{:06d}.fits' save_template = '/storage-home/w/wtb2/data/shine2018/{}_{}_{}.fits' cluster = distributed.LocalCluster(n_workers=64,threads_per_worker=1) client = distributed.Client(cluster) client # ## Models frequencies = ['high_frequency','intermediate_frequency','low_frequency', 'cooling','cooling_outofphase_long'] for f in frequencies: irange = range(500,2500) if f!='cooling' else range(0,1000) tl_cubes = AIATimeLags(*[DistributedAIACube.from_files([read_template.format(f,c,i) for i in irange]) for c in channels]) for ca,cb in channel_pairs: tmap,cmap = tl_cubes.make_timelag_map(float(ca),float(cb), timelag_bounds=timelag_bounds, return_correlation_map=True) tmap.save(save_template.format(f,f'{ca}-{cb}','timelag')) cmap.save(save_template.format(f,f'{ca}-{cb}','correlation')) # ## Data # Need to figure out what to do here since interpolating cube in Dask is challenging...
shine_2018/notebooks/timelags.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Forecast Cases # # Using a generative model, simulate the number of infectious individuals to forecast at National and State level. # # We have three types of infectious individuals: Imported $\left(I_{I}\right),$ Asymptomatic $\left(I_{A}\right),$ and Symptomatic $\left(I_{S}\right)$ # - Each case is assumed to generate a number of cases from a Negative Binomial distribution, with parameters $k$ and, respectively, $\alpha_{I} R_{\mathrm{eff}} /\left(\alpha_{I} R_{\mathrm{eff}}+k\right), \alpha_{A} R_{\mathrm{eff}} /\left(\alpha_{A} R_{\mathrm{eff}}+k\right)$ and $\alpha_S R_{\mathrm{eff}} /\left(\alpha_S R_{\mathrm{eff}}+k\right)$ # - The parameter $k$ is the shape parameter of an Erlang infectious period; we will likely fix this at $k=3$ (but can try a few values) # $-$ The parameters $\alpha_{I}$ and $\alpha_{A}$ correspond to the reduced transmissibility of, respectively, imported and asymptomatic cases. Perhaps we want to infer these, but prior (and initial distribution for generation might be $\operatorname{Beta}(a, b)$ with mean 0.1 and low variance. # $-$ The parameter $R_{\mathrm{eff}}$ can be sampled from David's estimates, or Dennis's model. # - New infectious indviduals generated as above are assigned to be Symptomatic with probability $p_{S}$ and are otherwise Asymptomatic. # $-$ We might try to infer $p_{S},$ but to start with we might have $p_{S} \sim \operatorname{Beta}(c, d)$ such that the mean is 0.5 and variance such that it is reasonably confidently between 0.25 and 0.75 # - Infectious individuals are detected, and hence become a case, with respective probabilities $q_{I}, q_{A}$ and $q_{S}$ respectively. # $-$ We might try to infer these, but to start with I think $q_{A} \sim \operatorname{Beta}(e, f)$ such that the mean is 0.001 and low variance, $q_{I}, q_{S} \sim \operatorname{Beta}(g, h)$ such that the mean is 0.9 and low variance. # - For each infectious individual, we generate the time that they became infected by adding to the time of infection of their parent a random time generated from a Gamma(mean $=i,$ variance $=j$ ) distribution. # $-$ We probably want to infer $i$ and $j,$ but to start I think $i=5$ and a reasonably large variance. # For those that are detected, we also need to add on to their time of infection the delay until they are detected (which rounded, gives the day they appear in the case data), generated from a Gamma(mean= $k$, variance $=l$ ) distribution. # $-$ We probably want to infer $k$ and $l,$ but to start I think $k=6$ and a large (but not as large as infection distribution above) # - We additionally have a $\operatorname{Poi}\left(\iota_{t}\right)$ number of new imported infectious individuals on day $t,$ where $\iota_{t}$ decreases in time, especially from quarantine restrictions, and to be inferred from data. # + import numpy as np import pandas as pd from scipy.stats import nbinom, erlang, beta, binom, gamma, poisson, beta import matplotlib.pyplot as plt import os class Person: """ Individuals in the forecast """ # Laura # default action_time to 0. This allows for code that doesn’t involve contact tracing (undetected cases) # to continue without modification. def __init__(self,parent, infection_time,detection_time, detected,category:str, action_time = 0): """ Category is one of 'I','A','S' for Imported, Asymptomatic and Symptomatic """ self.parent = parent self.infection_time = infection_time self.detection_time = detection_time self.detected = detected self.category = category # Laura # Add action time to Person object self.action_time = action_time class Forecast: """ Forecast object that contains methods to simulate a forcast forward, given Reff and current state. """ def __init__(self,current, state,start_date, people, Reff=2.2,k=0.1,alpha_i=1,gam_list=[0.8],qi_list=[1], qa_list=[1/8], qs_list=[0.8], qua_ai= 1, qua_qi_factor=1, qua_qs_factor=1,forecast_R=None,R_I=None, forecast_date='2020-07-01', cross_border_state=None,cases_file_date=('25Jun','0835'), ps_list=[0.7], test_campaign_date=None, test_campaign_factor=1, Reff_file_date=None, ): import numpy as np self.initial_state = current.copy() #Observed cases on start day #self.current=current self.state = state #start date sets day 0 in script to start_date self.start_date = pd.to_datetime(start_date,format='%Y-%m-%d') self.quarantine_change_date = pd.to_datetime( '2020-04-01',format='%Y-%m-%d').dayofyear - self.start_date.dayofyear self.initial_people = people.copy() #detected people only self.Reff = Reff self.alpha_i = alpha_i self.gam_list = gam_list self.ps_list = ps_list#beta.rvs(7,3,size=1000) self.qi_list = qi_list self.qa_list = qa_list self.qs_list = qs_list self.k = k self.qua_ai = qua_ai self.qua_qi_factor = qua_qi_factor self.qua_qs_factor=qua_qs_factor self.forecast_R = forecast_R self.R_I = R_I np.random.seed(1) #self.max_cases = 100000 self.forecast_date = pd.to_datetime( forecast_date,format='%Y-%m-%d').dayofyear - self.start_date.dayofyear self.Reff_file_date = Reff_file_date self.cross_border_state = cross_border_state self.cases_file_date = cases_file_date if self.cross_border_state is not None: self.travel_prob = self.p_travel() self.travel_cases_after = 0 #placeholders for run_state script self.cross_border_seeds = np.zeros(shape=(1,2),dtype=int) self.cross_border_state_cases = np.zeros_like(self.cross_border_seeds) if test_campaign_date is not None: self.test_campaign_date = pd.to_datetime( test_campaign_date,format='%Y-%m-%d').dayofyear - self.start_date.dayofyear self.test_campaign_factor = test_campaign_factor else: self.test_campaign_date = None #import model parameters self.a_dict = { 'ACT': { 1:2, 2:22, 3:31*1.3, 4:17, 5:15, 6:3, }, 'NSW': { 1: 90, 2: 408, 3: 694*1.3, 4: 380, 5: 312, 6: 276, }, 'NT': { 1: 3, 2: 4, 3: 7*1.3, 4: 9, 5: 6, 6: 4, }, 'QLD': { 1:61, 2:190, 3:305*1.3, 4:162, 5:87, 6:25, }, 'SA': { 1:13, 2:68, 3:115*1.3, 4:67, 5:27, 6:6 }, 'TAS':{ 1:6, 2:14, 3:32*1.3, 4:19, 5:11, 6:2, }, 'VIC': { 1:62, 2:208, 3:255*1.3, 4:157, 5:87, 6:188, }, 'WA': { 1:15, 2:73, 3:154*1.3, 4:115, 5:110, 6:78 }, } #changes below also need to be changed in simulate self.b_dict = { 1: 6.2, 2: 7.2, 3: 5.2, 4: 5.2, 5: 22.2, 6: 145.2 ## this needs to change for # each change in forecast date } dir_path = os.getcwd() self.datapath = os.path.join(dir_path,'../data/') assert len(people) == sum(current), "Number of people entered does not equal sum of counts in current status" def generate_times(self, i=2.5, j=1.25, m=1.2, n=1, size=10000): """ Generate large amount of gamma draws to save on simulation time later """ self.inf_times = 1 + np.random.gamma(i/j, j, size =size) #shape and scale self.detect_times = 1 + np.random.gamma(m/n,n, size = size) return None def iter_inf_time(self): """ access Next inf_time """ from itertools import cycle for time in cycle(self.inf_times): yield time def iter_detect_time(self): """ access Next detect_time """ from itertools import cycle for time in cycle(self.detect_times): yield time def initialise_sim(self,curr_time=0): """ Given some number of cases in self.initial_state (copied), simulate undetected cases in each category and their infectious times. Updates self.current for each person. """ from math import ceil if curr_time ==0: #grab a sample from parameter lists self.qs = self.choose_random_item(self.qs_list) self.qa = self.choose_random_item(self.qa_list) #resample qa until it is less than self.qs while self.qa>=self.qs: self.qa = self.choose_random_item(self.qa_list) self.qi = self.choose_random_item(self.qi_list) self.gam = self.choose_random_item(self.gam_list) self.ps = self.choose_random_item(self.ps_list) self.alpha_s = 1/(self.ps + self.gam*(1-self.ps)) self.alpha_a = self.gam * self.alpha_s self.current = self.initial_state.copy() self.people = self.initial_people.copy() #N samples for each of infection and detection times #Grab now and iterate through samples to save simulation self.generate_times(size=10000) self.get_inf_time = self.iter_inf_time() self.get_detect_time = self.iter_detect_time() #counters for terminating early self.inf_backcast_counter = 0 self.inf_forecast_counter = 0 #assign infection time to those discovered # obs time is day =0 for person in self.people.keys(): self.people[person].infection_time = -1*next(self.get_inf_time) else: #reinitialising, so actual people need times #assume all symptomatic prob_symp_given_detect = self.qs*self.ps/( self.qs*self.ps + self.qa*(1-self.ps) ) num_symp = binom.rvs(n=int(self.current[2]), p=prob_symp_given_detect) for person in range(int(self.current[2])): self.infected_queue.append(len(self.people)) inf_time = next(self.get_inf_time) detection_time = next(self.get_detect_time) if person <- num_symp: new_person = Person(-1, curr_time-1*detection_time , curr_time, 1, 'S') else: new_person = Person(-1, curr_time-1*detection_time , curr_time, 1, 'A') self.people[len(self.people)] = new_person #self.cases[max(0,ceil(new_person.infection_time)), 2] +=1 #num undetected is nbinom (num failures given num detected) if self.current[2]==0: num_undetected_s = nbinom.rvs(1,self.qs*self.qua_qs_factor) else: num_undetected_s = nbinom.rvs(self.current[2],self.qs*self.qua_qs_factor) if self.current[0]==0: num_undetected_i = nbinom.rvs(1,self.qs*self.qua_qs_factor) else: num_undetected_i = nbinom.rvs(self.current[0], self.qi*self.qua_qi_factor) total_s = num_undetected_s + self.current[2] #infer some non detected asymp at initialisation if total_s==0: num_undetected_a = nbinom.rvs(1, self.ps) else: num_undetected_a = nbinom.rvs(total_s, self.ps) #simulate cases that will be detected within the next week #for n in range(1,8): #just symptomatic? #self.people[len(self.people)] = Person(0, -1*next(self.get_inf_time) , n, 0, 'S') if curr_time==0: #Add each undetected case into people for n in range(num_undetected_i): self.people[len(self.people)] = Person(0, curr_time-1*next(self.get_inf_time) , 0, 0, 'I') self.current[0] +=1 for n in range(num_undetected_a): self.people[len(self.people)] = Person(0, curr_time-1*next(self.get_inf_time) , 0, 0, 'A') self.current[1] +=1 for n in range(num_undetected_s): self.people[len(self.people)] = Person(0, curr_time-1*next(self.get_inf_time) , 0, 0, 'S') self.current[2] +=1 else: #reinitialised, so add these cases back onto cases #Add each undetected case into people for n in range(num_undetected_i): new_person = Person(-1, curr_time-1*next(self.get_inf_time) , 0, 0, 'I') self.infected_queue.append(len(self.people)) self.people[len(self.people)] = new_person self.cases[max(0,ceil(new_person.infection_time)),0] +=1 for n in range(num_undetected_a): new_person = Person(-1, curr_time-1*next(self.get_inf_time) , 0, 0, 'A') self.infected_queue.append(len(self.people)) self.people[len(self.people)] = new_person self.cases[max(0,ceil(new_person.infection_time)),1] +=1 for n in range(num_undetected_s): new_person = Person(-1, curr_time-1*next(self.get_inf_time) , 0, 0, 'S') self.infected_queue.append(len(self.people)) self.people[len(self.people)] = new_person self.cases[max(0,ceil(new_person.infection_time)),2] +=1 return None def read_in_Reff(self): """ Read in Reff csv from Price et al 2020. Originals are in RDS, are converted to csv in R script """ import pandas as pd #df= pd.read_csv(self.datapath+'R_eff_2020_04_23.csv', parse_dates=['date']) if self.cross_border_state is not None: states = [self.state,self.cross_border_state] else: states=[self.state] if self.forecast_R is not None: if self.Reff_file_date is None: import glob, os list_of_files = glob.glob(self.datapath+'soc_mob_R*.h5') latest_file = max(list_of_files, key=os.path.getctime) print("Using file "+latest_file) df_forecast = pd.read_hdf(latest_file, key='Reff') else: df_forecast = pd.read_hdf(self.datapath+'soc_mob_R'+self.Reff_file_date+'.h5', key='Reff') num_days = df_forecast.loc[ (df_forecast.type=='R_L')&(df_forecast.state==self.state)].shape[0] if self.R_I is not None: self.R_I = df_forecast.loc[ (df_forecast.type=='R_I')& (df_forecast.state==self.state), [i for i in range(1000)]].values[0,:] #R_L here df_forecast = df_forecast.loc[df_forecast.type==self.forecast_R] #df = pd.concat([ # df.drop(['type','date_onset','confidence', # 'bottom','top','mean_window','prob_control', # 'sd_window'],axis=1), # df_forecast.drop(['type'],axis=1) # ]) #df = df.drop_duplicates(['state','date'],keep='last') df = df_forecast df = df.set_index(['state','date']) Reff_lookupdist ={} for state in states: Reff_lookupstate = {} if self.forecast_R =='R_L': dfReff_dict = df.loc[state,[0,1]].to_dict(orient='index') for key, stats in dfReff_dict.items(): #instead of mean and std, take all columns as samples of Reff #convert key to days since start date for easier indexing newkey = key.dayofyear - self.start_date.dayofyear Reff_lookupstate[newkey] = df.loc[(state,key), [i for i in range(1000)]].values else: #R_L0 for day in range(num_days): Reff_lookupstate[day] = df.loc[state, [i for i in range(1000)]].values[0] #Nested dict with key to state, then key to date Reff_lookupdist[state] = Reff_lookupstate if self.cross_border_state is not None: self.Reff_travel = Reff_lookupdist[self.cross_border_state] self.Reff = Reff_lookupdist[self.state] return None def choose_random_item(self, items,weights=None): from numpy.random import random if weights is None: #Create uniform weights weights = [1/len(items)] * len(items) r = random() for i,item in enumerate(items): r-= weights[i] if r <0: return item def new_symp_cases(self,num_new_cases:int): """ Given number of new cases generated, assign them to symptomatic (S) with probability ps """ #repeated Bernoulli trials is a Binomial (assuming independence of development of symptoms) symp_cases = binom.rvs(n=num_new_cases, p=self.ps) return symp_cases def generate_new_cases(self,parent_key, Reff,k,travel=True): """ Generate offspring for each parent, check if they travel """ from math import ceil from numpy.random import random #check parent category if self.people[parent_key].category=='S': num_offspring = nbinom.rvs(n=k,p= 1- self.alpha_s*Reff/(self.alpha_s*Reff + k)) elif self.people[parent_key].category=='A': num_offspring = nbinom.rvs(n=k, p = 1- self.alpha_a*Reff/(self.alpha_a*Reff + k)) else: #Is imported if self.R_I is not None: #if splitting imported from local, change Reff to R_I Reff = self.choose_random_item(self.R_I) if self.people[parent_key].infection_time < self.quarantine_change_date: #factor of 3 times infectiousness prequarantine changes num_offspring = nbinom.rvs(n=k, p = 1- self.qua_ai*Reff/(self.qua_ai*Reff + k)) else: num_offspring = nbinom.rvs(n=k, p = 1- self.alpha_i*Reff/(self.alpha_i*Reff + k)) if num_offspring >0: num_sympcases = self.new_symp_cases(num_offspring) if self.people[parent_key].category=='A': child_times = [] for new_case in range(num_offspring): #define each offspring inf_time = self.people[parent_key].infection_time + next(self.get_inf_time) # LAURA # print(inf_time) # print(self.forecast_date) # Laura # add an action_time = 0 when an offspring is first examined: action_time = 0 if inf_time > self.forecast_date: self.inf_forecast_counter +=1 if travel: if self.cross_border_state is not None: #check if SA person if random() < self.travel_prob: if ceil(inf_time) <= self.cases.shape[0]: self.cross_border_state_cases[max(0,ceil(inf_time)-1),self.num_of_sim] += 1 detection_rv = random() detect_time = 0 #give 0 by default, fill in if passes recovery_time = 0 #for now not tracking recoveries if new_case <= num_sympcases-1: #minus 1 as new_case ranges from 0 to num_offspring-1 #first num_sympcases are symnptomatic, rest are asymptomatic category = 'S' if detection_rv < self.qs: #case detected detect_time = inf_time + next(self.get_detect_time) else: category = 'A' detect_time = 0 if detection_rv < self.qa: #case detected detect_time = inf_time + next(self.get_detect_time) self.people[len(self.people)] = Person(parent_key, inf_time, detect_time,recovery_time, category) self.cross_border_sim(len(self.people)-1,ceil(inf_time)) #skip simulating this offspring in VIC #continue else: #cross border seed happened after forecast self.travel_cases_after +=1 else: self.inf_backcast_counter +=1 #normal case within state if self.people[parent_key].category=='A': child_times.append(ceil(inf_time)) if ceil(inf_time) > self.cases.shape[0]: #new infection exceeds the simulation time, not recorded self.cases_after = self.cases_after + 1 else: #within forecast time detection_rv = random() detect_time = inf_time + next(self.get_detect_time) isdetected = 0 if new_case <= num_sympcases-1: #minus 1 as new_case ranges from 0 to num_offspring-1 #first num_sympcases are symnptomatic, rest are asymptomatic category = 'S' self.cases[max(0,ceil(inf_time)-1),2] += 1 if self.test_campaign_date is not None: #see if case is during a testing campaign if inf_time <self.test_campaign_date: detect_prob = self.qs else: detect_prob = min(0.95,self.qs*self.test_campaign_factor) else: detect_prob = self.qs if detection_rv < detect_prob: #case detected isdetected=1 # Laura # if parent is undetected, assign a new time to action if self.people[parent_key].detected==0: action_time = detect_time + gamma(t_a_shape,t_a_scale) if detect_time < self.cases.shape[0]: self.observed_cases[max(0,ceil(detect_time)-1),2] += 1 else: category = 'A' self.cases[max(0,ceil(inf_time)-1),1] += 1 #detect_time = 0 if self.test_campaign_date is not None: #see if case is during a testing campaign if inf_time <self.test_campaign_date: detect_prob = self.qa else: detect_prob = min(0.95,self.qa*self.test_campaign_factor) else: detect_prob=self.qa if detection_rv < detect_prob: #case detected isdetected=1 #detect_time = inf_time + next(self.get_detect_time) # Laura # Get absolute action time, # if parent is not detected, assign an action time # action_time = self.people[parent_key].detection_time + # 2* draw from distrubtion if self.people[parent_key].detected==0: action_time = detect_time + 2*gamma(t_a_shape,t_a_scale) if detect_time < self.cases.shape[0]: self.observed_cases[max(0,ceil(detect_time)-1),1] += 1 # Laura #add new infected to queue # contact trace 2=1 day before parent's detection time if self.people[parent_key].detected==1: #only check contact tracing if parent was detected if inf_time < self.people[parent_key].detection_time - DAYS: self.infected_queue.append(len(self.people)) #elif (self.people[parent_key].detection_time - DAYS) < inf_time < (self.people[parent_key].action_time): # elif ((self.people[parent_key].detection_time - DAYS) < inf_time) and (inf_time < (self.people[parent_key].action_time)): elif inf_time < (self.people[parent_key].action_time): x_rn = random() if x_rn <= p_c: action_time = self.people[parent_key].action_time self.infected_queue.append(len(self.people)) # else assign new time to action. # need to add if de else: action_time = inf_time + gamma(t_a_shape,t_a_scale) self.infected_queue.append(len(self.people)) else: #parent undetected self.infected_queue.append(len(self.people)) #add person to tracked people # Laura # add action_time when recording self.people[len(self.people)] = Person(parent_key, inf_time, detect_time,isdetected, category,action_time) if travel: #for parent, check their cross border travel if self.cross_border_state is not None: #Run cross border sim across children inf_time = self.people[parent_key].infection_time detect_time = self.people[parent_key].detection_time if self.people[parent_key].infection_time>self.forecast_date: #check it is after forecast date but before #end date if ceil(inf_time)-1 < self.cases.shape[0]: #check if travel #symptomatic people here pre_symp_time = inf_time while pre_symp_time < detect_time: travel_rv = random() if travel_rv<self.travel_prob: #travelled ## did they infect? #symptomatic self.cross_border_sim(parent_key,ceil(pre_symp_time)) #can travel more than once pre_symp_time +=1 #move forward a day if pre_symp_time>self.cases.shape[0]: break if detect_time==0: #asymptomatics if self.people[parent_key].category=='A': for pre_symp_time in child_times: if pre_symp_time< self.cases.shape[0] -1: #only care if still within forecast time travel_rv = random() if travel_rv<self.travel_prob: #travelled ## did they infect? self.cross_border_sim(parent_key,ceil(pre_symp_time)) #remove case from original state? return None def cases_detected(self,new_cases): """ Given a tuple of new_cases generated, return the number of cases detected """ #Number of detected cases in each class is Binomial with p = q_j i_detected = binom.rvs(n=new_cases[0],p=self.qi) a_detected = binom.rvs(n=new_cases[1],p=self.qa) s_detected = binom.rvs(n=new_cases[2],p=self.qs) return i_detected, a_detected, s_detected def import_arrival(self,period,size=1): """ Poisson likelihood of arrivals of imported cases, with a Gamma prior on the mean of Poisson, results in a posterior predictive distribution of imported cases a Neg Binom """ a = self.a_dict[self.state][period] b = self.b_dict[period] if size==1: return nbinom.rvs(a, 1-1/(b+1)) else: return nbinom.rvs(a, 1-1/(b+1),size=size) def simulate(self, end_time,sim,seed): """ Simulate forward until end_time """ from collections import deque from math import ceil import gc np.random.seed(seed) self.num_of_sim = sim #generate storage for cases self.cases = np.zeros(shape=(end_time, 3),dtype=float) self.observed_cases = np.zeros_like(self.cases) self.observed_cases[0,:] = self.initial_state.copy() #Initalise undetected cases and add them to current self.initialise_sim() #number of cases after end time self.cases_after = 0 #gets incremented in generate new cases #Record day 0 cases self.cases[0,:] = self.current.copy() # Generate imported cases num_days={ 1: 6, 2: 8, 3: 4, 4: 5, 5: 22,#min(end_time - self.quarantine_change_date -7, 24 ), 6: max(0,end_time- 6-8-4-5-22), } qi = { 1:self.qi *self.qua_qi_factor, 2:self.qi, 3:self.qi, 4:0.95, 5:0.98, 6:0.98, } new_imports = [] unobs_imports =[] for period in range(1,7): ##ADDED continue TO SKIP THIS FOR LB continue ###### obs_cases = self.import_arrival( period=period, size=num_days[period]) #generate undetected people #if obs_cases includes 0.... then add one for nbinom nbinom_var = [o+1 if o ==0 else o for o in obs_cases ] unobs = nbinom.rvs(nbinom_var, p=qi[period])#modify qi here unobs_imports.extend(unobs) new_imports.extend(obs_cases + unobs) for day, imports in enumerate(new_imports): ##ADDED continue TO SKIP THIS FOR LB continue ####### self.cases[day,0] = imports for n in range(imports): #Generate people if n - unobs_imports[day]>=0: #number of observed people new_person = Person(0,day,day +next(self.get_detect_time),1,'I') self.people[len(self.people)] = new_person if new_person.detection_time <= end_time: self.observed_cases[max(0,ceil(new_person.detection_time)-1),0] +=1 else: #unobserved people new_person = Person(0,day,0,0,'I') self.people[len(self.people)] = new_person if day <= end_time: self.cases[max(0,day-1), 0] +=1 ##### #Create queue for infected people self.infected_queue = deque() #Assign people to infected queue for key, person in self.people.items(): #add to the queue self.infected_queue.append(key) #Record their times if person.infection_time> end_time: #initial undetected cases have slim chance to be infected #after end_time if person.category!='I': #imports shouldn't count for extinction counts self.cases_after +=1 print("cases after at initialisation") #else: # if person.category=='S': # self.cases[max(0,ceil(person.infection_time)),2] +=1 # if (person.detection_time < end_time) & (person.detection_time!=0): # self.observed_cases[max(0,ceil(person.detection_time)), 2] +=1 # elif person.category=='I': #Imports recorded on creation in sim # continue # elif person.category=='A': # self.cases[max(0,ceil(person.infection_time)),1] +=1 # if (person.detection_time < end_time) & (person.detection_time!=0): # self.observed_cases[max(0,ceil(person.detection_time)), 1] +=1 # else: print("ERROR: not right category") #Record initial inferred obs including importations. self.inferred_initial_obs = self.observed_cases[0,:].copy() #print(self.inferred_initial_obs, self.current) # General simulation through time by proceeding through queue # of infecteds n_resim = 0 self.bad_sim = False reinitialising_window = 0 self.daycount= 0 while len(self.infected_queue)>0: day_end = self.people[self.infected_queue[0]].infection_time if day_end < self.forecast_date: if self.inf_backcast_counter> self.max_backcast_cases: print("Sim "+str(self.num_of_sim )+" in "+self.state+" has > "+str(self.max_backcast_cases)+" cases in backcast. Ending") self.num_too_many+=1 self.bad_sim = True break else: #check max cases for after forecast date if self.inf_forecast_counter>self.max_cases: #hold value forever if day_end < self.cases.shape[0]-1: self.cases[ceil(day_end):,2] = self.cases[ceil(day_end)-2,2] self.observed_cases[ceil(day_end):,2] = self.observed_cases[ceil(day_end)-2,2] else: self.cases_after +=1 print("Sim "+str(self.num_of_sim )+" in "+self.state+" has >"+str(self.max_cases)+" cases in forecast period.") self.num_too_many+=1 break ## stop if parent infection time greater than end time if self.people[self.infected_queue[0]].infection_time >end_time: self.infected_queue.popleft() print("queue had someone exceed end_time!!") else: #take approproate Reff based on parent's infection time curr_time = self.people[self.infected_queue[0]].infection_time if type(self.Reff)==int: Reff = 1 print("using flat Reff") elif type(self.Reff)==dict: while True: #sometimes initial cases infection time is pre #Reff data, so take the earliest one try: Reff = self.choose_random_item(self.Reff[ceil(curr_time)-1]) except KeyError: if curr_time>0: print("Unable to find Reff for this parent at time: %.2f" % curr_time) raise KeyError curr_time +=1 continue break #generate new cases with times parent_key = self.infected_queue.popleft() #recorded within generate new cases self.generate_new_cases(parent_key,Reff=Reff,k = self.k) #self.people.clear() if self.bad_sim ==False: #Check simulation for discrepancies for day in range(end_time): #each day runs through self.infected_queue ##ADDED continue TO SKIP THIS FOR LB continue ####### missed_outbreak = self.data_check(day) #True or False if missed_outbreak: self.daycount +=1 if self.daycount >= reinitialising_window: n_resim +=1 #print("Local outbreak in "+self.state+" not simulated on day %i" % day) #cases to add #treat current like empty list self.current[2] = max(0,self.actual[day] - sum(self.observed_cases[day,1:])) self.current[2] += max(0,self.actual[day-1] - sum(self.observed_cases[day-1,1:])) self.current[2] += max(0,self.actual[day-2] - sum(self.observed_cases[day-2,1:])) #how many cases are symp to asymp prob_symp_given_detect = self.qs*self.ps/( self.qs*self.ps + self.qa*(1-self.ps) ) num_symp = binom.rvs(n=int(self.current[2]), p=prob_symp_given_detect) #distribute observed cases over 3 days #Triangularly self.observed_cases[max(0,day),2] += num_symp//2 self.cases[max(0,day),2] += num_symp//2 self.observed_cases[max(0,day-1),2] += num_symp//3 self.cases[max(0,day-1),2] += num_symp//3 self.observed_cases[max(0,day-2),2] += num_symp//6 self.cases[max(0,day-2),2] +=num_symp//6 #add asymptomatic num_asymp = self.current[2] - num_symp self.observed_cases[max(0,day),2] += num_asymp//2 self.cases[max(0,day),2] += num_asymp//2 self.observed_cases[max(0,day-1),2] += num_asymp//3 self.cases[max(0,day-1),2] += num_asymp//3 self.observed_cases[max(0,day-2),2] += num_asymp//6 self.cases[max(0,day-2),2] +=num_asymp//6 self.initialise_sim(curr_time=day) #print("Reinitialising with %i new cases " % self.current[2] ) #reset days to zero self.daycount = 0 if n_resim> 10: print("This sim reinitilaised %i times" % n_resim) self.bad_sim = True n_resim = 0 break #Each check of day needs to simulate the cases before moving # to next check, otherwise will be doubling up on undetecteds while len(self.infected_queue)>0: day_end = self.people[self.infected_queue[0]].infection_time #check for exceeding max_cases if day_end <self.forecast_date: if self.inf_backcast_counter > self.max_backcast_cases: print("Sim "+str(self.num_of_sim )+" in "+self.state+" has > "+str(self.max_backcast_cases)+" cases in backcast. Ending") self.num_too_many+=1 self.bad_sim = True break else: if self.inf_forecast_counter> self.max_cases: self.cases[ceil(day_end):,2] = self.cases[ceil(day_end)-2,2] self.observed_cases[ceil(day_end):,2] = self.observed_cases[ceil(day_end)-2,2] print("Sim "+str(self.num_of_sim )+" in "+self.state+" has >"+str(self.max_cases)+" cases in forecast period.") self.num_too_many+=1 break ## stop if parent infection time greater than end time if self.people[self.infected_queue[0]].infection_time >end_time: personkey =self.infected_queue.popleft() print("queue had someone exceed end_time!!") else: #take approproate Reff based on parent's infection time curr_time = self.people[self.infected_queue[0]].infection_time if type(self.Reff)==int: Reff = 2 elif type(self.Reff)==dict: while True: #sometimes initial cases infection time is pre #Reff data, so take the earliest one try: Reff = self.choose_random_item(self.Reff[ceil(curr_time)-1]) except KeyError: if curr_time>0: print("Unable to find Reff for this parent at time: %.2f" % curr_time) raise KeyError curr_time +=1 continue break #generate new cases with times parent_key = self.infected_queue.popleft() self.generate_new_cases(parent_key,Reff=Reff,k=self.k) #missed_outbreak = max(1,missed_outbreak*0.9) else: #pass in here if while queue loop completes continue #only reach here if while loop breaks, so break the data check break #LB needs people recorded, do not clear this attribute #self.people.clear() gc.collect() if self.bad_sim: #return NaN arrays for all bad_sims self.metric = np.nan self.cumulative_cases = np.empty_like(self.cases) self.cumulative_cases[:] = np.nan return (self.cumulative_cases,self.cumulative_cases, { 'qs':self.qs, 'metric':self.metric, 'qa':self.qa, 'qi':self.qi, 'alpha_a':self.alpha_a, 'alpha_s':self.alpha_s, #'accept':self.accept, 'ps':self.ps, 'bad_sim':self.bad_sim, # Laura add 'Model_people':len(Model.people), 'cases_after':self.cases_after, 'travel_seeds': self.cross_border_seeds[:,self.num_of_sim], 'travel_induced_cases'+str(self.cross_border_state):self.cross_border_state_cases, 'num_of_sim':self.num_of_sim, } ) else: #good sim ## Perform metric for ABC self.get_metric(end_time) return ( self.cases.copy(), self.observed_cases.copy(), { 'qs':self.qs, 'metric':self.metric, 'qa':self.qa, 'qi':self.qi, 'alpha_a':self.alpha_a, 'alpha_s':self.alpha_s, #'accept':self.metric>=0.8, 'ps':self.ps, 'bad_sim':self.bad_sim, # Laura add 'Model_people':len(Model.people), 'cases_after':self.cases_after, 'travel_seeds': self.cross_border_seeds[:,self.num_of_sim], 'travel_induced_cases'+str(self.cross_border_state):self.cross_border_state_cases[:,self.num_of_sim], 'num_of_sim':self.num_of_sim, } ) def simulate_many(self, end_time, n_sims): """ Simulate multiple times """ self.end_time = end_time # Read in actual cases from NNDSS self.read_in_cases() import_sims = np.zeros(shape=(end_time, n_sims), dtype=float) import_sims_obs = np.zeros_like(import_sims) import_inci = np.zeros_like(import_sims) import_inci_obs = np.zeros_like(import_sims) asymp_inci = np.zeros_like(import_sims) asymp_inci_obs = np.zeros_like(import_sims) symp_inci = np.zeros_like(import_sims) symp_inci_obs = np.zeros_like(import_sims) bad_sim = np.zeros(shape=(n_sims),dtype=int) #ABC parameters metrics = np.zeros(shape=(n_sims),dtype=float) qs = np.zeros(shape=(n_sims),dtype=float) qa = np.zeros_like(qs) qi = np.zeros_like(qs) alpha_a = np.zeros_like(qs) alpha_s = np.zeros_like(qs) accept = np.zeros_like(qs) ps = np.zeros_like(qs) #extinction prop cases_after = np.empty_like(metrics) #dtype int self.cross_border_seeds = np.zeros(shape=(end_time,n_sims),dtype=int) self.cross_border_state_cases = np.zeros_like(self.cross_border_seeds) self.num_bad_sims = 0 self.num_too_many = 0 for n in range(n_sims): if n%(n_sims//10)==0: print("{} simulation number %i of %i".format(self.state) % (n,n_sims)) inci, inci_obs, param_dict = self.simulate(end_time, n,n) if self.bad_sim: bad_sim[n] = 1 print("Sim "+str(n)+" of "+self.state+" is a bad sim") self.num_bad_sims +=1 else: #good sims ## record all parameters and metric metrics[n] = self.metric qs[n] = self.qs qa[n] = self.qa qi[n] = self.qi alpha_a[n] = self.alpha_a alpha_s[n] = self.alpha_s accept[n] = int(self.metric>=0.8) cases_after[n] = self.cases_after ps[n] =self.ps import_inci[:,n] = inci[:,0] asymp_inci[:,n] = inci[:,1] symp_inci[:,n] = inci[:,2] import_inci_obs[:,n] = inci_obs[:,0] asymp_inci_obs[:,n] = inci_obs[:,1] symp_inci_obs[:,n] = inci_obs[:,2] #Apply sim metric here and record #dict of arrays n_days by sim columns results = { 'imports_inci': import_inci, 'imports_inci_obs': import_inci_obs, 'asymp_inci': asymp_inci, 'asymp_inci_obs': asymp_inci_obs, 'symp_inci': symp_inci, 'symp_inci_obs': symp_inci_obs, 'total_inci_obs': symp_inci_obs + asymp_inci_obs, 'total_inci': symp_inci + asymp_inci, 'all_inci': symp_inci + asymp_inci + import_inci, 'bad_sim': bad_sim, 'metrics': metrics, 'accept': accept, 'qs':qs, 'qa':qa, 'qi':qi, 'alpha_a':alpha_a, 'alpha_s':alpha_s, 'cases_after':cases_after, 'travel_seeds': self.cross_border_seeds, 'travel_induced_cases'+str(self.cross_border_state):self.cross_border_state_cases, 'ps':ps, } self.results = self.to_df(results) print("Number of bad sims is %i" % self.num_bad_sims) print("Number of sims in "+self.state\ +" exceeding "+\ str(self.max_cases//1000)+"k cases is "+str(self.num_too_many)) return self.state,self.results def to_df(self,results): """ Put results into a pandas dataframe and record as h5 format """ import pandas as pd df_results = pd.DataFrame() n_sims = results['symp_inci'].shape[1] days = results['symp_inci'].shape[0] sim_vars=['bad_sim','metrics','qs','qa','qi', 'accept','cases_after','alpha_a','alpha_s','ps'] for key, item in results.items(): if key not in sim_vars: df_results = df_results.append( pd.DataFrame( item.T,index=pd.MultiIndex.from_product([ [key], range(n_sims)], names=['Category', 'sim'] ) ) ) df_results.columns = pd.date_range(start = self.start_date, periods=days #num of days ) df_results.columns = [col.strftime('%Y-%m-%d') for col in df_results.columns] #Record simulation variables for var in sim_vars: df_results[var] = [results[var][sim] for cat,sim in df_results.index] print("Saving results for state "+self.state) if self.forecast_R is None: df_results.to_parquet( "./results/"+self.state+self.start_date.strftime( format='%Y-%m-%d')+"sim_results"+str(n_sims)+"days_"+str(days)+".parquet", ) else: df_results.to_parquet( "./results/"+self.state+self.start_date.strftime( format='%Y-%m-%d')+"sim_"+self.forecast_R+str(n_sims)+"days_"+str(days)+".parquet", ) return df_results def data_check(self,day): """ A metric to calculate how far the simulation is from the actual data """ try: actual_3_day_total = 0 for i in range(3): actual_3_day_total += self.actual[max(0,day-i)] threshold = 10*max(1,sum( self.observed_cases[ max(0,day-2):day+1,2] + self.observed_cases[ max(0,day-2):day+1,1] ) ) if actual_3_day_total > threshold: return min(3,actual_3_day_total/threshold) else: #no outbreak missed return False except KeyError: #print("No cases on day %i" % day) return False def get_metric(self,end_time,omega=0.2): """ Calculate the value of the metric of the current sim compared to NNDSS data """ ##missing dates #Deprecated now (DL 03/07/2020) #missed_dates = [day for day in range(end_time) # if day not in self.actual.keys()] self.actual_array = np.array([self.actual[day] #if day not in missed_dates else 0 for day in range(end_time) ]) #calculate case differences #moving windows sim_cases =self.observed_cases[ :len(self.actual_array),2] + \ self.observed_cases[: len(self.actual_array),1] #include asymp cases. #convolution with 1s should do cum sum window = 7 sim_cases = np.convolve(sim_cases, [1]*window,mode='valid') actual_cum = np.convolve(self.actual_array, [1]*window,mode='valid') cases_diff = abs(sim_cases - actual_cum) #if sum(cases_diff) <= omega * sum(self.actual_array): #cumulative diff passes, calculate metric #sum over days number of times within omega of actual self.metric = sum( np.square(cases_diff)#,np.maximum(omega* actual_cum,7) ) self.metric = self.metric/(end_time-window) #max is end_time return None def read_in_cases(self): """ Read in NNDSS case data to measure incidence against simulation """ import pandas as pd from datetime import timedelta import glob if self.cases_file_date is None: import glob, os list_of_files = glob.glob(self.datapath+'COVID-19 UoM*.xlsx') path = max(list_of_files, key=os.path.getctime) print("Using file "+path) else: path = self.datapath+"COVID-19 UoM "+self.cases_file_date+"*.xlsx" for file in glob.glob(path): df = pd.read_excel(file, parse_dates=['SPECIMEN_DATE','NOTIFICATION_DATE','NOTIFICATION_RECEIVE_DATE','TRUE_ONSET_DATE'], dtype= {'PLACE_OF_ACQUISITION':str}) if len(glob.glob(path))!=1: print("There are %i files with the same date" %len(glob.glob(path))) if len(glob.glob(path)) >1: print("Using an arbritary file") df = df.loc[df.STATE==self.state] #Set imported cases, local cases have 1101 as first 4 digits df.PLACE_OF_ACQUISITION.fillna('00038888',inplace=True) #Fill blanks with simply unknown df['date_inferred'] = df.TRUE_ONSET_DATE df.loc[df.TRUE_ONSET_DATE.isna(),'date_inferred'] = df.loc[df.TRUE_ONSET_DATE.isna()].NOTIFICATION_DATE - timedelta(days=5) df.loc[df.date_inferred.isna(),'date_inferred'] = df.loc[df.date_inferred.isna()].NOTIFICATION_RECEIVE_DATE - timedelta(days=6) df['imported'] = df.PLACE_OF_ACQUISITION.apply(lambda x: 1 if x[-4:]=='8888' and x != '00038888' else 0) df['local'] = 1 - df.imported if self.state=='VIC': #data quality issue df.loc[df.date_inferred=='2002-07-03','date_inferred'] = pd.to_datetime('2020-07-03') df.loc[df.date_inferred=='2002-07-17','date_inferred'] = pd.to_datetime('2020-07-17') df = df.groupby(['date_inferred'])[['imported','local']].sum() df.reset_index(inplace=True) df['date'] = df.date_inferred.apply(lambda x: x.dayofyear) -self.start_date.dayofyear df = df.sort_values(by='date') self.max_cases = max(500000,10*sum(df.local.values) + sum(df.imported.values)) self.max_backcast_cases = max(100,4*sum(df.local.values) + sum(df.imported.values)) #self.max_cases = max(self.max_cases, 1000) df = df.set_index('date') #fill missing dates with 0 up to end_time df = df.reindex(range(self.end_time), fill_value=0) self.actual = df.local.to_dict() return None def p_travel(self): """ given a state to go to, what it probability of travel? """ ##Pop from Rob's work pop = { 'NSW': 5730000, 'VIC': 5191000, 'SA': 1408000, 'WA': 2385000, 'TAS': 240342, 'NT': 154280, 'ACT': 410199, 'QLD': 2560000, } T_volume_ij = { 'NSW':{ 'ACT':3000, #'NT':?, 'SA':5300, 'VIC':26700, 'QLD':14000, 'TAS':2500, 'WA':5000, }, 'VIC':{ 'ACT':3600, 'NSW':26700, 'SA':12700, 'QLD':11000, 'TAS':5000, 'WA':6000, #'NT':, }, 'SA':{ 'ACT':1200, 'NSW':5300, 'QLD':2500, #'TAS':, 'VIC':12700, 'WA':2000, }, } #air and car travel from VIC to SA divided by pop of VIC try: p = T_volume_ij[ self.state][self.cross_border_state ]/(pop[self.state]+pop[self.cross_border_state]) except KeyError: print("Cross border state not implemented yet") raise KeyError return p def cross_border_sim(self,parent_key,day:int): """ Simulate a cross border interaction between two states, where export_state is the state in which a case is coming from. Need to feed in people, can be blank in attributes Feed in a time series of cases? Read in the timeseries? """ import pandas as pd import numpy as np from math import ceil from collections import deque Reff = self.choose_random_item(self.Reff_travel[day]) self.travel_infected_queue = deque() self.travel_people = {} #check parent category if self.people[parent_key].category=='S': num_offspring = nbinom.rvs(self.k, 1- self.alpha_s*Reff/(self.alpha_s*Reff + self.k)) elif self.people[parent_key].category=='A': num_offspring = nbinom.rvs(n=self.k, p = 1- self.alpha_a*Reff/(self.alpha_a*Reff + self.k)) else: #Is imported if self.R_I is not None: #if splitting imported from local, change Reff to R_I Reff = self.choose_random_item(self.R_I) if self.people[parent_key].infection_time < self.quarantine_change_date: #factor of 3 times infectiousness prequarantine changes num_offspring = nbinom.rvs(n=self.k, p = 1- self.qua_ai*Reff/(self.qua_ai*Reff + self.k)) else: num_offspring = nbinom.rvs(n=self.k, p = 1- self.alpha_i*Reff/(self.alpha_i*Reff + self.k)) if num_offspring >0: #import was successful, generate first gen offspring num_sympcases = self.new_symp_cases(num_offspring) for new_case in range(num_offspring): inf_time = next(self.get_inf_time) + self.people[parent_key].infection_time if inf_time < day +1: #record seeded if ceil(inf_time) > self.cases.shape[0]: #new infection exceeds the simulation time, not recorded self.travel_cases_after = self.travel_cases_after + 1 else: self.cross_border_seeds[day-1,self.num_of_sim] += 1 #successful only if day trip detection_rv = 1 #random() zeroed to just see all travel for now detect_time = 0 #give 0 by default, fill in if passes recovery_time = 0 #for now not tracking recoveries if new_case <= num_sympcases-1: #minus 1 as new_case ranges from 0 to num_offspring-1 #first num_sympcases are symnptomatic, rest are asymptomatic category = 'S' #record all cases the same for now self.cross_border_state_cases[max(0,ceil(inf_time)-1),self.num_of_sim] += 1 if detection_rv < self.qs: #case detected detect_time = inf_time + next(self.get_detect_time) if detect_time < self.cases.shape[0]: print("placeholder") #self.observed_cases[max(0,ceil(detect_time)-1),2] += 1 else: category = 'A' self.cross_border_state_cases[max(0,ceil(inf_time)-1),self.num_of_sim] +=1 detect_time = 0 if detection_rv < self.qa: #case detected detect_time = inf_time + next(self.get_detect_time) if detect_time < self.cases.shape[0]: print("placeholder") #self.observed_cases[max(0,ceil(detect_time)-1),1] += 1 #add new infected to queue self.travel_infected_queue.append(len(self.people)) #add person to tracked people self.travel_people[len(self.people)] = Person(parent_key, inf_time, detect_time,recovery_time, category) while len(self.travel_infected_queue) >0: parent_key = self.travel_infected_queue.popleft() inf_day = ceil(self.travel_people[parent_key].infection_time) Reff = self.choose_random_item(self.Reff_travel[inf_day]) self.generate_travel_cases(parent_key, Reff) return None def generate_travel_cases(self,parent_key,Reff): """ Generate and record cases in cross border state """ from math import ceil #check parent category if self.travel_people[parent_key].category=='S': num_offspring = nbinom.rvs(self.k, 1- self.alpha_s*Reff/(self.alpha_s*Reff + self.k)) elif self.travel_people[parent_key].category=='A': num_offspring = nbinom.rvs(n=self.k, p = 1- self.alpha_a*Reff/(self.alpha_a*Reff + self.k)) else: #Is imported if self.R_I is not None: #if splitting imported from local, change Reff to R_I Reff = self.choose_random_item(self.R_I) num_offspring = nbinom.rvs(n=self.k, p = 1- self.alpha_i*Reff/(self.alpha_i*Reff + self.k)) if num_offspring >0: num_sympcases = self.new_symp_cases(num_offspring) for new_case in range(num_offspring): inf_time = next(self.get_inf_time) + self.travel_people[parent_key].infection_time if inf_time < self.cases.shape[0]: #record case self.cross_border_state_cases[max(0,ceil(inf_time)-1),self.num_of_sim] += 1 detection_rv = 1 #random() zeroed to just see all travel for now detect_time = 0 #give 0 by default, fill in if passes recovery_time = 0 #for now not tracking recoveries if new_case <= num_sympcases-1: #minus 1 as new_case ranges from 0 to num_offspring-1 #first num_sympcases are symnptomatic, rest are asymptomatic category = 'S' #record all cases the same for now self.cross_border_state_cases[max(0,ceil(inf_time)-1),self.num_of_sim] += 1 if detection_rv < self.qs: #case detected detect_time = inf_time + next(self.get_detect_time) if detect_time < self.cases.shape[0]: print("placeholder") #self.observed_cases[max(0,ceil(detect_time)-1),2] += 1 else: category = 'A' self.cross_border_state_cases[max(0,ceil(inf_time)-1),self.num_of_sim] +=1 detect_time = 0 if detection_rv < self.qa: #case detected detect_time = inf_time + next(self.get_detect_time) if detect_time < self.cases.shape[0]: print("placeholder") #self.observed_cases[max(0,ceil(detect_time)-1),1] += 1 #add new infected to queue self.travel_infected_queue.append(len(self.people)) #add person to tracked people self.travel_people[len(self.people)] = Person(parent_key, inf_time, detect_time,recovery_time, category) else: #new infection exceeds the simulation time, not recorded #not added to queue self.travel_cases_after = self.travel_cases_after + 1 return None def reset_to_start(self,people): """ Reset forecast object back to initial conditions and reinitialise """ import gc self.people.clear() gc.collect() self.people = people local_detection = { 'NSW':0.2, #0.8 #0.2 #0.556,#0.65, 'QLD':0.9,#0.353,#0.493,#0.74, 'SA':0.7,#0.597,#0.75, 'TAS':0.4,#0.598,#0.48, 'VIC':0.55,#0.558,#0.77, 'WA':0.7,#0.409,#0.509,#0.66, 'ACT':0.95,#0.557,#0.65, 'NT':0.95,#0.555,#0.71 } a_local_detection = { 'NSW':0.05,#0.556,#0.65, 'QLD':0.05,#0.353,#0.493,#0.74, 'SA':0.05,#0.597,#0.75, 'TAS':0.05,#0.598,#0.48, 'VIC':0.05,#0.558,#0.77, 'WA':0.05,#0.409,#0.509,#0.66, 'ACT':0.7,#0.557,#0.65, 'NT':0.7,#0.555,#0.71 } qi_d = { 'NSW':0.95,#0.758, 'QLD':0.95,#0.801, 'SA':0.95,#0.792, 'TAS':0.95,#0.800, 'VIC':0.95,#0.735, 'WA':0.95,#0.792, 'ACT':0.95,#0.771, 'NT':0.95,#0.761 } # + import pandas as pd from numpy.random import beta, gamma ########## #PARAMETERS TO PLAY WITH ######### time_end = 30 forecast_type = 'R_L0' state = 'NSW' case_file_date = None #'24Jul' #Reff_file_date = '2020-07-20' Reff_file_date = '2020-08-06' #Number of initial symptomatic and asymptomatic cases respectively initial_cases = [10,0] # Laura # sets the seed for only the `action_time’ for the initial cases, # and so all simulations will start with the same initial cases and the same time to action np.random.seed(1) ############# ### These parameters do not need to be changed, ask DL XBstate = None start_date = '2020-03-01' test_campaign_date = '2020-06-25' test_campaign_factor = 1.25 R_I='R_I' abc =False forecast_date = '2020-03-02' ############################## print("Simulating state " +state) ##Initialise the number of cases as 1st of March data incidence current = { 'ACT':[0,0,0], 'NSW':[10,0,2], #1 'NT':[0,0,0], 'QLD':[2,0,0], 'SA':[2,0,0], 'TAS':[0,0,0], 'VIC':[2,0,0], #1 'WA':[0,0,0], } current ={state: [0,initial_cases[0],initial_cases[1]]} forecast_dict = {} initial_people = ['I']*current[state][0] + \ ['A']*current[state][1] + \ ['S']*current[state][2] people = {} if abc: qs_prior = beta(2,2,size=10000) qi_prior = beta(2, 2, size=10000) qa_prior = beta(2,2, size=10000) #qi_prior = [qi_d[state]] #qs_prior = [local_detection[state]] #qa_prior = [a_local_detection[state]] gam =0.1 + beta(2,2,size=10000) *0.9 #np.minimum(3,gamma(4,0.25, size=1000)) ps_prior = 0.1+beta(2,2,size=10000)*0.9 else: qi_prior = [qi_d[state]] qs_prior = [local_detection[state]] qa_prior = [a_local_detection[state]] gam =[1/2] ps_prior = 0.7 ps_prior= [ps_prior] ##create dictionary to input intial People # Laura # give action_times to each initial case t_a_shape = 3/2 t_a_scale = 2 for i,cat in enumerate(initial_people): people[i] = Person(0,0,0,1,cat, action_time = gamma(t_a_shape,t_a_scale)) #create forecast object if state in ['VIC']: #XBstate = 'SA' Model = Forecast(current[state], state,start_date,people, alpha_i= 1, k =0.1,gam_list=gam, qs_list=qs_prior,qi_list=qi_prior,qa_list=qa_prior, qua_ai=1,qua_qi_factor=1,qua_qs_factor=1, forecast_R =forecast_type, R_I = R_I,forecast_date=forecast_date, cross_border_state=XBstate,cases_file_date=case_file_date, ps_list = ps_prior, test_campaign_date=test_campaign_date, test_campaign_factor=test_campaign_factor,Reff_file_date=Reff_file_date ) elif state in ['NSW']: Model = Forecast(current[state], state,start_date,people, alpha_i= 1, k =0.1,gam_list=gam, qs_list=qs_prior,qi_list=qi_prior,qa_list=qa_prior, qua_ai=1,qua_qi_factor=1,qua_qs_factor=1, forecast_R =forecast_type, R_I = R_I,forecast_date=forecast_date, cross_border_state=None,cases_file_date=case_file_date, ps_list = ps_prior,Reff_file_date=Reff_file_date ) elif state in ['ACT','NT','SA','WA','QLD']: Model = Forecast(current[state], state,start_date,people, alpha_i= 0.1, k =0.1,gam_list=gam, qs_list=qs_prior,qi_list=qi_prior,qa_list=qa_prior, qua_ai=1,qua_qi_factor=1,qua_qs_factor=1, forecast_R =forecast_type, R_I = R_I,forecast_date=forecast_date, cross_border_state=None,cases_file_date=case_file_date, ps_list = ps_prior,Reff_file_date=Reff_file_date ) else: Model = Forecast(current[state],state, start_date,people, alpha_i= 0.5, k =0.1,gam_list=gam, qs_list=qs_prior,qi_list=qi_prior,qa_list=qa_prior, qua_ai=1,qua_qi_factor=1,qua_qs_factor=1, forecast_R = forecast_type , R_I = R_I,forecast_date=forecast_date, cases_file_date=case_file_date, ps_list = ps_prior,Reff_file_date=Reff_file_date ) # + #Set up some required attributes for simulation Model.end_time = time_end Model.cross_border_seeds = np.zeros(shape=(time_end,1000),dtype=int) Model.cross_border_state_cases = np.zeros_like(Model.cross_border_seeds) Model.num_bad_sims = 0 Model.num_too_many = 0 #Read in files Model.read_in_Reff() Model.read_in_cases() # + #simulate takes arguments days, sim number, and seed ## It will return: ## cases: a n_days by 3 array where each column represents ## Imported, Asymptomatic and Symptomatic cases, in that order. ## Cases are indexed in time by rows by their date of infection. ## observed_cases: a n_days by 3 array, same as cases, but only observed cases, ## and are indexed in time by their date of symptom onset. N=1 p_c=1.0 DAYS = 2 Model.simulate(time_end,1,N) # + # Simulation study for delay time t_a_shape = 3/2 t_a_scale = 2 n=1000 DAYS = 3 p_c = 1 pc_100_day_N3 = [] for N in range(0, n): cases_array, observed_cases_array, params = Model.simulate(time_end,1,N) #v = list(x)[2] #v2 = v.values() Cases = params['Model_people'] CasesAfter = params['cases_after'] CasesTotal = Cases + CasesAfter pc_100_day_N3.append((CasesTotal)) if N%100==0: print("sim number %i " % N) print("Timeline of Cases:\n", cases_array) print("Length of People (CasesTotal): %i " % CasesTotal) print('Completed Days = -3 , p = 1.0') # + # trace back branches #Look at the last person #Model.people[len(Model.people)-1].__dict__ #Model.people[4].__dict__ Model.people[29].__dict__ # + #Look at a person in the people dictionary Model.people[7].__dict__ # - #Look at the last person Model.people[len(Model.people)-1].__dict__ # Laura # Look at people in order Model.people[2].__dict__ # Laura # Total number of people infected len(Model.people) #how many offspring are in the next generation after simulation end_date Model.cases_after #Delay distribution fig,ax = plt.subplots(figsize=(12,9)) #x = np.random.gamma(5/2, 2, size = 10000) x = np.random.gamma(3/2, 2, size = 10000) print("Mean: %f.2" %np.mean(x)) print("Variance: %f.2" %np.var(x)) ax.hist(x,bins=40) ax.set_title("Time to action distribution") plt.show() # + #reproduction number for day n #if forecast_type is R_L0, then every day has the same distribution for Reff # which is baseline for 1st March with no social distancing in Aus. n = 30 fig, ax = plt.subplots() ax.hist(Model.Reff[n],bins=30) plt.show() # - #Infection time distribution fig,ax = plt.subplots(figsize=(12,9)) x = 1+np.random.gamma(3.5/0.5, 0.5, size = 10000) print("Mean: %f.2" %np.mean(x)) print("Variance: %f.2" %np.var(x)) ax.hist(x,bins=40) ax.set_title("Generation time distribution") plt.show() # + print(np.quantile(x,0.4)) #infection time y = 1+np.random.gamma(3/1, 1, size = 10000) #symptom time fig, ax = plt.subplots() ax.hist(y, bins=40) #ax.hist(y-x,bins =40) print(np.percentile(y-x, 40)) plt.show() # - #Observation time distribution fig,ax = plt.subplots(figsize=(12,9)) y = np.random.gamma(5*5/1, 1/5, size = 10000) y = [yi for yi in y if yi >2] print("Mean: %f.2" %np.mean(y)) print("Variance: %f.2" %np.var(y)) ax.hist(y,bins=40) ax.set_title("Observation time distribution") plt.show() # + #Symptom onset time distribution fig,ax = plt.subplots(figsize=(12,9)) y = np.random.gamma(5.807/0.948, 0.948, size = 10000) print("Mean: %f.2" %np.mean(y)) print("Variance: %f.2" %np.var(y)) print("95 percent interval is %.2f to %.2f" % (np.quantile(y,0.025), np.quantile(y,0.975)) ) ax.hist(y,bins=40) ax.set_title("Symptom time distribution") plt.show() # + #Symptom onset time distribution fig,ax = plt.subplots(figsize=(12,9)) y = np.random.gamma(5.807/0.948, 0.948, size = 10000) print("Mean: %f.2" %np.mean(y)) print("Variance: %f.2" %np.var(y)) print("95 percent interval is %.2f to %.2f" % (np.quantile(y,0.025), np.quantile(y,0.975)) ) ax.hist(y,bins=40) ax.set_title("Symptom time distribution") #Symptom onset time distribution fig,ax = plt.subplots(figsize=(12,9)) y = 2+np.random.gamma(3/1, 1, size = 10000) print("Mean: %f.2" %np.mean(y)) print("Variance: %f.2" %np.var(y)) print("95 percent interval is %.2f to %.2f" % (np.quantile(y,0.025), np.quantile(y,0.975)) ) ax.hist(y,bins=40) ax.set_title("Symptom time distribution") plt.show() # + #Neg Binomial offspring distribution Reff=1.4 n = 3 p = 1- Reff/(Reff+k) fig,ax = plt.subplots(figsize=(12,9)) rv = nbinom(n, p) x = np.arange(nbinom.ppf(0.01, n, p), nbinom.ppf(0.99, n, p)) ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1, label='frozen pmf') print("Mean: %f.2" % nbinom.stats(n,p)[0]) print("Variance: %f.2" %nbinom.stats(n,p)[1]) ax.set_title("Offspring distribution") plt.show() # + ## Check Neg Binom distribution k=0.1 Reff = pd.read_hdf('../data/soc_mob_R2020-06-22.h5', key='Reff') R = Reff.loc[(Reff.type=='R_L')&(Reff.state=='VIC'),['date']+list(range(99))] R = R.loc[R.date>='2020-06-15'] fig,ax = plt.subplots(figsize=(12,9)) ax.plot(R.date, 0.89*R[range(99)].median(axis=1)) num_offspring = nbinom.rvs(k, 1- 0.89*R[range(99)]/(0.89*R[range(99)] + k)) bins = np.bincount(num_offspring) fig,ax = plt.subplots(figsize=(12,9)) ax.vlines(range(len(bins)),0, bins) print("Mean is %.2f" %np.mean(num_offspring)) plt.show() # + k = 0.1 alpha_s = 0 R_L = 0.3 p = 1 - alpha_s* R_L/ (alpha_s*R_L + k) x = nbinom.rvs(k ,p,size=100000) #plotting print("mean should be %.4f " % (alpha_s*R_L)) print("Mean is %.4f" % np.mean(x)) print("Variance is %.2f " %np.var(x)) fig,ax = plt.subplots() ax.vlines(range(len(np.bincount(x))),0,np.bincount(x)) ax.set_xlim((0,15)) plt.locator_params(axis='x', nbins=4) plt.show() # + ## imports NT alpha = 15 b = 22.2 p = 1 - 1/ (1 + b) x = nbinom.rvs(alpha ,p,size=10000) #plotting print("Mean is %.4f" % np.mean(x)) print("Variance is %.2f " %np.var(x)) fig,ax = plt.subplots() ax.vlines(range(len(np.bincount(x))),0,np.bincount(x)) #ax.set_xlim((0,15)) plt.locator_params(axis='x', nbins=4) plt.show() # + #Posterior predictive distribution of imports a_dict = { 'ACT': { 1:10, 2:21, 3:22, 4:2 }, 'NSW': { 1: 315, 2: 620, 3: 799, 4: 19, }, 'NT': { 1: 4, 2: 6, 3: 17, 4: 3, }, 'QLD': { 1:170, 2:268, 3:351, 4:14, }, 'SA': { 1:44, 2:124, 3:125, 4:5, }, 'TAS':{ 1:10, 2:31, 3:39, 4:2, }, 'VIC': { 1:150, 2:158, 3:223, 4:22, }, 'WA': { 1:78, 2:114, 3:255, 4:3, }, } b_dict = { 1: 14.2, 2: 5.2, 3: 26.2, 4: 23.2 } ## Check Neg Binom distribution a = a_dict['NSW'][2] b = b_dict[2] num_offspring = nbinom.rvs(a, 1- 1/(b + 1),size=1000) bins = np.bincount(num_offspring) fig,ax = plt.subplots(figsize=(12,9)) ax.vlines(range(len(bins)),0, bins) print("Mean is %.2f" %np.mean(num_offspring)) plt.show() # - # From numpy (but not scipy), the probability density for the negative binomial distribution is # # \begin{equation} # P(N ; n, p)={N+n-1 \choose n-1} p^{n}(1-p)^{N} \\ # \end{equation} # where $n-1$ is the number of successes, $p$ is the probability of success, and $N+n-1$ is the number of trials. The negative binomial distribution gives the probability of $n-1$ successes and $N$ failures in $N+n-1$ trials, and success on the (N+n)th trial. # + alpha_i = 0.1 Reff=2.2 k = 3 p = alpha_i*Reff/(alpha_i*Reff + k) print("Probability of a success is: %.3f" % p) nbinomI = nbinom(k,1-p) samples = nbinomI.rvs(size=1000) print("mean is: %.2f" % np.mean(samples)) ax = plt.hist(samples) plt.show() # + def my_nbinom(s, k, p): """ my own nbinom, s= failures, k = successes, p = probability of success """ from scipy.special import comb return comb(k+s-1,s)* p**k*(1-p)**s pdf = [] for s in np.arange(0,10): pdf.append(my_nbinom(s,3 ,1-p)) plt.bar(np.arange(0,10),pdf) plt.show() # + Reff=2.2 k = 3 p =1- Reff/(Reff + k) print("Probability of a success is: %.3f" % p) nbinomI = nbinom(n=k, p = p ) samples = nbinomI.rvs(size=100) print("Mean is %.2f" %np.mean(samples)) print("Variance is %.2f" %np.var(samples)) ax = plt.hist(samples, bins=20) plt.show() # -
model/contact_tracing/simulation_model_delay.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %load_ext autoreload # %autoreload 2 # + # # Plot the histogram of the cycles between checkpoints # import matplotlib.pyplot as plt from matplotlib.patches import Patch from matplotlib.lines import Line2D import matplotlib.ticker as ticker import pandas as pd import numpy as np from Color import * # Matplotlib font configuration from MatplotlibFonts import * rcParams.update({"font.size": 13}) # - RESULT_DIR='../benchmarks/results' # + # Benchmarks in order Benchmarks = [ 'coremark', 'sha', 'crc', 'aes', 'dijkstra', 'picojpeg' ] # Configurations in order Configurations = [ 'opt-ratchet', 'opt-baseline', 'opt-all' ] from BenchmarkConfiguration import * # + # Dict with each benchmark data = {} def load_data(bench, config): global data # Add the benchmark if not there if bench not in data: data[bench] = {} # Add the config filename = RESULT_DIR+'/raw/checkpoint-frequency/'+bench+'-checkpointfreq-'+config+'.csv' print('Loading', filename) data[bench][config] = load_csv(filename) def load_csv(filename): df = pd.read_csv(filename, names=['cycles', 'delta']).iloc[1:,:].reset_index() # ignore the startup gap (useless) df = df['delta'].to_frame() return df # - for bench in Benchmarks: for config in Configurations: load_data(bench, config) print('Done') # + tags=[] fig, axs = plt.subplots(2, 6, sharex=False, figsize=(11,4), gridspec_kw={'height_ratios': [1, 5]}) plt.subplots_adjust(hspace=0.1) group_spacing = 1 bar_spacing = 0.2 bar_width = 0.15 for gidx, bench in enumerate(data): #print('Analyzing bench', bench) for idx, config in enumerate(data[bench]): #print(' config:', config) pos = idx*bar_spacing #print(' pos:', pos) #data[bench][config].boxplot(notch=True, ax=ax, widths=bar_width, positions=[pos], showfliers=False, labels=['test']) b = axs[1, gidx].boxplot(data[bench][config], notch=True, patch_artist=True, widths=bar_width, positions=[pos], showfliers=False, labels=[ConfigurationNameMap[config]], showmeans=True, boxprops=dict(facecolor=ConfigurationColorMap[config], linewidth=1), medianprops=dict(color='white', linewidth=2), meanprops=dict(color='black', markeredgecolor='black', markerfacecolor='white', markersize=7) ) groups = len(data) bar_per_group = len(data[next(iter(data))]) xlim = [-0.18, 0.7] for gidx, bench in enumerate(data): axs[0, gidx].set_axis_on axs[0, gidx].axes.xaxis.set_visible(False) #axs[0, gidx].axes.yaxis.set_visible(False) axs[0, gidx].axes.yaxis.set_ticks([]) axs[0, gidx].set_ylim(0,1) axs[1, gidx].set_xlim(xlim) axs[1, gidx].set_ylim(0, None) axs[1, gidx].spines['right'].set_visible(False) axs[1, gidx].spines['top'].set_visible(False) axs[0, gidx].set_xlim(xlim) axs[0, gidx].spines['right'].set_visible(False) axs[0, gidx].spines['top'].set_visible(False) axs[0, gidx].spines['bottom'].set_linestyle('--') axs[0, gidx].spines['bottom'].set_alpha(0.5) #pos = (bar_per_group-1)/2*bar_spacing pos = (xlim[0]+xlim[1])/2 xticks = [] xlabels = [] xticks.append(pos) xlabels.append(BenchmarkNameMap[bench]) axs[1, gidx].set_xticks(xticks) axs[1, gidx].set_xticklabels(xlabels) axs[1, gidx].xaxis.set_ticks_position('none') axs[1, gidx].yaxis.set_major_locator(plt.MaxNLocator(5)) # Build the outlier dots in axtop dot_y = 0.5 for gidx, bench in enumerate(data): for idx, config in enumerate(data[bench]): pos = idx*bar_spacing maxval = data[bench][config]['delta'].max() #print(' pos:', pos) #print(' max:', maxval) if (idx % 2) == 0: ytext = 10 else: ytext = -12 axs[0, gidx].plot([pos], [dot_y], 'D', color=ConfigurationColorMap[config]) axs[0, gidx].annotate("{:d}".format(maxval), xy=(pos, dot_y),xytext=(0,ytext), xycoords=('data'), textcoords='offset points', horizontalalignment='center', verticalalignment='center') #axs[0, 0].set_ylabel('max\nx$10^3$') axs[0, 0].set_ylabel('max') axs[1, 0].set_ylabel('region size (clock cycles)') # Add the legend handles = [] for config in Configurations: #print(configuration_color_map[config]) handles.append(Patch(label=ConfigurationNameMap[config], facecolor=ConfigurationColorMap[config])) # Add the markers to the legend handles.append(Line2D([], [], markeredgecolor='black', markerfacecolor='white', markersize=7, marker='^', linestyle='None', label='mean region size')) handles.append(Line2D([], [], markeredgecolor='black', markerfacecolor='black', markersize=6, marker='D', linestyle='None', label='max. region size')) # Place the legend axs[0, 0].legend(handles=handles, bbox_to_anchor=(0, 1.0, 1, 0), loc="lower left", ncol=5) # Add a single X-axis fig.add_subplot(111, frameon=False) plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False) #plt.xlabel('benchmark') # Place a text box explaining the significance of the numbers # Avg value explained props = dict(boxstyle='round', facecolor=Color['cyan'], alpha=0.2) text = '$\\bf{200}$ cycles\n' + \ '8MHz$\\rightarrow \\bf{25 \\, \\boldsymbol{\\mu}s}$\n' + \ '50MHz$\\rightarrow \\bf{4 \\boldsymbol{\\mu}s}$' plt.text(0.15, 0.1, text, transform=axs[1,2].transAxes, fontsize=9, verticalalignment='bottom', bbox=props) # Max value explained props = dict(boxstyle='round', facecolor=Color['cyan'], alpha=0.2) text = '$\\bf{45000}$ cycles\n' + \ '8MHz$\\rightarrow\\bf{5.6ms}$\n' + \ '50MHz$\\rightarrow\\bf{0.9ms}$' plt.text(0.15, 0.1, text, transform=axs[1,5].transAxes, fontsize=9, verticalalignment='bottom', bbox=props) # Show the plot plt.show() # - # Save the figure #fig = bars.get_figure() fig.savefig('plots/benchmark-region-size.pdf') # # # TWO ROW VERSION # # # + group_spacing = 1 bar_spacing = 0.2 bar_width = 0.15 def plotit(data, plot_type): plt.clf() fig, axs = plt.subplots(2, 3, sharex=False, figsize=(7,2.5), gridspec_kw={'height_ratios': [1.8, 5]}) plt.subplots_adjust(hspace=0.1) for gidx, bench in enumerate(data): #print('Analyzing bench', bench) for idx, config in enumerate(data[bench]): #print(' config:', config) pos = idx*bar_spacing #print(' pos:', pos) #data[bench][config].boxplot(notch=True, ax=ax, widths=bar_width, positions=[pos], showfliers=False, labels=['test']) b = axs[1, gidx].boxplot(data[bench][config], notch=True, patch_artist=True, widths=bar_width, positions=[pos], showfliers=False, labels=[ConfigurationNameMap[config]], showmeans=True, boxprops=dict(facecolor=ConfigurationColorMap[config], linewidth=1), medianprops=dict(color='white', linewidth=2), meanprops=dict(color='black', markeredgecolor='black', markerfacecolor='white', markersize=7) ) groups = len(data) bar_per_group = len(data[next(iter(data))]) xlim = [-0.18, 0.7] for gidx, bench in enumerate(data): axs[0, gidx].set_axis_on axs[0, gidx].axes.xaxis.set_visible(False) #axs[0, gidx].axes.yaxis.set_visible(False) axs[0, gidx].axes.yaxis.set_ticks([]) axs[0, gidx].set_ylim(0,1) axs[1, gidx].set_xlim(xlim) axs[1, gidx].set_ylim(0, None) axs[1, gidx].spines['right'].set_visible(False) axs[1, gidx].spines['top'].set_visible(False) axs[0, gidx].set_xlim(xlim) axs[0, gidx].spines['right'].set_visible(False) axs[0, gidx].spines['top'].set_visible(False) axs[0, gidx].spines['bottom'].set_linestyle('--') axs[0, gidx].spines['bottom'].set_alpha(0.5) #pos = (bar_per_group-1)/2*bar_spacing pos = (xlim[0]+xlim[1])/2 xticks = [] xlabels = [] xticks.append(pos) xlabels.append(BenchmarkNameMap[bench]) axs[1, gidx].set_xticks(xticks) axs[1, gidx].set_xticklabels(xlabels) axs[1, gidx].xaxis.set_ticks_position('none') axs[1, gidx].yaxis.set_major_locator(plt.MaxNLocator(5)) # Build the outlier dots in axtop dot_y = 0.5 for gidx, bench in enumerate(data): for idx, config in enumerate(data[bench]): pos = idx*bar_spacing maxval = data[bench][config]['delta'].max() #print(' pos:', pos) #print(' max:', maxval) if (idx % 2) == 0: ytext = 10 else: ytext = -12 axs[0, gidx].plot([pos], [dot_y], 'D', color=ConfigurationColorMap[config]) axs[0, gidx].annotate("{:d}".format(maxval), xy=(pos, dot_y),xytext=(0,ytext), xycoords=('data'), textcoords='offset points', horizontalalignment='center', verticalalignment='center') #axs[0, 0].set_ylabel('max\nx$10^3$') axs[0, 0].set_ylabel('max') axs[1, 0].set_ylabel('idempotent region size\n(clock cycles)') #axs[1, 0].set_ylabel('idemp. reg. size (clock cycles)') # Add a single X-axis fig.add_subplot(111, frameon=False) plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False) #plt.xlabel('benchmark') if plot_type == 'top': # Place a text box explaining the significance of the numbers # Avg value explained props = dict(boxstyle='round', facecolor=Color['cyan'], alpha=0.2) #text = '$\\bf{200}$ cycles\n' + \ # '8MHz$\\rightarrow \\bf{25 \\, \\boldsymbol{\\mu}s}$\n' + \ # '50MHz$\\rightarrow \\bf{4 \\boldsymbol{\\mu}s}$' #plt.text(0.15, 0.1, text, transform=axs[1,2].transAxes, fontsize=13, # verticalalignment='bottom', bbox=props) text = '$\\bf{200}$ clock cycles\n' + \ r'8\,MHz$\rightarrow \bf{25 \boldsymbol{\mu}s}$'+'\n' + \ r'50\,MHz$\rightarrow \bf{4 \boldsymbol{\mu}s}$' plt.text(0.15, 0.05, text, transform=axs[1,2].transAxes, fontsize=11, verticalalignment='bottom', bbox=props) #text = '$\\bf{45000}$ clock cycles\n' + \ # r'8\,MHz$\rightarrow\bf{5.6ms}$'+'\n' + \ # r'50\,MHz$\rightarrow\bf{0.9ms}$' #plt.text(0.1, 0.05, text, transform=axs[1,2].transAxes, fontsize=12, # verticalalignment='bottom', bbox=props) # Place the legend (only on the top) # Add the legend handles = [] for config in Configurations: #print(configuration_color_map[config]) handles.append(Patch(label=ConfigurationNameMap[config], facecolor=ConfigurationColorMap[config])) # Add the markers to the legend # Spacer legend handles.append(Line2D([], [], markeredgecolor='white', markerfacecolor='white', markersize=7, marker=None, linestyle='None', label='')) handles.append(Line2D([], [], markeredgecolor='black', markerfacecolor='white', markersize=7, marker='^', linestyle='None', label='average region size')) handles.append(Line2D([], [], markeredgecolor='black', markerfacecolor='black', markersize=6, marker='D', linestyle='None', label='maximum region size')) axs[0, 0].legend(handles=handles, bbox_to_anchor=(0, 1.0, 1, 0), loc="lower left", ncol=3, fontsize=11) if plot_type == 'bottom': # Max value explained props = dict(boxstyle='round', facecolor=Color['cyan'], alpha=0.2) text = '$\\bf{45000}$ cycles\n' + \ '8MHz$\\rightarrow\\bf{5.6ms}$\n' + \ '50MHz$\\rightarrow\\bf{0.9ms}$' plt.text(0.15, 0.05, text, transform=axs[1,2].transAxes, fontsize=11, verticalalignment='bottom', bbox=props) # Show the plot #fig.subplots_adjust(top=6) # or whatever plt.show() fig.savefig('plots/benchmark-region-size-'+plot_type+'.pdf',bbox_inches='tight') data_top = {} data_top['coremark'] = data['coremark'] data_top['sha'] = data['sha'] data_top['crc'] = data['crc'] data_bot = {} data_bot['aes'] = data['aes'] data_bot['dijkstra'] = data['dijkstra'] data_bot['picojpeg'] = data['picojpeg'] # - plotit(data_top, 'top') plotit(data_bot, 'bottom')
plotting/CallFrequencyPlot.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] raw_mimetype="text/restructuredtext" # .. _nb_perm: # + [markdown] raw_mimetype="text/restructuredtext" # # Permutations # - # Permutations are a very special type where each integer value occurs only once. Your algorithm to solve your optimization problem efficiently might need some customization regarding the evolutionary operators. # # In the following, two examples for permutation problems shall be provided. # ## Traveling Salesman Problem (TSP) # The traditional traveling salesman problems aims to minimize the time to travel to visit each city exactly once. # Since a permutation can start with an arbitrary number it is advisable to avoid oranges with apples and to repair each individual to start with the index `0`. Therefore, let us define a `Repair` operator as follows: # + import numpy as np from pymoo.model.repair import Repair class StartFromZeroRepair(Repair): def _do(self, problem, pop, **kwargs): X = pop.get("X") I = np.where(X == 0)[1] for k in range(len(X)): i = I[k] x = X[k] _x = np.concatenate([x[i:], x[:i]]) pop[k].set("X", _x) return pop # - # For the permutations the corresponding operators need to be supplied to the `GA` constructor. Here, we choose random permutations, edge recombination crossover and inversion mutation. Also, the repair defined above is provided. # The termination is defined to consider the improvement of the last 200 generations. If the improvement is above a tolerance value (default: `f_tol=1e-6`) the algorithm is considered as terminated. # + from pymoo.algorithms.so_genetic_algorithm import GA from pymoo.optimize import minimize from pymoo.factory import get_algorithm, get_crossover, get_mutation, get_sampling from pymoo.problems.single.traveling_salesman import create_random_tsp_problem from pymoo.util.termination.default import SingleObjectiveDefaultTermination problem = create_random_tsp_problem(30, 100, seed=1) algorithm = GA( pop_size=20, sampling=get_sampling("perm_random"), crossover=get_crossover("perm_erx"), mutation=get_mutation("perm_inv"), repair=StartFromZeroRepair(), eliminate_duplicates=True ) # if the algorithm did not improve the last 200 generations then it will terminate (and disable the max generations) termination = SingleObjectiveDefaultTermination(n_last=200, n_max_gen=np.inf) res = minimize( problem, algorithm, termination, seed=1, ) # - print("Traveling Time:", np.round(res.F[0], 3)) print("Function Evaluations:", res.algorithm.evaluator.n_eval) from pymoo.problems.single.traveling_salesman import visualize visualize(problem, res.X) # ## Flowshop Schedule # This problem is purely optimization the permutations and the initial value is not of importance. # + from pymoo.problems.single.flowshop_scheduling import create_random_flowshop_problem problem = create_random_flowshop_problem(n_machines=5, n_jobs=10, seed=1) algorithm = GA( pop_size=20, eliminate_duplicates=True, sampling=get_sampling("perm_random"), crossover=get_crossover("perm_ox"), mutation=get_mutation("perm_inv"), ) termination = SingleObjectiveDefaultTermination(n_last=50, n_max_gen=10000) res = minimize( problem, algorithm, termination, seed=1 ) # - print("Maximum Span:", np.round(res.F[0], 3)) print("Function Evaluations:", res.algorithm.evaluator.n_eval) from pymoo.problems.single.flowshop_scheduling import visualize visualize(problem, res.X) # <sub>This implementation is based on a contribution made by [Peng-YM](https://github.com/Peng-YM).</sub>
doc/source/customization/permutation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Activation from keras.layers import Conv2D, MaxPooling2D from keras import backend as K from keras.layers.normalization import BatchNormalization import matplotlib.pyplot as plt import numpy as np from sklearn.externals import joblib import pandas as pd from sklearn.model_selection import train_test_split import os import glob import scipy import cv2 as cv # + our_own_dataset = [] # load the png image data for image_file_name in glob.glob('nepali_characters/*/*/*.jpg'): # use the filename to set the correct label label = int(image_file_name[-14:-11]) # load image data from png files into an array print ("loading ... ", image_file_name) img_array = cv.imread(image_file_name, 0) #Read an image from a file as an array (thresh, image_array) = cv.threshold(img_array, 128, 255, cv.THRESH_BINARY | cv.THRESH_OTSU) # reshape from 28x28 to list of 784 values, invert values # img_data = (255.0 - img_array.reshape(784))/255.0 # then scale data to range from 0.01 to 1.0 # img_data = (img_data / 255.0 * 0.99) + 0.01 # print(np.min(img_data)) # print(np.max(img_data)) # append label and image data to test data set record = np.append(label,image_array) our_own_dataset.append(record) # - data = np.array(our_own_dataset) np.random.shuffle(data) xx = pd.DataFrame(data) xx.tail() x = np.array(xx) X = x[:,1:] y = x[:,0] x.shape # X = data_pd.iloc[:,1:] # y = data_pd.iloc[:,0:1].values X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,stratify = y) # X_train = X_train.reshape(X_train.shape[0], 1, 36, 36).astype('float32') # X_test = X_test.reshape(X_test.shape[0], 1, 36, 36).astype('float32') img_rows = img_cols = 36 X_train = X_train.reshape(X_train.shape[0], img_cols, img_rows, 1) X_test = X_test.reshape(X_test.shape[0], img_cols, img_rows, 1) # + # if K.image_data_format() == 'channels_first': # x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) # x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) # input_shape = (1, img_rows, img_cols) # else: # x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) # x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) # input_shape = (img_rows, img_cols, 1) # x_train = x_train.astype('float32') # x_test = x_test.astype('float32') # x_train /= 255 # x_test /= 255 # print('x_train shape:', x_train.shape) # print(x_train.shape[0], 'train samples') # print(x_test.shape[0], 'test samples') # # convert class vectors to binary class matrices # y_train = keras.utils.to_categorical(y_train, num_classes) # y_test = keras.utils.to_categorical(y_test, num_classes) print("X_train shape", X_train.shape) print("y_train shape", y_train.shape) print("X_test shape", X_test.shape) print("y_test shape", y_test.shape) # building the input vector from the 28x28 pixels X_train = X_train.astype('float32') X_test = X_test.astype('float32') # normalizing the data to help with the training X_train /= 255 X_test /= 255 # print the final input shape ready for training print("Train matrix shape", X_train.shape) print("Test matrix shape", X_test.shape) # - # one-hot encoding using keras' numpy-related utilities n_classes = 58 print("Shape before one-hot encoding: ", y_train.shape) Y_train = keras.utils.to_categorical(y_train, n_classes) Y_test = keras.utils.to_categorical(y_test, n_classes) print("Shape after one-hot encoding: ", Y_train.shape) # + # model = Sequential() # model.add(Dense(256, input_shape=(1296,))) # model.add(Activation('relu')) # model.add(Dropout(0.2)) # model.add(Dense(192)) # model.add(Activation('relu')) # model.add(Dropout(0.2)) # model.add(Dense(128)) # model.add(Activation('relu')) # model.add(Dropout(0.2)) # model.add(Dense(58)) # model.add(Activation('softmax')) # define the larger model def larger_model(): # create model model = Sequential() model.add(Conv2D(10, (5, 5), strides=(1,1), input_shape=(36, 36, 1), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2), strides = (2,2))) model.add(Dropout(0.2)) model.add(Conv2D(20, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(64, activation='relu')) model.add(Dense(58, activation='softmax')) # Compile model # model.add(Conv2D(72, kernel_size=(5, 5), strides=(1, 1),activation='relu',input_shape=(36,36,1))) # model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) # model.add(Conv2D(64, (5, 5), activation='relu')) # model.add(MaxPooling2D(pool_size=(2, 2))) # model.add(Flatten()) # model.add(Dense(1000, activation='relu')) # model.add(Dense(58, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model # - # build the model model = larger_model() # + # model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam') # + history = model.fit(X_train, Y_train, batch_size=100, epochs=30, verbose=2, validation_data=(X_test, Y_test)) # saving the model save_dir = "./" model_name = 'model_cnn.h5' model_path = os.path.join(save_dir, model_name) model.save(model_path) print('Saved trained model at %s ' % model_path) # plotting the metrics fig = plt.figure() plt.subplot(2,1,1) plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='lower right') plt.subplot(2,1,2) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper right') plt.tight_layout() fig # - # # # + #get the predictions for the test data predicted_classes = model.predict_classes(X_test) #get the indices to be plotted correct = np.nonzero(predicted_classes==y_test)[0] incorrect = np.nonzero(predicted_classes!=y_test)[0] # - from sklearn.metrics import classification_report target_names = ["Class {}".format(i) for i in range(58)] print(classification_report(y_test, predicted_classes, target_names=target_names)) for i, correct in enumerate(correct[:9]): plt.subplot(3,3,i+1) plt.imshow(X_test[correct].reshape(36,36), cmap='gray', interpolation='none') plt.title("Predicted {}, Class {}".format(predicted_classes[correct], y_test[correct])) plt.tight_layout() for i, incorrect in enumerate(incorrect[0:9]): plt.subplot(3,3,i+1) plt.imshow(X_test[incorrect].reshape(36,36), cmap='gray', interpolation='none') plt.title("Predicted {}, Class {}".format(predicted_classes[incorrect], y_test[incorrect])) plt.tight_layout() test_im = X_train[154] plt.imshow(test_im.reshape(36,36), cmap='autumn', interpolation='none') plt.show()
CNN.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Calculate NDVI # # The Normalized Difference Vegetation Index (NDVI) is a standard calculation frequently used to analyze ecological remote sensing data. In short, the NDVI indicates whether the remotely-sensed target contains live green vegetation. When sunlight strikes objects, certain wavelengths of this spectrum are absorbed and other wavelengths are reflected. The pigment chlorophyll in plant leaves strongly absorbs visible light (with wavelengths in the range of 400-700 nm) for use in photosynthesis. The cell structure of the leaves, however, strongly reflects near-infrared light (wavelengths ranging from 700 - 1100 nm). Plants reflect up to 60% more light in the near infrared portion of the spectrum than they do in the green portion of the spectrum. By comparing the ratio of Near Infrared (NIR) to Visible (VIS) bands in hyperspectral data, we can obtain a quick look at vegetation in the region of interest. NDVI is a normalized measure of the difference between reflectance at near infrared and visible bands of the electromagnetic spectrum. # # The formula for NDVI is: $$NDVI = \frac{(NIR - VIS)}{(NIR+ VIS)}$$ # # <p> # <img src="files/ndvi_tree.png" style="width: 250px;"/> # <center><font size="2">Figure: (Wu et al. 2014)</font></center> # <center><font size="2">https://www.researchgate.net/figure/266947355_fig1_Figure-1-Green-vegetation-left-absorbs-visible-light-and-reflects-near-infrared-light</font></center> # </p> # # ### Load neon_aop.py module # + # # %load ../neon_aop.py """ Created on Wed Feb 8 10:06:25 2017 @author: bhass """ # # %load ./neon_aop_python.py """ Created on Mon Feb 6 16:36:10 2017 @author: bhass """ import numpy as np import matplotlib.pyplot as plt import h5py, gdal, osr, copy #list_dataset lists the names of datasets in an hdf5 file #call syntax: f.visititems(list_dataset) def list_dataset(name,node): if isinstance(node, h5py.Dataset): print(name) #ls_dataset displays the name, shape, and type of datasets in hdf5 file #call syntax: f.visititems(ls_dataset) def ls_dataset(name,node): if isinstance(node, h5py.Dataset): print(node) def h5refl2array(refl_filename,sitename): hdf5_file = h5py.File(refl_filename,'r') refl = hdf5_file[sitename]['Reflectance'] reflArray = refl['Reflectance_Data'] refl_shape = reflArray.shape wavelengths = refl['Metadata']['Spectral_Data']['Wavelength'] #Create metadata dictionary metadata = {} metadata['shape'] = reflArray.shape metadata['mapInfo'] = refl['Metadata']['Coordinate_System']['Map_Info'] #Extract no data value & set no data value to NaN metadata['noDataVal'] = float(reflArray.attrs['Data_Ignore_Value']) metadata['scaleFactor'] = float(reflArray.attrs['Scale_Factor']) metadata['projection'] = refl['Metadata']['Coordinate_System']['Proj4'].value metadata['EPSG'] = int(refl['Metadata']['Coordinate_System']['EPSG Code'].value) mapInfo = refl['Metadata']['Coordinate_System']['Map_Info'].value mapInfo_string = str(mapInfo); #print('Map Info:',mapInfo_string) mapInfo_split = mapInfo_string.split(",") #Extract the resolution & convert to floating decimal number metadata['res'] = {} metadata['res']['pixelWidth'] = mapInfo_split[5] metadata['res']['pixelHeight'] = mapInfo_split[6] #Extract the upper left-hand corner coordinates from mapInfo xMin = float(mapInfo_split[3]) yMax = float(mapInfo_split[4]) #Calculate the xMax and yMin values from the dimensions #xMax = left corner + (# of columns * resolution) xMax = xMin + (refl_shape[1]*float(metadata['res']['pixelWidth'])) yMin = yMax - (refl_shape[0]*float(metadata['res']['pixelHeight'])) metadata['extent'] = (xMin,xMax,yMin,yMax) metadata['ext_dict'] = {} metadata['ext_dict']['xMin'] = xMin metadata['ext_dict']['xMax'] = xMax metadata['ext_dict']['yMin'] = yMin metadata['ext_dict']['yMax'] = yMax return reflArray, metadata, wavelengths def extract_raw_band(reflArray,reflArray_metadata,band_ind): bandArray = reflArray[:,:,band_ind-1].astype(np.float) return bandArray def extract_clean_band(reflArray,reflArray_metadata,band_ind): bandArray = reflArray[:,:,band_ind-1].astype(np.float) bandCleaned = copy.copy(bandArray) bandCleaned[bandCleaned==int(reflArray_metadata['noDataVal'])]=np.nan bandCleaned = bandCleaned/reflArray_metadata['scaleFactor'] return bandCleaned def subset_clean_band(reflArray,reflArray_metadata,clipIndex,bandIndex): bandSubCleaned = reflArray[clipIndex['yMin']:clipIndex['yMax'],clipIndex['xMin']:clipIndex['xMax'],bandIndex-1].astype(np.float) bandSubCleaned[bandSubCleaned==int(reflArray_metadata['noDataVal'])]=np.nan bandSubCleaned = bandSubCleaned/reflArray_metadata['scaleFactor'] return bandSubCleaned def subset_clean_refl(reflArray,reflArray_metadata,clipIndex): reflSubCleaned = reflArray[clipIndex['yMin']:clipIndex['yMax'],clipIndex['xMin']:clipIndex['xMax'],:].astype(np.float) reflSubCleaned[reflSubCleaned==int(reflArray_metadata['noDataVal'])]=np.nan reflSubCleaned = reflSubCleaned/reflArray_metadata['scaleFactor'] return reflSubCleaned # def plot_flightline_band(band_array,refl_extent,size=(6,6),title='',cmap_title='',colormap='spectral'): # fig = plt.figure(figsize=size) # plot = plt.imshow(band_array,extent=refl_extent); # cbar = plt.colorbar(plot,aspect=40); plt.set_cmap(colormap); # cbar.set_label(cmap_title,rotation=90,labelpad=20) # plt.title(title); ax = plt.gca(); # ax.ticklabel_format(useOffset=False, style='plain') #do not use scientific notation # # rotatexlabels = plt.setp(ax.get_xticklabels(),rotation=90) #rotate x tick labels 90 degrees def plot_band_array(band_array,refl_extent,title='',cmap_title='',colormap='spectral'): plot = plt.imshow(band_array,extent=refl_extent); cbar = plt.colorbar(plot); plt.set_cmap(colormap); cbar.set_label(cmap_title,rotation=90,labelpad=20) plt.title(title); ax = plt.gca(); ax.ticklabel_format(useOffset=False, style='plain') #do not use scientific notation # rotatexlabels = plt.setp(ax.get_xticklabels(),rotation=90) #rotate x tick labels 90 degrees def array2raster(newRaster,reflBandArray,reflArray_metadata,epsg): cols = reflBandArray.shape[1] rows = reflBandArray.shape[0] pixelWidth = float(reflArray_metadata['res']['pixelWidth']) pixelHeight = -float(reflArray_metadata['res']['pixelHeight']) originX = reflArray_metadata['ext_dict']['xMin'] originY = reflArray_metadata['ext_dict']['yMax'] driver = gdal.GetDriverByName('GTiff') outRaster = driver.Create('hopb_b56.tif', cols, rows, 1, gdal.GDT_Byte) outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight)) outband = outRaster.GetRasterBand(1) outband.WriteArray(reflBandArray) outRasterSRS = osr.SpatialReference() outRasterSRS.ImportFromEPSG(epsg) #4326 = WGS84 outRaster.SetProjection(outRasterSRS.ExportToWkt()) outband.FlushCache() def calc_clip_index(clipExtent, h5Extent, xscale=1, yscale=1): #Define a dictionary for the index extent (ind_ext): h5rows = h5Extent['yMax'] - h5Extent['yMin'] h5cols = h5Extent['xMax'] - h5Extent['xMin'] ind_ext = {} ind_ext['xMin'] = round((clipExtent['xMin']-h5Extent['xMin'])/xscale) ind_ext['xMax'] = round((clipExtent['xMax']-h5Extent['xMin'])/xscale) ind_ext['yMax'] = round(h5rows - (clipExtent['yMin']-h5Extent['yMin'])/xscale) ind_ext['yMin'] = round(h5rows - (clipExtent['yMax']-h5Extent['yMin'])/yscale) return ind_ext def stack_bands(reflArray,reflArray_metadata,bands): band_clean_dict = {} band_clean_names = [] stackedArray = np.zeros((reflArray.shape[0],reflArray.shape[1],len(bands)),'uint8') #pre-allocate stackedArray matrix for i in range(len(bands)): band_clean_names.append("b"+str(bands[i])+"_refl_clean") band_clean_dict[band_clean_names[i]] = extract_clean_band(reflArray,reflArray_metadata,bands[i]) stackedArray[...,i] = band_clean_dict[band_clean_names[i]]*256 return stackedArray def stack_subset_bands(reflArray,reflArray_metadata,bands,clipIndex): band_clean_dict = {} band_clean_names = [] subArray_rows = clipIndex['yMax'] - clipIndex['yMin'] subArray_cols = clipIndex['xMax'] - clipIndex['xMin'] stackedArray = np.zeros((subArray_rows,subArray_cols,len(bands)),'uint8') #pre-allocate stackedArray matrix for i in range(len(bands)): band_clean_names.append("b"+str(bands[i])+"_refl_clean") band_clean_dict[band_clean_names[i]] = subset_clean_band(reflArray,reflArray_metadata,clipIndex,bands[i]) stackedArray[...,i] = band_clean_dict[band_clean_names[i]]*256 return stackedArray # - # ## Read in SERC Flightline & Subset # + #Define inputs filename = '../data/SERC/hyperspectral/NEON_D02_SERC_DP1_20160807_160559_reflectance.h5' sercRefl, sercRefl_md, wavelengths = h5refl2array(filename,'SERC') clipExtDict = {} clipExtDict['xMin'] = 367400. clipExtDict['xMax'] = 368100. clipExtDict['yMin'] = 4305750. clipExtDict['yMax'] = 4306350. clipExtent = (clipExtDict['xMin'],clipExtDict['xMax'],clipExtDict['yMin'],clipExtDict['yMax']) clipIndex = calc_clip_index(clipExtDict,sercRefl_md['ext_dict']) sercReflSubset = subset_clean_refl(sercRefl,sercRefl_md,clipIndex) # - # ## Stack NIR and VIS bands # # Now that we have uploaded all the required functions, we can calculate NDVI and plot it. # We will compute NDVI using bands 58 and 90. These correspond to wavelength ranges of: # $$band 60: \lambda_{VIS} = 666.6-671.6 nm$$ $$band 83: \lambda_{NIR} = 826.8-831.9 nm$$. # + #Select bands to be used in the NDVI calculation ndvi_bands = (58,90) #NIR and VIS (Red) bands #Check the center wavelengths that these bands represent band_width = wavelengths.value[1]-wavelengths.value[0] print('band 58 wavelength range: ' + str(round(wavelengths.value[57]-band_width/2,2)) + '-' + str(round(wavelengths.value[57]+band_width/2,2)) + ' nm') print('band 90 wavelength range: ' + str(round(wavelengths.value[89]-band_width/2,2)) + '-' + str(round(wavelengths.value[89]+band_width/2,2)) + ' nm') #Use the stack_subset_bands function to create a stack of the subsetted red and NIR bands needed to calculate NDVI ndvi_stack = stack_subset_bands(sercRefl,sercRefl_md,ndvi_bands,clipIndex) # - # # Calculate NDVI & Plot # + vis = ndvi_stack[:,:,0].astype(float) nir = ndvi_stack[:,:,1].astype(float) #the numpy divide function divides the array element by element # if the denominator (nir+vis) = 0, set the answer to be zero ndvi = np.divide((nir-vis),(nir+vis),out=np.zeros_like(nir-vis),where=(nir+vis)!=0) # print(ndvi) # %matplotlib inline import warnings warnings.filterwarnings('ignore') plot_band_array(ndvi,clipExtent,title='SERC Subset NDVI \n (VIS = Band 58, NIR = Band 90)',cmap_title='NDVI',colormap='seismic') # plot_band_array(ndvi,clipExtent,'NDVI (VIS = Band 58, NIR = Band 90)') # - # # Extract Spectra Using Masks # # In the second part of this tutorial, we will learn how to extract the spectra of pixels whose NDVI exceeds a specified threshold value. There are several ways to do this using `numpy`, including the mask functions `numpy.ma`, as well as `numpy.where` and finally using `boolean` indexing. # # To start, lets copy the NDVI calculated above and use booleans to create an array only containing NDVI > 0.6. # + import copy ndvi_gtpt6 = copy.copy(ndvi) ndvi_gtpt6[ndvi<0.6] = np.nan #set all pixels with NDVI < 0.6 to nan, keeping only values > 0.6 print('Mean NDVI > 0.6:',round(np.nanmean(ndvi_gtpt6),2)) plot_band_array(ndvi_gtpt6,clipExtent,title='SERC Subset NDVI > 0.6 \n (VIS = Band 58, NIR = Band 90)', cmap_title='NDVI',colormap='RdYlGn') # - # # Function to calculate the mean spectra for reflectance values thresholed by NDVI using `numpy.ma`: # %pdb # + ## FOR SOME REASON THIS FUNCTION DOESN'T WORK WHEN THE NDVI THRESHOLD IS ZERO ?? --> MEAN_MASKED_REFL = NaN ## BUT SEEMS TO WORK OTHERWISE import numpy.ma as ma def calculate_mean_masked_spectra(reflArray,ndvi,ndvi_threshold,ineq='>'): mean_masked_refl = np.zeros(reflArray.shape[2]) for i in np.arange(reflArray.shape[2]): refl_band = reflArray[:,:,i] if ineq == '>': ndvi_mask = ma.masked_where(ndvi<ndvi_threshold,ndvi) elif ineq == '<': ndvi_mask = ma.masked_where(ndvi>ndvi_threshold,ndvi) else: print('ERROR: Invalid inequality. Enter < or >') masked_refl = ma.MaskedArray(refl_band,mask=ndvi_mask.mask) mean_masked_refl[i] = ma.mean(masked_refl) return mean_masked_refl # + sercRefl_ndvi_gt0 = calculate_mean_masked_spectra(sercReflSubset,ndvi,0.) ## > 0 DOESN'T WORK ?? sercRefl_ndvi_gtpt05 = calculate_mean_masked_spectra(sercReflSubset,ndvi,0.05) sercRefl_ndvi_gtpt6 = calculate_mean_masked_spectra(sercReflSubset,ndvi,0.6) sercRefl_ndvi_gtpt95 = calculate_mean_masked_spectra(sercReflSubset,ndvi,0.95) sercRefl_ndvi_lt0 = calculate_mean_masked_spectra(sercReflSubset,ndvi,-0.,ineq='<') ## < 0 DOESN'T WORK?? sercRefl_ndvi_ltnpt05 = calculate_mean_masked_spectra(sercReflSubset,ndvi,-0.05,ineq='<') import pandas #Remove water vapor band windows & last 10 bands w = copy.copy(wavelengths.value) w[((w >= 1340) & (w <= 1445)) | ((w >= 1790) & (w <= 1955))]=np.nan w[-10:]=np.nan; # the last 10 bands sometimes have noise - best to eliminate nan_ind = np.argwhere(np.isnan(w)) sercRefl_ndvi_gt0[nan_ind] = np.nan sercRefl_ndvi_gtpt05[nan_ind] = np.nan sercRefl_ndvi_gtpt6[nan_ind] = np.nan sercRefl_ndvi_gtpt95[nan_ind] = np.nan sercRefl_ndvi_lt0[nan_ind] = np.nan sercRefl_ndvi_ltnpt05[nan_ind] = np.nan #Create dataframe with masked NDVI mean spectra sercSpectra_ndvi_df = pandas.DataFrame() sercSpectra_ndvi_df['wavelength'] = w sercSpectra_ndvi_df['mean_refl_ndvi_gt0'] = sercRefl_ndvi_gt0 ##?? sercSpectra_ndvi_df['mean_refl_ndvi_gtpt05'] = sercRefl_ndvi_gtpt05 sercSpectra_ndvi_df['mean_refl_ndvi_gtpt6'] = sercRefl_ndvi_gtpt6 sercSpectra_ndvi_df['mean_refl_ndvi_gtpt95'] = sercRefl_ndvi_gtpt95 sercSpectra_ndvi_df['mean_refl_ndvi_lt0'] = sercRefl_ndvi_lt0 sercSpectra_ndvi_df['mean_refl_ndvi_ltnpt05'] = sercRefl_ndvi_ltnpt05 # + # sercSpectra_ndvi_df.plot(x='wavelength',y='mean_refl_ndvi_gt0',label='NDVI > 0',legend=True,color='yellow',edgecolor='none',kind='scatter'); # ax = plt.gca(); sercSpectra_ndvi_df.plot(x='wavelength',y='mean_refl_ndvi_gtpt05',label='NDVI > 0.05',legend=True,color='lightgreen',edgecolor='none',kind='scatter'); ax = plt.gca(); sercSpectra_ndvi_df.plot(ax=ax,x='wavelength',y='mean_refl_ndvi_gtpt6',color='green',edgecolor='none',kind='scatter',label='NDVI > 0.6',legend=True); sercSpectra_ndvi_df.plot(ax=ax,x='wavelength',y='mean_refl_ndvi_ltnpt05',color='red',edgecolor='none',kind='scatter',label='NDVI < -0.05',legend=True); ax.set_title('Mean Spectra of Reflectance Masked by NDVI') ax.set_xlim([np.nanmin(w),np.nanmax(w)]); ax.set_ylim(0,0.45) ax.set_xlabel("Wavelength, nm"); ax.set_ylabel("Reflectance") ax.grid('on'); # - # ## References # # <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, et al. (2014) Linking Student Performance in Massachusetts Elementary Schools with the “Greenness” of School Surroundings Using Remote Sensing. PLoS ONE 9(10): e108548. doi:10.1371/journal.pone.0108548
code/calculate_ndvi_extract_spectra_with_masks.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Environment (conda_anaconda3) # language: python # name: conda_anaconda3 # --- # + [markdown] tags=[] # # An Introduction to Linear Learner with MNIST # _**Making a Binary Prediction of Whether a Handwritten Digit is a 0**_ # # 1. [Introduction](#Introduction) # 2. [Prerequisites and Preprocessing](#Prequisites-and-Preprocessing) # 1. [Permissions and environment variables](#Permissions-and-environment-variables) # 2. [Data ingestion](#Data-ingestion) # 3. [Data inspection](#Data-inspection) # 4. [Data conversion](#Data-conversion) # 3. [Training the linear model](#Training-the-linear-model) # 4. [Set up hosting for the model](#Set-up-hosting-for-the-model) # 5. [Validate the model for use](#Validate-the-model-for-use) # # + [markdown] tags=[] # ## Introduction # # Welcome to our example introducing Amazon SageMaker's Linear Learner Algorithm! Today, we're analyzing the [MNIST](https://en.wikipedia.org/wiki/MNIST_database) dataset which consists of images of handwritten digits, from zero to nine. We'll use the individual pixel values from each 28 x 28 grayscale image to predict a yes or no label of whether the digit is a 0 or some other digit (1, 2, 3, ... 9). # # The method that we'll use is a linear binary classifier. Linear models are supervised learning algorithms used for solving either classification or regression problems. As input, the model is given labeled examples ( **`x`**, `y`). **`x`** is a high dimensional vector and `y` is a numeric label. Since we are doing binary classification, the algorithm expects the label to be either 0 or 1 (but Amazon SageMaker Linear Learner also supports regression on continuous values of `y`). The algorithm learns a linear function, or linear threshold function for classification, mapping the vector **`x`** to an approximation of the label `y`. # # Amazon SageMaker's Linear Learner algorithm extends upon typical linear models by training many models in parallel, in a computationally efficient manner. Each model has a different set of hyperparameters, and then the algorithm finds the set that optimizes a specific criteria. This can provide substantially more accurate models than typical linear algorithms at the same, or lower, cost. # # To get started, we need to set up the environment with a few prerequisite steps, for permissions, configurations, and so on. # + [markdown] tags=[] # ## Prequisites and Preprocessing # # The notebook works with *Data Science* kernel in SageMaker Studio. # # ### Permissions and environment variables # # _This notebook was created and tested on an ml.m4.xlarge notebook instance._ # # Let's start by specifying: # # - The S3 bucket and prefix that you want to use for training and model data. This should be within the same region as the Notebook Instance, training, and hosting. # - The IAM role arn used to give training and hosting access to your data. See the documentation for how to create these. Note, if more than one role is required for notebook instances, training, and/or hosting, please replace the boto regexp with a the appropriate full IAM role arn string(s). # + isConfigCell=true tags=["parameters"] import sagemaker bucket = sagemaker.Session().default_bucket() prefix = "sagemaker/DEMO-linear-mnist" # Define IAM role import boto3 import re from sagemaker import get_execution_role role = get_execution_role() # + [markdown] tags=[] # ### Data ingestion # # Next, we read the dataset from an online URL into memory, for preprocessing prior to training. This processing could be done *in situ* by Amazon Athena, Apache Spark in Amazon EMR, Amazon Redshift, etc., assuming the dataset is present in the appropriate location. Then, the next step would be to transfer the data to S3 for use in training. For small datasets, such as this one, reading into memory isn't onerous, though it would be for larger datasets. # + tags=[] # %%time import pickle, gzip, numpy, urllib.request, json fobj = boto3.client('s3').get_object( Bucket='sagemaker-sample-files', Key='datasets/image/MNIST/mnist.pkl.gz' )['Body'].read() with open('mnist.pkl.gz', 'wb') as f: f.write(fobj) # Load the dataset with gzip.open("mnist.pkl.gz", "rb") as f: train_set, valid_set, test_set = pickle.load(f, encoding="latin1") # + [markdown] tags=[] # ### Data inspection # # Once the dataset is imported, it's typical as part of the machine learning process to inspect the data, understand the distributions, and determine what type(s) of preprocessing might be needed. You can perform those tasks right here in the notebook. As an example, let's go ahead and look at one of the digits that is part of the dataset. # + tags=[] # %matplotlib inline import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (2, 10) def show_digit(img, caption="", subplot=None): if subplot == None: _, (subplot) = plt.subplots(1, 1) imgr = img.reshape((28, 28)) subplot.axis("off") subplot.imshow(imgr, cmap="gray") plt.title(caption) show_digit(train_set[0][30], "This is a {}".format(train_set[1][30])) # + [markdown] tags=[] # ### Data conversion # # Since algorithms have particular input and output requirements, converting the dataset is also part of the process that a data scientist goes through prior to initiating training. In this particular case, the Amazon SageMaker implementation of Linear Learner takes recordIO-wrapped protobuf, where the data we have today is a pickle-ized numpy array on disk. # # Most of the conversion effort is handled by the Amazon SageMaker Python SDK, imported as `sagemaker` below. # + tags=[] import io import numpy as np import sagemaker.amazon.common as smac vectors = np.array([t.tolist() for t in train_set[0]]).astype("float32") labels = np.where(np.array([t.tolist() for t in train_set[1]]) == 0, 1, 0).astype("float32") buf = io.BytesIO() smac.write_numpy_to_dense_tensor(buf, vectors, labels) buf.seek(0) # + [markdown] tags=[] # ## Upload training data # Now that we've created our recordIO-wrapped protobuf, we'll need to upload it to S3, so that Amazon SageMaker training can use it. # + tags=[] import boto3 import os key = "recordio-pb-data" boto3.resource("s3").Bucket(bucket).Object(os.path.join(prefix, "train", key)).upload_fileobj(buf) s3_train_data = "s3://{}/{}/train/{}".format(bucket, prefix, key) print("uploaded training data location: {}".format(s3_train_data)) # + [markdown] tags=[] # Let's also setup an output S3 location for the model artifact that will be output as the result of training with the algorithm. # + tags=[] output_location = "s3://{}/{}/output".format(bucket, prefix) print("training artifacts will be uploaded to: {}".format(output_location)) # + [markdown] tags=[] # ## Training the linear model # # Once we have the data preprocessed and available in the correct format for training, the next step is to actually train the model using the data. Since this data is relatively small, it isn't meant to show off the performance of the Linear Learner training algorithm, although we have tested it on multi-terabyte datasets. # # Again, we'll use the Amazon SageMaker Python SDK to kick off training, and monitor status until it is completed. In this example that takes between 7 and 11 minutes. Despite the dataset being small, provisioning hardware and loading the algorithm container take time upfront. # # First, let's specify our containers. Since we want this notebook to run in all 4 of Amazon SageMaker's regions, we'll create a small lookup. More details on algorithm containers can be found in [AWS documentation](https://docs-aws.amazon.com/sagemaker/latest/dg/sagemaker-algo-docker-registry-paths.html). # + tags=[] from sagemaker.image_uris import retrieve container = retrieve("linear-learner", boto3.Session().region_name) # + [markdown] tags=[] # Next we'll kick off the base estimator, making sure to pass in the necessary hyperparameters. Notice: # - `feature_dim` is set to 784, which is the number of pixels in each 28 x 28 image. # - `predictor_type` is set to 'binary_classifier' since we are trying to predict whether the image is or is not a 0. # - `mini_batch_size` is set to 200. This value can be tuned for relatively minor improvements in fit and speed, but selecting a reasonable value relative to the dataset is appropriate in most cases. # + jupyter={"outputs_hidden": true} tags=[] import boto3 sess = sagemaker.Session() linear = sagemaker.estimator.Estimator( container, role, train_instance_count=1, train_instance_type="ml.c4.xlarge", output_path=output_location, sagemaker_session=sess, ) linear.set_hyperparameters(feature_dim=784, predictor_type="binary_classifier", mini_batch_size=200) linear.fit({"train": s3_train_data}) # + [markdown] tags=[] # ## Set up hosting for the model # Now that we've trained our model, we can deploy it behind an Amazon SageMaker real-time hosted endpoint. This will allow out to make predictions (or inference) from the model dyanamically. # # _Note, Amazon SageMaker allows you the flexibility of importing models trained elsewhere, as well as the choice of not importing models if the target of model creation is AWS Lambda, AWS Greengrass, Amazon Redshift, Amazon Athena, or other deployment target._ # + tags=[] from sagemaker.serializers import CSVSerializer from sagemaker.deserializers import JSONDeserializer linear_predictor = linear.deploy( initial_instance_count=1, instance_type="ml.m4.xlarge", serializer=CSVSerializer(), deserializer=JSONDeserializer() ) # + [markdown] tags=[] # ## Validate the model for use # Finally, we can now validate the model for use. We can pass HTTP POST requests to the endpoint to get back predictions. To make this easier, we'll again use the Amazon SageMaker Python SDK and specify how to serialize requests and deserialize responses that are specific to the algorithm. # + [markdown] tags=[] # Now let's try getting a prediction for a single record. # + tags=[] result = linear_predictor.predict(train_set[0][30:31]) print(result) # + [markdown] tags=[] # OK, a single prediction works. We see that for one record our endpoint returned some JSON which contains `predictions`, including the `score` and `predicted_label`. In this case, `score` will be a continuous value between [0, 1] representing the probability we think the digit is a 0 or not. `predicted_label` will take a value of either `0` or `1` where (somewhat counterintuitively) `1` denotes that we predict the image is a 0, while `0` denotes that we are predicting the image is not of a 0. # # Let's do a whole batch of images and evaluate our predictive accuracy. # + tags=[] import numpy as np predictions = [] for array in np.array_split(test_set[0], 100): result = linear_predictor.predict(array) predictions += [r["predicted_label"] for r in result["predictions"]] predictions = np.array(predictions) # + tags=[] import pandas as pd pd.crosstab( np.where(test_set[1] == 0, 1, 0), predictions, rownames=["actuals"], colnames=["predictions"] ) # + [markdown] tags=[] # As we can see from the confusion matrix above, we predict 931 images of 0 correctly, while we predict 44 images as 0s that aren't, and miss predicting 49 images of 0. # + [markdown] tags=[] # ### (Optional) Delete the Endpoint # # If you're ready to be done with this notebook, please run the delete_endpoint line in the cell below. This will remove the hosted endpoint you created and avoid any charges from a stray instance being left on. # + tags=[] sagemaker.Session().delete_endpoint(linear_predictor.endpoint)
aws_sagemaker_studio/sagemaker_algorithms/linear_learner_mnist/linear_learner_mnist.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Optimal learning rates # # In this tutorial, we'll use the MedNIST dataset to explore MONAI's `LearningRateFinder` and use it to get an initial estimate of a learning rate. # # We then employ one of Pytorch's cyclical learning rate schedulers to vary the learning rate over the course of the optimisation. This has been shown to give improved results: https://arxiv.org/abs/1506.01186. We'll compare this to the optimiser's (ADAM) default learning rate and the learning rate suggested by `LearningRateFinder`. # # This 2D classification is fairly easy, so to make it a little harder (and faster), we'll use a small network, only a subset of the images (~250 and ~25 for training and validation, respectively), we'll crop the images (from 64x64 to 20x20) and we won't use any random transformations. In a more difficult scenario, we probably wouldn't want to do any of these things. # # [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Project-MONAI/tutorials/blob/master/modules/learning_rate.ipynb) # ## Setup environment # !python -c "import monai" || pip install -q monai[pillow, tqdm] # !python -c "import matplotlib" || pip install -q matplotlib # ## Setup imports # + tags=[] # Copyright 2020 MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil import tempfile import matplotlib.pyplot as plt import numpy as np import torch from monai.apps import MedNISTDataset from monai.config import print_config from monai.metrics import compute_roc_auc from monai.networks.nets import DenseNet from monai.networks.utils import eval_mode from monai.optimizers import LearningRateFinder from monai.transforms import ( AddChanneld, CenterSpatialCropd, Compose, LoadImaged, ScaleIntensityd, ToTensord, ) from monai.utils import set_determinism from torch.utils.data import DataLoader from tqdm import trange print_config() # - # ## Setup data directory # # You can specify a directory with the `MONAI_DATA_DIRECTORY` environment variable. # This allows you to save results and reuse downloads. # If not specified a temporary directory will be used. # + tags=[] directory = os.environ.get("MONAI_DATA_DIRECTORY") root_dir = tempfile.mkdtemp() if directory is None else directory print(root_dir) # - # ## Set deterministic training for reproducibility set_determinism(seed=0) # ## Define MONAI transforms and get dataset and data loader transforms = Compose( [ LoadImaged(keys="image"), AddChanneld(keys="image"), ScaleIntensityd(keys="image"), CenterSpatialCropd(keys="image", roi_size=(20, 20)), ToTensord(keys="image"), ] ) # + # Set fraction of images used for testing to be very high, then don't use it. In this way, we can reduce the number # of images in both train and val. Makes it faster and makes the training a little harder. def get_data(section): ds = MedNISTDataset( root_dir=root_dir, transform=transforms, section=section, download=True, num_workers=10, val_frac=0.0005, test_frac=0.995, ) loader = DataLoader(ds, batch_size=30, shuffle=True, num_workers=10) return ds, loader train_ds, train_loader = get_data("training") val_ds, val_loader = get_data("validation") print(len(train_ds)) print(len(val_ds)) print(train_ds[0]["image"].shape) num_classes = train_ds.get_num_classes() # - # ## Randomly pick images from the dataset to visualize and check # %matplotlib inline fig, axes = plt.subplots(3, 3, figsize=(15, 15), facecolor="white") for i, k in enumerate(np.random.randint(len(train_ds), size=9)): data = train_ds[k] im, title = data["image"], data["class_name"] ax = axes[i // 3, i % 3] im_show = ax.imshow(im[0]) ax.set_title(title, fontsize=25) ax.axis("off") # ## Define loss function and network # + device = "cuda" if torch.cuda.is_available() else "cpu" loss_function = torch.nn.CrossEntropyLoss() def get_new_net(): return DenseNet( spatial_dims=2, in_channels=1, out_channels=num_classes, init_features=2, growth_rate=2, block_config=(2,), ).to(device) model = get_new_net() # - # # Estimate optimal learning rate # # Use MONAI's `LearningRateFinder` to get an initial estimate of a learning rate. Assume that it's in the range 1e-5, 1e0. If that weren't the case (which we'd notice in the plot), we could just try again over a larger/different window. # # We can plot the results and extract the learning rate with the steepest gradient. # %matplotlib inline lower_lr, upper_lr = 1e-3, 1e-0 optimizer = torch.optim.Adam(model.parameters(), lower_lr) lr_finder = LearningRateFinder(model, optimizer, loss_function, device=device) lr_finder.range_test(train_loader, val_loader, end_lr=upper_lr, num_iter=20) steepest_lr, _ = lr_finder.get_steepest_gradient() ax = plt.subplots(1, 1, figsize=(15, 15), facecolor="white")[1] _ = lr_finder.plot(ax=ax) # ## Live plotting # # This function is just a wrapper around `range`/`trange` such that the plots are updated on every iteration. def plot_range(data, wrapped_generator): plt.ion() for q in data.values(): for d in q.values(): if isinstance(d, dict): ax = d["line"].axes ax.legend() fig = ax.get_figure() fig.show() for i in wrapped_generator: yield i for q in data.values(): for d in q.values(): if isinstance(d, dict): d["line"].set_data(d["x"], d["y"]) ax = d["line"].axes ax.legend() ax.relim() ax.autoscale_view() fig.canvas.draw() # ## Training # # The training looks slightly different from a vanilla loop, but this is only because it loops across each of the different learning rate methods (standard, steepest and cyclical), such that they can be updated simultaneously # + def get_model_optimizer_scheduler(d): d["model"] = get_new_net() if "lr_lims" in d: d["optimizer"] = torch.optim.Adam( d["model"].parameters(), d["lr_lims"][0] ) d["scheduler"] = torch.optim.lr_scheduler.CyclicLR( d["optimizer"], base_lr=d["lr_lims"][0], max_lr=d["lr_lims"][1], step_size_up=d["step"], cycle_momentum=False, ) elif "lr_lim" in d: d["optimizer"] = torch.optim.Adam(d["model"].parameters(), d["lr_lim"]) else: d["optimizer"] = torch.optim.Adam(d["model"].parameters()) def train(max_epochs, axes, data): for d in data.keys(): get_model_optimizer_scheduler(data[d]) for q, i in enumerate(["train", "auc", "acc"]): data[d][i] = {"x": [], "y": []} (data[d][i]["line"],) = axes[q].plot( data[d][i]["x"], data[d][i]["y"], label=d ) val_interval = 1 for epoch in plot_range(data, trange(max_epochs)): for d in data.keys(): data[d]["epoch_loss"] = 0 for batch_data in train_loader: inputs = batch_data["image"].to(device) labels = batch_data["label"].to(device) for d in data.keys(): data[d]["optimizer"].zero_grad() outputs = data[d]["model"](inputs) loss = loss_function(outputs, labels) loss.backward() data[d]["optimizer"].step() if "scheduler" in data[d]: data[d]["scheduler"].step() data[d]["epoch_loss"] += loss.item() for d in data.keys(): data[d]["epoch_loss"] /= len(train_loader) data[d]["train"]["x"].append(epoch + 1) data[d]["train"]["y"].append(data[d]["epoch_loss"]) if (epoch + 1) % val_interval == 0: with eval_mode(*[data[d]["model"] for d in data.keys()]): for d in data: data[d]["y_pred"] = torch.tensor( [], dtype=torch.float32, device=device ) y = torch.tensor([], dtype=torch.long, device=device) for val_data in val_loader: val_images = val_data["image"].to(device) val_labels = val_data["label"].to(device) for d in data: data[d]["y_pred"] = torch.cat( [data[d]["y_pred"], data[d]["model"](val_images)], dim=0, ) y = torch.cat([y, val_labels], dim=0) for d in data: auc_metric = compute_roc_auc( data[d]["y_pred"], y, to_onehot_y=True, softmax=True ) data[d]["auc"]["x"].append(epoch + 1) data[d]["auc"]["y"].append(auc_metric) acc_value = torch.eq(data[d]["y_pred"].argmax(dim=1), y) acc_metric = acc_value.sum().item() / len(acc_value) data[d]["acc"]["x"].append(epoch + 1) data[d]["acc"]["y"].append(acc_metric) # + # %matplotlib notebook fig, axes = plt.subplots(3, 1, figsize=(10, 10), facecolor="white") for ax in axes: ax.set_xlabel("Epoch") axes[0].set_ylabel("Train loss") axes[1].set_ylabel("AUC") axes[2].set_ylabel("ACC") # In the paper referenced at the top of this notebook, a step # size of 8 times the number of iterations per epoch is suggested. step_size = 8 * len(train_loader) max_epochs = 100 data = {} data["Default LR"] = {} data["Steepest LR"] = {"lr_lim": steepest_lr} data["Cyclical LR"] = { "lr_lims": (0.8 * steepest_lr, 1.2 * steepest_lr), "step": step_size, } train(max_epochs, axes, data) # - # ## Conclusion # # Unsurprisingly, both `Steepest LR` and `Cyclical LR` show quicker convergence of the loss function than `Default LR`. # # There's not much of a difference in this example between `Steepest LR` and `Cyclical LR`. A bigger difference may be apparent in a more complex optimisation problem, but feel free to play with the step size, and the lower and upper cyclical limits. # ## Cleanup data directory # # Remove directory if a temporary was used. if directory is None: shutil.rmtree(root_dir)
modules/learning_rate.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Python Tutorial: Basic Operator # author: [uJhin's GitHub](https://github.com/uJhin) # --- # + [markdown] toc=true # <h1>Table of Contents<span class="tocSkip"></span></h1> # <div class="toc"><ul class="toc-item"><li><span><a href="#Python-Tutorial:-Basic-Operator" data-toc-modified-id="Python-Tutorial:-Basic-Operator-1">Python Tutorial: Basic Operator</a></span><ul class="toc-item"><li><span><a href="#정수-계산하기" data-toc-modified-id="정수-계산하기-1.1">정수 계산하기</a></span><ul class="toc-item"><li><span><a href="#덧셈" data-toc-modified-id="덧셈-1.1.1">덧셈</a></span></li><li><span><a href="#뺄셈" data-toc-modified-id="뺄셈-1.1.2">뺄셈</a></span></li><li><span><a href="#곱셈" data-toc-modified-id="곱셈-1.1.3">곱셈</a></span><ul class="toc-item"><li><span><a href="#거듭제곱" data-toc-modified-id="거듭제곱-1.1.3.1">거듭제곱</a></span></li></ul></li><li><span><a href="#나눗셈" data-toc-modified-id="나눗셈-1.1.4">나눗셈</a></span><ul class="toc-item"><li><span><a href="#나눗셈:-몫" data-toc-modified-id="나눗셈:-몫-1.1.4.1">나눗셈: 몫</a></span></li><li><span><a href="#나눗셈:-나머지" data-toc-modified-id="나눗셈:-나머지-1.1.4.2">나눗셈: 나머지</a></span></li></ul></li></ul></li></ul></li></ul></div> # - # --- # ## 정수 계산하기 # 기본적인 사칙연산을 사용해 정수를 계산하여 파이썬 REPL에 바로 출력을 시켜보도록 하자. # ### 덧셈 1 + 1 # ### 뺄셈 10 - 2 # ### 곱셈 2 * 3 # #### 거듭제곱 2 ** 3 # ### 나눗셈 11 / 2 # #### 나눗셈: 몫 11 // 2 # #### 나눗셈: 나머지 11 % 2
python-tutorial/note/02. Python Tutorial - Basic Operator.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: conda_python3 # language: python # name: conda_python3 # --- # # UFO Modeling Lab # # <u>Use Case</u> # <p><NAME> wants to deploy a network of 10 sensors across the globe. He would like to locate these sensors in the center of the most likely locations for UFO sighting.</p> # # <u>Goal</u> # <p>build a model that will output 10 points (point = pair of {long,lat}) to place the sensors</p> # # <u>Table Of Contents</u> # 1. [Data Collection](#DC) # 1. [Assumptions](#assumptions) # 1. [Model Selection](#MS) # 1. [Feature Selection](#FS) # 1. [Handling Missing Values](#HMV) # 1. [EDA](#eda) # 1. [Data Preparation](#dp) # 1. [Modeling](#model) # 1. [Results](#results) # 1. [Summary](#summary) # # <u>Note</u> # <p>in every code cell that I'm using external libraries I'm importing it every time, although I can import all of them once on the start of the notebook, I wanted to show what libraries I'm using on every step</p> # ## Data Collection<a id='DC'></a> # ### Downloading a File from an S3 Bucket to Notebook instance<a id='S3To'></a> # + import boto3 import botocore BUCKET_NAME = '<PUT_HERE_THE_BUCKET_NAME>' KEY = 'ModelingLab - 2019/ufo_fullset.csv' s3 = boto3.resource('s3') try: s3.Bucket(BUCKET_NAME).download_file(KEY, 'ufo_fullset.csv') except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": print("The object does not exist.") else: raise # - # ### Load Data from CSV File to DataFrame using Pandas<a id='LoadData'></a> # + import pandas as pd data = pd.read_csv("ufo_fullset.csv") data.head() # - # <u>Feature Explanation</u> # <ul> # <li>reportedTimestamp: The date when the UFO sighting was reported</li> # <li>eventDate: The date when the UFO sighting happened</li> # <li>eventTime: The time when the UFO sighting happened (24 hour format)</li> # <li>latitude: The location where the UFO sighting happened</li> # <li>longitude: The location where the UFO sighting happened</li> # <li>shape: The shape of the UFO</li> # <li>duration: How many seconds the sighting happened</li> # <li>witnesses: The amount of witnesses that saw the UFO</li> # <li>weather: The weather when the sighting happened</li> # <li>firstName: The first name of the person who saw a UFO</li> # <li>lastName: The last name of the person who saw a UFO</li> # <li>sighting: If a UFO was sighted (is always Y = Yes)</li> # <li>physicalEvidence: Whether there was physical evidence left by UFO (Y = Yes, N = No)</li> # <li>contact: Whether there was contact by UFO beings (Y = Yes, N = No)</li> # <li>researchOutcome: Whether the experts had an explanation for sighting</li> # <ul> # <li>explained: There was some explanation to the sighting</li> # <li>unexplained: There was no explanation to the sighting</li> # <li>probable: There is enough evidence that the sighting were from extraterrestrials # </ul> # </ul> # ## Assumptions<a id='assumptions'></a> # <ul> # <li>it's an unsupervised clustering problem (discrete) - we will need to find 10 clusters without a given target data.</li> # ## Model Selection<a id='MS'></a> # <p>before run to do EDA, data cleansing/analyzing/preparing adventure I decided to select the model first and then I will know what data to use and how to prepare it.</p> # <p>we need a model to cluster each data point (latitude,longitude) to one of ten clusters, and return a center point for each of the cluster, these points will be our answer.</p> # <p>in clustering problems there are two approaches: Hierarchical clustering and Non-Hierarchical Clustering. we are in Non-Hierarchical Clustering, there are a lot of algorithms, and I decided to use K-Means, K-Medians, and K-Medoids that looks to me the best fit for our use case.</p> # <p>these algorethims aim to groups similar objects together (meaning, group data points in a way that minimize the distance between them and the group centroid). # K-Means calculating the <b>mean</b> for each cluster to determine its centroid, while K-Medians calculating the <b>median</b> for each cluster to determine its centroid, and K-Medoids chooses <b>one data point</b> form each cluster as the centroid. # </p> # # ### Notice: # <p> # <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/algos.html">Amazon SageMaker Built-in Algorithms</a> doesn't include K-Medians nor K-Medoids, so I will only use K-Means in this notebook. # </p> # ## Handling Missing Values<a id='HMV'></a> data.isnull().sum() # here are only 2 rows with missing data out of 18,000 records (around 0.01% of the data), dropping these rows will not cause any change in our final model. data=data.dropna(axis = 0, how ='any') data.isnull().values.any() # All missing values have been removed # ## Feature Selection<a id='FS'></a> # <p>now that we know we are going to use SageMaker built-in K-Means algorithm, and understand that the algorithm attempts to find discrete groupings within data, where members of a group are as similar as possible to one another and as different as possible from members of other groups. the only features that are reasonable to provide to the algorithm are 'latitude' and 'longitude', because we want the algorithm to group data points by a geographical closeness and not by sighting's shape/weather/witnesses number/the name of the person who saw the sighting/other.</p> # <p>but still there is a feature the I think we should take in account - 'researchOutcome', from my prospective not all the data point should treat equally, data point that with researchOutcome='probable' should be more importent than 'explained' or 'unexplained' and data point that with researchOutcome='unexplained' should be more importent than 'explained'.</p> # <p>therefor I have decided to do oversampling for 'unexplained' and 'probable', first let's see 'researchOutcome' distribution and decide how to oversample from each of the groups.</p> # ## Exploratory data analysis (EDA)<a id='eda'></a> data=data[['latitude','longitude','researchOutcome']] data['researchOutcome']=data['researchOutcome'].astype('category') # + # Distribution for researchOutcome import matplotlib.pyplot as plt import seaborn as sns sns.set_context("paper", font_scale=1.4) sns.countplot(x='researchOutcome',data=data) plt.show() # - # by the distribution for `researchOutcome` I have decided to mutiple each `researchOutcome`='probable' by 4 (oversample) and `researchOutcome`='unexplained' by 2, we want to give these points more weight but not too much that will totally change the dataset. # ## Data Preparation<a id='dp'></a> # + oversample_data=data.copy() # create more data points for 'probable' - add 3 copies of the dataset of point with researchOutcome='probable' data_to_oversample=oversample_data[oversample_data['researchOutcome']=='probable'] oversample_data=pd.concat([data_to_oversample,data_to_oversample,data_to_oversample,oversample_data],ignore_index=True) # create more data points for 'unexplained' - add 1 copies of the dataset of point with researchOutcome='unexplained' data_to_oversample=oversample_data[oversample_data['researchOutcome']=='unexplained'] oversample_data=pd.concat([data_to_oversample,oversample_data],ignore_index=True) # - # Distribution for researchOutcome with the new oversampled data sns.countplot(x='researchOutcome',data=oversample_data) plt.show() # ## Modeling<a id='model'></a> # I have decided to run 2 train jobs, one with the origin dataset on `latitude` and `longitude` features and the other with the oversample dataset on `latitude` and `longitude` features, and at the end I will compare the results. # # ### General Configuration for both of the Training Job in SageMaker # + # this code was written base on "https://docs.aws.amazon.com/sagemaker/latest/dg/k-means.html#kmeans-sample-notebooks" from sagemaker import get_execution_role from sagemaker.session import Session from sagemaker import KMeans role = get_execution_role() bucket='<PUT_HERE_THE_BUCKET_NAME>' num_of_clusters = 10 # - # ### Origin Dataset - Configuration # + output_folder_path = 'ModelingLab - 2019/original_dataset_output' output_location = 's3://{}/{}'.format(bucket,output_folder_path) #for 'train_instance_type' go to https://aws.amazon.com/sagemaker/pricing/instance-types/ kmeans_1 = KMeans(role=role, train_instance_count=1, train_instance_type='ml.p3.16xlarge', output_path=output_location, k=num_of_clusters) # - # convert our DataFrame to numpy.ndarray because kmeans.record_set() Build a RecordSet from a numpy ndarray matrix # https://sagemaker.readthedocs.io/en/stable/kmeans.html data_numpy_1=data[['longitude','latitude']].to_numpy(dtype='float32') # %%time kmeans_1.fit(kmeans_1.record_set(data_numpy_1),logs=True,job_name='ufo-modeling-lab-originalDatasetOutput') # ### Oversampled Dataset - Configuration # + output_folder_path = 'ModelingLab - 2019/oversampled_dataset_output' output_location = 's3://{}/{}'.format(bucket,output_folder_path) #for 'train_instance_type' go to https://aws.amazon.com/sagemaker/pricing/instance-types/ kmeans_2 = KMeans(role=role, train_instance_count=1, train_instance_type='ml.p3.16xlarge', output_path=output_location, k=num_of_clusters) # - # convert our DataFrame to numpy.ndarray because kmeans.record_set() Build a RecordSet from a numpy ndarray matrix # https://sagemaker.readthedocs.io/en/stable/kmeans.html data_numpy_2=oversample_data[['longitude','latitude']].to_numpy(dtype='float32') # %%time kmeans_2.fit(kmeans_2.record_set(data_numpy_2),logs=True,job_name='ufo-modeling-lab-oversampledDatasetOutput') # ## Results<a id='results'></a> # ### Downloading trained model from an S3 Bucket to Notebook instance # + import boto3 import botocore BUCKET_NAME = '<PUT_HERE_THE_BUCKET_NAME>' FILE_PATH_1 = 'ModelingLab - 2019/original_dataset_output/ufo-modeling-lab-originalDatasetOutput/output/model.tar.gz' FILE_PATH_2 = 'ModelingLab - 2019/oversampled_dataset_output/ufo-modeling-lab-oversampledDatasetOutput/output/model.tar.gz' key_dict={'original_dataset_output':FILE_PATH_1,'oversampled_dataset_output':FILE_PATH_2} s3 = boto3.resource('s3') for i in key_dict: try: s3.Bucket(BUCKET_NAME).download_file(key_dict[i], i+'.tar.gz') except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": print("The object does not exist.") else: raise # - # ### Unzip model file in the Notebook instance # + import os for i in key_dict: os.system('mkdir '+i) os.system('tar -C '+i+'/ -zxvf '+i+'.tar.gz') # - # ### Draw the points on a map # #### Install Libraries # !pip install mxnet # !pip install shapely # !pip install geopandas # !pip install descartes # #### original dataset output # + import mxnet as mx Kmeans_model_params_1 = mx.ndarray.load(list(key_dict.keys())[0]+'/model_algo-1') cluster_centroids_kmeans_1 = pd.DataFrame(Kmeans_model_params_1[0].asnumpy()) cluster_centroids_kmeans_1.columns=['longitude','latitude'] cluster_centroids_kmeans_1 # + from shapely.geometry import Point import geopandas as gpd from geopandas import GeoDataFrame geometry = [Point(xy) for xy in zip(cluster_centroids_kmeans_1['longitude'], cluster_centroids_kmeans_1['latitude'])] gdf = GeoDataFrame(cluster_centroids_kmeans_1, geometry=geometry) #this is a simple map that goes with geopandas world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) gdf.plot(ax=world.plot(figsize=(10, 6)), marker='o', color='black', markersize=15); plt.show() # - # #### oversampled dataset output # + import mxnet as mx Kmeans_model_params_2 = mx.ndarray.load(list(key_dict.keys())[1]+'/model_algo-1') cluster_centroids_kmeans_2 = pd.DataFrame(Kmeans_model_params_2[0].asnumpy()) cluster_centroids_kmeans_2.columns=['longitude','latitude'] cluster_centroids_kmeans_2 # + from shapely.geometry import Point import geopandas as gpd from geopandas import GeoDataFrame geometry = [Point(xy) for xy in zip(cluster_centroids_kmeans_2['longitude'], cluster_centroids_kmeans_2['latitude'])] gdf = GeoDataFrame(cluster_centroids_kmeans_2, geometry=geometry) #this is a simple map that goes with geopandas world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) gdf.plot(ax=world.plot(figsize=(10, 6)), marker='o', color='red', markersize=15); plt.show() # - # ## Summary <a id='summary'></a> # for summary, from the points on the maps we can see that: # 1. six points that were placed in USA are identical for both of the trained models. # 1. the point that was placed in Europe is identical for both of the trained models. # 1. rest of the points were placed on different places for both of the trained models. # # I can't say if one model is better than the other, but it was a fun ride!
CHAPTER 6 - Modeling/Modeling Lab/ufo-modeling-lab-Idan.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from bs4 import BeautifulSoup as BS from selenium import webdriver from functools import reduce import pandas as pd import time def render_page(url): driver = webdriver.Chrome('/Users/cp/Downloads/chromedriver') driver.get(url) time.sleep(3) r = driver.page_source driver.quit() return r def scraper(page, dates): output = pd.DataFrame() for d in dates: url = str(str(page) + str(d)) r = render_page(url) soup = BS(r, "html.parser") container = soup.find('lib-city-history-observation') check = container.find('tbody') data = [] for c in check.find_all('tr', class_='ng-star-inserted'): for i in c.find_all('td', class_='ng-star-inserted'): trial = i.text trial = trial.strip(' ') data.append(trial) if round(len(data) / 17 - 1) == 31: Temperature = pd.DataFrame([data[32:128][x:x + 3] for x in range(0, len(data[32:128]), 3)][1:], columns=['Temp_max', 'Temp_avg', 'Temp_min']) Dew_Point = pd.DataFrame([data[128:224][x:x + 3] for x in range(0, len(data[128:224]), 3)][1:], columns=['Dew_max', 'Dew_avg', 'Dew_min']) Humidity = pd.DataFrame([data[224:320][x:x + 3] for x in range(0, len(data[224:320]), 3)][1:], columns=['Hum_max', 'Hum_avg', 'Hum_min']) Wind = pd.DataFrame([data[320:416][x:x + 3] for x in range(0, len(data[320:416]), 3)][1:], columns=['Wind_max', 'Wind_avg', 'Wind_min']) Pressure = pd.DataFrame([data[416:512][x:x + 3] for x in range(0, len(data[416:512]), 3)][1:], columns=['Pres_max', 'Pres_avg', 'Pres_min']) Date = pd.DataFrame(data[:32][1:], columns=data[:1]) Precipitation = pd.DataFrame(data[512:][1:], columns=['Precipitation']) print(str(str(d) + ' finished!')) elif round(len(data) / 17 - 1) == 28: Temperature = pd.DataFrame([data[29:116][x:x + 3] for x in range(0, len(data[29:116]), 3)][1:], columns=['Temp_max', 'Temp_avg', 'Temp_min']) Dew_Point = pd.DataFrame([data[116:203][x:x + 3] for x in range(0, len(data[116:203]), 3)][1:], columns=['Dew_max', 'Dew_avg', 'Dew_min']) Humidity = pd.DataFrame([data[203:290][x:x + 3] for x in range(0, len(data[203:290]), 3)][1:], columns=['Hum_max', 'Hum_avg', 'Hum_min']) Wind = pd.DataFrame([data[290:377][x:x + 3] for x in range(0, len(data[290:377]), 3)][1:], columns=['Wind_max', 'Wind_avg', 'Wind_min']) Pressure = pd.DataFrame([data[377:464][x:x + 3] for x in range(0, len(data[377:463]), 3)][1:], columns=['Pres_max', 'Pres_avg', 'Pres_min']) Date = pd.DataFrame(data[:29][1:], columns=data[:1]) Precipitation = pd.DataFrame(data[464:][1:], columns=['Precipitation']) print(str(str(d) + ' finished!')) elif round(len(data) / 17 - 1) == 29: Temperature = pd.DataFrame([data[30:120][x:x + 3] for x in range(0, len(data[30:120]), 3)][1:], columns=['Temp_max', 'Temp_avg', 'Temp_min']) Dew_Point = pd.DataFrame([data[120:210][x:x + 3] for x in range(0, len(data[120:210]), 3)][1:], columns=['Dew_max', 'Dew_avg', 'Dew_min']) Humidity = pd.DataFrame([data[210:300][x:x + 3] for x in range(0, len(data[210:300]), 3)][1:], columns=['Hum_max', 'Hum_avg', 'Hum_min']) Wind = pd.DataFrame([data[300:390][x:x + 3] for x in range(0, len(data[300:390]), 3)][1:], columns=['Wind_max', 'Wind_avg', 'Wind_min']) Pressure = pd.DataFrame([data[390:480][x:x + 3] for x in range(0, len(data[390:480]), 3)][1:], columns=['Pres_max', 'Pres_avg', 'Pres_min']) Date = pd.DataFrame(data[:30][1:], columns=data[:1]) Precipitation = pd.DataFrame(data[480:][1:], columns=['Precipitation']) print(str(str(d) + ' finished!')) elif round(len(data) / 17 - 1) == 30: Temperature = pd.DataFrame([data[31:124][x:x + 3] for x in range(0, len(data[31:124]), 3)][1:], columns=['Temp_max', 'Temp_avg', 'Temp_min']) Dew_Point = pd.DataFrame([data[124:217][x:x + 3] for x in range(0, len(data[124:217]), 3)][1:], columns=['Dew_max', 'Dew_avg', 'Dew_min']) Humidity = pd.DataFrame([data[217:310][x:x + 3] for x in range(0, len(data[217:310]), 3)][1:], columns=['Hum_max', 'Hum_avg', 'Hum_min']) Wind = pd.DataFrame([data[310:403][x:x + 3] for x in range(0, len(data[310:403]), 3)][1:], columns=['Wind_max', 'Wind_avg', 'Wind_min']) Pressure = pd.DataFrame([data[403:496][x:x + 3] for x in range(0, len(data[403:496]), 3)][1:], columns=['Pres_max', 'Pres_avg', 'Pres_min']) Date = pd.DataFrame(data[:31][1:], columns=data[:1]) Precipitation = pd.DataFrame(data[496:][1:], columns=['Precipitation']) print(str(str(d) + ' finished!')) else: print('Data not in normal length') dfs = [Date, Temperature, Dew_Point, Humidity, Wind, Pressure, Precipitation] df_final = reduce(lambda left, right: pd.merge(left, right, left_index=True, right_index=True), dfs) df_final['Date'] = str(d) + "-" + df_final.iloc[:, :1].astype(str) output = output.append(df_final) print('Scraper done!') output = output[['Temp_avg', 'Temp_min', 'Dew_max', 'Dew_avg', 'Dew_min', 'Hum_max', 'Hum_avg', 'Hum_min', 'Wind_max', 'Wind_avg', 'Wind_min', 'Pres_max', 'Pres_avg', 'Pres_min', 'Precipitation', 'Date']] return output dates = ['2020-1','2020-2','2020-3','2020-4','2020-5','2020-6','2020-7','2020-8','2020-9','2020-10','2020-11','2020-12'] page = 'https://www.wunderground.com/history/monthly/us/tx/houston/date/' df_output = scraper(page,dates) df_output.shape df_output.shape df_output.head(62) df_output.shape df_output.info() df_output.to_csv (r'/Users/cp/Desktop/capstone2/Houston_weather.csv', index = False, header=True) houston_df = pd.read_csv('/Users/cp/Desktop/capstone2/Houston_weather.csv') houston_df.head() dates = ['2020-1','2020-2','2020-3','2020-4','2020-5','2020-6','2020-7','2020-8','2020-9','2020-10','2020-11','2020-12'] page = 'https://www.wunderground.com/history/monthly/us/tx/dallas/KDAL/date/' df_output = scraper(page,dates) df_output.to_csv (r'/Users/cp/Desktop/capstone2/Dallas_weather.csv', index = False, header=True) # + page = 'https://www.wunderground.com/history/monthly/us/tx/san-antonio/KSAT/date/' df_output = scraper(page,dates) # - df_output.to_csv (r'/Users/cp/Desktop/capstone2/san_antonio_weather.csv', index = False, header=True) page = 'https://www.wunderground.com/history/monthly/us/tx/austin/KAUS/date/' df_output = scraper(page,dates) df_output.to_csv (r'/Users/cp/Desktop/capstone2/austin_weather.csv', index = False, header=True) page = 'https://www.wunderground.com/history/monthly/us/tx/el-paso/KELP/date/' df_output = scraper(page,dates) df_output.to_csv (r'/Users/cp/Desktop/capstone2/el-paso_weather.csv', index = False, header=True) page = 'https://www.wunderground.com/history/monthly/us/tx/lubbock/KLBB/date/' df_output = scraper(page,dates) df_output.to_csv (r'/Users/cp/Desktop/capstone2/lubbock_weather.csv', index = False, header=True) page = 'https://www.wunderground.com/history/monthly/us/tx/galveston/KGLS/date/' df_output = scraper(page,dates) df_output.to_csv (r'/Users/cp/Desktop/capstone2/galveston_weather.csv', index = False, header=True) page = 'https://www.wunderground.com/history/monthly/us/tx/galveston/KGLS/date/' df_output df_output
notebooks/Weather_scraper.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.6 # language: python # name: python36 # --- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-data-dependency-steps.png) # # Azure Machine Learning Pipelines with Data Dependency # In this notebook, we will see how we can build a pipeline with implicit data dependency. # ## Prerequisites and Azure Machine Learning Basics # If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, make sure you go through the [configuration Notebook](https://aka.ms/pl-config) first if you haven't. This sets you up with a working config file that has information on your workspace, subscription id, etc. # # ### Azure Machine Learning and Pipeline SDK-specific Imports # + import azureml.core from azureml.core import Workspace, Experiment, Datastore from azureml.core.compute import AmlCompute from azureml.core.compute import ComputeTarget from azureml.widgets import RunDetails # Check core SDK version number print("SDK version:", azureml.core.VERSION) from azureml.data.data_reference import DataReference from azureml.pipeline.core import Pipeline, PipelineData from azureml.pipeline.steps import PythonScriptStep print("Pipeline SDK-specific imports completed") # - # ### Initialize Workspace # # Initialize a [workspace](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.workspace(class%29) object from persisted configuration. # + tags=["create workspace"] ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\n') # Default datastore (Azure blob storage) # def_blob_store = ws.get_default_datastore() def_blob_store = Datastore(ws, "workspaceblobstore") print("Blobstore's name: {}".format(def_blob_store.name)) # - # ### Source Directory # The best practice is to use separate folders for scripts and its dependent files for each step and specify that folder as the `source_directory` for the step. This helps reduce the size of the snapshot created for the step (only the specific folder is snapshotted). Since changes in any files in the `source_directory` would trigger a re-upload of the snapshot, this helps keep the reuse of the step when there are no changes in the `source_directory` of the step. # + # source directory source_directory = 'data_dependency_run_train' print('Sample scripts will be created in {} directory.'.format(source_directory)) # - # ### Required data and script files for the the tutorial # Sample files required to finish this tutorial are already copied to the project folder specified above. Even though the .py provided in the samples don't have much "ML work," as a data scientist, you will work on this extensively as part of your work. To complete this tutorial, the contents of these files are not very important. The one-line files are for demostration purpose only. # ### Compute Targets # See the list of Compute Targets on the workspace. cts = ws.compute_targets for ct in cts: print(ct) # #### Retrieve or create an Aml compute # Azure Machine Learning Compute is a service for provisioning and managing clusters of Azure virtual machines for running machine learning workloads. Let's get the default Aml Compute in the current workspace. We will then run the training script on this compute target. # + from azureml.core.compute_target import ComputeTargetException aml_compute_target = "cpu-cluster" try: aml_compute = AmlCompute(ws, aml_compute_target) print("found existing compute target.") except ComputeTargetException: print("creating new compute target") provisioning_config = AmlCompute.provisioning_configuration(vm_size = "STANDARD_D2_V2", min_nodes = 1, max_nodes = 4) aml_compute = ComputeTarget.create(ws, aml_compute_target, provisioning_config) aml_compute.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) print("Aml Compute attached") # + # For a more detailed view of current Azure Machine Learning Compute status, use get_status() # example: un-comment the following line. # print(aml_compute.get_status().serialize()) # - # **Wait for this call to finish before proceeding (you will see the asterisk turning to a number).** # # Now that you have created the compute target, let's see what the workspace's compute_targets() function returns. You should now see one entry named 'amlcompute' of type AmlCompute. # ## Building Pipeline Steps with Inputs and Outputs # As mentioned earlier, a step in the pipeline can take data as input. This data can be a data source that lives in one of the accessible data locations, or intermediate data produced by a previous step in the pipeline. # # ### Datasources # Datasource is represented by **[DataReference](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.data_reference.datareference?view=azure-ml-py)** object and points to data that lives in or is accessible from Datastore. DataReference could be a pointer to a file or a directory. # + # Reference the data uploaded to blob storage using DataReference # Assign the datasource to blob_input_data variable # DataReference(datastore, # data_reference_name=None, # path_on_datastore=None, # mode='mount', # path_on_compute=None, # overwrite=False) blob_input_data = DataReference( datastore=def_blob_store, data_reference_name="test_data", path_on_datastore="20newsgroups/20news.pkl") print("DataReference object created") # - # ### Intermediate/Output Data # Intermediate data (or output of a Step) is represented by **[PipelineData](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-core/azureml.pipeline.core.pipelinedata?view=azure-ml-py)** object. PipelineData can be produced by one step and consumed in another step by providing the PipelineData object as an output of one step and the input of one or more steps. # # #### Constructing PipelineData # - **name:** [*Required*] Name of the data item within the pipeline graph # - **datastore_name:** Name of the Datastore to write this output to # - **output_name:** Name of the output # - **output_mode:** Specifies "upload" or "mount" modes for producing output (default: mount) # - **output_path_on_compute:** For "upload" mode, the path to which the module writes this output during execution # - **output_overwrite:** Flag to overwrite pre-existing data # + # Define intermediate data using PipelineData # Syntax # PipelineData(name, # datastore=None, # output_name=None, # output_mode='mount', # output_path_on_compute=None, # output_overwrite=None, # data_type=None, # is_directory=None) # Naming the intermediate data as processed_data1 and assigning it to the variable processed_data1. processed_data1 = PipelineData("processed_data1",datastore=def_blob_store) print("PipelineData object created") # - # ### Pipelines steps using datasources and intermediate data # Machine learning pipelines can have many steps and these steps could use or reuse datasources and intermediate data. Here's how we construct such a pipeline: # #### Define a Step that consumes a datasource and produces intermediate data. # In this step, we define a step that consumes a datasource and produces intermediate data. # # **Open `train.py` in the local machine and examine the arguments, inputs, and outputs for the script. That will give you a good sense of why the script argument names used below are important.** # #### Specify conda dependencies and a base docker image through a RunConfiguration # # This step uses a docker image and scikit-learn, use a [**RunConfiguration**](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.runconfiguration?view=azure-ml-py) to specify these requirements and use when creating the PythonScriptStep. # + from azureml.core.runconfig import RunConfiguration from azureml.core.conda_dependencies import CondaDependencies from azureml.core.runconfig import DEFAULT_CPU_IMAGE # create a new runconfig object run_config = RunConfiguration() # enable Docker run_config.environment.docker.enabled = True # set Docker base image to the default CPU-based image run_config.environment.docker.base_image = DEFAULT_CPU_IMAGE # use conda_dependencies.yml to create a conda environment in the Docker image for execution run_config.environment.python.user_managed_dependencies = False # specify CondaDependencies obj run_config.environment.python.conda_dependencies = CondaDependencies.create(conda_packages=['scikit-learn']) # - # step4 consumes the datasource (Datareference) in the previous step # and produces processed_data1 trainStep = PythonScriptStep( script_name="train.py", arguments=["--input_data", blob_input_data, "--output_train", processed_data1], inputs=[blob_input_data], outputs=[processed_data1], compute_target=aml_compute, source_directory=source_directory, runconfig=run_config ) print("trainStep created") # #### Define a Step that consumes intermediate data and produces intermediate data # In this step, we define a step that consumes an intermediate data and produces intermediate data. # # **Open `extract.py` in the local machine and examine the arguments, inputs, and outputs for the script. That will give you a good sense of why the script argument names used below are important.** # + # step5 to use the intermediate data produced by step4 # This step also produces an output processed_data2 processed_data2 = PipelineData("processed_data2", datastore=def_blob_store) source_directory = "data_dependency_run_extract" extractStep = PythonScriptStep( script_name="extract.py", arguments=["--input_extract", processed_data1, "--output_extract", processed_data2], inputs=[processed_data1], outputs=[processed_data2], compute_target=aml_compute, source_directory=source_directory) print("extractStep created") # - # #### Define a Step that consumes intermediate data and existing data and produces intermediate data # In this step, we define a step that consumes multiple data types and produces intermediate data. # # This step uses the output generated from the previous step as well as existing data on a DataStore. The location of the existing data is specified using a [**PipelineParameter**](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-core/azureml.pipeline.core.pipelineparameter?view=azure-ml-py) and a [**DataPath**](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.datapath.datapath?view=azure-ml-py). Using a PipelineParameter enables easy modification of the data location when the Pipeline is published and resubmitted. # # **Open `compare.py` in the local machine and examine the arguments, inputs, and outputs for the script. That will give you a good sense of why the script argument names used below are important.** # + # Reference the data uploaded to blob storage using a PipelineParameter and a DataPath from azureml.pipeline.core import PipelineParameter from azureml.data.datapath import DataPath, DataPathComputeBinding datapath = DataPath(datastore=def_blob_store, path_on_datastore='20newsgroups/20news.pkl') datapath_param = PipelineParameter(name="compare_data", default_value=datapath) data_parameter1 = (datapath_param, DataPathComputeBinding(mode='mount')) # + # Now define the compare step which takes two inputs and produces an output processed_data3 = PipelineData("processed_data3", datastore=def_blob_store) source_directory = "data_dependency_run_compare" compareStep = PythonScriptStep( script_name="compare.py", arguments=["--compare_data1", data_parameter1, "--compare_data2", processed_data2, "--output_compare", processed_data3], inputs=[data_parameter1, processed_data2], outputs=[processed_data3], compute_target=aml_compute, source_directory=source_directory) print("compareStep created") # - # #### Build the pipeline pipeline1 = Pipeline(workspace=ws, steps=[compareStep]) print ("Pipeline is built") pipeline_run1 = Experiment(ws, 'Data_dependency').submit(pipeline1) print("Pipeline is submitted for execution") RunDetails(pipeline_run1).show() # #### Wait for pipeline run to complete pipeline_run1.wait_for_completion(show_output=True) # ### See Outputs # # See where outputs of each pipeline step are located on your datastore. # # ***Wait for pipeline run to complete, to make sure all the outputs are ready*** # Get Steps for step in pipeline_run1.get_steps(): print("Outputs of step " + step.name) # Get a dictionary of StepRunOutputs with the output name as the key output_dict = step.get_outputs() for name, output in output_dict.items(): output_reference = output.get_port_data_reference() # Get output port data reference print("\tname: " + name) print("\tdatastore: " + output_reference.datastore_name) print("\tpath on datastore: " + output_reference.path_on_datastore) # ### Download Outputs # # We can download the output of any step to our local machine using the SDK. # + # Retrieve the step runs by name 'train.py' train_step = pipeline_run1.find_step_run('train.py') if train_step: train_step_obj = train_step[0] # since we have only one step by name 'train.py' train_step_obj.get_output_data('processed_data1').download("./outputs") # download the output to current directory # - # # Next: Publishing the Pipeline and calling it from the REST endpoint # See this [notebook](https://aka.ms/pl-pub-rep) to understand how the pipeline is published and you can call the REST endpoint to run the pipeline.
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-data-dependency-steps.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd import random import torch import torch.nn as nn import matplotlib.pyplot as plt % matplotlib inline df = pd.read_csv('./data/names.csv') data = ' '.join(df.name.tolist()) df.head() # data I/O chars = list(set(data)) data_size, vocab_size = len(data), len(chars) print(f'data has {data_size} characters, {vocab_size} unique.') char_to_ix = { ch:i for i,ch in enumerate(chars) } ix_to_char = { i:ch for i,ch in enumerate(chars) } # hyperparameters hidden_size = 100 # size of hidden layer of neurons seq_length = 25 # number of steps to unroll the RNN for learning_rate = 1e-1 X_train = np.zeros((len(data), len(chars))) char_id = np.array([chars.index(c) for c in data]) X_train[np.arange(len(X_train)), char_id] = 1 y_train = np.roll(char_id,-1) X_train.shape y_train.shape # ## Build a RNN model class CharRNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super().__init__() self.fc_x = nn.Linear(input_size, hidden_size) self.fc_h = nn.Linear(hidden_size, hidden_size) self.tanh = nn.Tanh() self.fc_out = nn.Linear(hidden_size, output_size) def forward(self, X, h): x_out = self.fc_x(X) h_out = self.fc_h(h) h_new = self.tanh(x_out + h_out) out = self.fc_out(h_new) return out, h_new def init_h(self): return torch.zeros(self.fc_x.out_features) rnn = CharRNN(vocab_size, 100, vocab_size) loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.Adagrad(rnn.parameters(), lr=0.1) #optimizer = torch.optim.Adam(rnn.parameters(), lr=0.001) def get_batch(X=X_train, y=y_train, batch_size=seq_length): #X_ids = list(range(len(X))) #random.shuffle(X_ids) #X = X[X_ids] #y = y[X_ids] X = torch.from_numpy(X).float() y = torch.from_numpy(y).long() for i in range(0, len(y), batch_size): id_stop = i+batch_size if i+batch_size < len(X) else len(X) yield([X[i:id_stop], y[i:id_stop]]) def sample_chars(X_seed, h_prev, length=20): for p in rnn.parameters(): p.requires_grad = False X_next = X_seed results = [] for i in range(length): y_score, h_prev = rnn(X_next, h_prev) y_prob = nn.Softmax(0)(y_score).detach().numpy() y_pred = np.random.choice(chars,1, p=y_prob).item() results.append(y_pred) X_next = torch.zeros_like(X_seed) X_next[chars.index(y_pred)] = 1 #print(f'{i} th char:{y_pred}') for p in rnn.parameters(): p.requires_grad = True return ''.join(results) len(all_losses) all_losses = [] for epoch in range(10): for batch in get_batch(X_train, y_train, seq_length): batch_loss = torch.tensor(0.0) X_batch, y_batch = batch h_prev = rnn.init_h() for ch_id in range(len(X_batch)): y_score, h_prev = rnn(X_batch[ch_id], h_prev) loss = loss_fn(y_score.view(1,-1), y_batch[ch_id].view(1)) batch_loss += loss optimizer.zero_grad() batch_loss.backward() for p in rnn.parameters(): p.grad = torch.clamp(p.grad, -5,5) optimizer.step() all_losses.append(batch_loss.item()) if len(all_losses)%100==0: print(f'----\nRunning Avg Loss:{np.mean(all_losses[-100:])} at iter: {len(all_losses)}\n----') print(sample_chars(X_batch[ch_id], h_prev, 200)) np.mean(all_losses) np.mean(all_losses) plt.plot(range(len(all_losses[50:])), all_losses[50:]) plt.plot(range(len(all_losses[50:])), all_losses[50:]) plt.hist(h_prev.detach().numpy()) print(sample_chars(X_batch[5], rnn.init_h(), 500))
rnn/.ipynb_checkpoints/rnn_names_pytorch-checkpoint.ipynb
# --- # title: "Mode-Metrics" # author: "<NAME>" # date: 2020-09-04 # description: "-" # type: technical_note # draft: false # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: kagglevil_ # language: python # name: kagglevil_ # --- import math import statistics import numpy as np import scipy.stats import pandas as pd x = [8.0, 1, 2.5, 4, 28.0] x_with_nan = [8.0, 1, 2.5, math.nan, 4, 28.0] x y, y_with_nan = np.array(x), np.array(x_with_nan) z, z_with_nan = pd.Series(x), pd.Series(x_with_nan) y u = [2, 3, 2, 8, 12] mode_ = max((u.count(item), item) for item in set(u))[1] mode_ mode_ = statistics.mode(u) mode_ mode_ = statistics.multimode(u) mode_ v = [12, 15, 12, 15, 21, 15, 12] statistics.multimode(v) statistics.mode([2, math.nan, 2]) statistics.multimode([2, math.nan, 2]) statistics.mode([2, math.nan, 0, math.nan, 5]) statistics.multimode([2, math.nan, 0, math.nan, 5]) u, v = np.array(u), np.array(v) mode_ = scipy.stats.mode(u) mode_ mode_ = scipy.stats.mode(v) mode_ mode_.mode mode_.count u, v, w = pd.Series(u), pd.Series(v), pd.Series([2, 2, math.nan]) u.mode() v.mode() w.mode()
content/python/numpy/.ipynb_checkpoints/Mode_Metrics-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # unpacking # + # need of unpacking # We use two operators * (for tuples) and ** (for dictionaries). # situation :Consider a situation where we have # a function that receives four arguments. We want # to make call to this function and we have a list # of size 4 with us that has all arguments for the # function. If we simply pass list to the function, # the call doesn’t work def printing (a, b, c, d): print(a, b, c, d) name = ["PENAN", "CHETAN", "RAHUL", "MANOJ"] printing(name) # + # Unpacking # Solution : We can use * to unpack the list # so that all elements of it can be passed # as different parameters. def printing (a, b, c, d): print(a, b, c, d) name = ["PENAN", "CHETAN", "RAHUL", "MANOJ"] printing(*name) # we pass * List # - # # Packing # + # Situation : When we don’t know how many # arguments need to be passed to a python # function, we can use Packing to pack all # arguments in a tuple. # - def summed(*args): # we receive as tuple sum = 0 for i in range(0, len(args)): sum = sum + args[i] print("sum =", sum ) summed( 1, 4, 6, 9 ) summed( 16, 25) # # Packing and Unpacking # + def fun1(a, b, c): #unpacking print(a, b, c) def fun2(*args): # Packing print(args) args = list(args) fun1(*args[0:3]) # we can only pass list items to unpacking args[0:2]=["HELLO", "WORLD"] # we convert into list to change the value fun1(*args[0:3]) fun2("LILY", "ROSE", "IRIS", "PALETTE") # - # # Tuple Packing and Unpacking student = ( "PENAN", 20, "B.Tech.") # tuple ## packing items into list student (name, age, course) = student ## unpacking list items into separate items and assigning to variables print(name) print(age) print(course)
09. Python Tuples/02. Packing and Unpacking.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.read_csv('Social_Network_Ads.csv') df.summary() X = df.iloc[:,:-1].values y = df.iloc[:,-1].values # + from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.25) # + from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_scaled = sc.fit_transform(X_train) X_t = sc.transform(X_test) # + from sklearn.svm import SVC svc = SVC(kernel = 'rbf',random_state = 0) # - svc.fit(X_scaled,y_train) y_pred = svc.predict(X_t) y_pred print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1)) # + from sklearn.metrics import confusion_matrix,accuracy_score cm = confusion_matrix(y_pred,y_test) accuracy_score(y_pred,y_test) # - cm
Kernel SVM.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide1.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide2.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide3.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide4.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide5.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide6.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide7.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide8.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide9.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide10.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide11.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide12.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide13.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide14.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide15.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ## Convolution Demo Run # ___ # * This notebook shows a single run of the convolution using CNNDataflow IP. # + [markdown] slideshow={"slide_type": "skip"} # # * The input feature map is read from memory, processed and output feature map is captured for one single convolution command. # * The cycle count and efficiency for the full operation is read and displayed at the end. # * The input data in memory is set with random integers in this notebook to test the convolution run. # + [markdown] slideshow={"slide_type": "skip"} # #### Terminology # | Term | Description | # | :------ | :--------------------------------------- | # | IFM | Input volume | # | Weights | A set of filter volumes | # | OFM | Output volume. | # # #### Arguments # | Convolution Arguments | Description | # | --------------------- | ---------------------------------------- | # | ifm-h, ifm-w | Height and width of an input feature map in an IFM volume | # | ifm-d | Depth of the IFM volume | # | kernel-h, kernel-w | Height and width of the weight filters | # | stride | Stride for the IFM volume | # | pad | Pad for the IFM volume | # | Channels | Number of Weight sets/number of output feature maps | # + [markdown] slideshow={"slide_type": "skip"} # ### Block diagram # + [markdown] slideshow={"slide_type": "skip"} # ![](../images/darius_bd.png) # Figure 1 # + [markdown] slideshow={"slide_type": "skip"} # Figure 1 presents a simplified block diagram including Darius CNN IP that is used for running convolution tasks. The Processing System (PS) represents the ARM processor, as well as the external DDR. The Programmable Logic (PL) incorporates the Darius IP for running convolution tasks, and an AXI Interconnect IP. The AXI_GP_0 is an AXILite interface for control signal communication between the ARM and the Darius IP. The data transfer happens through the AXI High Performance Bus, denoted as AXI_HP_0. __For more information about the Zynq architecture, visit:__ [Link](https://www.xilinx.com/support/documentation/user_guides/ug585-Zynq-7000-TRM.pdf) # # + [markdown] slideshow={"slide_type": "skip"} # ### Dataflow # # The dataflow begins by creating an input volume, and a set of weights in python local memory. In Figure 1, these volumes are denoted as “ifm_sw”, and “weights_sw”, respectively. After populating random data, the ARM processor reshapes and copies these volumes into contiguous blocks of shared memory, represented as “ifm” and “weights” in Figure 1, using the “copy_and_reshape()” function. Once the data is accessible by the hardware, the PS starts the convolution operation by asserting the start bit of Darius IP, through the “AXI_GP_0” interface. Darius starts the processing by reading the “ifm” and “weights” volumes from the external memory and writing the results back to a pre-allocated location, shown as “ofm” in Figure 1. # Notes: # - We presume the data in the “ifm_sw” and “weight_sw”, are populated in a row-major format. In order to get the correct results, these volumes have to be reshaped into an interleaved format, as expected by the Darius IP. # - No data reformatting is required for subsequent convolution calls to Darius, as it produces the “ofm” volume in the same format as it expects the “ifm” volume. # - Since the shared memory region is accessible both by the PS and PL regions, one can perform any post-processing steps that may be required directly on the “ofm” volume without transferring data back-and-forth to the python local memory. # # + [markdown] slideshow={"slide_type": "slide"} # ### Step 1: Set the arguments for the convolution in CNNDataflow IP # + slideshow={"slide_type": "fragment"} # Input Feature Map (IFM) dimensions ifm_height = 14 ifm_width = 14 ifm_depth = 64 # Kernel Window dimensions kernel_height = 3 kernel_width = 3 # Other arguments pad = 0 stride = 1 # Channels channels = 32 print( "HOST CMD: CNNDataflow IP Arguments set are - IH %d, IW %d, ID %d, KH %d," " KW %d, P %d, S %d, CH %d" % (ifm_height, ifm_width, ifm_depth, kernel_height, kernel_width, pad, stride, channels)) # + [markdown] slideshow={"slide_type": "slide"} # ### Step 2: Download `Darius Convolution IP` bitstream # + slideshow={"slide_type": "fragment"} from pynq import Overlay overlay = Overlay( "/opt/python3.6/lib/python3.6/site-packages/pynq/overlays/darius/" "convolution.bit") overlay.download() print(f'Bitstream download status: {overlay.is_loaded()}') # + [markdown] slideshow={"slide_type": "slide"} # ### Step 3: Create MMIO object to access the CNNDataflow IP # For more on MMIO visit: [MMIO Documentation](http://pynq.readthedocs.io/en/latest/overlay_design_methodology/pspl_interface.html#mmio) # + slideshow={"slide_type": "fragment"} from pynq import MMIO # Constants CNNDATAFLOW_BASEADDR = 0x43C00000 NUM_COMMANDS_OFFSET = 0x60 CMD_BASEADDR_OFFSET = 0x70 CYCLE_COUNT_OFFSET = 0xd0 cnn = MMIO(CNNDATAFLOW_BASEADDR, 65536) print(f'Idle state: {hex(cnn.read(0x0, 4))}') # + [markdown] slideshow={"slide_type": "slide"} # ### Step 4: Create Xlnk object # Xlnk object (Memory Management Unit) for allocating contiguous array in memory for data transfer between software and hardware # + [markdown] slideshow={"slide_type": "skip"} # <div class="alert alert-danger">Note: You may run into problems if you exhaust and do not free memory buffers – we only have 128MB of contiguous memory, so calling the allocation twice (allocating 160MB) would lead to a “failed to allocate memory” error. Do a xlnk_reset() before re-allocating memory or running this cell twice </div> # + slideshow={"slide_type": "fragment"} from pynq import Xlnk import numpy as np # Constant SIZE = 5000000 # 20 MB of numpy.uint32s mmu = Xlnk() cmd = mmu.cma_array(SIZE) ifm = mmu.cma_array(SIZE) weights = mmu.cma_array(SIZE) ofm = mmu.cma_array(SIZE) cmd_baseaddr = cmd.physical_address ifm_baseaddr = ifm.physical_address weights_baseaddr = weights.physical_address ofm_baseaddr = ofm.physical_address # + [markdown] slideshow={"slide_type": "slide"} # ### Step 5: Functions to print Xlnk statistics # + slideshow={"slide_type": "fragment"} def get_kb(mmu): return int(mmu.cma_stats()['CMA Memory Available'] // 1024) def get_bufcount(mmu): return int(mmu.cma_stats()['Buffer Count']) def print_kb(mmu): print("Available Memory (KB): " + str(get_kb(mmu))) print("Available Buffers: " + str(get_bufcount(mmu))) print_kb(mmu) # + [markdown] slideshow={"slide_type": "slide"} # ### Step 6: Construct convolution command # Check that arguments are in supported range and construct convolution command for hardware # + slideshow={"slide_type": "fragment"} from darius import cnndataflow_lib conv = cnndataflow_lib.CNNDataflow(ifm_height, ifm_width, ifm_depth, kernel_height, kernel_width, pad, stride, channels, ifm_baseaddr, weights_baseaddr, ofm_baseaddr) conv.construct_conv_cmd(ifm_height, ifm_width, ifm_depth, kernel_height, kernel_width, pad, stride, channels, ifm_baseaddr, weights_baseaddr, ofm_baseaddr) # + [markdown] slideshow={"slide_type": "slide"} # ### Step 7: Create IFM volume and weight volume. # Volumes are created in software and populated with random values in a row-major format. # + slideshow={"slide_type": "fragment"} from random import * ifm_sw = np.empty(ifm_width * ifm_height * ifm_depth, dtype=np.int16) for i in range(0, ifm_depth): for j in range(0, ifm_height): for k in range(0, ifm_width): index = i * ifm_height * ifm_width + j * ifm_width + k ifm_sw[index] = randint(0, 255) weights_sw = np.empty(channels * ifm_depth * kernel_height * kernel_width, dtype=np.int16) for i in range(0, channels): for j in range(0, ifm_depth): for k in range(0, kernel_height * kernel_width): addr = i * ifm_depth * kernel_height * kernel_width + \ j * kernel_height * kernel_width + k weights_sw[addr] = randint(0, 255) # + [markdown] slideshow={"slide_type": "slide"} # #### Reshape IFM volume and weights # Volumes are reshaped from row-major format to IP format and data is copied to their respective shared buffer # + slideshow={"slide_type": "fragment"} conv.reshape_and_copy_ifm(ifm_height, ifm_width, ifm_depth, ifm_sw, ifm) conv.reshape_and_copy_weights(kernel_height, kernel_width, ifm_depth, weights_sw, weights) # + [markdown] slideshow={"slide_type": "slide"} # ### Step 8: Load convolution command and start CNNDataflow IP # + slideshow={"slide_type": "fragment"} # Send convolution command to CNNDataflow IP conv.load_conv_cmd(cmd_baseaddr) # Load the number of commands and command physical address to offset addresses cnn.write(NUM_COMMANDS_OFFSET, 1) cnn.write(CMD_BASEADDR_OFFSET, cmd_baseaddr) # Start Convolution if CNNDataflow IP is in Idle state state = cnn.read(0x0) if state == 4: # Idle state print("state: IP IDLE; hence Starting IP") start = cnn.write(0x0, 1) # Start IP start else: print("state %x: IP BUSY" % state) # + [markdown] slideshow={"slide_type": "slide"} # #### Check status of the CNNDataflow IP # + slideshow={"slide_type": "fragment"} # Check if Convolution IP is in Done state state = cnn.read(0x0) if state == 6: # Done state print("state: IP DONE") else: print("state %x: IP BUSY" % state) # + [markdown] slideshow={"slide_type": "slide"} # ### Step 9: Read back first few words of OFM # + slideshow={"slide_type": "fragment"} for i in range(0, 15, 4): print(hex(ofm[i])) # + [markdown] slideshow={"slide_type": "slide"} # ### Step 10: Read cycle count and efficiency of the complete run # + slideshow={"slide_type": "fragment"} hw_cycles = cnn.read(CYCLE_COUNT_OFFSET, 4) efficiency = conv.calc_efficiency(kernel_height, kernel_width, ifm_depth, hw_cycles) print("CNNDataflow IP cycles: %d\nEffciency: %.2f%%" % (hw_cycles, efficiency)) # + [markdown] slideshow={"slide_type": "slide"} # #### Reset Xlnk # + slideshow={"slide_type": "fragment"} mmu.xlnk_reset() print_kb(mmu) print("Cleared Memory!") # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide16.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide17.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide18.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide19.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide20.JPG) # + [markdown] slideshow={"slide_type": "slide"} # # Resizing an image # This reference design illustrates how to run a kernel for resizing an image on the FPGA. # + [markdown] slideshow={"slide_type": "skip"} # ## Hardware # A simplified block diagram is shown below: # # ![](../images/resize_bd.png) # + [markdown] slideshow={"slide_type": "skip"} # ## Software # The software enables users to run the kernel on the fpga and display the results in the notebook. # + [markdown] slideshow={"slide_type": "slide"} # ### Step 1: Import libraries # + slideshow={"slide_type": "fragment"} import sys import math import numpy as np import os import time from PIL import Image from matplotlib import pyplot import cv2 from pynq import Xlnk from pynq import Overlay # + [markdown] slideshow={"slide_type": "slide"} # # ### Step 2. Download the `Resize IP` bitstream # + slideshow={"slide_type": "fragment"} overlay = Overlay("/opt/python3.6/lib/python3.6/site-packages/pynq/overlays/resize/resize.bit") dma = overlay.axi_dma_0 kernel = overlay.resize_accel_0 # + [markdown] slideshow={"slide_type": "slide"} # ### Step 3: View image that is to be re-sized # The picture pixel data can be read using `opencv` library. # # + slideshow={"slide_type": "fragment"} interval_time = 0 image_path = "../images/img_l.png" original_image = Image.open(image_path) original_array = np.array(original_image) original_image.close() pyplot.imshow(original_array, interpolation='nearest') pyplot.show() old_width, old_height = original_image.size print("Original image size: {}x{} pixels.".format(old_height, old_width)) # + [markdown] slideshow={"slide_type": "slide"} # ### Step 4: Resize in software and display the time profile # __Note: The software example you will notice is quite slow.__ # + slideshow={"slide_type": "fragment"} new_width, new_height = int(old_width/2), int(old_height/2) original_image = Image.open(image_path) # %timeit resized_image = original_image.resize((new_width, new_height), Image.ANTIALIAS) # + [markdown] slideshow={"slide_type": "slide"} # #### Display SW re-sized image # + slideshow={"slide_type": "fragment"} resized_image = original_image.resize((new_width, new_height), Image.ANTIALIAS) orig_image_array = np.array(original_image) resized_array = np.array(resized_image) original_image.close() pyplot.imshow(resized_array, interpolation='nearest') pyplot.show() width, height = resized_image.size print("Resized image size: {}x{} pixels.".format(height, width)) # + [markdown] slideshow={"slide_type": "slide"} # ### Step 5: Allocating memory to process data on PL # Data is provided through contiguous memory locations. # # The size of the buffer depends on the size of the input or output data. # The image dimensions extracted from the read image are used to allocate contiguous memory as follows. # We will use `cma_array` of the corresponding size. # + slideshow={"slide_type": "fragment"} xlnk = Xlnk() in_buffer = xlnk.cma_array(shape=(old_height, old_width, 3), dtype=np.uint8) out_buffer = xlnk.cma_array(shape=(new_height, new_width, 3), dtype=np.uint8) # + [markdown] slideshow={"slide_type": "skip"} # __Note: In the following example, we are only dealing with one image. We will just send one image to the kernel and obtain the results.__ # # __Also Note: The `orig_image_array` has to be copied into the contiguous memory array(deep copy).__ # + [markdown] slideshow={"slide_type": "slide"} # #### Display the image in buffer # + slideshow={"slide_type": "fragment"} interval_time = 0 in_buffer[:] = orig_image_array pyplot.imshow(in_buffer) pyplot.show() # + [markdown] slideshow={"slide_type": "slide"} # # ### Step 6: Resize in hardware and display image # + slideshow={"slide_type": "fragment"} kernel.write(0x10, old_height) kernel.write(0x18, old_width) kernel.write(0x20, new_height) kernel.write(0x28, new_width) def run_kernel(): dma.sendchannel.transfer(in_buffer) dma.recvchannel.transfer(out_buffer) kernel.write(0x00,0x81) dma.sendchannel.wait() dma.recvchannel.wait() run_kernel() pyplot.imshow(out_buffer) pyplot.show() # + [markdown] slideshow={"slide_type": "slide"} # ### Step 7: Time profile resize in HW # + slideshow={"slide_type": "fragment"} # %%timeit #src_rows kernel.write(0x10, old_height) #src_cols kernel.write(0x18, old_width) #dst_rows kernel.write(0x20, new_height) #dst_cols kernel.write(0x28, new_width) def run_kernel(): dma.sendchannel.transfer(in_buffer) dma.recvchannel.transfer(out_buffer) kernel.write(0x00,0x81) dma.sendchannel.wait() dma.recvchannel.wait() run_kernel() # + [markdown] slideshow={"slide_type": "slide"} # #### Reset Xlnk # + slideshow={"slide_type": "fragment"} xlnk.xlnk_reset() # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide21.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide22.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide23.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide24.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide25.JPG) # + [markdown] slideshow={"slide_type": "slide"} # ![](../images/w2slides/Slide26.JPG)
notebooks/DAC2018_xilinx_webinar_slides/DAC2018_xilinx_webinar_slides.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:c3dev] * # language: python # name: conda-env-c3dev-py # --- # # Extracting maximum likelihood estimates from a `model_result` # # If you want to get the stats out-of a fitted model, use the `evo.tabulate_stats()` app. # # We first fit a model. # + from cogent3.app import io, evo loader = io.load_aligned(format="fasta", moltype="dna") aln = loader("../data/primate_brca1.fasta") model = evo.model("GN", tree="../data/primate_brca1.tree") result = model(aln) # - # ## Create and apply `tabulate_stats` app tabulator = evo.tabulate_stats() tabulated = tabulator(result) tabulated # `tabulated` is a `tabular_result` instance which, like other result types, has `dict` like behaviour. It also contains key/value pairs for each model parameter type. # ## Edge parameters # # These are all parameters that differ between edges. Since the current model is time-homogeneous (a single rate matrix), only the table only has entries for the branch scalar (denoted "length"). tabulated["edge params"] # **NOTE:** Unless the model is time-reversible, the lengths in that table are not ENS ([Kaehler et al](https://academic.oup.com/gbe/article-lookup/doi/10.1093/gbe/evw308)). As we used a non-stationary nucleotide model in this example, the length values are a scalar used to adjust the matrices during optimisation. # ## Global parameters # # In this example, these are the elements of the rate matrix. tabulated["global params"] # ## Motif parameters # # In the current example, these are estimates of the nucleotide probabilities in the unobserved ancestor. tabulated["motif params"]
doc/app/evo-extract-model-stats.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # ![license_header_logo](../../../images/license_header_logo.png) # # > **Copyright (c) 2021 <EMAIL>ifAI Sdn. Bhd.**<br> # <br> # This program is part of OSRFramework. You can redistribute it and/or modify # <br>it under the terms of the GNU Affero General Public License as published by # <br>the Free Software Foundation, either version 3 of the License, or # <br>(at your option) any later version. # <br> # <br>This program is distributed in the hope that it will be useful # <br>but WITHOUT ANY WARRANTY; without even the implied warranty of # <br>MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # <br>GNU Affero General Public License for more details. # <br> # <br>You should have received a copy of the GNU Affero General Public License # <br>along with this program. If not, see <http://www.gnu.org/licenses/>. # <br> # + [markdown] papermill={"duration": 0.011679, "end_time": "2021-06-04T13:12:12.521267", "exception": false, "start_time": "2021-06-04T13:12:12.509588", "status": "completed"} slideshow={"slide_type": "slide"} tags=[] # # Introduction # # Oftentimes data will come to us with column names, index names, or other naming conventions that we are not satisfied with. In that case, you'll learn how to use pandas functions to change the names of the offending entries to something better. # # You'll also explore how to combine data from multiple DataFrames and/or Series. # - # # Notebook Content # # * [Renaming](#Renaming) # # # * [Combining](#Combining) # # Renaming # # The first function we'll introduce here is `rename()`, which lets you change index names and/or column names. For example, to change the `Avg_viewers` column in our dataset to `Viewers`, we would do: # + _kg_hide-input=true papermill={"duration": 2.032002, "end_time": "2021-06-04T13:12:14.563150", "exception": false, "start_time": "2021-06-04T13:12:12.531148", "status": "completed"} slideshow={"slide_type": "subslide"} tags=[] import pandas as pd games = pd.read_csv("../../../resources/day_01/twitch_game_data.csv", index_col=0) # + slideshow={"slide_type": "subslide"} games # + papermill={"duration": 0.073618, "end_time": "2021-06-04T13:12:14.646671", "exception": false, "start_time": "2021-06-04T13:12:14.573053", "status": "completed"} slideshow={"slide_type": "slide"} tags=[] games.rename(columns={'Avg_viewers': 'Viewers', 'Avg_channels': 'Channels', 'Avg_viewer_ratio': 'Ratio'}) # + [markdown] papermill={"duration": 0.01062, "end_time": "2021-06-04T13:12:14.668678", "exception": false, "start_time": "2021-06-04T13:12:14.658058", "status": "completed"} slideshow={"slide_type": "subslide"} tags=[] # `rename()` lets you rename index _or_ column values by specifying a `index` or `column` keyword parameter, respectively. It supports a variety of input formats, but usually a Python dictionary is the most convenient. Here is an example using it to rename some elements of the index. # + papermill={"duration": 0.142183, "end_time": "2021-06-04T13:12:14.823876", "exception": false, "start_time": "2021-06-04T13:12:14.681693", "status": "completed"} slideshow={"slide_type": "subslide"} tags=[] games.rename(index={1: 'Champion', 2: 'First-Runner-Up', 3: 'Second-Runner-Up'}) # + [markdown] papermill={"duration": 0.012852, "end_time": "2021-06-04T13:12:15.001801", "exception": false, "start_time": "2021-06-04T13:12:14.988949", "status": "completed"} slideshow={"slide_type": "slide"} tags=[] # # Combining # # When performing operations on a dataset, we will sometimes need to combine different DataFrames and/or Series in non-trivial ways. Pandas has three core methods for doing this. In order of increasing complexity, these are `concat()`, `join()`, and `merge()`. Most of what `merge()` can do can also be done more simply with `join()`, so we will omit it and focus on the first two functions here. # # The simplest combining method is `concat()`. Given a list of elements, this function will smush those elements together along an axis. # # This is useful when we have data in different DataFrame or Series objects but having the same fields (columns). One example: the [YouTube Videos dataset](https://www.kaggle.com/datasnaek/youtube-new), which splits the data up based on country of origin (e.g. Canada and the UK, in this example). If we want to study multiple countries simultaneously, we can use `concat()` to smush them together: # + papermill={"duration": 3.016257, "end_time": "2021-06-04T13:12:18.038669", "exception": false, "start_time": "2021-06-04T13:12:15.022412", "status": "completed"} slideshow={"slide_type": "subslide"} tags=[] canadian_youtube = pd.read_csv("../../../resources/day_01/ca_videos.csv") british_youtube = pd.read_csv("../../../resources/day_01/gb_videos.csv") pd.concat([canadian_youtube, british_youtube]) # + [markdown] papermill={"duration": 0.014456, "end_time": "2021-06-04T13:12:18.067045", "exception": false, "start_time": "2021-06-04T13:12:18.052589", "status": "completed"} slideshow={"slide_type": "subslide"} tags=[] # The middlemost combiner in terms of complexity is `join()`. `join()` lets you combine different DataFrame objects which have an index in common. For example, to pull down videos that happened to be trending on the same day in _both_ Canada and the UK, we could do the following: # + papermill={"duration": 0.987984, "end_time": "2021-06-04T13:12:19.068921", "exception": false, "start_time": "2021-06-04T13:12:18.080937", "status": "completed"} slideshow={"slide_type": "subslide"} tags=[] left = canadian_youtube.set_index(['title', 'trending_date']) right = british_youtube.set_index(['title', 'trending_date']) left.join(right, lsuffix='_CAN', rsuffix='_UK') # + [markdown] papermill={"duration": 0.013978, "end_time": "2021-06-04T13:12:19.096640", "exception": false, "start_time": "2021-06-04T13:12:19.082662", "status": "completed"} slideshow={"slide_type": "subslide"} tags=[] # The `lsuffix` and `rsuffix` parameters are necessary here because the data has the same column names in both British and Canadian datasets. If this wasn't true (because, say, we'd renamed them beforehand) we wouldn't need them. # - # # Contributors # # **Author** # <br><NAME> # # References # # 1. [Learning Pandas](https://www.kaggle.com/learn/pandas) # 2. [Pandas Documentation](https://pandas.pydata.org/docs/reference/index.html)
nlp-labs/Day_01/Pandas Basic/06_renaming-and-combining.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd pd.set_option('display.float_format', lambda x: '%.3f' % x) pd.options.mode.chained_assignment = None # %matplotlib inline import matplotlib #matplotlib.use('agg') matplotlib.style.use('ggplot') from matplotlib import pyplot as plt from functools import reduce compounds=pd.read_csv("/data/dharp/compounding/datasets/compounds_reduced.csv",sep="\t",index_col=0) compounds=compounds.query('decade != 2000') compounds=compounds.reindex() compounds.drop('compounds',axis=1,inplace=True) compounds.head() heads=pd.read_csv("/data/dharp/compounding/datasets/heads_reduced.csv",sep="\t") heads=heads.query('decade != 2000') heads=heads.reindex() heads modifiers=pd.read_csv("/data/dharp/compounding/datasets/modifiers_reduced.csv",sep="\t") modifiers=modifiers.query('decade != 2000') modifiers=modifiers.reindex() modifiers compound_decade_counts=compounds.groupby(['decade'])['count'].sum().to_frame() compound_decade_counts.columns=['N'] compound_decade_counts # ## PPMI , LMI, LL XY=compounds.groupby(['modifier','head','decade'])['count'].sum().to_frame() XY.columns=['a'] X_star=compounds.groupby(['modifier','decade'])['count'].sum().to_frame() X_star.columns=['x_star'] Y_star=compounds.groupby(['head','decade'])['count'].sum().to_frame() Y_star.columns=['star_y'] merge1=pd.merge(XY.reset_index(),X_star.reset_index(),on=['modifier','decade']) information_feat=pd.merge(merge1,Y_star.reset_index(),on=['head','decade']) information_feat['b']=information_feat['x_star']-information_feat['a'] information_feat['c']=information_feat['star_y']-information_feat['a'] information_feat=pd.merge(information_feat,compound_decade_counts.reset_index(),on=['decade']) information_feat['d']=information_feat['N']-(information_feat['a']+information_feat['b']+information_feat['c']) information_feat['x_bar_star']=information_feat['N']-information_feat['x_star'] information_feat['star_y_bar']=information_feat['N']-information_feat['star_y'] #information_feat['LR']=-2*np.sum(information_feat['a']*np.log2((information_feat['a']*information_feat['N'])/(information_feat['x_star']*information_feat['star_y']))) information_feat.set_index(['modifier','head','decade'],inplace=True) information_feat.replace(0,0.001,inplace=True) information_feat['log_ratio']=2*(information_feat['a']*np.log((information_feat['a']*information_feat['N'])/(information_feat['x_star']*information_feat['star_y']))+\ information_feat['b']*np.log((information_feat['b']*information_feat['N'])/(information_feat['x_star']*information_feat['star_y_bar']))+\ information_feat['c']*np.log((information_feat['c']*information_feat['N'])/(information_feat['x_bar_star']*information_feat['star_y']))+\ information_feat['d']*np.log((information_feat['d']*information_feat['N'])/(information_feat['x_bar_star']*information_feat['star_y_bar']))) information_feat['ppmi']=np.log2((information_feat['a']*information_feat['N'])/(information_feat['x_star']*information_feat['star_y'])) information_feat['local_mi']=information_feat['a']*information_feat['ppmi'] information_feat.ppmi.loc[information_feat.ppmi<=0]=0 information_feat.drop(['a','x_star','star_y','b','c','d','N','d','x_bar_star','star_y_bar'],axis=1,inplace=True) information_feat # # Cosine features modifier_decade_counts=modifiers.groupby(['decade'])['count'].sum().to_frame() modifier_decade_counts.columns=['N'] modifier_decade_counts head_decade_counts=heads.groupby(['decade'])['count'].sum().to_frame() head_decade_counts.columns=['N'] head_decade_counts modifier_denom=modifiers.groupby(['modifier','decade'])['count'].agg(lambda x: np.sqrt(np.sum(np.square(x)))).to_frame() modifier_denom.columns=['modifier_denom'] modifier_denom head_denom=heads.groupby(['head',"decade"])['count'].agg(lambda x: np.sqrt(np.sum(np.square(x)))).to_frame() head_denom.columns=['head_denom'] head_denom compound_denom=compounds.groupby(['modifier','head',"decade"])['count'].agg(lambda x: np.sqrt(np.sum(np.square(x)))).to_frame() compound_denom.columns=['compound_denom'] compound_denom # ### Similarity between Modifier and Compound mod_cols=modifiers.columns.tolist() mod_cols[-1]="mod_count" modifiers.columns=mod_cols #compounds.drop(['comp_count'],axis=1,inplace=True) comp_cols=compounds.columns.tolist() comp_cols[-1]="comp_count" compounds.columns=comp_cols compound_modifier_sim=pd.merge(compounds,modifiers,on=["modifier","context",'decade']) compound_modifier_sim['numerator']=compound_modifier_sim['comp_count']*compound_modifier_sim['mod_count'] compound_modifier_sim=compound_modifier_sim.groupby(['modifier','head','decade'])['numerator'].sum().to_frame() compound_modifier_sim=pd.merge(compound_modifier_sim.reset_index(),compound_denom.reset_index(),on=["modifier","head",'decade']) compound_modifier_sim=pd.merge(compound_modifier_sim,modifier_denom.reset_index(),on=['modifier','decade']) compound_modifier_sim['sim_with_modifier']=compound_modifier_sim['numerator']/(compound_modifier_sim['compound_denom']*compound_modifier_sim['modifier_denom']) compound_modifier_sim.set_index(['modifier','head','decade'],inplace=True) compound_modifier_sim.drop(['numerator','compound_denom'],axis=1,inplace=True) compound_modifier_sim compound_modifier_sim.sim_with_modifier.describe() _=compound_modifier_sim.hist(by= 'decade',column ='sim_with_modifier', figsize=(20, 20),bins=100,density=True,sharex=True,sharey=True,range=(-0.1,1.1)) # ### Similarity between Head and Compound # + head_cols=heads.columns.tolist() head_cols[-1]="head_count" heads.columns=head_cols compound_head_sim=pd.merge(compounds,heads,on=["head","context",'decade']) compound_head_sim['numerator']=compound_head_sim['comp_count']*compound_head_sim['head_count'] compound_head_sim=compound_head_sim.groupby(['modifier','head','decade'])['numerator'].sum().to_frame() compound_head_sim=pd.merge(compound_head_sim.reset_index(),compound_denom.reset_index(),on=["modifier","head",'decade']) compound_head_sim=pd.merge(compound_head_sim,head_denom.reset_index(),on=['head','decade']) compound_head_sim['sim_with_head']=compound_head_sim['numerator']/(compound_head_sim['compound_denom']*compound_head_sim['head_denom']) compound_head_sim.set_index(['modifier','head','decade'],inplace=True) compound_head_sim.drop(['numerator','compound_denom'],axis=1,inplace=True) compound_head_sim # - compound_head_sim.sim_with_head.describe() _=compound_head_sim.hist(by= 'decade',column ='sim_with_head', figsize=(20, 20),bins=100,density=True,sharex=True,sharey=True,range=(-0.1,1.1)) # ### Similarity between constituents constituent_sim=pd.merge(heads,compounds,on=["head","context","decade"]) #constituent_sim.drop('comp_count',axis=1,inplace=True) constituent_sim=pd.merge(constituent_sim,modifiers,on=["modifier","context","decade"]) constituent_sim['numerator']=constituent_sim['head_count']*constituent_sim['mod_count'] constituent_sim=constituent_sim.groupby(['modifier','head','decade'])['numerator'].sum().to_frame() constituent_sim=pd.merge(constituent_sim.reset_index(),head_denom.reset_index(),on=["head","decade"]) constituent_sim=pd.merge(constituent_sim,modifier_denom.reset_index(),on=["modifier","decade"]) constituent_sim['sim_bw_constituents']=constituent_sim['numerator']/(constituent_sim['head_denom']*constituent_sim['modifier_denom']) constituent_sim.set_index(['modifier','head','decade'],inplace=True) constituent_sim.drop(['numerator','modifier_denom','head_denom'],axis=1,inplace=True) constituent_sim constituent_sim.sim_bw_constituents.describe() _=constituent_sim.hist(by= 'decade',column ='sim_bw_constituents', figsize=(20, 20),bins=100,density=True,sharex=True,sharey=True,range=(-0.1,1.1)) # + dfs = [constituent_sim.reset_index(), compound_head_sim.reset_index(), compound_modifier_sim.reset_index(), information_feat.reset_index()] compounds_final = reduce(lambda left,right: pd.merge(left,right,on=['modifier','head','decade']), dfs) compounds_final.drop(['head_denom','modifier_denom'],axis=1,inplace=True) compounds_final=pd.pivot_table(compounds_final, index=['modifier','head'], columns=['decade']) compounds_final.fillna(0,inplace=True) compounds_final -= compounds_final.min() compounds_final /= compounds_final.max() compounds_final_1=compounds_final.columns.get_level_values(0) compounds_final_2=compounds_final.columns.get_level_values(1) cur_year=0 new_columns=[] for year in compounds_final_2: new_columns.append(str(year)+"_"+compounds_final_1[cur_year]) cur_year+=1 compounds_final.columns=new_columns compounds_final # - compounds_final.to_csv("/data/dharp/compounding/datasets/DFM_Contextual_Temporal.csv",sep='\t')
novel_compound_predictor/Preprocessing_DFM_Contextual_Decadal.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import mph import numpy as np # + ''' Computing the Groebner bases of the image and kernel of a random map of free p-graded modules ''' random_map, image_gb, kernel_gb = mph.examples.random_map_gbs(3, 5, n_parameters=3, grade_range=100) print(random_map) print(image_gb) print(kernel_gb) # + ''' The presentation of a random Free Implicit representation. ''' presentation_matrix = mph.examples.random_FIrep_presentation(5, 9, n_parameters=4, grade_range=100) print(presentation_matrix) # - m=6 n=12 density = 0.5 n_parameters = 3 grade_range = 10000 low_matrix = np.random.choice([0, 1], size=(m, n), p=[density, 1-density]) # Choose random grades for the columns column_grades_l = [ np.random.choice(grade_range, size=(n_parameters,)) for _ in range(n) ] # Compute the kernel of this graded matrix output = mph.groebner_bases(low_matrix, column_grades_l) print(output[1])
python/.ipynb_checkpoints/examples-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import gensim import sqlite3 from operator import itemgetter # + class WordSplitter(object): def __init__(self, filename): self.filename = filename def __iter__(self): with open(self.filename) as fin: for line in fin: yield line.split() model = gensim.models.Word2Vec(model_input, min_count=4) # - model.save(open('zoo/15/songs.word2vec', 'wb')) # + conn = sqlite3.connect('data/songs.db') def find_song(song_name, limit=10): c = conn.cursor() c.execute("SELECT * FROM songs WHERE UPPER(name) LIKE '%" + song_name + "%'") res = sorted((x + (model.wv.vocab[x[0]].count,) for x in c.fetchall() if x[0] in model.wv.vocab), key=itemgetter(-1), reverse=True) return [*res][:limit] for t in find_song('the eye of the tiger'): print(*t) # + def suggest_songs(song_id): c = conn.cursor() similar = dict(model.most_similar([song_id])) song_ids = ', '.join(("'%s'" % x) for x in similar.keys()) c.execute("SELECT * FROM songs WHERE id in (%s)" % song_ids) res = sorted((rec + (similar[rec[0]],) for rec in c.fetchall()), key=itemgetter(-1), reverse=True) return [*res] for t in suggest_songs('4rr0ol3zvLiEBmep7HaHtx'): print(*t) # - x = model.wv.vocab['2yqVlvXgZ51ynGqwfYADx4'] x.count
15.4 Train a music recommender.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # 一维同构列 `pandas.Series` # 列 `Series` 中的标签被称为 `index`,标签缺省是从 `0` 开始的自然数列数。 # + # %matplotlib widget import matplotlib.pyplot as plt import pandas as pd plt.rcParams['font.serif'] = ['STSong', 'SimSun', 'SimSun-ExtB'] + plt.rcParams['font.serif'] plt.rcParams['font.serif'] = ['STFangson', 'FangSong'] + plt.rcParams['font.serif'] plt.rcParams['font.serif'] = ['STKaiti', 'KaiTi'] + plt.rcParams['font.serif'] plt.rcParams['font.sans-serif'] = ['SimHei'] + plt.rcParams['font.sans-serif'] plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] + plt.rcParams['font.sans-serif'] plt.rcParams['font.sans-serif'] = ['STXihei'] + plt.rcParams['font.sans-serif'] # - # ___ # ## 加载数据 # ### 从 Python 序列创建列 s = pd.Series(['北京', '上海', '广州', '深圳']) s # ___ # ## 展示数据 # ### 直方图 s.hist() # ___ # ## 访问数据 # ___ # ## 操控数据
rrpandas/ipynb/Series.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import os os.chdir('..') import convokit convokit from convokit import Corpus, Utterance, User """ Basic Conversation tree (left to right within subtree => earliest to latest) 0 1 2 3 4 5 6 7 8 9 10 11 """ corpus = Corpus(utterances = [ Utterance(id="0", reply_to=None, root="0", user=User(name="alice"), timestamp=0), Utterance(id="2", reply_to="0", root="0", user=User(name="alice"), timestamp=2), Utterance(id="1", reply_to="0", root="0", user=User(name="alice"), timestamp=1), Utterance(id="3", reply_to="0", root="0", user=User(name="alice"), timestamp=3), Utterance(id="4", reply_to="1", root="0", user=User(name="alice"), timestamp=4), Utterance(id="5", reply_to="1", root="0", user=User(name="alice"), timestamp=5), Utterance(id="6", reply_to="1", root="0", user=User(name="alice"), timestamp=6), Utterance(id="7", reply_to="2", root="0", user=User(name="alice"), timestamp=4), Utterance(id="8", reply_to="2", root="0", user=User(name="alice"), timestamp=5), Utterance(id="9", reply_to="3", root="0", user=User(name="alice"), timestamp=4), Utterance(id="10", reply_to="4", root="0", user=User(name="alice"), timestamp=5), Utterance(id="11", reply_to="9", root="0", user=User(name="alice"), timestamp=10), Utterance(id="other", reply_to=None, root="other", user=User(name="alice"), timestamp=99) ]) # Adding some simple metadata: corpus.get_conversation("0").meta['hey'] = 'jude' corpus.meta['foo'] = 'bar' # ## Tree Traversals convo = corpus.get_conversation("0") bfs_traversal = [utt.id for utt in convo.traverse("bfs", as_utterance=True)] bfs_traversal # traverse() returns an iterator of Utterances OR an iterator of UtteranceNodes for utt in list(convo.traverse("bfs", as_utterance=True)): print(utt) list(convo.traverse("bfs", as_utterance=False)) dfs_traversal = [utt.id for utt in convo.traverse("dfs", as_utterance=True)] dfs_traversal postorder_traversal = [utt.id for utt in convo.traverse("postorder", as_utterance=True)] postorder_traversal preorder_traversal = [utt.id for utt in convo.traverse("preorder", as_utterance=True)] preorder_traversal # ## Root to leaf paths paths = convo.get_root_to_leaf_paths() # Number of root to leaf paths len(paths) for path in paths: print([utt.id for utt in path]) # ## Subtree extraction subtree_node = convo.get_subtree("1") [node.utt.id for node in subtree_node.bfs_traversal()] [node.utt.id for node in subtree_node.dfs_traversal()] [node.utt.id for node in subtree_node.pre_order()] [node.utt.id for node in subtree_node.post_order()] # ## Reindexing Conversations in a Corpus corpus.print_summary_stats() reindexed_corpus = corpus.reindex_conversations(new_convo_roots=["1", "2", "3"]) reindexed_corpus.print_summary_stats() reindexed_corpus.get_conversation("1").print_conversation_structure() [utt.id for utt in reindexed_corpus.get_conversation("1").traverse("bfs")]
convokit/tests/notebook_testers/reindex_conversations_example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np # + keys = ['USDT_BTC', 'USDT_ETH', 'USDT_LTC', 'USDT_XRP', 'USDT_XMR', 'USDT_ETC', 'USDT_ZEC', 'USDT_DASH', 'USDT_BTC', 'USDT_ETH', 'USDT_LTC', 'USDT_XRP', 'USDT_XMR', 'USDT_ETC', 'USDT_ZEC', 'USDT_DASH', 'USDT'] df1 = pd.DataFrame(np.random.randn(50, 6), columns=['open', 'high', 'low', 'close','volume','BTC'], index=pd.date_range('1/1/2011', periods=50, freq='D')) df2 = pd.DataFrame(np.random.randn(50, 6), columns=['open', 'high', 'low', 'close','volume','BTC'], index=pd.date_range('1/1/2011', periods=50, freq='D')) df3 = pd.DataFrame(np.random.randn(20, 6), columns=['open', 'high', 'low', 'close','volume','BTC'], index=pd.date_range('1/1/2011', periods=20, freq='D')) s1 = [df1, df2, df3] s1 # - pd.concat(s1, keys=keys, axis=1)
notebooks/Untitled.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="C9HmC2T4ld5B" # ### Explore overfitting and underfitting # + [markdown] colab_type="text" id="kRTxFhXAlnl1" # <table class="tfo-notebook-buttons" align="left"> # <td> # <a target="_blank" href="https://www.tensorflow.org/tutorials/keras/overfit_and_underfit"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> # </td> # <td> # <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/keras/overfit_and_underfit.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> # </td> # <td> # <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/keras/overfit_and_underfit.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> # </td> # </table> # + [markdown] colab_type="text" id="19rPukKZsPG6" # As always, the code in this example will use the `tf.keras` API, which you can learn more about in the TensorFlow [Keras guide](https://www.tensorflow.org/guide/keras). # # In both of the previous examples—classifying movie reviews, and predicting fuel efficiency—we saw that the accuracy of our model on the validation data would peak after training for a number of epochs, and would then start decreasing. # # In other words, our model would *overfit* to the training data. Learning how to deal with overfitting is important. Although it's often possible to achieve high accuracy on the *training set*, what we really want is to develop models that generalize well to a *testing data* (or data they haven't seen before). # # The opposite of overfitting is *underfitting*. Underfitting occurs when there is still room for improvement on the test data. This can happen for a number of reasons: If the model is not powerful enough, is over-regularized, or has simply not been trained long enough. This means the network has not learned the relevant patterns in the training data. # # If you train for too long though, the model will start to overfit and learn patterns from the training data that don't generalize to the test data. We need to strike a balance. Understanding how to train for an appropriate number of epochs as we'll explore below is a useful skill. # # To prevent overfitting, the best solution is to use more training data. A model trained on more data will naturally generalize better. When that is no longer possible, the next best solution is to use techniques like regularization. These place constraints on the quantity and type of information your model can store. If a network can only afford to memorize a small number of patterns, the optimization process will force it to focus on the most prominent patterns, which have a better chance of generalizing well. # # In this notebook, we'll explore two common regularization techniques—weight regularization and dropout—and use them to improve our IMDB movie review classification notebook. # + colab={} colab_type="code" id="49PPQ0TbBX0v" # keras.datasets.imdb is broken in 1.13 and 1.14, by np 1.16.3 # !pip install tf_nightly # + colab={} colab_type="code" id="5pZ8A2liqvgk" from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt print(tf.__version__) # + [markdown] colab_type="text" id="1cweoTiruj8O" # ### Download the IMDB dataset # # Rather than using an embedding as in the previous notebook, here we will multi-hot encode the sentences. This model will quickly overfit to the training set. It will be used to demonstrate when overfitting occurs, and how to fight it. # # Multi-hot-encoding our lists means turning them into vectors of 0s and 1s. Concretely, this would mean for instance turning the sequence `[3, 5]` into a 10,000-dimensional vector that would be all-zeros except for indices 3 and 5, which would be ones. # + colab={} colab_type="code" id="QpzE4iqZtJly" NUM_WORDS = 10000 (train_data, train_labels), (test_data, test_labels) = keras.datasets.imdb.load_data(num_words=NUM_WORDS) def multi_hot_sequences(sequences, dimension): # Create an all-zero matrix of shape (len(sequences), dimension) results = np.zeros((len(sequences), dimension)) for i, word_indices in enumerate(sequences): results[i, word_indices] = 1.0 # set specific indices of results[i] to 1s return results train_data = multi_hot_sequences(train_data, dimension=NUM_WORDS) test_data = multi_hot_sequences(test_data, dimension=NUM_WORDS) # + [markdown] colab_type="text" id="MzWVeXe3NBTn" # Let's look at one of the resulting multi-hot vectors. The word indices are sorted by frequency, so it is expected that there are more 1-values near index zero, as we can see in this plot: # + colab={} colab_type="code" id="71kr5rG4LkGM" plt.plot(train_data[0]) # + [markdown] colab_type="text" id="lglk41MwvU5o" # ### Demonstrate overfitting # # The simplest way to prevent overfitting is to reduce the size of the model, i.e. the number of learnable parameters in the model (which is determined by the number of layers and the number of units per layer). In deep learning, the number of learnable parameters in a model is often referred to as the model's "capacity". Intuitively, a model with more parameters will have more "memorization capacity" and therefore will be able to easily learn a perfect dictionary-like mapping between training samples and their targets, a mapping without any generalization power, but this would be useless when making predictions on previously unseen data. # # Always keep this in mind: deep learning models tend to be good at fitting to the training data, but the real challenge is generalization, not fitting. # # On the other hand, if the network has limited memorization resources, it will not be able to learn the mapping as easily. To minimize its loss, it will have to learn compressed representations that have more predictive power. At the same time, if you make your model too small, it will have difficulty fitting to the training data. There is a balance between "too much capacity" and "not enough capacity". # # Unfortunately, there is no magical formula to determine the right size or architecture of your model (in terms of the number of layers, or the right size for each layer). You will have to experiment using a series of different architectures. # # To find an appropriate model size, it's best to start with relatively few layers and parameters, then begin increasing the size of the layers or adding new layers until you see diminishing returns on the validation loss. Let's try this on our movie review classification network. # # We'll create a simple model using only ```Dense``` layers as a baseline, then create smaller and larger versions, and compare them. # + [markdown] colab_type="text" id="_ReKHdC2EgVu" # ### Create a baseline model # + colab={} colab_type="code" id="QKgdXPx9usBa" baseline_model = keras.Sequential([ # `input_shape` is only required here so that `.summary` works. keras.layers.Dense(16, activation=tf.nn.relu, input_shape=(NUM_WORDS,)), keras.layers.Dense(16, activation=tf.nn.relu), keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) baseline_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy', 'binary_crossentropy']) baseline_model.summary() # + colab={} colab_type="code" id="LqG3MXF5xSjR" baseline_history = baseline_model.fit(train_data, train_labels, epochs=20, batch_size=512, validation_data=(test_data, test_labels), verbose=2) # + [markdown] colab_type="text" id="L-DGRBbGxI6G" # ### Create a smaller model # + [markdown] colab_type="text" id="SrfoVQheYSO5" # Let's create a model with less hidden units to compare against the baseline model that we just created: # + colab={} colab_type="code" id="jksi-XtaxDAh" smaller_model = keras.Sequential([ keras.layers.Dense(4, activation=tf.nn.relu, input_shape=(NUM_WORDS,)), keras.layers.Dense(4, activation=tf.nn.relu), keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) smaller_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy', 'binary_crossentropy']) smaller_model.summary() # + [markdown] colab_type="text" id="jbngCZliYdma" # And train the model using the same data: # + colab={} colab_type="code" id="Ofn1AwDhx-Fe" smaller_history = smaller_model.fit(train_data, train_labels, epochs=20, batch_size=512, validation_data=(test_data, test_labels), verbose=2) # + [markdown] colab_type="text" id="vIPuf23FFaVn" # ### Create a bigger model # # As an exercise, you can create an even larger model, and see how quickly it begins overfitting. Next, let's add to this benchmark a network that has much more capacity, far more than the problem would warrant: # + colab={} colab_type="code" id="ghQwwqwqvQM9" bigger_model = keras.models.Sequential([ keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(NUM_WORDS,)), keras.layers.Dense(512, activation=tf.nn.relu), keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) bigger_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy','binary_crossentropy']) bigger_model.summary() # + [markdown] colab_type="text" id="D-d-i5DaYmr7" # And, again, train the model using the same data: # + colab={} colab_type="code" id="U1A99dhqvepf" bigger_history = bigger_model.fit(train_data, train_labels, epochs=20, batch_size=512, validation_data=(test_data, test_labels), verbose=2) # + [markdown] colab_type="text" id="Fy3CMUZpzH3d" # ### Plot the training and validation loss # # <!--TODO(markdaoust): This should be a one-liner with tensorboard --> # + [markdown] colab_type="text" id="HSlo1F4xHuuM" # The solid lines show the training loss, and the dashed lines show the validation loss (remember: a lower validation loss indicates a better model). Here, the smaller network begins overfitting later than the baseline model (after 6 epochs rather than 4) and its performance degrades much more slowly once it starts overfitting. # + colab={} colab_type="code" id="0XmKDtOWzOpk" def plot_history(histories, key='binary_crossentropy'): plt.figure(figsize=(12, 6)) for name, history in histories: val = plt.plot(history.epoch, history.history['val_'+key], '--', label=name.title()+' Val') plt.plot(history.epoch, history.history[key], color=val[0].get_color(), label=name.title()+' Train') plt.xlabel('Epochs') plt.ylabel(key.replace('_',' ').title()) plt.legend(frameon=False) plt.xlim([0,max(history.epoch)]) plot_history([('baseline', baseline_history), ('smaller', smaller_history), ('bigger', bigger_history)]) # + [markdown] colab_type="text" id="Bi6hBhdnSfjA" # Notice that the larger network begins overfitting almost right away, after just one epoch, and overfits much more severely. The more capacity the network has, the quicker it will be able to model the training data (resulting in a low training loss), but the more susceptible it is to overfitting (resulting in a large difference between the training and validation loss). # + [markdown] colab_type="text" id="ASdv7nsgEFhx" # ## Strategies # + [markdown] colab_type="text" id="4rHoVWcswFLa" # ### Add weight regularization # # # + [markdown] colab_type="text" id="kRxWepNawbBK" # You may be familiar with Occam's Razor principle: given two explanations for something, the explanation most likely to be correct is the "simplest" one, the one that makes the least amount of assumptions. This also applies to the models learned by neural networks: given some training data and a network architecture, there are multiple sets of weights values (multiple models) that could explain the data, and simpler models are less likely to overfit than complex ones. # # A "simple model" in this context is a model where the distribution of parameter values has less entropy (or a model with fewer parameters altogether, as we saw in the section above). Thus a common way to mitigate overfitting is to put constraints on the complexity of a network by forcing its weights only to take small values, which makes the distribution of weight values more "regular". This is called "weight regularization", and it is done by adding to the loss function of the network a cost associated with having large weights. This cost comes in two flavors: # # * [L1 regularization](https://developers.google.com/machine-learning/glossary/#L1_regularization), where the cost added is proportional to the absolute value of the weights coefficients (i.e. to what is called the "L1 norm" of the weights). # # * [L2 regularization](https://developers.google.com/machine-learning/glossary/#L2_regularization), where the cost added is proportional to the square of the value of the weights coefficients (i.e. to what is called the squared "L2 norm" of the weights). L2 regularization is also called weight decay in the context of neural networks. Don't let the different name confuse you: weight decay is mathematically the exact same as L2 regularization. # # In `tf.keras`, weight regularization is added by passing weight regularizer instances to layers as keyword arguments. Let's add L2 weight regularization now. # + colab={} colab_type="code" id="HFGmcwduwVyQ" l2_model = keras.models.Sequential([ keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001), activation=tf.nn.relu, input_shape=(NUM_WORDS,)), keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001), activation=tf.nn.relu), keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) l2_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy', 'binary_crossentropy']) l2_model_history = l2_model.fit(train_data, train_labels, epochs=20, batch_size=512, validation_data=(test_data, test_labels), verbose=2) # + [markdown] colab_type="text" id="bUUHoXb7w-_C" # ```l2(0.001)``` means that every coefficient in the weight matrix of the layer will add ```0.001 * weight_coefficient_value**2``` to the total loss of the network. Note that because this penalty is only added at training time, the loss for this network will be much higher at training than at test time. # # Here's the impact of our L2 regularization penalty: # + colab={} colab_type="code" id="7wkfLyxBZdh_" plot_history([('baseline', baseline_history), ('l2', l2_model_history)]) # + [markdown] colab_type="text" id="Kx1YHMsVxWjP" # As you can see, the L2 regularized model has become much more resistant to overfitting than the baseline model, even though both models have the same number of parameters. # + [markdown] colab_type="text" id="HmnBNOOVxiG8" # ### Add dropout # # Dropout is one of the most effective and most commonly used regularization techniques for neural networks, developed by Hinton and his students at the University of Toronto. Dropout, applied to a layer, consists of randomly "dropping out" (i.e. set to zero) a number of output features of the layer during training. Let's say a given layer would normally have returned a vector [0.2, 0.5, 1.3, 0.8, 1.1] for a given input sample during training; after applying dropout, this vector will have a few zero entries distributed at random, e.g. [0, 0.5, # 1.3, 0, 1.1]. The "dropout rate" is the fraction of the features that are being zeroed-out; it is usually set between 0.2 and 0.5. At test time, no units are dropped out, and instead the layer's output values are scaled down by a factor equal to the dropout rate, so as to balance for the fact that more units are active than at training time. # # In tf.keras you can introduce dropout in a network via the Dropout layer, which gets applied to the output of layer right before. # # Let's add two Dropout layers in our IMDB network to see how well they do at reducing overfitting: # + colab={} colab_type="code" id="OFEYvtrHxSWS" dpt_model = keras.models.Sequential([ keras.layers.Dense(16, activation=tf.nn.relu, input_shape=(NUM_WORDS,)), keras.layers.Dropout(0.5), keras.layers.Dense(16, activation=tf.nn.relu), keras.layers.Dropout(0.5), keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) dpt_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy','binary_crossentropy']) dpt_model_history = dpt_model.fit(train_data, train_labels, epochs=20, batch_size=512, validation_data=(test_data, test_labels), verbose=2) # + colab={} colab_type="code" id="SPZqwVchx5xp" plot_history([('baseline', baseline_history), ('dropout', dpt_model_history)]) # + [markdown] colab_type="text" id="gjfnkEeQyAFG" # Adding dropout is a clear improvement over the baseline model. # # # To recap: here the most common ways to prevent overfitting in neural networks: # # * Get more training data. # * Reduce the capacity of the network. # * Add weight regularization. # * Add dropout. # # And two important approaches not covered in this guide are data-augmentation and batch normalization.
keras/105_regularization.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Advanced tour of the Bayesian Optimization package from bayes_opt import BayesianOptimization # ## 1. Suggest-Evaluate-Register Paradigm # # Internally the `maximize` method is simply a wrapper around the methods `suggest`, `probe`, and `register`. If you need more control over your optimization loops the Suggest-Evaluate-Register paradigm should give you that extra flexibility. # # For an example of running the `BayesianOptimization` in a distributed fashion (where the function being optimized is evaluated concurrently in different cores/machines/servers), checkout the `async_optimization.py` script in the examples folder. # Let's start by defining our function, bounds, and instanciating an optimization object. def black_box_function(x, y): return -x ** 2 - (y - 1) ** 2 + 1 # Notice that the evaluation of the blackbox function will NOT be carried out by the optimizer object. We are simulating a situation where this function could be being executed in a different machine, maybe it is written in another language, or it could even be the result of a chemistry experiment. Whatever the case may be, you can take charge of it and as long as you don't invoke the `probe` or `maximize` methods directly, the optimizer object will ignore the blackbox function. optimizer = BayesianOptimization( f=None, pbounds={'x': (-2, 2), 'y': (-3, 3)}, verbose=2, random_state=1, ) # One extra ingredient we will need is an `UtilityFunction` instance. In case it is not clear why, take a look at the literature to understand better how this method works. # + from bayes_opt import UtilityFunction utility = UtilityFunction(kind="ucb", kappa=2.5, xi=0.0) # - # The `suggest` method of our optimizer can be called at any time. What you get back is a suggestion for the next parameter combination the optimizer wants to probe. # # Notice that while the optimizer hasn't observed any points, the suggestions will be random. However, they will stop being random and improve in quality the more points are observed. next_point_to_probe = optimizer.suggest(utility) print("Next point to probe is:", next_point_to_probe) # You are now free to evaluate your function at the suggested point however/whenever you like. target = black_box_function(**next_point_to_probe) print("Found the target value to be:", target) # Last thing left to do is to tell the optimizer what target value was observed. optimizer.register( params=next_point_to_probe, target=target, ) # ### 1.1 The maximize loop # # And that's it. By repeating the steps above you recreate the internals of the `maximize` method. This should give you all the flexibility you need to log progress, hault execution, perform concurrent evaluations, etc. for _ in range(5): next_point = optimizer.suggest(utility) target = black_box_function(**next_point) optimizer.register(params=next_point, target=target) print(target, next_point) print(optimizer.max) # ## 2. Dealing with discrete parameters # # **There is no principled way of dealing with discrete parameters using this package.** # # Ok, now that we got that out of the way, how do you do it? You're bound to be in a situation where some of your function's parameters may only take on discrete values. Unfortunately, the nature of bayesian optimization with gaussian processes doesn't allow for an easy/intuitive way of dealing with discrete parameters - but that doesn't mean it is impossible. The example below showcases a simple, yet reasonably adequate, way to dealing with discrete parameters. def func_with_discrete_params(x, y, d): # Simulate necessity of having d being discrete. assert type(d) == int return ((x + y + d) // (1 + d)) / (1 + (x + y) ** 2) def function_to_be_optimized(x, y, w): d = int(w) return func_with_discrete_params(x, y, d) optimizer = BayesianOptimization( f=function_to_be_optimized, pbounds={'x': (-10, 10), 'y': (-10, 10), 'w': (0, 5)}, verbose=2, random_state=1, ) optimizer.maximize(alpha=1e-3) # ## 3. Tuning the underlying Gaussian Process # # The bayesian optimization algorithm works by performing a gaussian process regression of the observed combination of parameters and their associated target values. The predicted parameter$\rightarrow$target hyper-surface (and its uncertainty) is then used to guide the next best point to probe. # ### 3.1 Passing parameter to the GP # # Depending on the problem it could be beneficial to change the default parameters of the underlying GP. You can simply pass GP parameters to the maximize method directly as you can see below: optimizer = BayesianOptimization( f=black_box_function, pbounds={'x': (-2, 2), 'y': (-3, 3)}, verbose=2, random_state=1, ) optimizer.maximize( init_points=1, n_iter=5, # What follows are GP regressor parameters alpha=1e-3, n_restarts_optimizer=5 ) # Another alternative, specially useful if you're calling `maximize` multiple times or optimizing outside the `maximize` loop, is to call the `set_gp_params` method. optimizer.set_gp_params(normalize_y=True) # ### 3.2 Tuning the `alpha` parameter # # When dealing with functions with discrete parameters,or particularly erratic target space it might be beneficial to increase the value of the `alpha` parameter. This parameters controls how much noise the GP can handle, so increase it whenever you think that extra flexibility is needed. # ### 3.3 Changing kernels # # By default this package uses the Mattern 2.5 kernel. Depending on your use case you may find that tunning the GP kernel could be beneficial. You're on your own here since these are very specific solutions to very specific problems. # ## Observers Continued # # Observers are objects that subscribe and listen to particular events fired by the `BayesianOptimization` object. # # When an event gets fired a callback function is called with the event and the `BayesianOptimization` instance passed as parameters. The callback can be specified at the time of subscription. If none is given it will look for an `update` method from the observer. from bayes_opt.event import DEFAULT_EVENTS, Events optimizer = BayesianOptimization( f=black_box_function, pbounds={'x': (-2, 2), 'y': (-3, 3)}, verbose=2, random_state=1, ) class BasicObserver: def update(self, event, instance): """Does whatever you want with the event and `BayesianOptimization` instance.""" print("Event `{}` was observed".format(event)) # + my_observer = BasicObserver() optimizer.subscribe( event=Events.OPTIMIZATION_STEP, subscriber=my_observer, callback=None, # Will use the `update` method as callback ) # - # Alternatively you have the option to pass a completely different callback. # + def my_callback(event, instance): print("Go nuts here!") optimizer.subscribe( event=Events.OPTIMIZATION_START, subscriber="Any hashable object", callback=my_callback, ) # - optimizer.maximize(init_points=1, n_iter=2) # For a list of all default events you can checkout `DEFAULT_EVENTS` DEFAULT_EVENTS
examples/advanced-tour.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Imports import os import tarfile from six.moves import urllib import pandas as pd import matplotlib.pyplot as plt import numpy as np # Constants variables DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/" HOUSING_PATH = os.path.join("c:/","datasets", "housing") HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz" HOUSING_PATH # Get data def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH): if not os.path.isdir(housing_path): os.makedirs(housing_path) tgz_path = os.path.join(housing_path, "housing.tgz") urllib.request.urlretrieve(housing_url, tgz_path) housing_tgz = tarfile.open(tgz_path) housing_tgz.extractall(path=housing_path) housing_tgz.close() #load data def load_housing_data(housing_path=HOUSING_PATH): csv_path = os.path.join(housing_path, "housing.csv") return pd.read_csv(csv_path) housing = fetch_housing_data() housing = load_housing_data() housing.head() housing.info() housing.describe() # %matplotlib inline housing.hist(bins=50, figsize=(20,15)) plt.show() def split_train_test(data, test_ratio): np.random.seed(42) shuffled_indices = np.random.permutation(len(data)) test_set_size = int(len(data) * test_ratio) test_indices = shuffled_indices[:test_set_size] train_indices = shuffled_indices[test_set_size:] return data.iloc[train_indices], data.iloc[test_indices] # Split data in train and test set train_set, test_set = split_train_test(housing, 0.2) len(train_set) len(test_set) # + # When you update your data_set with new data the test_set will change to a fit # with some variances. This is a solution for this. # It method get the first test_ratio (20% in the example) # of total data and fit whit consitence data. from zlib import crc32 def test_set_check(identifier, test_radio): return crc32(np.int64(identifier)) & 0xffffffff < test_ratio * 2**32 def split_train_test_by_id(data, test_ratio, id_column): ids = data[id_column] in_test_set = ids.apply(lambda id: test_set_check(id_,test_radio)) return data.loc[~in_test_set], data.loc[in_test_set] # - # But, data_set does not have a index column housing_with_id = housing.reset_index() # adds an `index` column train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "index") # ## Note # Like i will not get new data the previous proccess is not necesary # Sklearn provide some functions to split datasets from sklearn.model_selection import train_test_split train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42) housing["income_cat"] = pd.cut(housing["median_income"], bins=[0., 1.5, 3.0, 4.5, 6., np.inf], labels=[1, 2, 3, 4, 5]) housing["income_cat"].hist() # + # Stratified sampling based on the income category from sklearn.model_selection import StratifiedShuffleSplit split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42) for train_index, test_index in split.split(housing, housing["income_cat"]): strat_train_set = housing.loc[train_index] strat_test_set = housing.loc[test_index] # - strat_test_set["income_cat"].value_counts() / len(strat_test_set) for set_ in (strat_train_set, strat_test_set): set_.drop("income_cat", axis=1, inplace=True) # get a copy to make manipulations easy and fast housing = strat_train_set.copy() # Visualizing Geographical Data housing.plot(kind="scatter", x="longitude", y="latitude") housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.1) housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4, s=housing["population"]/100, label="population", figsize=(10,7), c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True, ) plt.legend() #correlation matrix corr_matrix = housing.corr() corr_matrix corr_matrix["median_house_value"].sort_values(ascending=False) # + # plot of correlation matrix. You need have in mind cuantity of parameters from pandas.plotting import scatter_matrix attributes = ["median_house_value", "median_income", "total_rooms", "housing_median_age"] # only four principals parameters scatter_matrix(housing[attributes], figsize=(12, 8)) # + # The most promising attribute to predict the median house value is the median # income, so let’s zoom in on their correlation scatterplot housing.plot(kind="scatter", x="median_income", y="median_house_value", alpha=0.1) # - # Create new attributes housing["rooms_per_household"] = housing["total_rooms"]/housing["households"] housing["bedrooms_per_room"] = housing["total_bedrooms"]/housing["total_rooms"] housing["population_per_household"]=housing["population"]/housing["households"] # New correlation matrix with new attributes corr_matrix = housing.corr() corr_matrix["median_house_value"].sort_values(ascending=False) # ## Prepare Data housing = strat_train_set.drop("median_house_value", axis=1) housing_labels = strat_train_set["median_house_value"].copy() # We have some options to clear N/A housing.dropna(subset=["total_bedrooms"]) # option 1 housing.drop("total_bedrooms", axis=1) # option 2 # In this option you need save the median value for new data or test_set median = housing["total_bedrooms"].median() # option 3 housing["total_bedrooms"].fillna(median, inplace=True) # Scikit-Learn privides a class to take care of missing values from sklearn.impute import SimpleImputer imputer = SimpleImputer(strategy="median") # we create a copy whitout text attributes housing_num = housing.drop("ocean_proximity", axis=1) # now we use the imputer and there give us all median values in the data_set imputer.fit(housing_num) imputer.statistics_ housing_num.median().values # now we use this trined inputer to remplace mising values X = imputer.transform(housing_num) X housing_tr = pd.DataFrame(X, columns=housing_num.columns) housing_tr.head() # ### Scikit-Learn Scheet-sheet # # <img src="https://scikit-learn.org/stable/_static/ml_map.png" # alt="Scikit-learn cheet sheet" # style="float: left; margin-right: 10px;" /> # get in https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html # Handling text and caterical atributes housing_cat = housing[["ocean_proximity"]] housing_cat.head(10) # + # Change categoricals featrures from text to numbers from sklearn.preprocessing import OrdinalEncoder ordinal_encoder = OrdinalEncoder() housing_cat_encoded = ordinal_encoder.fit_transform(housing_cat) # The funciton fit_transform is same to fit(housing_cat) later # transform(housing_cat) but more optimized housing_cat_encoded[:10] # - # original categories ordinal_encoder.categories_ # convert from categories to one-hot vector because the original categories # haven't from sklearn.preprocessing import OneHotEncoder cat_encoder = OneHotEncoder() housing_cat_1hot = cat_encoder.fit_transform(housing_cat) housing_cat_1hot # change SciPy parse matrix to a NumPy array to save memory housing_cat_1hot.toarray() # original categories cat_encoder.categories_ # + from sklearn.base import BaseEstimator, TransformerMixin rooms_ix, bedrooms_ix, population_ix, households_ix = 3, 4, 5, 6 class CombinedAttributesAdder(BaseEstimator, TransformerMixin): def __init__(self, add_bedrooms_per_room = True): # no *args or **kargs self.add_bedrooms_per_room = add_bedrooms_per_room def fit(self, X, y=None): return self # nothing else to do def transform(self, X, y=None): rooms_per_household = X[:, rooms_ix] / X[:, households_ix] population_per_household = X[:, population_ix] / X[:, households_ix] if self.add_bedrooms_per_room: bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix] return np.c_[X, rooms_per_household, population_per_household, bedrooms_per_room] else: return np.c_[X, rooms_per_household, population_per_household] attr_adder = CombinedAttributesAdder(add_bedrooms_per_room=False) housing_extra_attribs = attr_adder.transform(housing.values) # - from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler num_pipeline = Pipeline([ # change all null values with median ('imputer', SimpleImputer(strategy="median")), # Combined Attributes Adder ('attribs_adder', CombinedAttributesAdder()), # standarization ('std_scaler', StandardScaler()), ]) housing_num_tr = num_pipeline.fit_transform(housing_num) # + # column transformer, presented in skl 2.0 This transformer can change numeric # and categorical features in a data-set # EXAMPLE from sklearn.compose import ColumnTransformer num_attribs = list(housing_num) cat_attribs = ["ocean_proximity"] full_pipeline = ColumnTransformer([ ("num", num_pipeline, num_attribs), ("cat", OneHotEncoder(), cat_attribs), ]) housing_prepared = full_pipeline.fit_transform(housing) # - # ## Select and train a model # Init a Linear regression model and fit from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(housing_prepared, housing_labels) # Let’s try it out on a few instances from the training set some_data = housing.iloc[:5] some_labels = housing_labels.iloc[:5] some_data_prepared = full_pipeline.transform(some_data) print("Predictions:", lin_reg.predict(some_data_prepared)) print("Labels:", list(some_labels)) # set a error function, RMSE from sklearn.metrics import mean_squared_error housing_predictions = lin_reg.predict(housing_prepared) lin_mse = mean_squared_error(housing_labels, housing_predictions) lin_rmse = np.sqrt(lin_mse) lin_rmse # + # $68628 UDS its a big error, in this point we have some ways to get a better # pediction. First will train a more powerful model from sklearn.tree import DecisionTreeRegressor tree_reg = DecisionTreeRegressor() tree_reg.fit(housing_prepared, housing_labels) # - # let's evaluate housing_precictions = tree_reg.predict(housing_prepared) tree_mse = mean_squared_error(housing_labels, housing_predictions) tree_rmse = np.sqrt(tree_mse) tree_rmse # ## Better evaluation using Cross-Validation # DecisionTreeRegressor from sklearn.model_selection import cross_val_score scores = cross_val_score(tree_reg, housing_prepared, housing_labels, scoring="neg_mean_squared_error", cv=10) tree_rmse_scores = np.sqrt(-scores) # Let's look at the results def display_scores(scores): print("Scores:",scores) print("Mean:", scores.mean()) print("Standar deviation:", scores.std()) display_scores(tree_rmse_scores) # LinearRegression lin_scores = cross_val_score(lin_reg, housing_prepared, housing_labels, scoring="neg_mean_squared_error", cv=10) lin_rmse_scores = np.sqrt(-lin_scores) display_scores(lin_rmse_scores) # RandomForestRegressor from sklearn.ensemble import RandomForestRegressor forest_reg = RandomForestRegressor() forest_reg.fit(housing_prepared, housing_labels) housing_precictions = forest_reg.predict(housing_prepared) forest_mse = mean_squared_error(housing_labels,housing_precictions) forest_rmse = np.sqrt(forest_mse) forest_rmse # Cross-Validation forest_scores = cross_val_score(forest_reg, housing_prepared, housing_labels, scoring="neg_mean_squared_error",cv=10) forest_rmse_scores = np.sqrt(-forest_scores) display_scores(forest_rmse_scores) # save and load easly models of sklearn from sklearn.externals import joblib joblib.dump(my_model, "my_model.pkl") # and later... my_model_loaded = joblib.load("my_model.pkl") # ## Fine-Tune Models # # ### Grid Search # + #research for the best combination with cross-validation and random forest from sklearn.model_selection import GridSearchCV param_grid = [ {'n_estimators':[3,10,30], 'max_features': [2,4,6,8]}, {'bootstrap': [False], 'n_estimators':[3,10], 'max_features': [2,3,4]}, ] forest_reg = RandomForestRegressor() grid_search = GridSearchCV(forest_reg, param_grid,cv=5, scoring='neg_mean_squared_error', return_train_score=True) grid_search.fit(housing_prepared, housing_labels) # - # best params grid_search.best_params_ # best estimator grid_search.best_estimator_ cvres = grid_search.cv_results_ for mean_score, params in zip(cvres['mean_test_score'], cvres['params']): print(np.sqrt(-mean_score), params) # best features feature_importances = grid_search.best_estimator_.feature_importances_ feature_importances # display these importance scores to their corresponfing attributes names: extra_attribs = ['rooms_per_hhold', 'pop_per_hhold', 'bedrooms_per_room'] cat_encoder = full_pipeline.named_transformers_['cat'] cat_one_hot_attribs = list(cat_encoder.categories_[0]) attributes = num_attribs + extra_attribs + cat_one_hot_attribs sorted(zip(feature_importances, attributes), reverse=True) # ## Evaluate system on the Test Set # + final_model = grid_search.best_estimator_ X_test = strat_test_set.drop('median_house_value', axis=1) y_test = strat_test_set['median_house_value'].copy() X_test_prepared = full_pipeline.transform(X_test) final_predictions = final_model.predict(X_test_prepared) final_mse = mean_squared_error(y_test, final_predictions) final_rmse = np.sqrt(final_mse) # - # computing a 95% confidence interval for the generalization error using from scipy import stats confidence = 0.95 squared_errors = (final_predictions - y_test) ** 2 np.sqrt(stats.t.interval(confidence, len(squared_errors) - 1, loc=squared_errors.mean(), scale=stats.sem(squared_errors))) # ## Exercise # + # support vector machine regresor from sklearn.svm import SVR param_grid = [ {'kernel': ['linear'], 'C': [10.,30.,100.,300.,1000.,3000.,10000.,30000.]}, { 'kernel': ['rbf'], 'C': [1.0,3.0,10.,30.,100.,300.,1000.0], 'gamma': [0.01,0.03,0.1,0.3,1.0,3.0] } ] svr = SVR() grid_search = GridSearchCV(svr,param_grid,cv=5,scoring='neg_mean_squared_error', verbose=2) grid_search.fit(housing_prepared,housing_labels) # - negative_mse = grid_search.best_score_ rmse = np.sqrt(-negative_mse) rmse grid_search.best_params_
hands_on_ml/housing_cap2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: PythonData # language: python # name: pythondata # --- # %matplotlib inline # Import dependencies. import matplotlib.pyplot as plt # + # Set the x-axis to a list of strings for each month. x_axis = ["Jan", "Feb", "Mar", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"] # Set the y-axis to a list of floats as the total fare in US dollars accumulated for each month. y_axis = [10.02, 23.24, 39.20, 35.42, 32.34, 27.04, 43.82, 10.56, 11.85, 27.90, 20.71, 20.09] # - # Create the plot plt.plot(x_axis, y_axis) # Create the plot with ax.plt() fig, ax = plt.subplots() ax.plot(x_axis, y_axis) # Create the plot with ax.plt() fig = plt.figure() ax = fig.add_subplot() ax.plot(x_axis, y_axis) # Create the plot. plt.plot(x_axis, y_axis) plt.show() # Create the the plot and add a label for the legend plt.plot(x_axis, y_axis, marker='*', linewidth=2, label ='Boston') # Create labels for x and y axis plt.xlabel('Date') plt.ylabel('Fares($)') # Set the y limit between 0 and 45 plt.ylim(0,45) # create a title plt.title("PyBer Fare by Month") # Add a grid plt.grid() # Add the legend. plt.legend() # + # Set the x-axis to a list of strings for each month. x_axis = ["Jan", "Feb", "Mar", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"] # Set the y-axis to a list of floats as the total fare in US dollars accumulated for each month. y_axis = [10.02, 23.24, 39.20, 35.42, 32.34, 27.04, 43.82, 10.56, 11.85, 27.90, 20.71, 20.09] # - #care the plot plt.bar(x_axis,y_axis) # Create the plot. plt.bar(x_axis, y_axis, color='green', label='Boston') # Create label for the x and y axes. plt.xlabel("Date") plt.ylabel("Fare($)") #Create title plt.title("Pyber Fare By Mount") # Add the legend. plt.legend() # Create the plot plt.barh(x_axis, y_axis, color='magenta', label='Boston') plt.legend() plt.xlabel("Fares ($)") plt.ylabel("Date") plt.title("PyBer Fare by Month") plt.gca().invert_yaxis() # + # Set the x-axis to a list of strings for each month. x_axis = ["Jan", "Feb", "Mar", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"] # Set the y-axis to a list of floats as the total fare in US dollars accumulated for each month. y_axis = [10.02, 23.24, 39.20, 35.42, 32.34, 27.04, 43.82, 10.56, 11.85, 27.90, 20.71, 20.09] # - # Create the plot with ax.plt() fig, ax = plt.subplots() ax.bar(x_axis,y_axis) # Create the plot with ax.plt() fig, ax = plt.subplots() ax.barh(x_axis, y_axis, color='cyan', label ='Chicago') ax.invert_yaxis() ax.set_xlabel('Fares($)') ax.set_ylabel('Date') ax.set_title('PyBear Fare by Month') ax.legend() # + # Set the x-axis to a list of strings for each month. x_axis = ["Jan", "Feb", "Mar", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"] # Set the y-axis to a list of floats as the total fare in US dollars accumulated for each month. y_axis = [10.02, 23.24, 39.20, 35.42, 32.34, 27.04, 43.82, 10.56, 11.85, 27.90, 20.71, 20.09] # - plt.plot(x_axis, y_axis, 'o') plt.scatter(x_axis, y_axis, c = 'red', label = 'Chicago') plt.xlabel('Fares ($)') plt.ylabel('Date') plt.title('PyBer Fare by Month') plt.legend() plt.gca().invert_yaxis() plt.scatter(x_axis, y_axis, s=y_axis) y_axis_larger = [] for data in y_axis: y_axis_larger.append(data*3) plt.scatter(x_axis, y_axis, s=y_axis_larger) plt.scatter(x_axis, y_axis, s = [i*3 for i in y_axis]) fig, ax = plt.subplots() ax.scatter(x_axis, y_axis, c = 'skyblue', s= [i*5 for i in y_axis]) plt.pie(y_axis, labels=x_axis) plt.show() plt.subplots(figsize=(8, 8)) explode_values = (0, 0, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 0) plt.pie(y_axis, explode=explode_values, labels=x_axis, autopct='%.1f%%') plt.show() # + # Assign 12 colors, one for each month. colors = ["slateblue", "magenta", "lightblue", "green", "yellowgreen", "greenyellow", "yellow", "orange", "gold", "indianred", "tomato", "mistyrose"] explode_values = (0, 0, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 0) plt.subplots(figsize=(8, 8)) plt.pie(y_axis, explode=explode_values, colors=colors, labels=x_axis, autopct='%.1f%%') plt.show() # - fig, ax = plt.subplots() ax.pie(y_axis,labels=x_axis) plt.show()
matplotlib_practice.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import random import numpy from matplotlib import pyplot as plt from torch_geometric.utils import * from datasets import WebKB, WikipediaNetwork, FilmNetwork, BGP, Airports from gnnutils import * from build_multigraph import build_pyg_struc_multigraph import seaborn as sns from torch_geometric.datasets import Planetoid def get_assortativity(data, use_weights=False): bg = to_networkx(data) print(bg.number_of_edges()) if use_weights: r_g = global_assortativity(bg, data.y.numpy(), data.edge_weight.numpy()) else: r_g = global_assortativity(bg, data.y.numpy()) print("Global Assortativity: ",r_g) if use_weights: _, r_l , _ = local_assortativity(bg,data.y.numpy(), data.edge_weight.numpy()) else: _, r_l , _ = local_assortativity(bg,data.y.numpy()) return r_g, r_l def get_data(d, bgp=False, airports=False): if airports: dataset = Airports(root="original_datasets/airports_dataset/"+d, dataset_name=d) original = dataset[0] elif bgp: dataset = BGP(root="original_datasets/bgp_dataset") original = dataset[0] else: if d in ["cornell", "texas", "wisconsin"]: dataset = WebKB(root="original_datasets/webkb", name=d) elif d in ["chameleon", "squirrel"]: dataset = WikipediaNetwork(root="original_datasets/wiki", name=d) else: dataset = FilmNetwork(root="original_datasets/film", name=d) original = dataset[0] print(original) return original def get_plot(dataset, b, bgp=False, airports=False): data = get_data(dataset, bgp, airports) r_g, r_l = get_assortativity(data) return r_g, r_l b = 20 r_g_c, r_l_c = get_plot("chameleon", b) r_g_s, r_l_s = get_plot("squirrel", b) r_g_f, r_l_f = get_plot("film", b) r_g_co, r_l_co = get_plot("cornell", b) r_g_t, r_l_t = get_plot("texas", b) r_g_w, r_l_w = get_plot("wisconsin", b) r_g_bgp, r_l_bgp = get_plot("bgp", b,bgp=True) r_g_br, r_l_br = get_plot("brazil", b,airports=True) r_g_eu, r_l_eu = get_plot("europe", b,airports=True) r_g_us, r_l_us = get_plot("usa", b, airports=True) # + sns.set_style("ticks") # Some example data to display fig, axs = plt.subplots(3, 3, gridspec_kw = {'wspace':.3, 'hspace':.5}) b = 20 ax = axs[1,0] ax.hist(r_l_c, bins=b,alpha=0.9, color='lightcoral',edgecolor='lightcoral', linewidth=1.5, label='local') ax.axvline(x=r_g_c[0], linestyle='--', alpha=0.6, linewidth=2.5, label='global') ax.set_title('Chame.',fontsize=25, loc="right") # ax.legend(loc='upper right', fontsize=20) b = 20 ax = axs[1,1] ax.hist(r_l_f, bins=b,alpha=0.9, color='lightcoral',edgecolor='lightcoral', linewidth=1.5) ax.axvline(x=r_g_f[0], linestyle='--', alpha=0.6, linewidth=2.5) ax.set_title('Actor',fontsize=25, loc="right") b = 20 ax = axs[0,0] ax.hist(r_l_co, bins=b,alpha=0.9, color='lightcoral',edgecolor='lightcoral', linewidth=1.5) ax.axvline(x=r_g_co[0], linestyle='--', alpha=0.6, linewidth=2.5) ax.set_title('Cornell',fontsize=25, loc="right") # ax.set_xlim(-0.75, 0.8) b = 20 ax = axs[0,1] ax.hist(r_l_w, bins=b,alpha=0.9, color='lightcoral',edgecolor='lightcoral', linewidth=1.5) ax.axvline(x=r_g_w[0], linestyle='--', alpha=0.6, linewidth=2.5) ax.set_title('Wiscon.',fontsize=25, loc="right") b = 20 ax = axs[0,2] ax.hist(r_l_t, bins=b,alpha=0.9, color='lightcoral',edgecolor='lightcoral', linewidth=1.5) ax.axvline(x=r_g_t[0], linestyle='--', alpha=0.6, linewidth=2.5) ax.set_title('Texas',fontsize=25, loc="right") b = 20 ax = axs[1,2] ax.hist(r_l_bgp, bins=b,alpha=0.9, color='lightcoral',edgecolor='lightcoral', linewidth=1.5) ax.axvline(x=r_g_bgp[0], linestyle='--', alpha=0.6, linewidth=2.5) ax.set_title('BGP',fontsize=25, loc="right") ax.set_xlim(-.45, 1.1) b = 20 ax = axs[2,0] ax.hist(r_l_br, bins=b,alpha=0.9, color='lightcoral',edgecolor='lightcoral', linewidth=1.5) ax.axvline(x=r_g_br[0], linestyle='--', alpha=0.6, linewidth=2.5) ax.set_title('Brazil',fontsize=25, loc="right") b = 20 ax = axs[2,2] ax.hist(r_l_us, bins=b,alpha=0.9, color='lightcoral',edgecolor='lightcoral', linewidth=1.5) ax.axvline(x=r_g_us[0], linestyle='--', alpha=0.6, linewidth=2.5) ax.set_title('USA',fontsize=25, loc="right") b=20 ax = axs[2,1] ax.hist(r_l_eu, bins=b,alpha=0.9, color='lightcoral',edgecolor='lightcoral', linewidth=1.5) ax.axvline(x=r_g_eu[0], linestyle='--', alpha=0.6, linewidth=2.5) ax.set_title('Europe',fontsize=25, loc="right") for ax in axs.flat: # ax.set_xlim(-.5, 1.0) ax.tick_params(axis='x',rotation=0, labelsize=20) ax.tick_params(axis='y',rotation=0, labelsize=20) ax.yaxis.set_major_formatter(plt.ScalarFormatter(useMathText=True)) ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) ax.yaxis.get_offset_text().set_fontsize(15) #Hide x labels and tick labels for top plots and y ticks for right plots. # for ax in axs.flat: # ax.label_outer() fig.set_figheight(9) fig.set_figwidth(9) # fig.tight_layout() fig.text(0.5, 0.04, 'Local Assortativity', ha='center', fontsize=22) fig.text(0.05, 0.5, 'Frequency', va='center', rotation='vertical', fontsize=22) fig.savefig('figures/local_assortativity_dataset.png', dpi=200, format='png', bbox_inches = 'tight') # -
local_assortativity_plots.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <a href="https://colab.research.google.com/github/THargreaves/beginners-python/blob/master/session_one/session_one_blank_template.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # <center>Spotted a mistake? Report it <a href="https://github.com/THargreaves/beginners-python/issues/new">here</a></center> # # Beginner's Python—Session One Template # + [markdown] colab_type="text" id="-Ceh1HnZIsVO" # ## Printing # + [markdown] colab_type="text" id="6AZ6H-6jKoSt" # ### Introduction # # - # Get Python to print "Hello World" # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="D4l_2DsZIlgB" outputId="e63ad5b1-2062-4d8c-9ee7-b03a25d72001" # + [markdown] colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="9lLW387eKgNN" outputId="860dcf3b-f3e5-402d-f58f-4d28fb69a6b1" # Print the number 5 # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="bIr0l5kJI_VV" outputId="c7891804-4acf-4856-e51a-271914a8dc60" # - # Print the product of 5 and 10 # Print both text and arithmetic # ### Standard Puzzles # Print your name using the print command # Print your three favourite colours # Calculate $26\times66+13$ # Calculate $6804 \div 162$ # ### Bonus Puzzles # Calculate $2^8$ # What happens if you put a mathematical expression in double quotes when you are printing? # try it on the next line and then write your answer in the next cell # # Calculate $6804\div162$ using integer division # ## Variables # ### Introduction # Create two variables, storing your name and age # Create a variable containing your favourite food and print this as a sentence # ### Standard Puzzles # Use the name and age variables from above to print a sentence # ### Bonus Puzzles # Print what your age will be in 5 year's time as a sentence # Create a variable with value $n$ the print $n$, $2n$, and $n-1$. Give the variable a new value and reprint these values. How did using variables make this easier? # write your code in this cell and answer in the next cell # # ## Manipulating Variables # ### Introduction # Overwrite the value of a variable # Create a new variable based on the value of another variable # Overwrite a variable with a new value based on its current value # ### Standard Puzzles # What do you think the value of `y` will be in the presentation code? # # ## Variable Types # ### Introduction # Create one variable for each of the types integer, float, and string. Check their types using the `type()` function # Create a string variable that contains the digits of a number. Create a new variable by converting this string to an integer. Print the types of both variables # ### Standard Puzzles # Define the variables `x`, `y`, and `z` as in the presentation. What are their types? # Add two string variables together and print the result # try it here and write your response below # # ### Bonus Puzzles # What happens if we omit don't wrap `type()` in `print()`? # Try multiplying a string by an integer. What happens? # # ## More Variable Puzzles # ### Standard Puzzles # Create variables `pi` and `radius` # Use these to print the area and circumference of the corresponding circle. Remember $A=\pi r^2$ and $C = 2\pi r$ # ### Bonus Puzzles # Repeat the above exercise using the `round()` function
session_one/session_one_blank_template.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="aWjiMM8qbM__" colab_type="code" outputId="cb1301cf-4514-4744-cc2d-e05fe425eba6" executionInfo={"status": "ok", "timestamp": 1589248258032, "user_tz": -480, "elapsed": 1524, "user": {"displayName": "\u5982\u5b50", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gi3ItGjzEGzUOlXTUHjOgeuVA5TICdNcY-Q1TGicA=s64", "userId": "01997730851420384589"}} colab={"base_uri": "https://localhost:8080/", "height": 36} from google.colab import drive drive.mount('/content/gdrive') import os os.chdir('/content/gdrive/My Drive/finch/tensorflow2/spoken_language_understanding/atis/main') # + id="jNTA2Vzj8j_V" colab_type="code" outputId="2fb9a2f3-5137-48fa-902e-1634c30122a4" executionInfo={"status": "ok", "timestamp": 1589248264210, "user_tz": -480, "elapsed": 6622, "user": {"displayName": "\u5982\u5b50", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gi3ItGjzEGzUOlXTUHjOgeuVA5TICdNcY-Q1TGicA=s64", "userId": "01997730851420384589"}} colab={"base_uri": "https://localhost:8080/", "height": 55} # %tensorflow_version 2.x # !pip install tensorflow-addons # + id="sRS_9RVFjoe1" colab_type="code" outputId="a66b480b-8621-4537-f85e-d93a96997c8c" executionInfo={"status": "ok", "timestamp": 1589248273772, "user_tz": -480, "elapsed": 15245, "user": {"displayName": "\u5982\u5b50", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gi3ItGjzEGzUOlXTUHjOgeuVA5TICdNcY-Q1TGicA=s64", "userId": "01997730851420384589"}} colab={"base_uri": "https://localhost:8080/", "height": 112} from sklearn.metrics import classification_report, f1_score, accuracy_score from tensorflow_addons.optimizers.cyclical_learning_rate import Triangular2CyclicalLearningRate import tensorflow as tf import pprint import logging import time import numpy as np print("TensorFlow Version", tf.__version__) print('GPU Enabled:', tf.test.is_gpu_available()) # + id="SY89xO1qRPbQ" colab_type="code" colab={} def get_vocab(vocab_path): word2idx = {} with open(vocab_path) as f: for i, line in enumerate(f): line = line.rstrip() word2idx[line] = i return word2idx # + id="WszANU_obncn" colab_type="code" colab={} def data_generator(f_path, params): print('Reading', f_path) with open(f_path) as f: for line in f: line = line.rstrip() text, slot_intent = line.split('\t') words = text.split()[1:-1] slot_intent = slot_intent.split() slots, intent = slot_intent[1:-1], slot_intent[-1] assert len(words) == len(slots) words = [params['word2idx'].get(w, len(params['word2idx'])) for w in words] intent = params['intent2idx'].get(intent, len(params['intent2idx'])) slots = [params['slot2idx'].get(s, len(params['slot2idx'])) for s in slots] yield (words, (intent, slots)) # + id="pKnp6C-kf2lr" colab_type="code" colab={} def dataset(is_training, params): _shapes = ([None], ((), [None])) _types = (tf.int32, (tf.int32, tf.int32)) _pads = (0, (-1, 0)) if is_training: ds = tf.data.Dataset.from_generator( lambda: data_generator(params['train_path'], params), output_shapes = _shapes, output_types = _types,) ds = ds.shuffle(params['num_samples']) ds = ds.padded_batch(params['batch_size'], _shapes, _pads) ds = ds.prefetch(tf.data.experimental.AUTOTUNE) else: ds = tf.data.Dataset.from_generator( lambda: data_generator(params['test_path'], params), output_shapes = _shapes, output_types = _types,) ds = ds.padded_batch(params['batch_size'], _shapes, _pads) ds = ds.prefetch(tf.data.experimental.AUTOTUNE) return ds # + id="ontDwjUKnNBE" colab_type="code" colab={} class Model(tf.keras.Model): def __init__(self, params: dict): super().__init__() self.embedding = tf.Variable(np.load(params['vocab_path']), dtype=tf.float32, name='pretrained_embedding') self.input_dropout = tf.keras.layers.Dropout(params['dropout_rate']) self.bidir_gru = tf.keras.layers.Bidirectional(tf.keras.layers.GRU( params['rnn_units'], return_state=True, return_sequences=True, zero_output_for_mask=True)) self.intent_dropout = tf.keras.layers.Dropout(params['dropout_rate']) self.fc_intent = tf.keras.layers.Dense(params['rnn_units'], tf.nn.elu, name='fc_intent') self.out_linear_intent = tf.keras.layers.Dense(params['intent_size'], name='output_intent') self.out_linear_slot = tf.keras.layers.Dense(params['slot_size'], name='output_slot') def call(self, inputs, training=False): if inputs.dtype != tf.int32: inputs = tf.cast(inputs, tf.int32) mask = tf.sign(inputs) rnn_mask = tf.cast(mask, tf.bool) x = tf.nn.embedding_lookup(self.embedding, inputs) x = self.input_dropout(x, training=training) x, s_fw, s_bw = self.bidir_gru(x, mask=rnn_mask) x_intent = tf.concat([tf.reduce_max(x, 1), s_fw, s_bw], -1) x_intent = self.intent_dropout(x_intent, training=training) x_intent = self.out_linear_intent(self.fc_intent(x_intent)) x_slot = self.out_linear_slot(x) return (x_intent, x_slot) # + id="GazxdEvTIblA" colab_type="code" colab={} params = { 'train_path': '../data/atis.train.w-intent.iob', 'test_path': '../data/atis.test.w-intent.iob', 'word_path': '../vocab/word.txt', 'vocab_path': '../vocab/word.npy', 'intent_path': '../vocab/intent.txt', 'slot_path': '../vocab/slot.txt', 'batch_size': 16, 'num_samples': 4978, 'rnn_units': 300, 'dropout_rate': .2, 'clip_norm': .1, } # + id="p3hzFqh5RLu1" colab_type="code" colab={} params['word2idx'] = get_vocab(params['word_path']) params['intent2idx'] = get_vocab(params['intent_path']) params['slot2idx'] = get_vocab(params['slot_path']) params['word_size'] = len(params['word2idx']) + 1 params['intent_size'] = len(params['intent2idx']) + 1 params['slot_size'] = len(params['slot2idx']) + 1 # + id="eGfxJdmzZPjs" colab_type="code" outputId="3010ce6e-ff1b-488f-805a-a46a26ccad28" executionInfo={"status": "ok", "timestamp": 1589249350117, "user_tz": -480, "elapsed": 1076291, "user": {"displayName": "\u5982\u5b50", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gi3ItGjzEGzUOlXTUHjOgeuVA5TICdNcY-Q1TGicA=s64", "userId": "01997730851420384589"}} colab={"base_uri": "https://localhost:8080/", "height": 1000} model = Model(params) model.build(input_shape=(None, None)) pprint.pprint([(v.name, v.shape) for v in model.trainable_variables]) decay_lr = Triangular2CyclicalLearningRate( initial_learning_rate = 1e-4, maximal_learning_rate = 8e-4, step_size = 8 * params['num_samples'] // params['batch_size'], ) optim = tf.optimizers.Adam(1e-4) global_step = 0 slot_best_f1 = .0 intent_acc_with_that = .0 t0 = time.time() logger = logging.getLogger('tensorflow') logger.setLevel(logging.INFO) for n_epoch in range(1, 64+1): # TRAINING for (words, (intent, slots)) in dataset(is_training=True, params=params): with tf.GradientTape() as tape: y_intent, y_slots = model(words, training=True) loss_intent = tf.compat.v1.losses.softmax_cross_entropy( onehot_labels = tf.one_hot(intent, len(params['intent2idx'])+1), logits = y_intent, label_smoothing = .2) # weight of 'O' is set to be small weights = tf.cast(tf.sign(slots), tf.float32) padding = tf.constant(1e-2, tf.float32, weights.shape) weights = tf.where(tf.equal(weights, 0.), padding, weights) loss_slots = tf.compat.v1.losses.softmax_cross_entropy( onehot_labels = tf.one_hot(slots, len(params['slot2idx'])+1), logits = y_slots, weights = tf.cast(weights, tf.float32), label_smoothing = .2) # joint loss loss = loss_intent + loss_slots optim.lr.assign(decay_lr(global_step)) grads = tape.gradient(loss, model.trainable_variables) grads, _ = tf.clip_by_global_norm(grads, params['clip_norm']) optim.apply_gradients(zip(grads, model.trainable_variables)) if global_step % 50 == 0: logger.info("Step {} | Loss: {:.4f} | Loss_intent: {:.4f} | Loss_slots: {:.4f} | Spent: {:.1f} secs | LR: {:.6f}".format( global_step, loss.numpy().item(), loss_intent.numpy().item(), loss_slots.numpy().item(), time.time()-t0, optim.lr.numpy().item())) t0 = time.time() global_step += 1 # EVALUATION intent_true = [] intent_pred = [] slot_true = [] slot_pred = [] for (words, (intent, slots)) in dataset(is_training=False, params=params): y_intent, y_slots = model(words, training=False) y_intent = tf.argmax(y_intent, -1) y_slots = tf.argmax(y_slots, -1) intent_true += intent.numpy().flatten().tolist() intent_pred += y_intent.numpy().flatten().tolist() slot_true += slots.numpy().flatten().tolist() slot_pred += y_slots.numpy().flatten().tolist() f1_slots = f1_score(y_true = slot_true, y_pred = slot_pred, labels = list(params['slot2idx'].values()), sample_weight = np.sign(slot_true), average='micro',) acc_intent = accuracy_score(intent_true, intent_pred) logger.info("Slot F1: {:.3f}, Intent Acc: {:.3f}".format(f1_slots, acc_intent)) if n_epoch != 1 and n_epoch % 8 == 0: logger.info('\n'+classification_report(y_true = intent_true, y_pred = intent_pred, labels = list(params['intent2idx'].values()), target_names = list(params['intent2idx'].keys()), digits=3)) logger.info('\n'+classification_report(y_true = slot_true, y_pred = slot_pred, labels = list(params['slot2idx'].values()), target_names = list(params['slot2idx'].keys()), sample_weight = np.sign(slot_true), digits=3)) if f1_slots > slot_best_f1: slot_best_f1 = f1_slots intent_acc_with_that = acc_intent # you can save model here logger.info("Best Slot F1: {:.3f}, Intent Acc: {:.3f}".format(slot_best_f1, intent_acc_with_that))
finch/tensorflow2/spoken_language_understanding/atis/main/bigru_clr.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/alirezash97/GenericDecoding2018/blob/main/DS2018_ResNet_cuda_binary_classification.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="_bNmLSfRxBMe" outputId="482f8abb-721d-4c55-f2b2-54671a521d97" colab={"base_uri": "https://localhost:8080/"} # from google.colab import drive # drive.mount('/content/drive') # + [markdown] id="4CVtkGYYYm6X" # # Download the data from openneuro using aws # + id="jSJi919H_8v3" # # !pip install awscli # + id="HlrioVew-qLq" # # !aws s3 sync --no-sign-request s3://openneuro.org/ds001246 ds001246-download/ # + [markdown] id="iUtWRsbEYgxR" # # Visualization and description of different types of the data # + id="IqfKUH44DzJ-" # import nibabel as nib # import matplotlib.pyplot as plt # def show_slices(slices): # """ Function to display row of image slices """ # fig, axes = plt.subplots(1, len(slices)) # for i, slice in enumerate(slices): # axes[i].imshow(slice.T, cmap="gray", origin="lower") # anat_img = nib.load('/content/ds001246-download/derivatives/preproc-spm/output/sub-01/ses-anatomy/anat/sub-01_ses-anatomy_T1w_preproc.nii.gz') # anat_img_data = anat_img.get_fdata() # print(anat_img_data.shape) # show_slices([anat_img_data[120, :, :], # anat_img_data[:, 120, :], # anat_img_data[:, :, 120]]) # plt.suptitle("Center slices for anatomical image") # + id="8vrj_BxYNWtq" # mid_slice_x = anat_img_data[120, :, :] # print(mid_slice_x.shape) # plt.imshow(mid_slice_x.T, cmap='gray', origin='lower') # plt.xlabel('First axis') # plt.ylabel('Second axis') # plt.colorbar(label='Signal intensity') # plt.suptitle("Center slice for anatomical image") # plt.show() # + id="s4_3AyqbEGRB" # f_img = nib.load('/content/ds001246-download/derivatives/preproc-spm/output/sub-01/ses-imageryTest01/func/sub-01_ses-imageryTest01_task-imagery_run-01_bold_preproc.nii.gz') # f_img_data = f_img.get_fdata() # print(f_img_data.shape) # show_slices([f_img_data[38, :, :, 0], # f_img_data[:, 38, :, 0], # f_img_data[:, :, 25, 0]]) # plt.suptitle("Center slices for functional image") # + id="G1yxrpUlMxCE" # mid_slice_x_fmri = f_img_data[38, :, :, 0] # x = 38, t = 0 # print("Shape of slice: %s" % (mid_slice_x_fmri.shape,)) # plt.imshow(mid_slice_x_fmri.T, cmap='gray', origin='lower') # plt.xlabel('First axis') # plt.ylabel('Second axis') # plt.colorbar(label='Signal intensity') # plt.suptitle("Center slice for functional image") # plt.show() # + id="YKerinsV8kGr" # mask_img = nib.load('/content/ds001246-download/sourcedata/sub-01/anat/sub-01_mask_RH_V1d.nii.gz') # mask_img_data = mask_img.get_fdata() # print(mask_img_data.shape) # show_slices([mask_img_data[32, :, :], # mask_img_data[:, 32, :], # mask_img_data[:, :, 25]]) # plt.suptitle("Brain Regions Mask For sub-01") # + id="6TdTGWGw-UjW" # import pandas as pd # events_df = pd.read_csv("/content/ds001246-download/sub-01/ses-imageryTest01/func/sub-01_ses-imageryTest01_task-imagery_run-01_events.tsv", sep='\t') # events_df.head(5) # + id="w39ACExAk6ms" # events_df2 = pd.read_csv("/content/ds001246-download/sub-01/ses-perceptionTest01/func/sub-01_ses-perceptionTest01_task-perception_run-01_events.tsv", sep="\t") # events_df2.head(5) # + [markdown] id="QoY-ahhlZvjI" # # creating a map for data generator # + id="MLgNuoyohGcJ" import os import os.path def get_paths(dir_addr): " ..:: here we create a file with all event addresses ::.. " file_paths = list() for dirpath, dirnames, filenames in os.walk(dir_addr): for filename in [f for f in filenames if f.endswith(".tsv")]: file_paths.append(os.path.join(dirpath, filename)) return file_paths # + id="kLDeUHB8JMbX" import pandas as pd def create_map(file_path): "..:: A dataframe which contains all the informations needed for data generator::.. " Map = pd.DataFrame(columns=["Onset", "Offset", "Stimuli/Category_ID", "Event_Type", "Image_Address"]) for addr in file_paths: tsv_file = pd.read_csv(addr, sep="\t") image_addr = "/content/ds001246-download/" + addr[27:-10] + "bold.nii.gz" for index, row in tsv_file.iterrows(): onset = row["onset"] offset = onset + row["duration"] event_type = row["event_type"] if "imagery" in image_addr: try: id = int(row["category_id"]) except ValueError: id = 0 elif "perception" in image_addr: try: id = int(row["stim_id"]) except ValueError: id = 0 Map = Map.append({"Onset":onset, "Offset":offset, "Stimuli/Category_ID":id, "Event_Type":event_type, "Image_Address":image_addr}, ignore_index=True) return Map # + id="cFKLOgFycj0-" outputId="605139fb-bf09-40c8-978e-d7de2d7c0f15" colab={"base_uri": "https://localhost:8080/", "height": 206} file_paths = get_paths("/content/ds001246-download/") map = create_map(file_paths) map.head(5) # + id="EjDTRrl-gQSt" # print("Number of Unique Image Addresses: ", len(map["Image_Address"].unique())) # print("Number of Unique IDs: ", len(map["Stimuli/Category_ID"].unique())) # print("Here is Top 10 (in terms of frequency)\n", map["Stimuli/Category_ID"].value_counts()[1:11]) # print("Number of total events", len(map)) # + [markdown] id="uiyLJMpP5ZWE" # # Here we select prefered categories and event types # + id="yihqpPwpgRSx" colab={"base_uri": "https://localhost:8080/"} outputId="433f473a-e70f-4d89-bbed-f9fd290e03a6" categories = list(map["Stimuli/Category_ID"].value_counts()[1:].index) # most frequent categories f_map = map.loc[ (map['Event_Type'].isin(['imagery', 'stimulus'])) & (map['Stimuli/Category_ID'].isin(categories))] len(f_map) # + id="e9_kmkCEfSeT" outputId="e08ed51f-d945-4286-c70b-65f0508cbbae" colab={"base_uri": "https://localhost:8080/", "height": 577} from sklearn.preprocessing import OneHotEncoder #creating instance of one-hot-encoder encoder_df = pd.get_dummies(f_map['Stimuli/Category_ID']) map = f_map.join(encoder_df) print(map['Event_Type'].value_counts()) final_map = map.groupby('Event_Type').apply(lambda x: x.sample(n=2475)).reset_index(drop = True) final_map = final_map.sample(frac=1, random_state=14) print(final_map['Event_Type'].value_counts()) final_map.head(5) # + id="EusliSR3lgZT" # final_map = final_map.sample(n=4) ################################ # + [markdown] id="5KJfBSQDSBlU" # # Preparing DataLoader # + id="_J1xaizFP3oq" colab={"base_uri": "https://localhost:8080/"} outputId="492d9e62-846b-4785-c3bd-c4ede2f129ac" import nibabel as nib import matplotlib.pyplot as plt from __future__ import print_function, division import torch from skimage import io, transform import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils # + id="Azfl6sbmSbwV" # for stimulus experiment, there are 175 samples for 534 seconds # for imagery experiment, there are 210 samples for 639 seconds # sampling rate ==> 1 sample every 3 seconds (fMRI limitation) import random import math import torchvision.transforms as transforms class Gdecoder(Dataset): def __init__(self, map, transform=None, img_stim=False, time_series=True): """ Args: """ self.img_stim = img_stim self.time_series = time_series self.map = map self.transform = transform def __len__(self): return len(self.map) def __getitem__(self, idx): if torch.is_tensor(idx): idx = idx.tolist() image_path = self.map.iloc[idx]['Image_Address'] onset = math.floor((self.map.iloc[idx]['Onset'])/3) offset = math.floor((self.map.iloc[idx]['Offset']/3)) image_obj = nib.load(image_path) event_type = self.map.iloc[idx]['Event_Type'] # here we select a sequence of 3 numbers in imagery image time points which is 5 # in order to solve input size incompatibility issue if event_type == 'imagery': imagery_onset = random.randint(onset, offset-3) imagery_offset = imagery_onset + 3 image = image_obj.dataobj[:, :, :, imagery_onset:imagery_offset] else: image = image_obj.dataobj[:, :, :, onset:offset] num_classes = 4 label = np.array(self.map.iloc[idx, -num_classes:], dtype=float) label = torch.from_numpy(label) label = torch.unsqueeze(label, 0) # ============> label = label.repeat(3, 1) # ============> label = label.type(torch.FloatTensor) if self.time_series == True: if self.img_stim == True: if event_type == 'stimulus': label = torch.Tensor([[0, 1], [0, 1], [0, 1]]) elif event_type == 'imagery': label = torch.Tensor([[1, 0], [1, 0], [1, 0]]) else: if self.img_stim == True: if event_type == 'stimulus': label = torch.Tensor([[0, 1]]) elif event_type == 'imagery': label = torch.Tensor([[1, 0]]) if image.shape[-1] != 3: # correction image = np.array(image[:, :, :, :], dtype=np.float64) rpt_image = image[:, :, :, 0:1] image = np.concatenate((image, rpt_image), axis=3) if self.time_series == False: image = image[:, :, :, random.randint(0,2)] image = np.expand_dims(image, axis=-1) if self.transform: image = np.array(image[:, :, :, :], dtype=np.float64) sample = {'image' : torch.from_numpy((image.T)), 'event type': event_type, 'label': label} else: sample = {'image' : image.T, 'event type': event_type, 'label': label} return sample # + id="mVs2zhF8Q5VC" # transform = transforms.Compose([transforms.ToTensor(), # transforms.Normalize()]) # dataset = Gdecoder(map=final_map, transform = transform) # loader = DataLoader( # dataset, # batch_size=4, # num_workers=2, # shuffle=False # ) # mean = 0. # std = 0. # nb_samples = 0. # for data in loader: # data = data['image'].float() # batch_samples = data.size(0) # data = data.view(batch_samples, data.size(1), -1) # mean += data.mean(2).sum(0) # std += data.std(2).sum(0) # nb_samples += batch_samples # mean /= nb_samples # std /= nb_samples # print(mean) # print(std) # + id="UbsbEo_WXoRX" # dataset = Gdecoder(map=final_map, transform = None) # + id="i16Pq7caUUQM" # for i in range(len(dataset)): # if dataset[i]['event type'] == 'stimulus': # sample = dataset[i] # print('one hot of the label:\n ', sample['label']) # print("Event Type: ", sample['event type']) # f_img_data = sample['image'].T # print("transposed sample shapes: ", f_img_data.shape) # show_slices([f_img_data[38, :, :, 2], # f_img_data[:, 38, :, 2], # f_img_data[:, :, 25, 2]]) # plt.suptitle("Center slices for functional image (stimulus experiment)") # break # + id="9MhvesSimBHQ" # for i in range(len(dataset)): # if dataset[i]['event type'] == 'imagery': # sample = dataset[i] # print('one hot of the label:\n ', sample['label']) # print("Event Type: ", sample['event type']) # f_img_data = sample['image'].T # print("transposed sample shapes: ", f_img_data.shape) # show_slices([f_img_data[38, :, :, 2], # f_img_data[:, 38, :, 2], # f_img_data[:, :, 25, 2]]) # plt.suptitle("Center slices for functional image (imagery experiment)") # break # + id="yIIRoTgRhJER" from torch.utils.data.sampler import SubsetRandomSampler import torchvision.transforms as transforms # transform = transforms.Compose([transforms.ToTensor(), # transforms.Normalize((258.7493, 258.8581, 258.8850), (347.9486, 348.1261, 388.1579))]) transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=(263.4574, 263.5031, 263.4838), std=(353.8419, 353.9187, 353.8715))]) # dataset = Gdecoder(map=final_map, transform = transform) dataset = Gdecoder(map=final_map, transform = transform, img_stim=True, time_series=False) # stimulus imagery classification batch_size = 4 test_split = .1 valid_split = .1 shuffle_dataset = True random_seed= 9 # Creating data indices for training and test splits: dataset_size = len(dataset) indices = list(range(dataset_size)) split_test = int(np.floor(test_split * dataset_size)) split_valid = int( split_test + (np.floor(valid_split * dataset_size))) if shuffle_dataset : np.random.seed(random_seed) np.random.shuffle(indices) test_indices = indices[:split_test] valid_indices = indices[split_test:split_valid] train_indices = indices[split_valid:] # Creating PT data samplers and loaders: train_sampler = SubsetRandomSampler(train_indices) valid_sampler = SubsetRandomSampler(valid_indices) test_sampler = SubsetRandomSampler(test_indices) train_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=train_sampler) valid_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=valid_sampler) test_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=test_sampler) # + id="vFJR3DCkNS4H" from torch import nn from torchvision import models import torch.nn.functional as F class mainnet(nn.Module): def __init__(self,hidden_size,n_layers,dropt,bi,N_classes): super(mainnet, self).__init__() self.hidden_size=hidden_size self.num_layers=n_layers self.dim_feats = 256 ############# Block 1 ############### self.conv1_0 = nn.Conv3d(1, 16, kernel_size=(3, 3, 3), stride=(2, 2, 2), padding=0) self.conv1_0_In = nn.InstanceNorm3d(16) self.conv1_1 = nn.Conv3d(16, 16, kernel_size=(5, 5, 5), stride=(1, 1, 1), padding='same') self.conv1_1_In = nn.InstanceNorm3d(16) self.conv1_2 = nn.Conv3d(16, 16, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding='same') self.conv1_2_In = nn.InstanceNorm3d(16) self.conv1_3 = nn.Conv3d(16, 16, kernel_size=(5, 5, 5), stride=(1, 1, 1), padding='same') self.conv1_3_In = nn.InstanceNorm3d(16) ############## Block 2 ############### self.conv2_0 = nn.Conv3d(16, 128, kernel_size=(3, 3, 3), stride=(2, 2, 2), padding=0) self.conv2_0_In = nn.InstanceNorm3d(128) self.conv2_1 = nn.Conv3d(128, 128, kernel_size=(5, 5, 5), stride=(1, 1, 1), padding='same') self.conv2_1_In = nn.InstanceNorm3d(128) self.conv2_2 = nn.Conv3d(128, 128, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding='same') self.conv2_2_In = nn.InstanceNorm3d(128) self.conv2_3 = nn.Conv3d(128, 128, kernel_size=(5, 5, 5), stride=(1, 1, 1), padding='same') self.conv2_3_In = nn.InstanceNorm3d(128) ############## Block 3 ############### self.conv3_0 = nn.Conv3d(128, 512, kernel_size=(7, 7, 7), stride=(2, 2, 2), padding=0) self.conv3_0_In = nn.InstanceNorm3d(512) self.conv3_1 = nn.Conv3d(512, 512, kernel_size=(5, 5, 5), stride=(1, 1, 1), padding='same') self.conv3_1_In = nn.InstanceNorm3d(512) self.conv3_2 = nn.Conv3d(512, 512, kernel_size=(7, 7, 7), stride=(1, 1, 1), padding='same') self.conv3_2_In = nn.InstanceNorm3d(512) self.conv3_3 = nn.Conv3d(512, 512, kernel_size=(5, 5, 5), stride=(1, 1, 1), padding='same') self.conv3_3_In = nn.InstanceNorm3d(512) ########## the rest ################# # self.conv4_0 = nn.Conv3d(128, 1024, kernel_size=(7, 7, 7), stride=(2, 2, 2), padding=0) # self.conv4_0_In = nn.InstanceNorm3d(128) # self.conv4_1 = nn.Conv3d(1024, 1024, kernel_size=(7, 7, 7), stride=(2, 2, 2), padding=0) # self.conv4_1_In = nn.InstanceNorm3d(1024) self.conv4_out = nn.Conv3d(512, 256, kernel_size=(3, 5, 5), stride=(1, 1, 1), padding=0) self.conv4_out_Ins = nn.InstanceNorm3d(256) # self.conv4 = nn.Conv3d(256, 512, kernel_size=(5, 5, 5), stride=(1, 1, 1), padding=0) # self.conv4_In = nn.InstanceNorm3d(512) self.n_cl=N_classes self.softmax = nn.Softmax(dim=-1) self.sigmoid = nn.Sigmoid() self.Leaky_ReLU = nn.LeakyReLU() self.last_linear = nn.Linear(self.dim_feats, 2048) self.bn1 = nn.BatchNorm1d(2048) self.last_linear_1 = nn.Linear(2048, 512) self.bn2 = nn.BatchNorm1d(512) self.last_linear_2 = nn.Linear(512, 64) self.bn3 = nn.BatchNorm1d(64) self.last_linear_3 = nn.Linear(64, self.n_cl) self.rnn = nn.LSTM( input_size=self.n_cl, hidden_size=self.hidden_size, bias = True, num_layers=self.num_layers, dropout=dropt, bidirectional=False, batch_first=True) def forward(self, x1, x2): batch_size, timesteps, C,H, W = x1.size() c_in = x1.view(batch_size, timesteps, C, H, W) res1 = (self.conv1_0(c_in)) # self.conv1_0_In res1_relu = self.Leaky_ReLU(res1) h = self.Leaky_ReLU((self.conv1_1(res1_relu))) # self.conv1_1_In h = self.Leaky_ReLU((self.conv1_2(h))) # self.conv1_2_In h = (self.conv1_3(h)) # self.conv1_3_In h = self.Leaky_ReLU(h+res1) res2 = (self.conv2_0(h)) # self.conv2_0_In res2_relu = self.Leaky_ReLU(res2) h = self.Leaky_ReLU((self.conv2_1(res2_relu))) # self.conv2_1_In h = self.Leaky_ReLU((self.conv2_2(h))) # self.conv2_2_In h = (self.conv2_3(h)) # self.conv2_3_In h = self.Leaky_ReLU(h+res2) res3 = (self.conv3_0(h)) #self.conv3_0_In res3_relu = self.Leaky_ReLU(res3) h = self.Leaky_ReLU((self.conv3_1(res3_relu))) #self.conv3_1_In h = self.Leaky_ReLU((self.conv3_2(h))) # self.conv3_2_In h = self.Leaky_ReLU((self.conv3_3(h))) # self.conv3_3_In # h = self.Leaky_ReLU(self.conv4_1_In(self.conv4_1(h))) h = self.Leaky_ReLU((self.conv4_out(h))) # self.conv4_out_Ins # h_identity_2 = self.conv3_0_In(self.conv3_0(h+res3)) # downsample # h_identity_3 = self.Leaky_ReLU(h+h_identity_2) # h = self.Leaky_ReLU(self.conv3_1_In(self.conv3_1(h_identity_3))) h = torch.flatten(h, start_dim=1) c_out = torch.unsqueeze(h, 0) fc_out = self.last_linear(c_out) fc_out = fc_out.permute(0, 2, 1) fc_out = self.Leaky_ReLU(self.bn1((fc_out))) fc_out = fc_out.permute(0, 2, 1) fc_out = self.last_linear_1(fc_out) fc_out = fc_out.permute(0, 2, 1) fc_out = self.Leaky_ReLU(self.bn2(fc_out)) fc_out = fc_out.permute(0, 2, 1) fc_out = self.last_linear_2(fc_out) fc_out = fc_out.permute(0, 2, 1) fc_out = self.Leaky_ReLU(self.bn3(fc_out)) fc_out = fc_out.permute(0, 2, 1) if x2 == None: fc_out = self.last_linear_3(fc_out) else: fc_out = self.last_linear_3(x2) # r_out, h_n = self.rnn(fc_out) return fc_out # r_out[-1] # + id="bsVU45fzXkYz" # net = mainnet(hidden_size=4, n_layers=3, dropt=0, bi=True, N_classes=4 ) net = mainnet(hidden_size=4, n_layers=3, dropt=0, bi=True, N_classes=2 ) # stimulus imagery classification # + id="1OnevQrcyfKH" colab={"base_uri": "https://localhost:8080/"} outputId="a85324dc-f86b-47c1-8c69-d54d84667c26" activation = {} def get_activation(name): def hook(model, input, output): activation[name] = output.detach() return hook # register activation saving on imagery layer net.last_linear_2.register_forward_hook(get_activation('last_linear_2')) # + [markdown] id="zkRsXFlRs5az" # ## Training # + id="3qEG3zK-afnh" # initialize model def init_weights(m): if isinstance(m, nn.Linear): torch.nn.init.kaiming_uniform_(m.weight) if m.bias != None: m.bias.data.fill_(0.001) net.apply(init_weights) # + id="5XlWBrM_YgC9" import torch.optim as optim from torch.optim.lr_scheduler import StepLR # def one_hot_ce_loss(outputs, targets): # criterion = nn.CrossEntropyLoss() # # _, labels = torch.max(targets, dim=1) # return criterion(outputs, labels) # criterion = nn.MultiMarginLoss() criterion = nn.BCEWithLogitsLoss() # imagery stimulus classification optimizer = optim.Adam(net.parameters(), lr=0.00075) scheduler = StepLR(optimizer, step_size=4, gamma=0.00001) # + id="o9JrwtQe4Cua" device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') net.to(device) # + id="UV3_Nhh4Dc-E" # free up disk space for saving weights for preprocessed data training # # !rm -rf /content/ds001246-download/sub-01 # # !rm -rf /content/ds001246-download/sub-02 # # !rm -rf /content/ds001246-download/sub-03 # # !rm -rf /content/ds001246-download/sub-04 # # !rm -rf /content/ds001246-download/sub-05 # + id="jG662J-iq2aL" # free up disk space for saving weights for raw data training # # !rm -rf /content/ds001246-download/derivatives # + id="7sMVOgG9a94m" outputId="1a77077f-a402-4edd-ae11-f526fbe8a262" colab={"base_uri": "https://localhost:8080/"} from tqdm import tqdm from time import sleep loss_history = [] num_classes = 2 Imgry_bag = torch.zeros(num_classes, 3, 128) # Imagery Layer Shape => num_classes x 3 x 128 bag_loss_flag = torch.zeros(2, num_classes) for epoch in range(100): # loop over the dataset multiple times corrects = 0 running_loss = 0.0 running_loss_step = 0.0 accuracy = 0.0 accuracy_step = 0.0 loss_values = [] for param in net.parameters(): param.requires_grad = True with tqdm(train_loader, unit="batch") as tepoch: net.train() for i, data in enumerate(tepoch, 0): # get the inputs; data is a list of [inputs, labels] tepoch.set_description(f"Epoch {epoch}") inputs, labels = data['image'].type(torch.float64), data['label'].type(torch.float64) inputs, labels = inputs.to(device, dtype=torch.float), labels.to(device, dtype=torch.float) # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs, None) labels = torch.squeeze(labels, 0) labels = torch.squeeze(labels, 1) # num_classes = labels.size(dim=1) num_classes = 2 # imagery stimulus classification my_class = labels[0] outputs = torch.squeeze(outputs, 0) loss = criterion(outputs.cuda(), labels.cuda()) # statistics labels = torch.max(labels, dim=1).indices prediction = torch.max(outputs, dim=1).indices corrects = torch.eq(prediction, labels).sum() running_loss += loss.item() running_loss_step += loss.item() sample_accuracy = np.array( (corrects / labels.shape[0]).cpu() ) accuracy += sample_accuracy accuracy_step += sample_accuracy #################### Imagination block ###################### # if corrects == torch.Tensor([3]).to(device): # # if class flag eq zero # if bag_loss_flag[1, my_class] == 0: # # save activation # Imgry_bag[my_class, :, :] = activation['last_linear_2'] # bag_loss_flag[0, my_class] = loss # bag_loss_flag[1, my_class] = 1 # set flag # elif loss < bag_loss_flag[0, my_class]: # Imgry_bag[my_class, :, :] = activation['last_linear_2'] # bag_loss_flag[0, my_class] = loss # else: # pass # # elif there is an elit for this class # elif (bag_loss_flag[1, my_class] == 1) and (epoch >= 1): # if np.random.rand(1) > np.array([0.5]): # # IMAGERY # # all except one last layer # for param in net.parameters(): # param.requires_grad = False # for param in net.last_linear_3.parameters(): # param.requires_grad = True # # forward + backward # class_elit = Imgry_bag[my_class, :, :] # outputs = net(inputs, class_elit.to(device)) # outputs = torch.squeeze(outputs, 0) # loss = criterion(outputs.cuda(), labels.cuda()) # loss.backward() # optimizer.step() # # AGAIN # for param in net.parameters(): # param.requires_grad = True # net.train() # outputs = net(inputs, None) # outputs = torch.squeeze(outputs, 0) # prediction = torch.max(outputs, dim=1).indices # loss = criterion(outputs.cuda(), labels.cuda()) ############################################################# loss.backward() optimizer.step() loss_values.append(running_loss / len(train_loader)) # torch.Tensor(i).to(device) # tepoch.set_postfix(loss=float(running_loss/(i+1)), accuracy=float(100. * (accuracy/(i+1)))) # sleep(0.1) update_step = 10 if i % update_step == 0: # print every 2000 mini-batches tepoch.set_postfix(loss=float(running_loss_step/update_step), accuracy=float(100. * (accuracy_step/update_step))) sleep(0.1) running_loss_step = 0.0 accuracy_step = 0 # ############ Validation ################ print('train loss:', running_loss/(len(train_loader))) print('train accuracy:', float(100. * (accuracy/len(train_loader)))) corrects = 0 running_loss = 0.0 accuracy = 0.0 net.eval() with tqdm(valid_loader, unit="batch") as tepoch: for i, data in enumerate(tepoch, 0): # get the inputs; data is a list of [inputs, labels] tepoch.set_description(f"Validation {epoch}") inputs, labels = data['image'].type(torch.float64), data['label'].type(torch.float64) inputs, labels = inputs.to(device, dtype=torch.float), labels.to(device, dtype=torch.float) with torch.no_grad(): # forward + backward + optimize outputs = net(inputs, None) labels = torch.squeeze(labels, 0) labels = torch.squeeze(labels, 1) labels = torch.max(labels, dim=1).indices outputs = torch.squeeze(outputs, 0) prediction = torch.max(outputs, dim=1).indices corrects = torch.eq(prediction, labels).sum() running_loss += loss.item() accuracy += np.array( (corrects / labels.shape[0]).cpu() ) valloss = np.array(running_loss) / len(valid_loader) print('Validation Accuracy: ', (accuracy/len(valid_loader))) print("Validation Loss: ", valloss) loss_history.append(loss_values) scheduler.step() torch.save(net.state_dict(), '/content/drive/MyDrive/Generic Decoding model weights/model_weights_epoch_{}_valloss_{}.pth'.format(epoch, valloss)) print('Finished Training') # + [markdown] id="tc6lUb4fY0a-" # # Test # + id="0w9tJbU6Y9hR" net.load_state_dict(torch.load('/content/drive/MyDrive/Generic Decoding model weights/model_weights_epoch_7.pth')) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') net.to(device) for param in net.parameters(): param.requires_grad = False # + id="DMuJtXgAZKbT" from tqdm import tqdm from time import sleep corrects = 0 running_loss = 0.0 accuracy = 0.0 with tqdm(test_loader, unit="batch") as tepoch: for i, data in enumerate(tepoch, 0): # get the inputs; data is a list of [inputs, labels] tepoch.set_description(f"Epoch {epoch}") inputs, labels = data['image'].type(torch.float64), data['label'].type(torch.float64) inputs, labels = inputs.to(device), labels.to(device) # forward + backward + optimize outputs = net(inputs) labels = torch.squeeze(labels, 0) labels = torch.max(labels, dim=1).indices outputs = torch.squeeze(outputs, 0) prediction = torch.max(outputs, dim=1).indices corrects = torch.eq(prediction, labels).sum() running_loss += loss.item() accuracy += np.array( (corrects / labels.shape[0]).cpu() ) print('Test Accuracy: ', (accuracy/len(valid_loader))) print("Test Loss: ", ( np.array(running_loss) / len(valid_loader))) # + id="XNoQV4vucWxB"
DS2018_ResNet_cuda_binary_classification.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # %matplotlib inline import numpy as np import pandas as pd from pathlib import Path import os, sys, datetime, time, random, fnmatch, math import matplotlib.pyplot as plt import matplotlib.animation as animation import skimage.metrics from sklearn.model_selection import KFold import torch from torchvision import transforms as tvtransforms from torch.utils.data import Dataset, DataLoader, random_split, SubsetRandomSampler, ConcatDataset import torchvision.utils as vutils import torch.utils.tensorboard as tensorboard import torch.nn as nn import torch.optim as optim import datasets, custom_transforms, GusarevModel, pytorch_msssim flag_debug = False flag_load_previous_save = False flag_selectFold, selectedFold = True, 5 # Input Directories #data_BSE = "D:/data/JSRT/BSE_JSRT" #data_normal = "D:/data/JSRT/JSRT" data_BSE = Path('G:/DanielLam/JSRT/HQ_JSRT_and_BSE-JSRT/177-20-20 split/trainValidate_LowRes/suppressed/') data_normal = Path('G:/DanielLam/JSRT/HQ_JSRT_and_BSE-JSRT/177-20-20 split/trainValidate_LowRes/normal/') #data_val_normal = 'G:/DanielLam/JSRT/HQ_JSRT_and_BSE-JSRT/177-20-20 split/validate/normal' #data_val_BSE = 'G:/DanielLam/JSRT/HQ_JSRT_and_BSE-JSRT/177-20-20 split/validate/suppressed/' # Save directories: output_save_directory = Path("./runs/6LayerCNN/177-20-20/Fold4_217perEpoch_400Epochs") output_save_directory.mkdir(parents=True, exist_ok=True) PATH_SAVE_NETWORK_INTERMEDIATE = os.path.join(output_save_directory, 'network_intermediate_{}.tar' ) PATH_SAVE_NETWORK_FINAL = os.path.join(output_save_directory, 'network_final_{}.pt') # Image Size: image_spatial_size = (256 , 256) _batch_size = 5 split_k_folds=10 sample_keys_images = ["source", "boneless"] # Optimisation lr_ini = 0.001 beta1 = 0.9 beta2 = 0.999 # Training num_reals_per_epoch_paper = 217 #4000 # in Gusarev et al. 2017 total_num_epochs_paper = 400 # 150 in paper num_epochs_decay_lr_paper = 100 lr_decay_ratio = 0.25 # Weight Initialisation def weights_init(m): classname = m.__class__.__name__ if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d): nn.init.normal_(m.weight.data, 0., 0.02) #nn.init.kaiming_normal_(m.weight.data,0) try: nn.init.constant_(m.bias.data, 0.) except: pass if isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.InstanceNorm2d): if m.affine: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0.) ## Code for putting things on the GPU ngpu = 1 #torch.cuda.device_count() os.environ["CUDA_VISIBLE_DEVICES"] = "0,1" device = torch.device("cuda" if (torch.cuda.is_available() and ngpu > 0) else "cpu") print(device) if (torch.cuda.is_available()): print(torch.cuda.get_device_name(torch.cuda.current_device())) if ngpu ==1: device=torch.device('cuda:0') # + # Current date: current_date=datetime.datetime.today().strftime('%Y-%m-%d') # Data Loader original_key = "source" target_key = "boneless" discriminator_keys_images = [original_key, target_key] #ds_training = datasets.JSRT_CXR(data_normal, data_BSE, # transform=tvtransforms.Compose([ # custom_transforms.HistogramEqualisation(discriminator_keys_images),-- check if training data is already equalised # custom_transforms.Resize(discriminator_keys_images, image_spatial_size), # custom_transforms.ToTensor(discriminator_keys_images), # ]) # ) #ds_val = datasets.JSRT_CXR(data_val_normal, data_val_BSE, # transform=tvtransforms.Compose([ #custom_transforms.HistogramEqualisation(discriminator_keys_images),# # custom_transforms.Resize(discriminator_keys_images, image_spatial_size), # custom_transforms.ToTensor(discriminator_keys_images), # ]) # ) # + # Loss definitions # Gusarev Loss def criterion_MSELoss(testImage, referenceImage): mse = nn.MSELoss() mse_loss = mse(testImage, referenceImage) return mse_loss, mse_loss, torch.zeros(1) def criterion_Gusarev(testImage, referenceImage, alpha=0.84): """ Gusarev et al. 2017. Deep learning models for bone suppression in chest radiographs. IEEE Conference on Computational Intelligence in Bioinformatics and Computational Biology. """ mse = nn.MSELoss() # L2 used for easier optimisation c.f. L1 mse_loss = mse(testImage, referenceImage) msssim = pytorch_msssim.MSSSIM(window_size=11, size_average=True, channel=1, normalize='relu') msssim_loss = 1 - msssim(testImage, referenceImage) total_loss = (1-alpha)*mse_loss + alpha*msssim_loss return total_loss, mse_loss, msssim_loss # + # Training # Data augmentation transformations data_transforms = { 'train_transforms': tvtransforms.Compose([ custom_transforms.RandomAutocontrast(sample_keys_images, cutoff_limits=(0.1,0.1)), custom_transforms.CenterCrop(sample_keys_images,256), custom_transforms.RandomHorizontalFlip(sample_keys_images, 0.5), custom_transforms.RandomAffine(sample_keys_images, degrees=10,translate=(0.1,0.1),scale=(0.9,1.1)), custom_transforms.ToTensor(sample_keys_images), custom_transforms.ImageComplement(sample_keys_images), ]) , 'test_transforms': tvtransforms.Compose([ custom_transforms.ToTensor(sample_keys_images), ]), } # K-FOLD VALIDATION #dataset = ConcatDataset([ds_training, ds_val]) splits=KFold(n_splits=split_k_folds,shuffle=True,random_state=42) foldperf={} print(target_key) dataset = datasets.JSRT_CXR(data_normal, data_BSE, transform=None) for fold, (train_idx,val_idx) in enumerate(splits.split(np.arange(len(dataset)))): # fold starts from 0 print('Fold {}'.format(fold + 1)) if flag_selectFold and selectedFold >= 1 and selectedFold <= split_k_folds: if fold + 1 != selectedFold: print("Skipping Fold") continue history = {'loss':[], 'ssim_acc':[]} # Subset sample from dataset train_sampler = SubsetRandomSampler(train_idx) test_sampler = SubsetRandomSampler(val_idx) dl_training = DataLoader(datasets.JSRT_CXR(data_normal, data_BSE, transform=data_transforms['train_transforms']), batch_size=_batch_size, sampler=train_sampler, num_workers=0) dl_validation = DataLoader(datasets.JSRT_CXR(data_normal, data_BSE, transform=data_transforms['train_transforms']), batch_size=_batch_size, sampler=test_sampler, num_workers=0) # Print example of transformed image for count, sample in enumerate(dl_training): image = sample["source"][0,:] image = torch.squeeze(image) plt.imshow(image) if count == 0: break # Network input_array_size = (_batch_size, 1, image_spatial_size[0], image_spatial_size[1]) net = GusarevModel.MultilayerCNN(input_array_size) # Initialise weights net.apply(weights_init) # Multi-GPU if (device.type == 'cuda') and (ngpu > 1): print("Neural Net on GPU") net = nn.DataParallel(net, list(range(ngpu))) net = net.to(device) # Optimiser optimizer = torch.optim.Adam(net.parameters(), lr=lr_ini, betas=(beta1, beta2)) # Learning Rate Scheduler epoch_factor = round(num_reals_per_epoch_paper/len(train_idx)) # need to have this factor as many epochs as that described in the paper print("Epoch Factor: "+str(epoch_factor)) total_num_epochs = int(total_num_epochs_paper*epoch_factor) num_epochs_decay_lr = int(num_epochs_decay_lr_paper*epoch_factor) lambda_rule = lambda epoch: 1*((1-lr_decay_ratio)**(epoch//num_epochs_decay_lr)) scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule, verbose=True) # For each epoch epochs_list = [] img_list = [] training_loss_list = [] reals_shown = [] #validation_loss_per_epoch_list = [] #training_loss_per_epoch_list = [] loss_per_epoch={"training":[], "validation":[]} ssim_average={"training":[], "validation":[]} #fixed_val_sample = next(iter(dl_validation)) #fig, ax = plt.subplots(1,2) #ax[0].imshow(fixed_val_sample[original_key][0,0,:]) #ax[1].imshow(fixed_val_sample[target_key][0,0,:]) #plt.show() # optionally resume from a checkpoint if flag_load_previous_save: if os.path.isfile(PATH_SAVE_NETWORK_INTERMEDIATE): print("=> loading checkpoint '{}'".format(PATH_SAVE_NETWORK_INTERMEDIATE)) checkpoint = torch.load(PATH_SAVE_NETWORK_INTERMEDIATE) start_epoch = checkpoint['epoch_next'] reals_shown_now = checkpoint['reals_shown'] scheduler.load_state_dict(checkpoint['scheduler_state_dict']) net.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) print("=> loaded checkpoint '{}' (epoch {}, reals shown {})".format(PATH_SAVE_NETWORK_INTERMEDIATE, start_epoch, reals_shown_now)) print(scheduler) else: print("=> NO CHECKPOINT FOUND AT '{}'" .format(PATH_SAVE_NETWORK_INTERMEDIATE)) raise RuntimeError("No checkpoint found at specified path.") else: print("FLAG: NO CHECKPOINT LOADED.") reals_shown_now = 0 start_epoch=0 # Loop variables flag_break = False # when debugging, this will automatically go to True iters = 0 net.train() for param in net.parameters(): param.requires_grad = True for epoch in range(start_epoch, total_num_epochs): print(optimizer.param_groups[0]['lr']) sum_loss_in_epoch = 0 for i, data in enumerate(dl_training): # Training net.zero_grad() noisy_data = data[original_key].to(device) cleaned_data = net(noisy_data) loss, maeloss, msssim_loss = criterion_Gusarev(cleaned_data, data[target_key].to(device)) loss.backward() # calculate gradients optimizer.step() # optimiser step along gradients # Output training stats if epoch%1000 == 0: print('[%d/%d][%d/%d]\tTotal Loss: %.4f\tMSELoss: %.4f\tMSSSIM Loss: %.4f' % (epoch, total_num_epochs, i, len(dl_training), loss.item(), maeloss.item(), msssim_loss.item())) # Record generator output #if reals_shown_now%(100*_batch_size)==0: # with torch.no_grad(): # val_cleaned = net(fixed_val_sample["source"].to(device)).detach().cpu() # print("Printing to img_list") # img_list.append(vutils.make_grid(val_cleaned[0:1,0:1,:], padding=2, normalize=True)) #iters +=1 #if flag_debug and iters>=10: # flag_break = True # break # Running counter of reals shown reals_shown_now += _batch_size reals_shown.append(reals_shown_now) # Training loss list for loss per minibatch training_loss_list.append(loss.item()) # training loss sum_loss_in_epoch += loss.item()*len(cleaned_data) # Turn the sum loss in epoch into a loss-per-epoch loss_per_epoch["training"].append(sum_loss_in_epoch/len(train_idx)) with torch.no_grad(): # Training Accuracy per EPOCH ssim_training_list = [] for train_count, data in enumerate(dl_training): noisy_training_data = data[original_key].to(device) true_training_data = data[target_key] cleaned_training_data = net(noisy_training_data) for ii, image in enumerate(cleaned_training_data): clean_training_numpy = image.cpu().detach().numpy() true_training_numpy = true_training_data[ii].numpy() clean_training_numpy = np.moveaxis(clean_training_numpy, 0, -1) true_training_numpy = np.moveaxis(true_training_numpy, 0, -1) ssim_training = skimage.metrics.structural_similarity(clean_training_numpy, true_training_numpy, multichannel=True) ssim_training_list.append(ssim_training) # SSIM per image ssim_average["training"].append(np.mean(ssim_training_list)) # Validation Loss and Accuracy per EPOCH sum_loss_in_epoch =0 ssim_val_list = [] for val_count, sample in enumerate(dl_validation): noisy_val_data = sample[original_key].to(device) cleaned_val_data = net(noisy_val_data) # Loss true_val_data = sample[target_key] val_loss, maeloss, msssim_loss = criterion_Gusarev(cleaned_val_data, true_val_data.to(device)) sum_loss_in_epoch += val_loss.item()*len(cleaned_val_data) # Accuracy for ii, image in enumerate(cleaned_val_data): clean_val_numpy = image.cpu().detach().numpy() true_val_numpy = true_val_data[ii].numpy() clean_val_numpy = np.moveaxis(clean_val_numpy, 0, -1) true_val_numpy = np.moveaxis(true_val_numpy, 0, -1) ssim_val = skimage.metrics.structural_similarity(clean_val_numpy, true_val_numpy, multichannel=True) ssim_val_list.append(ssim_val) # SSIM per image # After considering all validation images loss_per_epoch["validation"].append(sum_loss_in_epoch/len(val_idx)) ssim_average["validation"].append(np.mean(ssim_val_list)) epochs_list.append(epoch) # LR Scheduler after epoch scheduler.step() #if epoch % 5 == 0: # if not flag_debug: # #torch.save(net.state_dict(), PATH_SAVE_NETWORK_INTERMEDIATE) # torch.save({ # 'epochs_completed': epoch+1, # 'epoch_next': epoch+1, # 'model_state_dict': net.state_dict(), # 'optimizer_state_dict': optimizer.state_dict(), # 'loss': loss, # 'scheduler_state_dict': scheduler.state_dict(), # 'reals_shown': reals_shown_now # }, PATH_SAVE_NETWORK_INTERMEDIATE.format(fold)) # print("Saved Intermediate: "+ str(PATH_SAVE_NETWORK_INTERMEDIATE.format(fold)) #if flag_break: # break #After all epochs, save results: history["loss"] = loss_per_epoch history["ssim_acc"] = ssim_average foldperf['fold{}'.format(fold+1)] = history # Final Save for each fold if not flag_debug: torch.save({ 'epochs_completed': epoch+1, 'epoch_factor': epoch_factor, 'total_num_epochs': total_num_epochs, 'total_num_epochs_paper': total_num_epochs_paper, 'model_state_dict': net.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'loss': loss, 'scheduler_state_dict': scheduler.state_dict(), 'reals_shown': reals_shown_now }, PATH_SAVE_NETWORK_INTERMEDIATE.format(fold)) print("Saved Intermediate: "+ str(PATH_SAVE_NETWORK_INTERMEDIATE.format(fold))) # - if not flag_debug and not flag_selectFold: torch.save({ 'epochs_completed': epoch+1, 'epoch_factor': epoch_factor, 'total_num_epochs': total_num_epochs, 'total_num_epochs_paper': total_num_epochs_paper, 'model_state_dict': net.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'loss': loss, 'scheduler_state_dict': scheduler.state_dict(), 'reals_shown': reals_shown_now }, PATH_SAVE_NETWORK_INTERMEDIATE.format(fold)) print("Saved Intermediate: "+ str(PATH_SAVE_NETWORK_INTERMEDIATE.format(fold))) # + print("Training complete") # Find the best fold # AVERAGE PERFORMANCE testl_f,tl_f,testa_f,ta_f=[],[],[],[] k=10 if flag_selectFold: initial_fold=selectedFold else: initial_fold=1 fold_range = range(initial_fold, initial_fold+len(foldperf.keys())) for f in fold_range: tl_f.append(np.mean(foldperf['fold{}'.format(f)]['loss']['training'])) testl_f.append(np.mean(foldperf['fold{}'.format(f)]['loss']['validation'])) ta_f.append(np.mean(foldperf['fold{}'.format(f)]['ssim_acc']['training'])) testa_f.append(np.mean(foldperf['fold{}'.format(f)]['ssim_acc']['validation'])) print('Performance of {} fold cross validation'.format(k)) print("Average Training Loss: {:.3f} \t Average Test Loss: {:.3f} \t Average Training Acc: {:.3f} \t Average Test Acc: {:.3f}" .format(np.mean(tl_f),np.mean(testl_f),np.mean(ta_f),np.mean(testa_f))) print("Best fold: {}".format(np.argmax(testa_f) + 1)) # Averaging accuracy and loss diz_ep = {'train_loss_ep':[],'test_loss_ep':[],'train_acc_ep':[],'test_acc_ep':[]} for i in range(total_num_epochs): diz_ep['train_loss_ep'].append(np.mean([foldperf['fold{}'.format(f)]['loss']['training'][i] for f in fold_range])) diz_ep['test_loss_ep'].append(np.mean([foldperf['fold{}'.format(f)]['loss']['validation'][i] for f in fold_range])) diz_ep['train_acc_ep'].append(np.mean([foldperf['fold{}'.format(f)]['ssim_acc']['training'][i] for f in fold_range])) diz_ep['test_acc_ep'].append(np.mean([foldperf['fold{}'.format(f)]['ssim_acc']['validation'][i] for f in fold_range])) # Plot losses plt.figure(figsize=(10,8)) plt.semilogy(diz_ep['train_loss_ep'], label='Train') plt.semilogy(diz_ep['test_loss_ep'], label='Validation') plt.xlabel('Epoch') plt.ylabel('Loss') #plt.grid() plt.legend() if not flag_debug: plt.savefig(os.path.join(output_save_directory, current_date + "_loss"+".png")) plt.show() # Plot accuracies plt.figure(figsize=(10,8)) plt.semilogy(diz_ep['train_acc_ep'], label='Train') plt.semilogy(diz_ep['test_acc_ep'], label='Validation') plt.xlabel('Epoch') plt.ylabel('SSIM') #plt.grid() plt.legend() if not flag_debug: plt.savefig(os.path.join(output_save_directory, current_date + "_accuracy"+".png")) plt.show() # + # %matplotlib inline import math current_date=datetime.datetime.today().strftime('%Y-%m-%d') # Accuracy plt.figure(figsize=(10,5)) plt.title("SSIM") plt.plot(epochs_list, ssim_average["training"], label='training') plt.plot(epochs_list, ssim_average["validation"] , label='validation') plt.xlabel("Epochs") plt.ylabel("SSIM") plt.legend() #if not flag_debug: # plt.savefig(os.path.join(output_save_directory, current_date + "_accuracy"+".png")) # All losses plt.figure(figsize=(10,5)) plt.title("Losses") plt.plot(epochs_list, loss_per_epoch["training"], label='training') plt.plot(epochs_list, loss_per_epoch["validation"] , label='validation') plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() #if not flag_debug: # plt.savefig(os.path.join(output_save_directory, current_date + "_loss"+".png")) # Loss for training plt.figure(figsize=(10,5)) plt.title("Loss during training") plt.plot(reals_shown, [math.log10(y) for y in training_loss_list]) plt.xlabel("reals_shown") plt.ylabel("Training Log10(Loss)") #if not flag_debug: # plt.savefig(os.path.join(output_save_directory, current_date + "_training_loss"+".png")) # Final Model: with torch.no_grad(): input_image = fixed_val_sample['source'] input_images = vutils.make_grid(input_image[0:1,:,:,:], padding=2, normalize=True) target_images = vutils.make_grid(fixed_val_sample['boneless'][0:1,:,:,:], padding=2, normalize=True) net = net.cpu() output_image = net(input_image[0:1,:,:,:]).detach().cpu() output_images = vutils.make_grid(output_image, padding=2, normalize=True) #print(str(torch.max(output_images)) + "," + str(torch.min(output_images))) plt.figure(1) fig, ax = plt.subplots(1,3, figsize=(15,15)) ax[0].imshow(np.transpose(input_images, (1,2,0)), vmin=0, vmax=1) ax[0].set_title("Source") ax[0].axis("off") ax[1].imshow(np.transpose(output_images, (1,2,0)), vmin=0, vmax=1) ax[1].set_title("Suppressed") ax[1].axis("off") ax[2].imshow(np.transpose(target_images, (1,2,0)), vmin=0, vmax=1) ax[2].set_title("Ideal Bone-suppressed") ax[2].axis("off") plt.show #if not flag_debug: # plt.savefig(os.path.join(output_save_directory, current_date + "_validation_ComparisonImages"+".png")) # ANIMATED VALIDATION IMAGE #fig = plt.figure(figsize=(8,8)) #ax = fig.add_subplot(111) #plt.axis("off") #ims = [] #training_ims_shown = [] #for i, im in enumerate(img_list): # if i % 50 == 0: # controls how many images are printed into the animation # training_ims_shown = i*(100*_batch_size) # frame = ax.imshow(np.transpose(im,(1,2,0))) # t = ax.annotate("Reals shown: {}".format(training_ims_shown), (0.5,1.02), xycoords="axes fraction") # ims.append([frame, t]) #ani = animation.ArtistAnimation(fig, ims, interval=200, repeat_delay=1000, blit=True) #if not flag_debug: # ani.save(os.path.join(output_save_directory, current_date+"_animation.mp4"), dpi=300) # -
.ipynb_checkpoints/main-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # - table IDs `tid` are in `contrib['content']['tables']` # - set `per_page` query parameter to retrieve up to 200 rows at once (paginate for more) # - structure IDs `sid` are in `contrib['content']['structures']` from mpcontribs.client import load_client from mpcontribs.io.core.recdict import RecursiveDict from mpcontribs.io.core.components.hdata import HierarchicalData from mpcontribs.io.core.components.tdata import Table # DataFrame with Backgrid IPython Display from mpcontribs.io.core.components.gdata import Plot # Plotly interactive graph from pymatgen import Structure
mpcontribs-api/kernel_imports.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="tJBmVSUL4PvO" # # Download Data # # Referenced: https://github.com/jamestjw/OCR # # Download Google Drive files using wget: https://medium.com/@acpanjan/download-google-drive-files-using-wget-3c2c025a8b99 # + id="B8TnSrop4PvY" colab={"base_uri": "https://localhost:8080/"} outputId="4e82cf08-87a7-4c97-edb5-6453bf0d1dcd" # %%shell # # rm -rf extra, train # # rm extra.tar.gz # # rm train.tar.gz # # rm extra_ocr.csv, train_ocr.csv # rm -r * # + colab={"base_uri": "https://localhost:8080/"} id="P6mVf4Qowmlc" outputId="a70f98de-22fd-43b1-d3f6-68a73e777f2f" # %%shell # get extra dataset for training wget 'http://ufldl.stanford.edu/housenumbers/train.tar.gz' wget 'http://ufldl.stanford.edu/housenumbers/extra.tar.gz' # get .csv files contains file names and labels wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=1-p4JC0jH_00gJBujERxnem357r4OVoHN' -O extra_ocr.csv wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=1UwHqNPszlG1LxmOkFLKhMn6jJUhbYIx0' -O train_ocr.csv # + colab={"base_uri": "https://localhost:8080/"} id="s9nD704fNvbQ" outputId="912ad2b6-6ad2-42f3-a4a1-05617c453101" # %%shell tar -xf train.tar.gz tar -xf extra.tar.gz # + id="Fo_TvylKjZD7" colab={"base_uri": "https://localhost:8080/"} outputId="3250b2fa-4e3d-4328-f85f-ef3b3adfcbdb" # installing old version PyTorch to work with FastAI # !pip install "torch==1.4" "torchvision==0.5.0" # + [markdown] id="6siJU9OV4PvZ" # # Converting .mat file to .csv # The label file is in the .mat format, we shall convert it to a more user-friendly format. # + id="vIUkC-kO4Pva" # # !git clone https://github.com/prijip/Py-Gsvhn-DigitStruct-Reader.git # # %cd Py-Gsvhn-DigitStruct-Reader/ # # !python digitStructMatToCsv.py ../extra/digitStruct.mat ../ocr.csv # + [markdown] id="37I7XtEj4Pva" # # Inspect Data # + id="RlJSUdst4Pvb" from fastai.vision import * from fastai.text import * # train on extra dataset 531131 additional images train_on_extra = True # import warnings # warnings.filterwarnings(action='once') # + id="YP6E1UXu4Pvb" if train_on_extra: df = pd.read_csv('extra_ocr.csv') images = get_image_files('extra') else: df = pd.read_csv('train_ocr.csv') images = get_image_files('train') # + id="jDoq1D4x4Pvc" labelled_df = df.groupby('FileName').apply(lambda x: ''.join([str(i) for i in x['DigitLabel']])).to_frame().reset_index(0) labelled_df.columns = ['filename','labels'] # + id="3Ge1pp1Y4Pvc" labels = labelled_df['labels'].tolist() labels_clean = [] for label in labels: label = str(label) idx = label.find('0') if idx != -1: if label[idx-1] == '1': label = label[:idx-1]+label[idx:] labels_clean += [int(label)] # + id="8ciinMgO4Pvd" labelled_df['labels'] = labels_clean # + id="BRzOGlBV4Pvd" colab={"base_uri": "https://localhost:8080/", "height": 862} outputId="90dc88c6-8812-4ba7-d7f1-16fa062951d0" _,axs = plt.subplots(5,2,figsize=(15,15)) axs = axs.flatten() for i in range(10): start = np.random.randint(len(images)-10) name = images[start+i].name im = open_image(images[start+i]) im.show(figsize=(6,6),ax=axs[i]) axs[i].set_title('Label: '+str(labelled_df.loc[labelled_df['filename'] == name]['labels'].item())) # + id="q4APJyRV4Pvf" colab={"base_uri": "https://localhost:8080/"} outputId="2da21aa9-185b-4db0-8ed6-8a97f0c1a88b" if train_on_extra: src = ImageList.from_folder('extra').split_by_rand_pct(0.1,seed=42) else: src = ImageList.from_folder('train').split_by_rand_pct(0.1,seed=42) train_names = [items.name for items in src.train.items] val_names = [items.name for items in src.valid.items] train_order = {v:k for k,v in enumerate(train_names)} val_order = {v:k for k,v in enumerate(val_names)} train_df = labelled_df[labelled_df['filename'].isin(train_names)] valid_df = labelled_df[labelled_df['filename'].isin(val_names)] train_df['order'] = train_df['filename'].apply(train_order.__getitem__) train_df = train_df.sort_values('order') valid_df['order'] = valid_df['filename'].apply(val_order.__getitem__) valid_df = valid_df.sort_values('order') # + id="G6E-WC6H4Pvg" class OCRTokenizer(BaseTokenizer): def __init__(self,lang=None): pass def tokenizer(self,t): bos = t[:5] eos = t[-5:] t = t[5:-5] return [bos] + [char for char in t] + [eos] # + id="vf-fsJaq4Pvg" tok_pre_rules = [] tok_post_rules = [] tok = Tokenizer(tok_func=OCRTokenizer, pre_rules=tok_pre_rules, post_rules=tok_post_rules) procs = [TokenizeProcessor(tokenizer=tok, include_bos=True, include_eos=True), NumericalizeProcessor(min_freq=1)] # + id="La3SISJk4Pvh" colab={"base_uri": "https://localhost:8080/", "height": 74} outputId="11405194-51b1-4b1e-ab17-465d10d08a5e" path = './' label_train_il = TextList.from_df(train_df, path=path, cols=['labels'], processor=procs).process() label_valid_il = TextList.from_df(valid_df, path=path, cols=['labels'], processor=procs).process() # + id="o06j5kId4Pvh" trn_ll = LabelList(src.train, label_train_il) val_ll = LabelList(src.valid, label_valid_il) lls = LabelLists(path, train=trn_ll, valid=val_ll) # + id="QIvwkeN84Pvi" def ocr_pad_collate(samples:BatchSamples, pad_idx:int=1, pad_first:bool=False, include_targets=True, include_lengths=True, include_masks=True, backwards:bool=False) -> Tuple[LongTensor, LongTensor]: "Function that collect samples and adds padding. Flips token order if needed" samples = to_data(samples) c,h,w = samples[0][0].shape samples.sort(key=lambda x: len(x[1]), reverse=True) y_lens = [len(s[1]) for s in samples] y_max_len = max(y_lens) y_res = torch.zeros(len(samples), y_max_len).long() + pad_idx x_res = torch.zeros(len(samples),c,h,w).float() if backwards: pad_first = not pad_first for i,s in enumerate(samples): if pad_first: y_res[i,-len(s[1]):] = LongTensor(s[1]) else: y_res[i,:len(s[1]):] = LongTensor(s[1]) x_res[i,:] = tensor(s[0]) return x_res, y_res # + id="WD7CsO4R4Pvi" data = ImageDataBunch.create_from_ll(lls,size=(48,100),collate_fn=ocr_pad_collate,bs=200).normalize(imagenet_stats) # + id="z5stBC3u4Pvj" colab={"base_uri": "https://localhost:8080/", "height": 65} outputId="c5e0ac03-e0c5-4325-d0ea-94747f2947f6" data.valid_ds[2][0] # + id="y-vVfknZ4Pvj" colab={"base_uri": "https://localhost:8080/"} outputId="40566863-56b1-4de2-a808-39f8141698f8" data.valid_ds[2][1] # + [markdown] id="oRlLc9oA4Pvk" # # Architecture # + id="Ic57sWqh4Pvk" class BidirectionalLSTM(nn.Module): def __init__(self, nIn, nHidden, nOut): super(BidirectionalLSTM, self).__init__() self.rnn = nn.LSTM(nIn, nHidden, bidirectional=True) self.embedding = nn.Linear(nHidden * 2, nOut) def forward(self, input): recurrent, _ = self.rnn(input) T, b, h = recurrent.size() t_rec = recurrent.view(T * b, h) output = self.embedding(t_rec) # [T * b, nOut] output = output.view(T, b, -1) return output # + id="Kvtfyjmy4Pvl" class ResNetFeatureExtractor(nn.Module): def __init__(self, nh, **kwargs): super().__init__() self.cnn = create_body(models.resnet34,pretrained=True) self.rnn = nn.Sequential( BidirectionalLSTM(512, nh, nh), BidirectionalLSTM(nh, nh, nh) ) def forward(self,input): #get features features = self.cnn(input) #We want `nc` from convs to be the hidden dim, and `width` to be the `sentence length` features = features.mean(-2) features = features.permute(2, 0, 1) encoder_outputs = self.rnn(features) # 25×bs×nh return encoder_outputs # + id="HNLWJRew4Pvl" class AttentionDecoder(nn.Module): def __init__(self, hidden_size, output_size, dropout_p=0.1): super(AttentionDecoder, self).__init__() self.hidden_size = hidden_size self.output_size = output_size self.dropout_p = dropout_p self.embedding = nn.Embedding(self.output_size, self.hidden_size) self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size) self.dropout = nn.Dropout(self.dropout_p) self.gru = nn.GRU(self.hidden_size, self.hidden_size) self.out = nn.Linear(self.hidden_size, self.output_size) # test self.vat = nn.Linear(hidden_size, 1) def forward(self, input, hidden, encoder_outputs): embedded = self.embedding(input) embedded = self.dropout(embedded) # test batch_size = encoder_outputs.shape[1] alpha = hidden + encoder_outputs alpha = alpha.view(-1, alpha.shape[-1]) attn_weights = self.vat( torch.tanh(alpha)) attn_weights = attn_weights.view(-1, 1, batch_size).permute((2,1,0)) attn_weights = F.softmax(attn_weights, dim=2) attn_applied = torch.matmul(attn_weights, encoder_outputs.permute((1, 0, 2))) try: output = torch.cat((embedded, attn_applied.squeeze(1) ), 1) except: output = torch.cat((embedded.unsqueeze(0), attn_applied.squeeze(1) ), 1) output = self.attn_combine(output).unsqueeze(0) output = F.relu(output) output, hidden = self.gru(output, hidden) ## index into 0 to remove the first dim (it is 1) logits = self.out(output) #output logits return logits, hidden, attn_weights def initHidden(self, batch_size): result = Variable(torch.zeros(1, batch_size, self.hidden_size)) return result class Decoder(nn.Module): def __init__(self, nh=256, nclass=13, dropout_p=0.1, teacher_forcing=0.75, max_len=15, pad_idx=1, bos_idx=2): super().__init__() self.hidden_size = nh self.decoder = AttentionDecoder(nh, nclass, dropout_p) self.teacher_forcing = 0.5 self.max_len = max_len self.pad_idx = pad_idx self.bos_idx = bos_idx def forward(self, encoded_images, target=None): bs = encoded_images.shape[1] decoder_hidden = self.initHidden(bs).cuda() decoder_input = encoded_images.new_zeros(bs).long() + self.bos_idx outputs = [] for i in range(1, self.max_len): decoder_output, decoder_hidden, decoder_attention = self.decoder(decoder_input, decoder_hidden, encoded_images) outputs += [decoder_output] _, topi = decoder_output.data.topk(1) decoder_input = topi.squeeze() if (decoder_input==self.pad_idx).all(): break if (target is not None) and (random.random()<self.teacher_forcing): if i>=target.shape[1]-1: break decoder_input = target[:,i] return torch.cat(outputs,0).permute(1,0,2) def initHidden(self, batch_size): result = torch.zeros(1, batch_size, self.hidden_size) return result # + id="fDfPpDcf4Pvr" class OCRModel(nn.Module): def __init__(self): super().__init__() self.encoder = ResNetFeatureExtractor(nh = 256) self.decoder = Decoder(256, 24, dropout_p=0.1) def forward(self,input, target=None): encoded = self.encoder(input) output = self.decoder(encoded, target) return output # + id="aD9SNxuI4Pvv" def OCR_loss(out, targ, pad_idx=1): targ = targ[:,1:] bs,targ_len = targ.size() _,out_len,vs = out.size() if targ_len>out_len: out = F.pad(out, (0,0,0,targ_len-out_len,0,0), value=pad_idx) if out_len>targ_len: targ = F.pad(targ, (0,out_len-targ_len,0,0), value=pad_idx) return CrossEntropyFlat()(out, targ) def OCR_acc(out, targ, pad_idx=1): targ = targ[:,1:] bs,targ_len = targ.size() _,out_len,vs = out.size() if targ_len>out_len: out = F.pad(out, (0,0,0,targ_len-out_len,0,0), value=pad_idx) if out_len>targ_len: targ = F.pad(targ, (0,out_len-targ_len,0,0), value=pad_idx) out = out.argmax(-1) return (out==targ).float().mean() class TeacherForcing(LearnerCallback): def __init__(self, learn, end_epoch): super().__init__(learn) self.end_epoch = end_epoch def on_batch_begin(self, last_input, last_target, train, **kwargs): if train: return {'last_input': [last_input, last_target]} def on_epoch_begin(self, epoch, **kwargs): self.learn.model.pr_force = 1 - 0.5 * epoch/self.end_epoch # + id="oAbfag4X4Pvw" learn = Learner(data,OCRModel(),loss_func=OCR_loss, metrics=[OCR_acc],callback_fns=partial(TeacherForcing, end_epoch=8)) # + id="zlBJhefL4Pvw" colab={"base_uri": "https://localhost:8080/", "height": 374} outputId="a8d88411-9b79-4d09-a90c-983dccffc03e" learn.lr_find() learn.recorder.plot() # + id="GBqomDp34Pvw" colab={"base_uri": "https://localhost:8080/", "height": 348} outputId="9bf5f633-be6e-482d-d34f-09fae3774086" learn.fit_one_cycle(10,1e-3) # + id="2u8GYwvz4Pvx" learn.save('resnet18-1') # + id="_GrNpqHp4Pvx" # with open('resnet18_itos.pkl','wb') as f: # pickle.dump(data.train_ds.vocab.itos,f) # + [markdown] id="HVo5p3Wf4Pvx" # # Inference # + id="lpiBhFqq4Pvx" def get_preds(num_preds, rows=2): start = np.random.randint(len(data.valid_ds)-num_preds) dim = num_preds // rows if num_preds % rows != 0: dim += 1 _ , axs = plt.subplots(dim,rows, figsize=(10,10)) axs = axs.flatten() for i in range(num_preds): x,_= data.valid_ds[start+i] input = normalize(x.data,tensor(imagenet_stats[0]),tensor(imagenet_stats[1])).unsqueeze(0) res = learn.model(input.cuda()) outs = [data.train_ds.vocab.itos[i] for i in res.argmax(-1)[0]] x.show(ax=axs[i]) to_print = '' for char in outs: if char in ['0','1','2','3','4','5','6','7','8','9']: to_print += char axs[i].title.set_text(f'Prediction: {to_print}') # + id="l-ckLWm84Pvy" colab={"base_uri": "https://localhost:8080/", "height": 591} outputId="4c115ced-a703-4e13-faa2-8e3eb6cc27e9" get_preds(10) # + id="4Hak6i6h4Pvy" # _ , ax = plt.subplots(figsize=(10,10)) # x = open_image('plate.png') # x = x.resize((3,48,100)) # input = normalize(x.data,tensor(imagenet_stats[0]),tensor(imagenet_stats[1])).unsqueeze(0) # res = learn.model(input.cuda()) # outs = [data.train_ds.vocab.itos[i] for i in res.argmax(-1)[0]] # x.show(ax=ax) # to_print = '' # for char in outs: # if char in ['0','1','2','3','4','5','6','7','8','9']: # to_print += char # ax.title.set_text(f'Prediction: {to_print}') # + id="k8r-aqJu4Pvy"
resnet_ocr.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] pycharm={"name": "#%% md\n"} # # Roles Classifier Alternative: Support Vector Machines # + pycharm={"name": "#%%\n"} import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline # + [markdown] pycharm={"name": "#%% md\n"} # ## Testing Several Files # + pycharm={"name": "#%%\n"} file_size = [150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 645] accuracy = [] for i in file_size: file_name = f'output/balanced_{i}.csv' roles = pd.read_csv(f'../{file_name}') mapping = {'Student': 0, 'Co-Facilitator': 1, 'Facilitator': 2} roles['Role'] = roles['Role'].apply(lambda x: mapping[x]) X = roles['Text'] y = roles['Role'] X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.2) # 'hinge' gives SVM # penalty is L2, for SVM svm = SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, random_state=42) svm.n_iter = 5 svm_classifier = Pipeline([ ('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', svm), ]) # Fitting our train data to the pipeline svm_classifier.fit(X_train, y_train) predicted = svm_classifier.predict(X_valid) accuracy_partial = np.mean(predicted == y_valid) print(f'Accuracy for file_size {i}: %.3f' % accuracy_partial) accuracy.append(accuracy_partial) # + [markdown] pycharm={"name": "#%% md\n"} # ## Graphical Performance Analysis # # In the following plots we can see the how the model behaves when it is trained with different amounts of data. # + pycharm={"name": "#%%\n"} # %matplotlib inline plt.plot(file_size, accuracy) plt.title('# of Rows vs. Accuracy') plt.suptitle('SVM Roles Classifier') plt.xlabel('# of Rows') plt.ylabel('Accuracy') plt.show() # + pycharm={"name": "#%%\n"} print(f'Mean Accuracy: {np.mean(accuracy)}') # + [markdown] pycharm={"name": "#%% md\n"} # ## Conclusions # # - The model doesn't show a good performance with the datasets, and we can see that the behavior is random, from which we can conclude that SVM was not able to learn anything from the datasets. Even if we consider that the Mean Accuracy is around 0.56, the variance between the results is not a good indicator. # # -
alternatives/svm_classifier.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.8.10 64-bit # language: python # name: python3 # --- # + import os print(os.getcwd()) print(os.path.abspath('../pyEpiabm')) import sys sys.path.append(os.path.abspath('../pyEpiabm')) import pyEpiabm as pe import pandas as pd import matplotlib.pyplot as plt # + pop_params = {"population_size": 100, "cell_number": 1, "microcell_number": 1, "household_number": 10, "place_number": 2} sim_params = {"simulation_start_time": 0, "simulation_end_time": 40, "initial_infected_number": 5} file_params = {"output_file": "output.csv", "output_dir": "./simulation_outputs"} # + pe.Parameters.instance().time_steps_per_day = 1 population = pe.routine.ToyPopulationFactory().make_pop(**pop_params) # + sim = pe.routine.Simulation() sim.configure( population, [pe.sweep.InitialInfectedSweep()], [pe.sweep.UpdatePlaceSweep(), pe.sweep.HouseholdSweep(), pe.sweep.PlaceSweep(), pe.sweep.QueueSweep(), pe.sweep.HostProgressionSweep()], sim_params, file_params) sim.run_sweeps() del(sim) # - df = pd.read_csv("simulation_outputs/output.csv") df.plot(x="time", y=["InfectionStatus.Susceptible", "InfectionStatus.InfectMild", "InfectionStatus.Recovered"]) plt.show()
python_examples/Susceptible_plot.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="HnLuFuVTsS2H" colab_type="code" colab={} import tensorflow.keras as k from tensorflow.keras.layers import Conv2D,MaxPooling2D,Dropout,Activation,UpSampling2D,Input,add from tensorflow.keras import regularizers from tensorflow.keras.datasets import cifar100 from tensorflow.keras.models import Model import numpy as np import matplotlib.pyplot as plt import pickle # %matplotlib inline # + id="I7Px6WU9t-IS" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="667d59a0-803d-4ca4-8e09-8532800ab191" from google.colab import drive drive.mount('/content/gdrive') # + id="hCpPzBpl2s1A" colab_type="code" colab={} with open('data.pickle','rb') as f: data=pickle.load(f) # + id="SyHEgbk-tLpJ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="ce2e9708-139f-48a2-afc8-48c2a5bdaced" x_train=data print(x_train.shape) # plt.imshow(x_train[100],cmap='gray') # + id="tFSYSB5rvH51" colab_type="code" colab={} # function to create blur dataset def make_blur(data_): # creating blur filter n=data_.shape[-1] blur_filter=np.zeros((n,n)) print(n) print(blur_filter.shape) for i in range(1,n-1): blur_filter[i,[i-1,i,i+1]]=[1,1,1] blur_filter[0,[0,1]]=1 blur_filter[n-1,[n-1,n-2]]=1 # making new blured data new_data=[] for img in data_: new_data.append(np.dot(img,blur_filter)/3) new_data=np.array(new_data) # visualizing blured images # plt.figure(figsize=(20,20)) # plt.subplot(121) # plt.imshow(data_[0],cmap='gray') # plt.subplot(122) # plt.imshow(np.dot(data_[0],blur_filter)/3,cmap='gray') return new_data # + id="gR3IVJlVxs1p" colab_type="code" colab={} data_=make_blur(data) # + id="D2nCi4iH-hFN" colab_type="code" colab={} data=np.expand_dims(data,axis=-1) data_=np.expand_dims(data_,axis=-1) # + id="wi681hQGC4ou" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="71dd8f81-10d6-43e3-bb0a-38dc0a6ba4e2" print(data.shape) print(data_.shape) # + [markdown] id="DJTg3meEAr7V" colab_type="text" # # + id="dSsTXCrZJxw9" colab_type="code" colab={} (data2,_),(_,_)=k.datasets.fashion_mnist.load_data() # + id="ui03uqsXJ4O_" colab_type="code" colab={} data2_=make_blur(data2) # + id="z0ASSDPyKPCj" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="94c1480a-9836-4328-f84a-bdcbd8d33630" data2=np.expand_dims(data2,axis=-1) data2_=np.expand_dims(data2_,axis=-1) print(data2_.shape) # + id="ztTMMoqYyI6f" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 825} outputId="73a8aff7-367a-4a55-d1e6-0c852efbde93" # creating autoencoder to predict hight resolution image input=Input(data2.shape[1:]) l1=Conv2D(64,(3,3),padding='same',activation='relu',activity_regularizer=regularizers.l1(10e-10))(input) l2=Conv2D(64,(3,3),padding='same',activation='relu',activity_regularizer=regularizers.l1(10e-10))(l1) l3=MaxPooling2D(padding='same')(l2) l4=Conv2D(128,(3,3),padding='same',activation='relu',activity_regularizer=regularizers.l1(10e-10))(l3) l5=Conv2D(128,(3,3),padding='same',activation='relu',activity_regularizer=regularizers.l1(10e-10))(l4) l6=MaxPooling2D(padding='same')(l5) l7=Conv2D(256,(3,3),padding='same',activation='relu',activity_regularizer=regularizers.l1(10e-10))(l6) # bottel nect layer. with latent features encoder=Model(inputs=input,outputs=l7) # encoder part of autoencoder #__________________________________________________________________________# l8=UpSampling2D()(l7) l9=Conv2D(128,(3,3),padding='same',activation='relu',activity_regularizer=regularizers.l1(10e-10))(l8) l10=Conv2D(128,(3,3),padding='same',activation='relu',activity_regularizer=regularizers.l1(10e-10))(l9) l11=add([l5,l10]) l12=UpSampling2D()(l11) l13=Conv2D(64,(3,3),padding='same',activation='relu',activity_regularizer=regularizers.l1(10e-10))(l12) l14=Conv2D(64,(3,3),padding='same',activation='relu',activity_regularizer=regularizers.l1(10e-10))(l13) l15=add([l2,l14]) output=Conv2D(1,(3,3),padding='same',activation='relu',activity_regularizer=regularizers.l1(10e-10))(l15) # output of decoder. #___________________________________________________________________________# autoencoder=Model(input,output) # autoencoder for image enhancement autoencoder.summary() # + id="gRxIp07x8vqL" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="83265978-0dd3-42ae-db23-925919462904" # visualizing the model k.utils.plot_model(autoencoder,to_file='model.png',show_shapes=True,show_layer_names=True,dpi=70) # + id="gZww2y-nBdwi" colab_type="code" colab={} # compiling model using adam optimizer and 'mae' loss autoencoder.compile('rmsprop',loss='mae',metrics=['accuracy']) # + id="A2JmgCkzCOQD" colab_type="code" colab={} # training model history=autoencoder.fit(data2_,data2,epochs=3,validation_split=.1) # + id="SjdRSZGGERBE" colab_type="code" colab={} pred=autoencoder.predict(data2_[:10]) # + id="lwox98pGLfUv" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 283} outputId="a2c3b822-0b6c-4681-d45c-e43de93bd842" plt.imshow(np.resize(pred[0],(28,28)),cmap='gray') # + id="VUwdBNDYLqJu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 283} outputId="9a61ef7b-a87c-4b71-efcf-0560178c7c6e" plt.imshow(np.resize(data2[0],(28,28)),cmap='gray') # + id="duwFgGNALzYA" colab_type="code" colab={}
projects/image_resolution.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # LatNetBuilder # # This demo shows how to use generating vectors and matricies from [latnetbuilder](https://github.com/umontreal-simul/latnetbuilder) in QMCPy. import latnetbuilder from qmcpy import Lattice, Sobol from qmcpy.util import latnetbuilder_linker import numpy numpy.set_printoptions(threshold=2**10) import os # make directory to store generating vectors + matricies from latnetbuilder try: os.mkdir('./lnb') os.mkdir('./lnb/lnb_qmcpy_linked') except: pass # ## Ordinary Lattice # use latnetbuilder to find an ordinary lattice generating vector search = latnetbuilder.SearchLattice() search.modulus = '2^3' search.construction = 'ordinary' search.dimension = 5 search.exploration_method = 'fast-CBC' search.figure_of_merit = 'CU:P2' search.weights = ['product:1'] search.execute(output_folder='./lnb/lnb_ordinary_lattice') # get points using latnetbuilder x_lnb = search.points() x_lnb # store generating vector in QMCPy format lnb_ol_p = latnetbuilder_linker( lnb_dir = './lnb/lnb_ordinary_lattice', out_dir = './lnb/lnb_qmcpy_linked', fout_prefix = 'lnb_ordinary_lattice') lnb_ol_p # path to generating vector compatible with QMCPy # use the custom generating vector in QMCPy lnb_lattice = Lattice( dimension = 5, randomize = False, order = 'linear', z_path = lnb_ol_p) # plug in the path x_qmcpy = lnb_lattice.gen_samples( n_min = 0, n_max = 8, warn = False) x_qmcpy # make sure the two matricies match if not (x_lnb==x_qmcpy).all(): raise Exception("Ordinary Lattice from latnetbuilder does not match QMCPy") # ## Polynomial Lattice search = latnetbuilder.SearchLattice() search.modulus = '2^3' search.construction = 'polynomial' search.dimension = 5 search.exploration_method = 'fast-CBC' search.figure_of_merit = 'CU:P2' search.weights = ['product:1'] search.execute(output_folder='./lnb/lnb_polynomial_lattice') x_lnb = search.points() x_lnb lnb_pl_p = latnetbuilder_linker( lnb_dir = './lnb/lnb_polynomial_lattice', out_dir = './lnb/lnb_qmcpy_linked', fout_prefix = 'lnb_polynomial_lattice') lnb_pl_p # note that we use QMCPy's Sobol' object rather than Lattice # this is because polynomial lattices are constructed like digital nets lnb_pl = Sobol( dimension = 5, randomize = False, graycode = False, z_path = lnb_pl_p) x_qmcpy = lnb_pl.gen_samples( n_min = 0, n_max = 8, warn = False) if not (x_lnb==x_qmcpy).all(): raise Exception("Ordinary Lattice from latnetbuilder does not match QMCPy") # ## Sobol' search = latnetbuilder.SearchNet() search.modulus = '2^3' search.construction = 'sobol' search.dimension = 5 search.exploration_method = 'full-CBC' search.figure_of_merit = 'CU:P2' search.weights = ['product:1'] search.execute(output_folder='./lnb/lnb_sobol') x_lnb = search.points() x_lnb lnb_s_p = latnetbuilder_linker( lnb_dir = './lnb/lnb_sobol', out_dir = './lnb/lnb_qmcpy_linked', fout_prefix = 'lnb_sobol') lnb_s_p lnb_sobol = Sobol( dimension = 5, randomize = False, graycode = False, z_path = lnb_s_p) x_qmcpy = lnb_sobol.gen_samples( n_min = 0, n_max = 8, warn = False) x_qmcpy if not (x_lnb==x_qmcpy).all(): raise Exception("Ordinary Lattice from latnetbuilder does not match QMCPy") # ## Output Directories # list output vectors / matricies os.listdir('./lnb/lnb_qmcpy_linked') # delete lnb dir import shutil shutil.rmtree('./lnb')
demos/latnetbuilder.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # %run notebook.config.ipy # *Unmelt the count data to a new table* # + statement = '''select * from featurecounts''' counts = DB.fetch_DataFrame(statement, db) count_table = counts.pivot(columns="track", index="gene_id", values="counts") print count_table.shape DB.write_DataFrame(count_table,"count_table",ipydb) #count_table.to_csv("count_table.txt",sep="\t") # - # *Select the cells based on the QC metrics* # + # e.g. select cells: # (i) expressing more than 3000 genes and # (ii) where <50% reads map to spike-in sequences and # (iii) whic have less than 7 million reads. statement = '''select sample_id from qc_summary q where q.cufflinks_no_genes_pc > 3000 and q.fraction_spike < 0.5 and q.total_reads < 7000000''' good_samples = DB.fetch_DataFrame(statement, db)["sample_id"].values print len(good_samples) # - # *Prepare table of selected cells* # + sample_stat = '"' + '", "'.join(good_samples) + '"' # fetch a pandas dataframe containing the "good" cells (samples) statement = '''select gene_id, %(sample_stat)s from count_table''' % locals() count_table_filtered = DB.fetch_DataFrame(statement, ipydb) print count_table_filtered.shape # write a new frame containing the filtered data DB.write_DataFrame(count_table_filtered, "count_table_filtered", ipydb)
pipelines/pipeline_notebooks/pipeline_scrnaseq/2 - Selection of cells and preparation of count table.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 0.4.0 # language: julia # name: julia-0.4 # --- # + # ENV["MPLBACKEND"] = "Agg" using Plots, DataFrames, OnlineAI pyplot() default(size=(500,300)) # load the table df = readtable(joinpath(Pkg.dir("ExamplePlots"), "examples", "meetup", "winequality-white.csv"), separator=';') M = Array(df) df[2,:] # + sp = subplot(M, n=ncols(M), lt=:hist, size=(1000,900), title=names(df)') # sp.o.fig[:subplots_adjust](hspace=.5); sp # - # extract the most correlated variables to wine quality C = cor(M) indices = sortperm(abs(C[1:end-1, end]), rev=true) indices = sort(indices[1:6]) nms = names(df)[indices] idx_w_quality = vcat(indices,12) corrplot(M[:, idx_w_quality], size = (1200,1200), labels = vcat(nms,:quality)') # + # notes: grouping by string labels, dataframe column names for data, separate opacities quality = ASCIIString[ if q > 7 "High Quality" elseif q < 5 "Low Quality" else " Tastes like wine..." end for q in df[:quality] ] # fields = (:citric_acid, :alcohol) fields = nms[[1,6]] default(xlab=fields[1], ylab=fields[2]) scatter(df, fields..., group=quality, m=[2 3 3], w=0, smooth=true, opacity=[0.1 1 1]) # plot!(xlim=(.985,1.005),ylim=(7,15)) # plot!(xlab=fields[1], ylab=fields[2]) # gui() # + default(grid=false, leg=false) subplot(df, fields..., group = quality, marker = 3, line = (:scatter,0), smooth = true, opacity = [0.05 1 1], title = sort(unique(quality))', n = 3, nr = 1, size = (1000,400), linky = true ) # + sp = subplot(df, fields..., group = :quality, line = (:hexbin, ColorGradient(:heat,[0,0.01,1])), n = 7, nr = 1, title = map(i->"Quality: $i", (3:9)'), size = (1200,300), linky = true ) # sp.o.fig[:subplots_adjust](wspace=.6); sp # - scatter(df, :density, :quality, smooth=true, m=(1,0.01), xlim=(0.99,1))
notebooks/scratch/meetup/wine.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import geemap import json import os import requests from geemap import geojson_to_ee, ee_to_geojson from ipyleaflet import GeoJSON geemap.show_youtube('DbK_SRgrCHw') Map = geemap.Map() Map # + file_path = os.path.abspath('../data/us-states.json') if not os.path.exists(file_path): url = 'https://github.com/giswqs/geemap/raw/master/examples/data/us-states.json' r = requests.get(url) with open(file_path, 'w') as f: f.write(r.content.decode("utf-8")) with open(file_path) as f: json_data = json.load(f) # - json_layer = GeoJSON(data=json_data, name='US States JSON', hover_style={'fillColor': 'red' , 'fillOpacity': 0.5}) Map.add_layer(json_layer) ee_data = geojson_to_ee(json_data) Map.addLayer(ee_data, {}, "US States EE") json_data_2 = ee_to_geojson(ee_data) json_layer_2 = GeoJSON(data=json_data_2, name='US States EE JSON', hover_style={'fillColor': 'red' , 'fillOpacity': 0.5}) Map.add_layer(json_layer_2) # + file_path = os.path.abspath('../data/countries.json') if not os.path.exists(file_path): url = 'https://github.com/giswqs/geemap/raw/master/examples/data/countries.json' r = requests.get(url) with open(file_path, 'w') as f: f.write(r.content.decode("utf-8")) with open(file_path) as f: json_data = json.load(f) # - json_layer = GeoJSON(data=json_data, name='Counties', hover_style={'fillColor': 'red' , 'fillOpacity': 0.5}) Map.add_layer(json_layer) # + from ipywidgets import Text, HTML from ipyleaflet import WidgetControl, GeoJSON html1 = HTML(''' <h4>Country</h4> Hover over a country ''') html1.layout.margin = '0px 20px 20px 20px' control1 = WidgetControl(widget=html1, position='bottomright') Map.add_control(control1) def update_html(feature, **kwargs): html1.value = ''' <h4>Country code: <b>{}</b></h4> Country name: {} '''.format(feature['id'], feature['properties']['name']) json_layer.on_hover(update_html)
examples/notebooks/07_geojson.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # pip install pymc3 seaborn import pymc3 as pm import numpy as np import seaborn as sns import arviz as az # - # Following: # # <NAME>., 1973. Dead-time problems. Nuclear Instruments and Methods, 112(1-2), pp.47-57. # # $\nu_{sup} = \nu_1 + \nu_2 - 2\tau \nu_1 \nu_2$ # # $\nu_1 + \nu_2 - \nu_{sup} = 2\tau \nu_1 \nu_2$ # # $ \tau = \frac{\nu_1 + \nu_2 - \nu_{sup}}{2 \nu_1 \nu_2}$ with pm.Model() as model: r1 = pm.HalfFlat('r1') nu1 = pm.Poisson('nu1', r1, observed=19999.927516) r2 = pm.HalfFlat('r2') nu2 = pm.Poisson('nu2', r2, observed=20544.593987) rsup = pm.HalfFlat('rsup') nusup = pm.Poisson('nusup', rsup, observed=39543.032686) tau = pm.Deterministic('tau', (r1+r2-rsup)/(2*r1*r2)) trace = pm.sample(10000, return_inferencedata=True) pm.plot_trace(trace); pm.summary(trace, round_to='none') tau = trace['posterior']['tau'].data.flatten() sns.histplot(tau) hdi = az.hdi(tau, hdi_prob=.94) # this is in the summary hdi print(f'So for this case the Dead Time calculation is {1e6*hdi[0]:.2f} -- {1e6*hdi[1]:.2f} us')
Dead Time/2 pulser deadtime.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="k6kiCHg2-U3F" # # **Exercise 1: Counting DNA Nucleotides** # + [markdown] id="Akeh2erv-aVb" # **Link: http://rosalind.info/problems/dna/** # # **Intro:** # # Making up all living material, the cell is considered to be the building block of life. The nucleus, a component of most eukaryotic cells, was identified as the hub of cellular activity 150 years ago. Viewed under a light microscope, the nucleus appears only as a darker region of the cell, but as we increase magnification, we find that the nucleus is densely filled with a stew of macromolecules called chromatin. During mitosis (eukaryotic cell division), most of the chromatin condenses into long, thin strings called chromosomes. See Figure 1 for a figure of cells in different stages of mitosis. # # One class of the macromolecules contained in chromatin are called nucleic acids. Early 20th century research into the chemical identity of nucleic acids culminated with the conclusion that nucleic acids are polymers, or repeating chains of smaller, similarly structured molecules known as monomers. Because of their tendency to be long and thin, nucleic acid polymers are commonly called strands. # # The nucleic acid monomer is called a nucleotide and is used as a unit of strand length (abbreviated to nt). Each nucleotide is formed of three parts: a sugar molecule, a negatively charged ion called a phosphate, and a compound called a nucleobase ("base" for short). Polymerization is achieved as the sugar of one nucleotide bonds to the phosphate of the next nucleotide in the chain, which forms a sugar-phosphate backbone for the nucleic acid strand. A key point is that the nucleotides of a specific type of nucleic acid always contain the same sugar and phosphate molecules, and they differ only in their choice of base. Thus, one strand of a nucleic acid can be differentiated from another based solely on the order of its bases; this ordering of bases defines a nucleic acid's primary structure. # # For example, Figure 2 shows a strand of deoxyribose nucleic acid (DNA), in which the sugar is called deoxyribose, and the only four choices for nucleobases are molecules called adenine (A), cytosine (C), guanine (G), and thymine (T). # # For reasons we will soon see, DNA is found in all living organisms on Earth, including bacteria; it is even found in many viruses (which are often considered to be nonliving). Because of its importance, we reserve the term genome to refer to the sum total of the DNA contained in an organism's chromosomes. # # **Problem:** # # A string is simply an ordered collection of symbols selected from some alphabet and formed into a word; the length of a string is the number of symbols that it contains. # # An example of a length 21 DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T') is "ATGCTTCAGAAAGGTCTTACG." # # **Given:** # - A DNA string s of length at most 1000 nt. # # **Return:** # - Four integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur in s. # # **Sample Dataset:** # # AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC # # **Sample Output:** # # 20 12 17 21 # + [markdown] id="km9uJS4KT2Mi" # ## **Manual and using BioPython** # + [markdown] id="qp402cJtrst-" # - Both of them (manual form and Biopython library use the same function - count() # + [markdown] id="HG51rOujoWsC" # - **From the sample:** # + [markdown] id="O8r_9eLAtVhY" # **String Formatting** # # ``` # # # %s - String (or any object with a string representation, like numbers) # # # # %d - Integers # # # # %f - Floating point numbers # # %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot. # # # # %x/%X - Integers in hex representation (lowercase/uppercase) # # ``` # + colab={"base_uri": "https://localhost:8080/"} id="ouTM3VyQk2Gi" outputId="f0a9c3f1-3aee-44f4-ddd1-c78e107fe632" # Creating the variable... dna = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC" # Counting the number of "A", "C", "G" e "T" in the given seq... a = dna.count("A") c = dna.count("C") g = dna.count("G") t = dna.count("T") print(a, c, g, t) print(f"A = {a} C = {c} G = {g} T = {t}") print("A = %d" % a, "C = %d" % c, "G = %d" % g, "T = %d" % t) # + [markdown] id="NwddTCy7oaKl" # - **From the file:** # + colab={"base_uri": "https://localhost:8080/", "height": 154} id="UQDNbe97T4_G" outputId="454ef65b-94f6-4d6b-9b52-efae3aae90a0" dna = "TGGTACGGCTTGGGCCATCGGGCATCACAGCGCCTCAATGTCCTGTTCGTTCCTGGAATAGATCCTCCCTAGTGGCCTGATATGCAGTAGTGAACTAGTTCTCACGTTGCGTTCGAAGATCTCGTTACAGTACGTCTTAGGGGGATCACGAAGCTGGTTAGCCCGATACGGTAGGTGGAGACTTACACACGTCTATACAGTCACTTCGTTCTAGGGACGCTCACGTATGCTGACCATGCAGACCGCGTGTCAGGCTGGTATCGACACGGTTGTGTGAGGTCGTACAGCACATCCAGAGAGTATTGTGACTAATAGCTAATGAGGTGGTGCTCCCCCTACACTTCTTTACGGTACTATCCTGCTTTATACGTAGGGCTACACTACTGTTAAGATATCAGTGCGCAGCTGATTGAATCCTCGATCAGGCTATACTTTCTGAGATCCCTATTGCCCCGCATGATGCGGTGCTGGACCTGTGTCCTCCTCCATCGAAGGGATTAACTTAGTGATCGTACGTGAAAAAAATTCCGACCAATTAATGCAAAACACGGTGTGTAAAAGCAAGAGTATAATCCTCGGGTTGTTAAGGTTTCCTACAATATACAGGCCTCTAAATAATGTCTGAGTGGCACTGAGTTCACAAGGAAGTGGGGAATCGAGGCCGCCAAGTGTCACGCATCGCCAAATGGCTACTAGGGCTCCTGCTGTATTACGGCAATTATATCTGGTCCATTGGAGGCACGGACACTATTCGACATCTCGGAACATAGCGAAGCGCAGCTACATGTGACACCCCGAAGTCAGAGAGATTTTGGTGAGTTGTGGTATTTGAGTCGTCCCTCCAAGGCAGGGTAAGAGGCAATCCAGATAGAAGTTACTTATTCGTTGCCACCCCCAGTATCGCGA" dna # + colab={"base_uri": "https://localhost:8080/"} id="9AlSM-o2o-3m" outputId="e71f2188-af07-4e1e-9eac-f4c4d2021fa0" # Counting the number of "A", "C", "G" e "T" in the given seq... a = dna.count("A") c = dna.count("C") g = dna.count("G") t = dna.count("T") print(a, c, g, t) # + [markdown] id="1t_ypQ0tATzC" # # **Exercise 2: Transcribing DNA into RNA** # + [markdown] id="UcETXQuRAZ3R" # **Link: http://rosalind.info/problems/rna/** # # **Intro:** # # In “Counting DNA Nucleotides”, we described the primary structure of a nucleic acid as a polymer of nucleotide units, and we mentioned that the omnipresent nucleic acid DNA is composed of a varied sequence of four bases. # # Yet a second nucleic acid exists alongside DNA in the chromatin; this molecule, which possesses a different sugar called ribose, came to be known as ribose nucleic acid, or RNA. RNA differs further from DNA in that it contains a base called uracil in place of thymine; structural differences between DNA and RNA are shown in Figure 1. Biologists initially believed that RNA was only contained in plant cells, whereas DNA was restricted to animal cells. However, this hypothesis dissipated as improved chemical methods discovered both nucleic acids in the cells of all life forms on Earth. # # The primary structure of DNA and RNA is so similar because the former serves as a blueprint for the creation of a special kind of RNA molecule called messenger RNA, or mRNA. mRNA is created during RNA transcription, during which a strand of DNA is used as a template for constructing a strand of RNA by copying nucleotides one at a time, where uracil is used in place of thymine. # # In eukaryotes, DNA remains in the nucleus, while RNA can enter the far reaches of the cell to carry out DNA's instructions. In future problems, we will examine the process and ramifications of RNA transcription in more detail. # # **Problem:** # # An RNA string is a string formed from the alphabet containing 'A', 'C', 'G', and 'U'. # # Given a DNA string t corresponding to a coding strand, its transcribed RNA string u is formed by replacing all occurrences of 'T' in t with 'U' in u. # # **Given:** # - A DNA string t having length at most 1000 nt. # # **Return:** # - The transcribed RNA string of t. # # **Sample Dataset:** # # GATGGAACTTGACTACGTAAATT # # **Sample Output:** # # GAUGGAACUUGACUACGUAAAUU # # + [markdown] id="wIvTpiLIqyk1" # ## **Manual** # + [markdown] id="wXDQL_SfGVjE" # **From the sample:** # + id="H6mnwn8zAQl1" colab={"base_uri": "https://localhost:8080/"} outputId="478a11e5-7b57-440f-e185-6bbb1b9b8b20" import re dna = "GATGGAACTTGACTACGTAAATT" while True: if "a" in dna or "A" in dna or "t" in dna or "T" in dna or "g" in dna or "G" in dna or "c" in dna or "C" in dna and dna.isalpha(): rna1 = re.sub("[^atcgATCG]", "", dna) rna2 = rna1.replace("T", "U").replace("t", "u") print(f"The RNA sequence for the given DNA is: {rna2.upper()}") break else: print("There is something wrong in your input") dna = str(input("Please, try again... enter a true DNA sequence: ")) continue # + [markdown] id="GCFxhesap0DZ" # - **From the file:** # + colab={"base_uri": "https://localhost:8080/", "height": 137} id="PbQ_ZkpWqSeJ" outputId="ee0761bb-c8c4-4d01-b059-099451799a05" dna = "AATTGGCACTGGCGTCCATGCGGCCCCTTTCAACGGATAGCCGTCCTATCGCAAATGTTTCATTGAGTCCTCCATTCTCCGCGGGCTGCGCCCCTGGGCATCTCCCTTACCCTACGTGGCGTAGAAAGCTGTAAAGGACCAGCGGTGATTTCAATAAAAGGGCCCGGGTGTAGCAAAGCAATACCCGTCTCGTACGCTATCAAATCATTGTAATTTGATATTTCATCGGGACCCGAAGGGCTCACGACACAAACTGCCGCTGCCACAATTGTGGTGGCGACCTCCGCCCCGTCTTCAGACACCAGTTATGCTAGTCGAAAGTACCGCCAGGTATTGCGCCATAATGCGCCAGTAGTTCCATTTAAGTGATACGAGCTTACAACTAATCCCAAGCACGAGTGCATCTGTCATCCATACTAAGCTACTCCGTCAAGGGTGCTGACAACGTTGTTGATTACAGGTGTCCTAGGAACGGCCTATGGCCGGGAGGCCTACTCAGGGGAGACCTTATCAGTGACGCAATGCGAACAAGTTGTAAATACTGTCTTTCATCTCTCACAATCCCAAGAGTAAAATTCCGCTGAGCATGGTTCCATTTGACGCTAATCGGACAAGAACTGCCGTACTTCCACCACGTTTGTCTTGTGAGACTTTCGTCTCTGCAACGACATGACAGCTTCCACGGTGCATATGAACAAATATCGTTCAACGCTGACCCATCGCCAGATAGCCTCCTACCTATGCGCATGGAAGGAACTGCTCCTTCAACCGCCTACAGATATATACGACGTGCCCATCGCTGAGAGCAGTCCGCGACCACTACAATACCCCGTTCCGATTATTAACAATTAGATGTGTTGTCAGGTTCGCCCGTCCTAACGTCTGCGTTACCCCTCTTTTCAGGCCAGTATCCAGGGTGGTATGAAACCAGATGTATTATTCCTCTGGGATTAACGGGTAACGG" dna # + colab={"base_uri": "https://localhost:8080/"} id="nOpr4QJFpzZs" outputId="8be7781a-3830-4b62-c558-0d32a9878f4b" import re while True: if "a" in dna or "A" in dna or "t" in dna or "T" in dna or "g" in dna or "G" in dna or "c" in dna or "C" in dna and dna.isalpha(): rna1 = re.sub("[^atcgATCG]", "", dna) rna2 = rna1.replace("T", "U").replace("t", "u") print(rna2.upper()) break else: print("There is something wrong in your input") dna = str(input("Please, try again... enter a true DNA sequence: ")) continue # + [markdown] id="u9hMt-sJqrFP" # ## **Using Biopython** # + colab={"base_uri": "https://localhost:8080/"} id="RGVMw7hHsRq5" outputId="c9130743-316b-478f-a70f-f115e1648f54" # Instalando as instâncias necessárias... # !pip install biopython from Bio.Seq import Seq # + [markdown] id="2j9AF-85s9eq" # - **From the sample** # + colab={"base_uri": "https://localhost:8080/"} id="ZKAZq3xxsU6X" outputId="bd82c32a-58b3-48b6-95fe-5bc321f893ac" # Criando a variável... dna = Seq("GATGGAACTTGACTACGTAAATT") dna # + colab={"base_uri": "https://localhost:8080/"} id="peEdk_uEqvby" outputId="d4250767-e640-4396-f642-2e731b059db3" # Fazendo a transcrição num único passo... dna = template_dna.transcribe() print(rna) # + [markdown] id="b64XLcoMtApq" # - **From the file** # + colab={"base_uri": "https://localhost:8080/"} id="Bgpj6XA8tFmE" outputId="dbd8398d-1ccd-42a0-8a5f-19de74c3cc78" # Criando a variável... dna = Seq("AATTGGCACTGGCGTCCATGCGGCCCCTTTCAACGGATAGCCGTCCTATCGCAAATGTTTCATTGAGTCCTCCATTCTCCGCGGGCTGCGCCCCTGGGCATCTCCCTTACCCTACGTGGCGTAGAAAGCTGTAAAGGACCAGCGGTGATTTCAATAAAAGGGCCCGGGTGTAGCAAAGCAATACCCGTCTCGTACGCTATCAAATCATTGTAATTTGATATTTCATCGGGACCCGAAGGGCTCACGACACAAACTGCCGCTGCCACAATTGTGGTGGCGACCTCCGCCCCGTCTTCAGACACCAGTTATGCTAGTCGAAAGTACCGCCAGGTATTGCGCCATAATGCGCCAGTAGTTCCATTTAAGTGATACGAGCTTACAACTAATCCCAAGCACGAGTGCATCTGTCATCCATACTAAGCTACTCCGTCAAGGGTGCTGACAACGTTGTTGATTACAGGTGTCCTAGGAACGGCCTATGGCCGGGAGGCCTACTCAGGGGAGACCTTATCAGTGACGCAATGCGAACAAGTTGTAAATACTGTCTTTCATCTCTCACAATCCCAAGAGTAAAATTCCGCTGAGCATGGTTCCATTTGACGCTAATCGGACAAGAACTGCCGTACTTCCACCACGTTTGTCTTGTGAGACTTTCGTCTCTGCAACGACATGACAGCTTCCACGGTGCATATGAACAAATATCGTTCAACGCTGACCCATCGCCAGATAGCCTCCTACCTATGCGCATGGAAGGAACTGCTCCTTCAACCGCCTACAGATATATACGACGTGCCCATCGCTGAGAGCAGTCCGCGACCACTACAATACCCCGTTCCGATTATTAACAATTAGATGTGTTGTCAGGTTCGCCCGTCCTAACGTCTGCGTTACCCCTCTTTTCAGGCCAGTATCCAGGGTGGTATGAAACCAGATGTATTATTCCTCTGGGATTAACGGGTAACGG") dna # + colab={"base_uri": "https://localhost:8080/"} id="cMHGV922tFmO" outputId="02c9e4cc-01c4-42f2-a85a-50d2636859e3" # Fazendo a transcrição num único passo... rna = dna.transcribe() print(rna)
estudo_rosalind/Fase 1/Exercicio_A_Sindy.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier from sklearn.cross_validation import train_test_split, cross_val_score from sklearn.grid_search import GridSearchCV from sklearn.metrics import roc_curve from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression # %matplotlib inline # - df = pd.read_csv('data/churn.csv') df.head() df.shape df.info() df['last_trip_date'] = pd.to_datetime(df['last_trip_date']) df['signup_date'] = pd.to_datetime(df['signup_date']) print df['last_trip_date'].max(),df['last_trip_date'].min() print df['signup_date'].max(),df['signup_date'].min() df['churn?'] = df['last_trip_date'] < '2014-06-01' print df[df['phone'].isnull()]['churn?'].sum() print df[df['phone'].isnull()].shape df['not_rate'] = df['avg_rating_of_driver'].isnull() df['iphone?'] = df['phone'] == 'iphone' df[df['city'].unique()] = pd.get_dummies(df['city']) # # Finish data conversion, some plotting df_yes = df[df['churn?']==True] df_no = df[df['churn?']==False] print df_yes.shape, df_no.shape num_var = ['avg_dist','avg_rating_by_driver','avg_rating_of_driver','avg_surge','surge_pct','trips_in_first_30_days','weekday_pct'] cat_var = ['city','phone','luxury_car_user'] #two are converted boolean_var = ['luxury_car_user','not_rate','iphone?','Astapor','Winterfell',"King's landing"] datetime_var = ['last_trip_date','signup_date'] #check distribution of entire df, churn or no churn df[num_var].hist(figsize=(12, 9), grid=False, normed=True); df_yes[num_var].hist(figsize=(12, 9), grid=False, color='red',normed=True); df_no[num_var].hist(figsize=(12, 9), grid=False, normed=True,color='green'); # # Numerical variables def plot_distplot(df1,df2,col,num=None): plt.figure(figsize=(12,6)) sns.distplot(df1[col],label='Churn') sns.distplot(df2[col],label='No Churn') if num: plt.xlim([0,num]) plt.legend() plot_distplot(df_yes,df_no,'avg_dist',50) sns.violinplot(x='churn?',y='avg_dist',data=df) plot_distplot(df_yes,df_no,'avg_surge',4) sns.violinplot(x='churn?',y='avg_surge',data=df) plot_distplot(df_yes,df_no,'surge_pct') sns.violinplot(x='churn?',y='surge_pct',data=df) plot_distplot(df_yes,df_no,'trips_in_first_30_days',30) sns.violinplot(x='churn?',y='trips_in_first_30_days',data=df) plot_distplot(df_yes,df_no,'weekday_pct') sns.violinplot(x='churn?',y='weekday_pct',data=df) #modify function for rating, cannot do distplot,only kde def plot_hisplot(df1,df2,col,num=None): plt.figure(figsize=(12,6)) sns.distplot(df1[col],label='Churn',hist=False) sns.distplot(df2[col],label='No Churn',hist=False) if num: plt.xlim([0,num]) plt.legend() plot_hisplot(df_yes,df_no,'avg_rating_by_driver') plot_hisplot(df_yes,df_no,'avg_rating_of_driver') fig,axes = plt.subplots(nrows=1, ncols=2, figsize = (12,4)) df_yes['avg_rating_by_driver'].hist(color ='r', alpha=0.5,ax=axes[0]) df_no['avg_rating_by_driver'].hist(color ='b', alpha=0.5,ax=axes[0]) axes[0].set_title('avg_rating_by_driver') df_yes['avg_rating_of_driver'].hist(color ='r', alpha=0.5,ax=axes[1]) df_no['avg_rating_of_driver'].hist(color ='b', alpha=0.5,ax=axes[1]) axes[1].set_title('avg_rating_of_driver') # # Categorical variables df.columns pd.crosstab(df['not_rate'],df['churn?']) pd.crosstab(df['luxury_car_user'],df['churn?']) pd.crosstab(df['phone'],df['churn?']) pd.crosstab(df['city'],df['churn?']) agg = df.groupby(['city','phone'])['churn?'].mean() sns.heatmap(agg.unstack(level='city'), annot=True) df[["King's Landing","Astapor", 'Winterfell']].head(10) # # Randomforest and feature selection df.columns #select some promising columns based on plotting, also drop one city column y=df['churn?'] cols_use = ['iphone?',"King's Landing","Astapor", 'trips_in_first_30_days', 'not_rate','luxury_car_user',\ 'surge_pct','weekday_pct','avg_dist','avg_surge'] cols_not =['avg_rating_of_driver','avg_rating_by_driver','Winterfell'] X = df[cols_use] #use all features except rating becuase some are missing RF_model = RandomForestClassifier(50) RF_model.fit(X,y) zip_feature = zip(cols_use, RF_model.feature_importances_) print sorted(zip_feature, key = lambda x: x[1], reverse=True) print np.mean(cross_val_score(RF_model, X, y, cv=5,scoring='accuracy')) print np.mean(cross_val_score(RF_model, X, y, cv=5,scoring='recall')) #write a function to print feature importance and score def prediction(model, df, cols, RF=None): y = df['churn?'] X = df[cols] model.fit(X,y) if RF: print 'Model Importances\n' zip_feature = zip(cols, RF_model.feature_importances_) for item in sorted(zip_feature, key = lambda x: x[1], reverse=True): print item print 'Accuracy score:', np.mean(cross_val_score(model, X, y, cv=5, scoring = 'accuracy')) print "Recall score", np.mean(cross_val_score(model, X, y, cv=5, scoring = 'recall')) #check all features except avg_dist cols = [x for x in cols_use if x!='avg_dist'] rf1 = RandomForestClassifier(50) prediction(rf1,df,cols,True) #check number of trees num_trees = range(5, 100, 5) accu=[] for n in num_trees: rf = RandomForestClassifier(n_estimators=n, n_jobs=-1) score = np.mean(cross_val_score(rf, X, y, cv=5, scoring = 'accuracy')) accu.append(score) plt.plot(num_trees, accu) #check average feature importance def plot_avg_feature_importance(model,X,y,n,m,features): feat_arr = np.zeros((n, X.shape[1])) for i in xrange(n): model.fit(X,y) feat_arr[i,:] = model.feature_importances_ fmean = feat_arr.mean(axis = 0) fstd = feat_arr.std(axis = 0) indices = np.argsort(fmean)[::-1][:m] #keep top m features sorted_fmean = fmean[indices][:m] sorted_fstd = fstd[indices][:m] sorted_fname = np.array(features)[indices][:m] for f in range(m): print("%d. %s (%f)" % (f + 1, sorted_fname[f], sorted_fmean[f])) fig = plt.figure(figsize=[12,6]) plt.barh(range(m), sorted_fmean[::-1], color='r', \ xerr=sorted_fstd[::-1], align = 'center') plt.yticks(range(m), sorted_fname[::-1]); plt.ylim([-0.5,m-0.5]) n = 20 #how many times to repeat m = len(cols_use) #how many features to plot #cols_use is features, X,y is the same rf_avg = RandomForestClassifier(n_estimators=100) plot_avg_feature_importance(rf_avg,X,y,n,m,cols_use) def feature_substract(model,df,cols_total, cols_to_choose): y = df['churn?'] scores =[] for col in cols_to_choose: temp_cols = [x for x in cols_total if x!=col] X = df[temp_cols] print 'Without ',col print 'Accuracy score: ',np.mean(cross_val_score(model, X, y, cv=5, scoring ='accuracy')) print 'Recall score: ',np.mean(cross_val_score(model, X, y, cv=5, scoring ='recall')) rf_feature = RandomForestClassifier(n_estimators=100,n_jobs=-1) cols_use = ['iphone?',"King's Landing","Astapor", 'trips_in_first_30_days', 'not_rate','luxury_car_user',\ 'surge_pct','weekday_pct','avg_dist','avg_surge'] cols_choose = ['avg_dist','avg_surge','iphone?','surge_pct','not_rate'] feature_substract(rf_feature,df,cols_use,cols_choose) #only avg_dist has a big impact, remove it from cols_use #remove avg_dist from overall list, then check all the rest cols_use = ['iphone?',"King's Landing","Astapor", 'trips_in_first_30_days', 'not_rate','luxury_car_user',\ 'surge_pct','weekday_pct','avg_surge'] cols_choose = cols_use feature_substract(rf_feature,df,cols_use,cols_choose) #none had major impact on score, check average importance again n = 20 #how many times to repeat m = len(cols_use) #how many features to plot #cols_use is features X = df[cols_use] y = df['churn?'] rf_avg = RandomForestClassifier(n_estimators=100) plot_avg_feature_importance(rf_avg,X,y,n,m,cols_use) # + #remove the two with lowest importance rf_test = RandomForestClassifier(n_estimators=100) cols_test = [x for x in cols_use if x not in ['iphone?','not_rate']] prediction(rf_test,df,cols_test,True) # - # # AdaBoost # + y=df['churn?'] cols_use = ['iphone?',"King's Landing","Astapor", 'trips_in_first_30_days', 'not_rate','luxury_car_user',\ 'surge_pct','weekday_pct','avg_dist','avg_surge'] X=df[cols_use] Ada_model = AdaBoostClassifier() params = {'learning_rate':[1,0.3,0.1,0.03, 0.01] } grid_ada = GridSearchCV(AdaBoostClassifier(n_estimators=100), params, scoring='recall') grid_ada.fit(X,y) print grid_ada.best_score_ print grid_ada.best_params_ # - best_ada = grid_ada.best_estimator_ prediction(best_ada,df,cols_use,True) #change scoring to accuracy grid_ada1 = GridSearchCV(AdaBoostClassifier(n_estimators=100), params, scoring='accuracy') grid_ada1.fit(X,y) print grid_ada1.best_score_ print grid_ada1.best_params_ #with metrics=accuracy, similar score as randomforest best_ada1 = grid_ada1.best_estimator_ prediction(best_ada1,df,cols_use,True) # + #grid search for gradientboosting def grid_search(est, grid): grid_cv = GridSearchCV(est, grid, n_jobs=-1, verbose=True, scoring='recall').fit(X,y) return grid_cv gd_grid = {'learning_rate': [0.1, 0.05, 0.02, 0.01], 'max_depth': [4, 6], 'min_samples_leaf': [3, 5, 9, 17], 'max_features': [1.0, 0.3, 0.1], 'n_estimators': [100]} gd_grid_search = grid_search(GradientBoostingClassifier(), gd_grid) gd_best = gd_grid_search.best_estimator_ gd_best.fit(X,y) # - gd_grid_search.best_score_ from sklearn.ensemble.partial_dependence import plot_partial_dependence features = gd_best.feature_importances_ sorted_index = np.argsort(features) fig, axs = plot_partial_dependence(gd_best, X, range(X.shape[1]) ,feature_names=cols_use, figsize=(15, 20)) fig.tight_layout() # # LogisticRegresion model_lm = LogisticRegression() #use cols_use for all ten features prediction(model_lm,df,cols_use,False) for item in zip(cols_use, np.exp(model_lm.coef_)[0]): print item # # profit curve # # # + def profit_curve(cb, predict_probas, labels): profits = [] probas = np.sort(predict_probas) for prob in probas: predict = predict_probas > prob confusion = confusion_matrix(labels, predict) profits.append(np.sum(confusion*cb)/labels.shape[0]) return profits def confusion_matrix(y_true, y_predict): y_true = np.array(y_true) y_predict = np.array(y_predict) output = np.zeros((2,2)) output[0,0]= np.sum((y_true==1) & (y_predict==1)) output[0,1]= np.sum((y_true==0) & (y_predict==1)) output[1,0]= np.sum((y_true==1) & (y_predict==0)) output[1,1]= np.sum((y_true==0) & (y_predict==0)) return output # - def plot_profit_curve(model, label, costbenefit, X_train, X_test, y_train, y_test) : model.fit(X_train, y_train) probas_test = model.predict_proba(X_test)[:,1] profits = profit_curve(costbenefit, probas_test, y_test) percentages = np.arange(0, 100, 100. / len(profits)) plt.plot(percentages, profits, label=label) plt.title("Profit Curve") plt.xlabel("Percentage of test instances (decreasing by score)") plt.ylabel("Profit") plt.legend(loc='lower right') # + #p=0.5 #c_b = np.array([[p*15+(1-p)*(-5),15],[0,20]]) # 0.8*15+0.2*(-5)= 12-1=11 # - y = df['churn?'] X = df[cols_use] X_train, X_test, y_train, y_test = train_test_split(X,y) rf_model = RandomForestClassifier(100) model_lm = LogisticRegression() c_b = np.array([[10,-5],[0,0]]) #number 10 and -5 are just a guess # + fig = plt.figure(figsize = (12,6)) plot_profit_curve(RF_model, 'profit_curve for random forest', c_b, X_train, X_test, y_train, y_test) plot_profit_curve(best_ada, 'profit_curve for adaboost', c_b, X_train, X_test, y_train, y_test) #plot_profit_curve(model_lm, 'profit_curve for Logistic', c_b, X_train, X_test, y_train, y_test) plt.legend() # + #convert datatype to float for logistic regression y = df['churn?'] X = df[cols_use].values X = X.astype(float) X_train, X_test, y_train, y_test = train_test_split(X,y) rf_model = RandomForestClassifier(100) model_lm = LogisticRegression() c_b = np.array([[10,-5],[0,0]]) fig = plt.figure(figsize = (12,6)) plot_profit_curve(RF_model, 'profit_curve for random forest', c_b, X_train, X_test, y_train, y_test) #use adaboost best_ada1 for different metrics plot_profit_curve(best_ada1, 'profit_curve for adaboost', c_b, X_train, X_test, y_train, y_test) plot_profit_curve(model_lm, 'profit_curve for Logistic', c_b, X_train, X_test, y_train, y_test) plt.legend() # + def plot_roc(model, label ,X_test, y_test): fpr, tpr, _ = roc_curve(y_test, model.predict_proba(X_test)[:,1]) plt.plot(fpr, tpr, label=label) plt.plot([0,1],[0,1], linestyle='--') fig = plt.figure(figsize = (12,6)) plot_roc(RF_model, 'roc_curve for random forest', X_test, y_test) plot_roc(best_ada1, 'roc_curve for adaboost', X_test, y_test) plot_roc(model_lm, 'roc_curve for Logistic', X_test, y_test) plt.legend() # -
churn_prediction.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # this script is down Py2.7 # <NAME> # #Path Plannting with B-Spline # # + import numpy as np import matplotlib.pyplot as plt import scipy.interpolate as si # parameter N = 3 # B Spline order def bspline_planning(x, y, sn): t = range(len(x)) x_tup = si.splrep(t, x, k=N) y_tup = si.splrep(t, y, k=N) x_list = list(x_tup) xl = x.tolist() x_list[1] = xl + [0.0, 0.0, 0.0, 0.0] y_list = list(y_tup) yl = y.tolist() y_list[1] = yl + [0.0, 0.0, 0.0, 0.0] ipl_t = np.linspace(0.0, len(x) - 1, sn) rx = si.splev(ipl_t, x_list) ry = si.splev(ipl_t, y_list) return rx, ry #两个关键命令: splreq, splev; 都在scipy库中; # splreq: # + def main(): print(" start!!") # way points, 变道的例子 x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) y = np.array([0.0, 0.0, 0.0, 1.5, 1.75, 1.75]) sn = 100 # sampling number rx, ry = bspline_planning(x, y, sn) # show results plt.plot(x, y, '-og', label="Waypoints") plt.plot(rx, ry, '-r', label="B-Spline path") plt.grid(True) plt.legend() plt.axis("equal") plt.show() if __name__ == '__main__': main() # -
Path_Generation/BSpline/BSpline.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + ## Day 9 n=int(input("enter a number: ")) sum=n%10 # to extract last digit of number while n!=0: r=n%10 n=n//10 sum=sum+r print("sum of first and last digit of number is",sum) # -
Day 9/1218muskan.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="H6ZYZf4adoW6" colab_type="text" # # Welcome to PsyNeuLink # # PsyNeuLink is an integrated language and toolkit for creating cognitive models. It decreases the overhead required for cognitive modeling by providing standard building blocks (DDMS, Neural Nets, etc.) and the means to connect them together in a single environment. PsyNeuLink is designed to make the user think about computation in a "mind/brain-like" way while imposing minimal constraint on the type of models that can be implemented. # + [markdown] id="V7laEcFxdoW7" colab_type="text" # ## How to get PsyNeuLink # # PsyNeuLink is compatible with python versions >= 3.6, and is available through PyPI: # # ```python # pip install psyneulink # ``` # Or you can clone the github repo [here](https://github.com/PrincetonUniversity/PsyNeuLink). Download the package with the green "Clone or download" button on the right side of the page and "Download ZIP." Open the version of this Tutorial in the cloned folder before continuing on. # # ## Installation # # To install the package, navigate to the cloned directory in a terminal, switch to your preferred python3 environment, then run the command __"pip install ."__ (make sure to include the period and to use the appropriate pip/pip3 command for python 3.6). All prerequisite packages will be automatically added to your enviroment. # # For the curious, these are: # * numpy (version 1.16) # * matplotlib # * toposort (version 1.4) # * typecheck-decorator (version 1.2) # * pillow # * llvmlite # * mpi4py (optional) # + [markdown] id="vK3d3A4NdoW8" colab_type="text" # # ## Tutorial Overview # # This tutorial is meant to get you accustomed to the structure of PsyNeuLink and be able to construct basic models. Starting with a simple 1-to-1 transformation, we will build up to making the Stroop model from Cohen et al. (1990). Let's get started! # + [markdown] id="6skRbr-sdoW9" colab_type="text" # ### Imports and file structure # # The following code blocks will import psyneulink and set up the jupyter environment for visualization. # + id="Knw8qifUdoW-" colab_type="code" outputId="4ea02df7-1e85-4d49-979b-bade8252cd8d" colab={"base_uri": "https://localhost:8080/", "height": 136.0} # #!pip install psyneulink #run this command if opening in Google CoLaboratory import psyneulink as pnl # + id="Cw_2dcCfdoXB" colab_type="code" colab={} import numpy as np import matplotlib.pyplot as plt # # %matplotlib inline # + [markdown] id="IMknYIZ0doXE" colab_type="text" # ### Creating a mechanism # # *[Mechanisms](https://princetonuniversity.github.io/PsyNeuLink/Mechanism.html)* are the basic units of computation in PsyNeuLink. At their core is a parameterized *function* but they also contain the machinery to interact with input, output, control, and learning signals. Our first mechanism will perform a linear transformation on a scalar input. For now, we will initialize it by just specifying the *function* of the mechanism. # + id="hbBADbLrdoXF" colab_type="code" colab={} linear_transfer_mechanism = pnl.TransferMechanism( function=pnl.Linear(slope=1, intercept=0)) # + [markdown] id="gt0gGfYYdoXN" colab_type="text" # In this case, we didn't actually need to specify the slope and intercept as the function will default to reasonable values (if we didn't specify it would have defaulted to a slope of 1 and intercept of 0). The function above has two parameters, slope and intercept. If we wrote the equation as y = ax + b, a is the slope, b is the input, x is the input and y is the output. As a function we write this f(x) = ax + b. Note that you can change these parameter values of a=1 and b=0 to other numbers -- because parameters are variables within a function. # # Some transfer functions other than Linear that you could use are: Exponential, Logistic, or SoftMax. An Exponential function raises some input number to an exponent (e.g. squaring a number is an exponent of 2, and the square root of a number is an exponent of 1/2). The output of a Logistic function is bounded between 0 and 1, and we'll learn a bit more about it later in this tutorial. SoftMax is a more complex function that is often used in neural networks, and you don't need to understand how it works yet. # # Next let's try inputing the number 2 to our linear transfer mechanism... # + id="EYzobUQjdoXI" colab_type="code" outputId="cdf049b2-2adf-4b36-a3a7-904a561f25c1" colab={"base_uri": "https://localhost:8080/", "height": 34.0} linear_transfer_mechanism.execute([2]) # + [markdown] id="3Y68tW8WfY6E" colab_type="text" # Try reparamaterizing the mechanism (change the slope and/or intercept) and executing again before moving on... # # If you change slope to 3, run the code by pressing play, then change the input value to 4, what output do you get? Why? Can you predict what will happen if you change the slope to 4 and intercept to 5 and run both cells again with an input of 3? # # Another way of expressing this function is (slope x input) + intercept. # # ### Logistic Function # # The following cell plots a logistic function with the default parameters; gain = 1, bias = 0, offset = 0. # + id="2pSgoHcHfkoS" colab_type="code" outputId="ec35c2f8-0afa-4f0d-cf3f-afeb1ac356e6" colab={"base_uri": "https://localhost:8080/", "height": 269.0} logistic_transfer_demo = pnl.TransferMechanism(function=pnl.Logistic(gain=1, bias=0, offset=0)) logistic_transfer_demo.plot() # + [markdown] id="E8Y4AwEefsxw" colab_type="text" # In the cell below you can plug a single number into this function and get an output value. Your input corresponds to a point on the x axis, and the output is the corresponding y value (height of the point on the curve above the x you specified). # + id="q6C_KmkEft-k" colab_type="code" outputId="4928c3b7-d58a-4648-fb6b-2e7609898882" colab={"base_uri": "https://localhost:8080/", "height": 34.0} logistic_transfer_demo.execute([-2]) # + [markdown] id="lBBsnUvaf2qk" colab_type="text" # The logistic function is useful because it is bounded between 0 and 1. Gain determines how steep the central portion of the S curve is, with higher values being steeper. Bias shifts the curve left or right. You can turn the logistic function effectively into a step function that works as a threshhold by increasing gain. The step in the step function (where it crosses through 0.5 on the Y axis) is located on the X axis at (offset/gain) + bias. # + id="76xpYsiMf7Bw" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 269.0} outputId="252c08d2-e098-45a9-8ec3-bee5f1d7cf89" logistic_transfer_offgain = pnl.TransferMechanism(function=pnl.Logistic(gain=5,offset=10, bias=0)) logistic_transfer_offgain.plot() # + [markdown] id="Q1NbpKYef_zX" colab_type="text" # Negative values of gain mirror reverse the S curve accross the vertical axis, centered at the x value of (offset/gain)+bias. Below notice that offset/gain is -2 (10/-5), and at an X value of -2 the Y value is 0.5. # + id="ouY4W0-VgAoy" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 269.0} outputId="7e71b829-2035-4623-efa5-29b738ae4525" logistic_transfer_invert = pnl.TransferMechanism(function=pnl.Logistic(gain=-5, bias=0, offset=10)) logistic_transfer_invert.plot() # + [markdown] id="pJYwFCtFgLL_" colab_type="text" # ### From Nodes to Graphs: Compositions # # Generally with PsyNeuLink, you won't be executing mechanisms as stand-alone entities. Rather, mechanisms will be nodes in a graph, with Projections as edges of the graph, connecting nodes. We call the graph a System. # # The simplest kind of System graph is one-dimensional: a linear progression from one node to the next. Information flowing through this graph will enter as input, be processed in the first mechanism, transfered via projection to the next mechanism, and so on. You can think of this with an analogy to digestion. Chew the food first, then swallow and it is "projected" to the stomach, then the stomach soaks food in digestive acid to further break it down, then the output is projected to the small intestine where nutrients are absorbed. Note that the order matters -- the small intestine wouldn't be effective if food hadn't been chewed and then broken down in the stompach. # # A Mechanism takes some input, performs a function, and delivers an output. The same is typically true of Systems -- they take some input, perform multiple functions using multiple Mechanisms, and deliver some output. A powerful feature of this input-output architecture is that an entire System today can become a Mechanism tomorrow in a more complex System, and that System can become a Mechanisms in yet a more complex System, all the way up. [Note: this is true in principle, but PsyNeuLink is actively under development and such scaled up functionality is not all implemented.] # # The main parameter when initializing a System is its pathway, which is the order in which the Mechanisms will execute. Of course, with only one Mechanism in our System, the list has just one element. # # To better see how the System runs, we can also turn on output reporting. Reporting can happen at every level in PsyNeuLink and here we set the preference for the Mechanism. # + id="Wy8RpatmdoXO" colab_type="code" outputId="d3e1287c-bae7-4340-e91c-5c51ba6c68d3" colab={"base_uri": "https://localhost:8080/", "height": 80.0} comp_simplest = pnl.Composition() comp_simplest.add_linear_processing_pathway(pathway = [linear_transfer_mechanism]) linear_transfer_mechanism.reportOutputPref = True comp_simplest.show_graph(output_fmt = 'jupyter') # + id="aUAu67OfdoXU" colab_type="code" outputId="b737679e-74dd-4d7b-e590-4ef3648514f3" colab={"base_uri": "https://localhost:8080/", "height": 323.0} comp_simplest.run([4]) # + [markdown] id="Gn9BTx3AhKe1" colab_type="text" # Let's turn off the reporting and look at our process' output over a wider range of values. # + id="6s3wlnUPdoXX" colab_type="code" outputId="e33caf50-e257-4ee4-938e-cf4777f20a00" colab={"base_uri": "https://localhost:8080/", "height": 286.0} linear_transfer_mechanism.reportOutputPref = False xVals = np.linspace(-3, 3, num=51) # create 51 points between -3 and +3 yVals = np.zeros((51,)) for i in range(xVals.shape[0]): yVals[i] = comp_simplest.run([xVals[i]])[0] # Progress bar print("-", end="") plt.plot(xVals, yVals) plt.show() # + [markdown] id="0FZlTGTJhkqq" colab_type="text" # Now let's put it all together and make a new transfer process, this time with a logistic activation function. We will also extend our mechanism by giving it two units (operating on a 1x2 matrix) rather than the default one (operating on a scalar). # + id="k3h7k2wIdoXb" colab_type="code" outputId="502edb72-a2b2-49c5-cef0-6ea30f1d3dd0" colab={"base_uri": "https://localhost:8080/", "height": 286.0} # Create composition comp_1x2 = pnl.Composition() # Create the mechanism logistic_transfer_mechanism = pnl.TransferMechanism(default_variable=[0, 0], function=pnl.Logistic(gain=1, bias=0)) # Place mechanism in composition comp_1x2.add_linear_processing_pathway(pathway = [logistic_transfer_mechanism]) # Iterate and plot xVals = np.linspace(-3, 3, num=51) y1Vals = np.zeros((51,)) y2Vals = np.zeros((51,)) for i in range(xVals.shape[0]): # clarify why multiplying times 2 output = comp_1x2.run([xVals[i], xVals[i] * 3]) y1Vals[i] = output[0][0] y2Vals[i] = output[0][1] # Progress bar print("-", end="") plt.plot(xVals, y1Vals) plt.plot(xVals, y2Vals) plt.show() # + [markdown] id="j4BXYFbLh8Zn" colab_type="text" # The `default_variable` parameter serves a dual function. It specifies the dimensionality of the mechanism as well as providing the inputs that will be given in the absence of explicit input at runtime. You can also specify the dimensionality using "size", e.g. size=2 will also create default_variable=[0,0]. # + id="FtN0VYCsiJwa" colab_type="code" colab={} logistic_transfer_step = pnl.TransferMechanism(default_variable=[0, 0], function=pnl.Logistic(gain=100, offset=100)) # + id="ddg9BFXfiLNB" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34.0} outputId="45be1414-3b25-404c-a0a1-08c5474fa3a9" logistic_transfer_step.execute([.9,1.1]) # + [markdown] id="dPaX0syYiShl" colab_type="text" # ### Adding Projections # # To connect Mechanisms together in a Composition, we need a way to link mechanisms together. This is done through *[Projections](https://princetonuniversity.github.io/PsyNeuLink/Projection.html)*. A projection takes a mechanism output, multiplies it by the projection's mapping matrix, and delivers the transformed value to the next mechanism in the Composition. # + id="VEUVwefgiXPn" colab_type="code" outputId="a9344b09-ca1c-4c51-a53e-bcd31331a065" colab={"base_uri": "https://localhost:8080/", "height": 286.0} # Create composition comp_linlog = pnl.Composition() # Create mechanisms linear_input_unit = pnl.TransferMechanism(function=pnl.Linear(slope=2, intercept=2)) logistic_output_unit = pnl.TransferMechanism(function=pnl.Logistic()) # Place mechanism in composition comp_linlog.add_linear_processing_pathway(pathway = [linear_input_unit, pnl.IDENTITY_MATRIX, logistic_output_unit]) # Iterate and plot xVals = np.linspace(-3, 3, num=51) yVals = np.zeros((51,)) for i in range(xVals.shape[0]): yVals[i] = comp_linlog.run([xVals[i]])[0] # Progress bar print("-", end="") plt.plot(xVals, yVals) plt.show() # + [markdown] id="gQP6ZFH-ifO2" colab_type="text" # `IDENTITY_MATRIX` is a keyword that provides a projection from the unit preceding it to the unit following that creates a one-to-one output to input projection between the two. # # Now let's make our projection definition a bit more explicit. # + id="9QF9E0TainCy" colab_type="code" outputId="9f5915c7-02af-462b-8a9e-5af00d7d434d" colab={"base_uri": "https://localhost:8080/", "height": 286.0} # Create composition comp_explicit = pnl.Composition() # Create mechanisms linear_input_unit = pnl.TransferMechanism(function=pnl.Linear(slope=2, intercept=2), name="linear") logistic_output_unit = pnl.TransferMechanism(function=pnl.Logistic(), name="logistic") # Create projection mapping_matrix = np.asarray([[1]]) unit_mapping_projection = pnl.MappingProjection(sender=linear_input_unit, receiver=logistic_output_unit, matrix=mapping_matrix) # Place mechanisms and projections in composition comp_explicit.add_linear_processing_pathway(pathway = [linear_input_unit, unit_mapping_projection, logistic_output_unit]) # Iterate and plot xVals = np.linspace(-3, 3, num=51) yVals = np.zeros((51,)) for i in range(xVals.shape[0]): yVals[i] = comp_explicit.run([xVals[i]])[0] # Progress bar print("-", end="") plt.plot(xVals, yVals) plt.show() # + id="wiKec76Riuop" colab_type="code" outputId="2017afbd-f503-4084-ec39-6c228181dca6" colab={"base_uri": "https://localhost:8080/", "height": 176.0} comp_explicit.show_graph(output_fmt = 'jupyter') # + [markdown] id="vmqMmXDrizMf" colab_type="text" # This time we specified our mapping matrix (which is a 2-D numpy array) then explicitly initialized a *[MappingProjection](https://princetonuniversity.github.io/PsyNeuLink/MappingProjection.html)* with that matrix as well as its input and output mechanisms. Note: because we specified the input and output mechanisms in the projection itself, we didn't need to include it in the composition pathway as the composition would have infered its position from those parameters. Ultimately, however, this does the exact same thing as our keyword method above which is far less verbose for this common use case. # + [markdown] id="XV91dEJ2i_rP" colab_type="text" # ### Compositions # # The highest level at which models are considered in PsyNeuLink is that of the *[Composition](https://princetonuniversity.github.io/PsyNeuLink/Composition.html)*. A composition is built out of one or more mechanisms connected by projections. This allows Composition graphs to be more complex than the strictly linear ones covered so far. Our first composition will consist of two input nodes that converge on a single output mechanism. We will be modelling competition between color naming and word reading in the Stroop task. [Recall that the Stroop task involves naming the ink color of words: when the word itself mismatches with the ink color it is written in (e.g. the word RED written in blue ink), that produces conflict and slower response times to name the ink color.] # # ### Mini-Stroop Model # + id="rAymk7bujTCG" colab_type="code" outputId="9d6ef8e9-f323-4b7e-ae20-72fd151e6a77" colab={"base_uri": "https://localhost:8080/", "height": 176.0} mini_stroop = pnl.Composition() colors = pnl.TransferMechanism(default_variable=[0, 0], function=pnl.Linear, name="Colors") words = pnl.TransferMechanism(default_variable=[0, 0], function=pnl.Linear(slope=1.5), name="Words") response = pnl.TransferMechanism(default_variable=[0, 0], function=pnl.Logistic, name="Response") # Place mechanisms and projections in composition mini_stroop.add_linear_processing_pathway(pathway = [colors, response]) mini_stroop.add_linear_processing_pathway(pathway = [words, response]) mini_stroop.show_graph(output_fmt = 'jupyter') # + [markdown] id="BOWowlx6kC4g" colab_type="text" # An input of [1, 0] to ink is red ink, and [0, 1] is blue ink. # An input of [1, 0] to word is "red" and [0, 1] is "blue". # If the input values to ink and word are the same, that is a congruent trial. If the input values to the ink and word are different that is an incongruent trial. # # In the output of the system, the first output value is the strength to respond red, and the second value is the strength to respond blue. # # In the following two cells we will first specify a congruent trial (blue ink, word "blue") to see the output, and then specify an incongruent trial (red ink, word "blue"). # + id="qgEakz_4kQLL" colab_type="code" outputId="d65ac391-5f02-4daa-ba67-0ddca93fc18b" colab={"base_uri": "https://localhost:8080/", "height": 34.0} input_allblue = {colors: [0, 1], words: [0, 1]} mini_stroop.run(input_allblue) # + id="xyHPjYkWj0gK" colab_type="code" outputId="d92538bb-889f-4e7a-d70b-697c451b8258" colab={"base_uri": "https://localhost:8080/", "height": 34.0} input_redblue = {colors: [1, 0], words: [0, 1]} mini_stroop.run(input_redblue) # + [markdown] id="OubMjYMkdoYQ" colab_type="text" # ### Pre-trained Complete Stroop Model # # Let's practice using compositions by recreating the more complex stroop model from Cohen et al (1990). Later we will train the network ourselves, but for now we will explicitly model the learned weights. # + id="XFNp0zgtdoYR" colab_type="code" outputId="d86f5d6d-8e79-4b39-87fa-0559d5bf3c61" colab={"base_uri": "https://localhost:8080/", "height": 272.0} stroop_model = pnl.Composition() ink_color = pnl.TransferMechanism(default_variable=[0, 0], function=pnl.Linear(),name="Ink_Color") word = pnl.TransferMechanism(default_variable=[0, 0], function=pnl.Linear(),name="Word") task_demand = pnl.TransferMechanism(default_variable=[0, 0], function=pnl.Linear(),name="Task") hidden_layer = pnl.TransferMechanism(default_variable=[0, 0, 0, 0], function=pnl.Logistic(bias=-4), name="Hidden") output_layer = pnl.TransferMechanism(default_variable=[[0, 0]], function=pnl.Linear(), name="Output") color_mapping_matrix = np.asarray([[2.2, -2.2, 0, 0], [-2.2, 2.2, 0, 0]]) color_projection = pnl.MappingProjection(sender=ink_color, receiver=hidden_layer, matrix=color_mapping_matrix) word_mapping_matrix = np.asarray([[0, 0, 2.6, -2.6], [0, 0, -2.6, 2.6]]) word_projection = pnl.MappingProjection(sender=word, receiver=hidden_layer, matrix=word_mapping_matrix) task_mapping_matrix = np.asarray([[4, 4, 0, 0], [0, 0, 4, 4]]) task_projection = pnl.MappingProjection(sender=task_demand, receiver=hidden_layer, matrix=task_mapping_matrix) output_mapping_matrix = np.asarray( [[1.3, -1.3], [-1.3, 1.3], [2.5, -2.5], [-2.5, 2.5]]) output_projection = pnl.MappingProjection(sender=hidden_layer, receiver=output_layer, matrix=output_mapping_matrix) stroop_model.add_linear_processing_pathway(pathway = [ink_color, color_projection, hidden_layer, output_projection, output_layer]) stroop_model.add_linear_processing_pathway(pathway = [word, word_projection, hidden_layer, output_projection, output_layer]) stroop_model.add_linear_processing_pathway(pathway = [task_demand, task_projection, hidden_layer, output_projection, output_layer]) ink_color.reportOutputPref = True word.reportOutputPref = True task_demand.reportOutputPref = True hidden_layer.reportOutputPref = True stroop_model.show_graph(output_fmt = 'jupyter') # + [markdown] id="cQ5qk7UadoYU" colab_type="text" # In the next cell we will run the model with inputs. The "ink_color" and "word" are the same as the previous model, and the addition of task demand allows us to specify whether the task is to name the color of ink [0, 1], or to read the word [1, 0]. The output can be thought of as activation strengths of two possible responses [red, blue]. # + id="_3h3HUQ2doYV" colab_type="code" outputId="9eac7bdb-a7c3-40cb-98cd-2fe620a4e935" colab={"base_uri": "https://localhost:8080/", "height": 1292.0} input_dict = {ink_color: [1, 0], word: [0, 1], task_demand: [1, 0]} stroop_model.run(input_dict) # + [markdown] id="a2g6AQLBdoYZ" colab_type="text" # To get a better sense of how the model works, try reverse engineering by changing each of the inputs (remember the options are only [1,0] or [0,1]) one at a time and running the model. Given 3 input states (Task, Word, Ink) with 2 options each, there will be 8 possibilities (2^3). # # # + [markdown] id="YPcQIM7odoYg" colab_type="text" # # Constructing Compositions # # As shown in the Stroop models above, mechanisms are the building blocks in PsyNeuLink, and projections are how these building blocks get connected. The configuration of mechanisms connected by projections determines how information will flow and be processed within each model. Next we'll explore how to build models with different configurations of mechanisms and projections, along with generating diagrams that visualize these configurations. # + id="HeNSMjrNdoYh" colab_type="code" outputId="94d9d639-f2d2-4dcb-e09a-694db78f8ee0" colab={"base_uri": "https://localhost:8080/", "height": 176.0} # Create composition comp_line2 = pnl.Composition() input_layer_cL2 = pnl.TransferMechanism( name='input_layer_cL2', function=pnl.Linear, default_variable=np.ones((4,)), ) output_layer_cL2 = pnl.TransferMechanism( name='output_layer_cL2', function=pnl.Linear, default_variable=np.ones((4,)), ) # Place mechanisms in composition comp_line2.add_linear_processing_pathway(pathway = [input_layer_cL2, output_layer_cL2]) input_layer_cL2.reportOutputPref = True output_layer_cL2.reportOutputPref = True comp_line2.show_graph(output_fmt = 'jupyter') # + id="yyYi8cMqdoYj" colab_type="code" outputId="0ab453d8-7705-4264-d0e5-ba96bcd07979" colab={"base_uri": "https://localhost:8080/", "height": 272.0} # Create composition comp_line3 = pnl.Composition() # Create mechanisms input_layer_cL3 = pnl.TransferMechanism( name='input_layer_cL3', function=pnl.Linear, default_variable=np.ones((4,)), ) hidden_layer_cL3 = pnl.TransferMechanism( name='hidden_layer_cL3', function=pnl.Linear, default_variable=np.ones((4,)), ) output_layer_cL3 = pnl.TransferMechanism( name='output_layer_cL3', function=pnl.Linear, default_variable=np.ones((4,)), ) # Place mechanisms in composition comp_line3.add_linear_processing_pathway(pathway = [input_layer_cL3, hidden_layer_cL3, output_layer_cL3]) input_layer_cL3.reportOutputPref = True hidden_layer_cL3.reportOutputPref = True output_layer_cL3.reportOutputPref = True comp_line3.show_graph(output_fmt = 'jupyter') # + id="v0KoxHnFdoYm" colab_type="code" outputId="418b710f-ba44-41ff-921c-698a99fb9ccb" colab={"base_uri": "https://localhost:8080/", "height": 368.0} # Create composition comp_recur1 = pnl.Composition() input_r1 = pnl.TransferMechanism( name='input_r1', function=pnl.Linear, default_variable=np.ones((4,)), ) hidden_r1a = pnl.TransferMechanism( name='hidden_r1a', function=pnl.Linear, default_variable=np.ones((4,)), ) hidden_r1b = pnl.TransferMechanism( name='hidden_r1b', function=pnl.Linear, default_variable=np.ones((4,)), ) output_r1 = pnl.TransferMechanism( name='output_r1', function=pnl.Linear, default_variable=np.ones((4,)), ) # Place mechanisms in composition comp_recur1.add_linear_processing_pathway(pathway = [input_r1, hidden_r1a, hidden_r1b, output_r1]) comp_recur1.add_linear_processing_pathway(pathway = [hidden_r1b, hidden_r1a]) input_r1.reportOutputPref = True hidden_r1a.reportOutputPref = True hidden_r1b.reportOutputPref = True output_r1.reportOutputPref = True comp_recur1.show_graph(output_fmt = 'jupyter') # + id="xx0P8GajdoYt" colab_type="code" outputId="62ef161c-abdb-44a1-bf13-871a7370ad05" colab={"base_uri": "https://localhost:8080/", "height": 272.0} # Create composition comp_multihidden = pnl.Composition() input_mh = pnl.TransferMechanism( name='input_mh', function=pnl.Linear, default_variable=np.ones((4,)), ) hidden_mh_a = pnl.TransferMechanism( name='hidden_mh_a', function=pnl.Linear, default_variable=np.ones((4,)), ) hidden_mh_b = pnl.TransferMechanism( name='hidden_mh_b', function=pnl.Linear, default_variable=np.ones((4,)), ) hidden_mh_c = pnl.TransferMechanism( name='hidden_mh_c', function=pnl.Linear, default_variable=np.ones((4,)), ) output_mh = pnl.TransferMechanism( name='output_mh', function=pnl.Linear, default_variable=np.ones((4,)), ) # Place mechanisms in composition comp_multihidden.add_linear_processing_pathway(pathway = [input_mh, hidden_mh_a, output_mh]) comp_multihidden.add_linear_processing_pathway(pathway = [input_mh, hidden_mh_b, output_mh]) comp_multihidden.add_linear_processing_pathway(pathway = [input_mh, hidden_mh_c, output_mh]) input_mh.reportOutputPref = True hidden_mh_a.reportOutputPref = True hidden_mh_b.reportOutputPref = True hidden_mh_c.reportOutputPref = True output_mh.reportOutputPref = True comp_multihidden.show_graph(output_fmt = 'jupyter') # + [markdown] id="eSHeXhofdoY2" colab_type="text" # This is currently the end of the tutorial, but more content is being added weekly. For further examples, look to the Scripts folder inside your PsyNeuLink directory for a variety of functioning models.
tutorial/PsyNeuLink Tutorial.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: mypydev # language: python # name: mypydev # --- # Import Numpy for calculations and matplotlib for charting import numpy as np import matplotlib.pyplot as plt # Creates a numpy array from 0 to 5 with each step being 0.1 higher than the last x_axis = np.arange(0, 5, 0.1) x_axis # Creates an exponential series of values which we can then chart e_x = [np.exp(x) for x in x_axis] e_x # Create a graph based upon the list and array we have created plt.plot(x_axis, e_x) # Show the graph that we have created plt.show() # + # Give our graph axis labels plt.xlabel("Time With MatPlotLib") plt.ylabel("How Cool MatPlotLib Seems") # Have to plot our chart once again as it doesn't stick after being shown plt.plot(x_axis, e_x) plt.show() # + jupyter={"outputs_hidden": true}
01-Lesson-Plans/05-Matplotlib/1/Activities/01-Ins_BasicLineGraphs/Solved/exponential_chart.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python # language: python # name: conda-env-python-py # --- # <center> # <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/Logos/organization_logo/organization_logo.png" width="300" alt="cognitiveclass.ai logo" /> # </center> # # # Loops in Python # # Estimated time needed: **20** minutes # # ## Objectives # # After completing this lab you will be able to: # # - work with the loop statements in Python, including for-loop and while-loop. # # <h1>Loops in Python</h1> # # <p><strong>Welcome!</strong> This notebook will teach you about the loops in the Python Programming Language. By the end of this lab, you'll know how to use the loop statements in Python, including for loop, and while loop.</p> # # <h2>Table of Contents</h2> # <div class="alert alert-block alert-info" style="margin-top: 20px"> # <ul> # <li> # <a href="#loop">Loops</a> # <ul> # <li><a href="range">Range</a></li> # <li><a href="for">What is <code>for</code> loop?</a></li> # <li><a href="while">What is <code>while</code> loop?</a></li> # </ul> # </li> # <li> # <a href="#quiz">Quiz on Loops</a> # </li> # </ul> # # </div> # # <hr> # # <h2 id="loop">Loops</h2> # # <h3 id="range">Range</h3> # # Sometimes, you might want to repeat a given operation many times. Repeated executions like this are performed by <b>loops</b>. We will look at two types of loops, <code>for</code> loops and <code>while</code> loops. # # Before we discuss loops lets discuss the <code>range</code> object. It is helpful to think of the range object as an ordered list. For now, let's look at the simplest case. If we would like to generate an object that contains elements ordered from 0 to 2 we simply use the following command: # # + # Use the range range(3) # - # <img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%203/images/range.PNG" width="300" /> # # **_NOTE: While in Python 2.x it returned a list as seen in video lessons, in 3.x it returns a range object._** # # <h3 id="for">What is <code>for</code> loop?</h3> # # The <code>for</code> loop enables you to execute a code block multiple times. For example, you would use this if you would like to print out every element in a list. # Let's try to use a <code>for</code> loop to print all the years presented in the list <code>dates</code>: # # This can be done as follows: # # + # For loop example dates = [1982,1980,1973] N = len(dates) for i in range(N): print(dates[i]) # - # The code in the indent is executed <code>N</code> times, each time the value of <code>i</code> is increased by 1 for every execution. The statement executed is to <code>print</code> out the value in the list at index <code>i</code> as shown here: # # <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%203/Images/LoopsForRange.gif" width="800" /> # # In this example we can print out a sequence of numbers from 0 to 7: # # + # Example of for loop for i in range(0, 8): print(i) # - # In Python we can directly access the elements in the list as follows: # # + # Exmaple of for loop, loop through list for year in dates: print(year) # - # For each iteration, the value of the variable <code>years</code> behaves like the value of <code>dates[i]</code> in the first example: # # <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%203/Images/LoopsForList.gif" width="800"> # # We can change the elements in a list: # # + # Use for loop to change the elements in list squares = ['red', 'yellow', 'green', 'purple', 'blue'] for i in range(0, 5): print("Before square ", i, 'is', squares[i]) squares[i] = 'white' print("After square ", i, 'is', squares[i]) # - # We can access the index and the elements of a list as follows: # # + # Loop through the list and iterate on both index and element value squares=['red', 'yellow', 'green', 'purple', 'blue'] for i, square in enumerate(squares): print(i, square) # - # <h3 id="while">What is <code>while</code> loop?</h3> # # As you can see, the <code>for</code> loop is used for a controlled flow of repetition. However, what if we don't know when we want to stop the loop? What if we want to keep executing a code block until a certain condition is met? The <code>while</code> loop exists as a tool for repeated execution based on a condition. The code block will keep being executed until the given logical condition returns a **False** boolean value. # # Let’s say we would like to iterate through list <code>dates</code> and stop at the year 1973, then print out the number of iterations. This can be done with the following block of code: # # + # While Loop Example dates = [1982, 1980, 1973, 2000] i = 0 year = dates[0] while(year != 1973): print(year) i = i + 1 year = dates[i] print("It took ", i ,"repetitions to get out of loop.") # - # A while loop iterates merely until the condition in the argument is not met, as shown in the following figure: # # <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%203/Images/LoopsWhile.gif" width="650" /> # # <hr> # # <h2 id="quiz">Quiz on Loops</h2> # # Write a <code>for</code> loop the prints out all the element between <b>-5</b> and <b>5</b> using the range function. # # Write your code below and press Shift+Enter to execute # <details><summary>Click here for the solution</summary> # # ```python # for i in range(-5, 6): # print(i) # # ``` # # </details> # # Print the elements of the following list: # <code>Genres=[ 'rock', 'R&B', 'Soundtrack', 'R&B', 'soul', 'pop']</code> # Make sure you follow Python conventions. # # Write your code below and press Shift+Enter to execute # <details><summary>Click here for the solution</summary> # # ```python # Genres = ['rock', 'R&B', 'Soundtrack', 'R&B', 'soul', 'pop'] # for Genre in Genres: # print(Genre) # # ``` # # </details> # # <hr> # # Write a for loop that prints out the following list: <code>squares=['red', 'yellow', 'green', 'purple', 'blue']</code> # # Write your code below and press Shift+Enter to execute # <details><summary>Click here for the solution</summary> # # ```python # squares=['red', 'yellow', 'green', 'purple', 'blue'] # for square in squares: # print(square) # # ``` # # </details> # # <hr> # # Write a while loop to display the values of the Rating of an album playlist stored in the list <code>PlayListRatings</code>. If the score is less than 6, exit the loop. The list <code>PlayListRatings</code> is given by: <code>PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]</code> # # Write your code below and press Shift+Enter to execute # <details><summary>Click here for the solution</summary> # # ```python # PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10] # i = 1 # Rating = PlayListRatings[0] # while(i < len(PlayListRatings) and Rating >= 6): # print(Rating) # Rating = PlayListRatings[i] # i = i + 1 # # ``` # # </details> # # <hr> # # Write a while loop to copy the strings <code>'orange'</code> of the list <code>squares</code> to the list <code>new_squares</code>. Stop and exit the loop if the value on the list is not <code>'orange'</code>: # # + # Write your code below and press Shift+Enter to execute squares = ['orange', 'orange', 'purple', 'blue ', 'orange'] new_squares = [] # - # <details><summary>Click here for the solution</summary> # # ```python # squares = ['orange', 'orange', 'purple', 'blue ', 'orange'] # new_squares = [] # i = 0 # while(i < len(squares) and squares[i] == 'orange'): # new_squares.append(squares[i]) # i = i + 1 # print (new_squares) # # ``` # # </details> # # # <hr> # <h2>The last exercise!</h2> # <p>Congratulations, you have completed your first lesson and hands-on lab in Python. However, there is one more thing you need to do. The Data Science community encourages sharing work. The best way to share and showcase your work is to share it on GitHub. By sharing your notebook on GitHub you are not only building your reputation with fellow data scientists, but you can also show it off when applying for a job. Even though this was your first piece of work, it is never too early to start building good habits. So, please read and follow <a href="https://cognitiveclass.ai/blog/data-scientists-stand-out-by-sharing-your-notebooks/" target="_blank">this article</a> to learn how to share your work. # <hr> # # ## Author # # <a href="https://www.linkedin.com/in/joseph-s-50398b136/" target="_blank"><NAME></a> # # ## Other contributors # # <a href="www.linkedin.com/in/jiahui-mavis-zhou-a4537814a"><NAME></a> # # ## Change Log # # | Date (YYYY-MM-DD) | Version | Changed By | Change Description | # | ----------------- | ------- | ---------- | ---------------------------------- | # | 2020-08-26 | 2.0 | Lavanya | Moved lab to course repo in GitLab | # | | | | | # | | | | | # # <hr/> # # ## <h3 align="center"> © IBM Corporation 2020. All rights reserved. <h3/> #
IBM Professional Certificates/Python for Data Science and AI/3-2-Loops.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] id="nI1LCVMKcfO1" # This tutorial trains a 3D densenet for lung lesion classification from CT image patches. # # The goal is to demonstrate MONAI's class activation mapping functions for visualising the classification models. # # For the demo data: # - Please see the `bbox_gen.py` script for generating the patch classification data from MSD task06_lung (available via `monai.apps.DecathlonDataset`). # - Alternatively, the patch dataset (~130MB) is available for direct downloading at: https://drive.google.com/drive/folders/1pQdzdkkC9c2GOblLgpGlG3vxsSK9NtDx # # [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Project-MONAI/tutorials/blob/main/modules/interpretability/class_lung_lesion.ipynb) # + id="AbhFzvu3JbZV" # !python -c "import monai" || pip install -q "monai-weekly[tqdm]" # + colab={"base_uri": "https://localhost:8080/"} id="nZYowi8fUVp5" outputId="10e08d85-02d9-4064-df3b-41050d13c005" import glob import os import random import tempfile import matplotlib.pyplot as plt import monai import numpy as np import torch from IPython.display import clear_output from monai.networks.utils import eval_mode from monai.transforms import ( AddChanneld, Compose, LoadImaged, RandFlipd, RandRotate90d, RandSpatialCropd, Resized, ScaleIntensityRanged, EnsureTyped, ) from monai.visualize import plot_2d_or_3d_image from sklearn.metrics import ( ConfusionMatrixDisplay, classification_report, confusion_matrix, ) from torch.utils.tensorboard import SummaryWriter monai.config.print_config() random_seed = 42 monai.utils.set_determinism(random_seed) np.random.seed(random_seed) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # + id="YcfTvuxyy9jX" directory = os.environ.get("MONAI_DATA_DIRECTORY") root_dir = ( tempfile.mkdtemp() if directory is None else os.path.expanduser(directory) ) data_path = os.path.join(root_dir, "patch") url = "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/lung_lesion_patches.tar.gz" monai.apps.download_and_extract(url, output_dir=data_path) # + colab={"base_uri": "https://localhost:8080/"} id="iTP8wvhS83ZS" outputId="9378fa98-408f-4234-82c3-b1824166fc4c" lesion = glob.glob(os.path.join(data_path, "lesion_*")) non_lesion = glob.glob(os.path.join(data_path, "norm_*")) # optionally make sure there's 50:50 lesion vs non-lesion balance_classes = True if balance_classes: print( f"Before balance -- Num lesion: {len(lesion)}," f" num non-lesion: {len(non_lesion)}" ) num_to_keep = min(len(lesion), len(non_lesion)) lesion = lesion[:num_to_keep] non_lesion = non_lesion[:num_to_keep] print( f"After balance -- Num lesion: {len(lesion)}," f" num non-lesion: {len(non_lesion)}" ) labels = np.asarray( [[0.0, 1.0]] * len(lesion) + [[1.0, 0.0]] * len(non_lesion) ) all_files = [ {"image": img, "label": label} for img, label in zip(lesion + non_lesion, labels) ] random.shuffle(all_files) print(f"total items: {len(all_files)}") # + [markdown] id="NnSCws-GzA2k" # Split the data into 80% training and 20% validation # # + colab={"base_uri": "https://localhost:8080/"} id="V6MQhLrgYyPV" outputId="50e2aa67-f73e-40c6-91f4-e6940f9117f8" train_frac, val_frac = 0.8, 0.2 n_train = int(train_frac * len(all_files)) + 1 n_val = min(len(all_files) - n_train, int(val_frac * len(all_files))) train_files, val_files = all_files[:n_train], all_files[-n_val:] train_labels = [data["label"] for data in train_files] print(f"total train: {len(train_files)}") val_labels = [data["label"] for data in val_files] n_neg, n_pos = np.sum(np.asarray(val_labels) == 0), np.sum( np.asarray(val_labels) == 1 ) print(f"total valid: {len(val_labels)}") # + [markdown] id="WF7QPpXczLuE" # Create the data loaders. These loaders will be used for both training/validation, as well as visualisations. # + colab={"base_uri": "https://localhost:8080/"} id="SSOwnizoaX0Z" outputId="bb8ceb46-a66e-4026-b0d7-29bce94777c5" # Define transforms for image win_size = (196, 196, 144) train_transforms = Compose( [ LoadImaged("image"), AddChanneld("image"), ScaleIntensityRanged( "image", a_min=-1000.0, a_max=500.0, b_min=0.0, b_max=1.0, clip=True, ), RandFlipd("image", spatial_axis=0, prob=0.5), RandFlipd("image", spatial_axis=1, prob=0.5), RandFlipd("image", spatial_axis=2, prob=0.5), RandSpatialCropd("image", roi_size=(64, 64, 40)), Resized("image", spatial_size=win_size, mode="trilinear", align_corners=True), RandRotate90d("image", prob=0.5, spatial_axes=[0, 1]), EnsureTyped("image"), ] ) val_transforms = Compose( [ LoadImaged("image"), AddChanneld("image"), ScaleIntensityRanged( "image", a_min=-1000.0, a_max=500.0, b_min=0.0, b_max=1.0, clip=True, ), Resized("image", spatial_size=win_size, mode="trilinear", align_corners=True), EnsureTyped(("image", "label")), ] ) persistent_cache = os.path.join(root_dir, "persistent_cache") train_ds = monai.data.PersistentDataset( data=train_files, transform=train_transforms, cache_dir=persistent_cache ) train_loader = monai.data.DataLoader( train_ds, batch_size=2, shuffle=True, num_workers=2, pin_memory=True ) val_ds = monai.data.PersistentDataset( data=val_files, transform=val_transforms, cache_dir=persistent_cache ) val_loader = monai.data.DataLoader( val_ds, batch_size=2, num_workers=2, pin_memory=True ) # + [markdown] id="cST2NTu2zUk_" # Start the model, loss function, and optimizer. # + id="bdGF-VX9bs6l" model = monai.networks.nets.DenseNet121( spatial_dims=3, in_channels=1, out_channels=2 ).to(device) bce = torch.nn.BCEWithLogitsLoss() def criterion(logits, target): return bce(logits.view(-1), target.view(-1)) optimizer = torch.optim.Adam(model.parameters(), 1e-5) # + [markdown] id="f2iAlkBTzYQD" # Run training iterations. # + id="rA_cp54ebxRv" # start training val_interval = 1 max_epochs = 100 best_metric = best_metric_epoch = -1 epoch_loss_values = [] metric_values = [] scaler = torch.cuda.amp.GradScaler() for epoch in range(max_epochs): clear_output() print("-" * 10) print(f"epoch {epoch + 1}/{max_epochs}") model.train() epoch_loss = step = 0 for batch_data in train_loader: inputs, labels = ( batch_data["image"].to(device), batch_data["label"].to(device), ) optimizer.zero_grad() with torch.cuda.amp.autocast(): outputs = model(inputs) loss = criterion(outputs.float(), labels.float()) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() epoch_loss += loss.item() epoch_len = len(train_ds) // train_loader.batch_size if step % 50 == 0: print(f"{step}/{epoch_len}, train_loss: {loss.item():.4f}") step += 1 epoch_loss /= step epoch_loss_values.append(epoch_loss) print(f"epoch {epoch + 1} average loss: {epoch_loss:.4f}") if (epoch + 1) % val_interval == 0: with eval_mode(model): num_correct = 0.0 metric_count = 0 for val_data in val_loader: val_images, val_labels = ( val_data["image"].to(device), val_data["label"].to(device), ) val_outputs = model(val_images) value = torch.eq( val_outputs.argmax(dim=1), val_labels.argmax(dim=1) ) metric_count += len(value) num_correct += value.sum().item() metric = num_correct / metric_count metric_values.append(metric) if metric >= best_metric: best_metric = metric best_metric_epoch = epoch + 1 torch.save( model.state_dict(), "best_metric_model_classification3d_array.pth", ) print( f"current epoch: {epoch + 1} current accuracy: {metric:.4f}" f" best accuracy: {best_metric:.4f}" f" at epoch {best_metric_epoch}" ) print( f"train completed, best_metric: {best_metric:.4f} at" f" epoch: {best_metric_epoch}" ) # + colab={"base_uri": "https://localhost:8080/", "height": 279} id="6s4S1zNgc__g" outputId="2d4860d0-a50b-4f90-e95a-691df9e6e023" plt.plot(epoch_loss_values, label="training loss") val_epochs = np.linspace( 1, max_epochs, np.floor(max_epochs / val_interval).astype(np.int32) ) plt.plot(val_epochs, metric_values, label="validation acc") plt.legend() plt.xlabel("Epoch") plt.ylabel("Value") # + # Reload the best network and display info model_3d = monai.networks.nets.DenseNet121( spatial_dims=3, in_channels=1, out_channels=2 ).to(device) model_3d.load_state_dict( torch.load("best_metric_model_classification3d_array.pth") ) model_3d.eval() y_pred = torch.tensor([], dtype=torch.float32, device=device) y = torch.tensor([], dtype=torch.long, device=device) for val_data in val_loader: val_images = val_data["image"].to(device) val_labels = val_data["label"].to(device).argmax(dim=1) outputs = model_3d(val_images) y_pred = torch.cat([y_pred, outputs.argmax(dim=1)], dim=0) y = torch.cat([y, val_labels], dim=0) print( classification_report( y.cpu().numpy(), y_pred.cpu().numpy(), target_names=["non-lesion", "lesion"], ) ) cm = confusion_matrix( y.cpu().numpy(), y_pred.cpu().numpy(), normalize="true", ) disp = ConfusionMatrixDisplay( confusion_matrix=cm, display_labels=["non-lesion", "lesion"], ) disp.plot(ax=plt.subplots(1, 1, facecolor="white")[1]) # + [markdown] id="iHE0RMEFIera" # # Interpretability # # Use GradCAM and occlusion sensitivity for network interpretability. # # The occlusion sensitivity returns two images: the sensitivity image and the most probable class. # # * Sensitivity image -- how the probability of an inferred class changes as the corresponding part of the image is occluded. # * Big decreases in the probability imply that that region was important in inferring the given class # * The output is the same as the input, with an extra dimension of size N appended. Here, N is the number of inferred classes. To then see the sensitivity image of the class we're interested (maybe the true class, maybe the predcited class, maybe anything else), we simply do ``im[...,i]``. # * Most probable class -- if that part of the image is covered up, does the predicted class change, and if so, to what? This feature is not used in this notebook. # + colab={"base_uri": "https://localhost:8080/"} id="ZD5DvgwFIdwj" outputId="7ad3f98f-7c77-4f3e-f30c-c7936c7a1b81" # cam = monai.visualize.CAM(nn_module=model_3d, target_layers="class_layers.relu", fc_layers="class_layers.out") cam = monai.visualize.GradCAM( nn_module=model_3d, target_layers="class_layers.relu" ) # cam = monai.visualize.GradCAMpp(nn_module=model_3d, target_layers="class_layers.relu") print( "original feature shape", cam.feature_map_size([1, 1] + list(win_size), device), ) print("upsampled feature shape", [1, 1] + list(win_size)) occ_sens = monai.visualize.OcclusionSensitivity( nn_module=model_3d, mask_size=12, n_batch=1, stride=28 ) # For occlusion sensitivity, inference must be run many times. Hence, we can use a # bounding box to limit it to a 2D plane of interest (z=the_slice) where each of # the arguments are the min and max for each of the dimensions (in this case CHWD). the_slice = train_ds[0]["image"].shape[-1] // 2 occ_sens_b_box = [-1, -1, -1, -1, -1, -1, the_slice, the_slice] # + colab={"base_uri": "https://localhost:8080/", "height": 240} id="SI3hJJ2R-wjZ" outputId="61c7a100-0064-4e26-94ba-82956d00fd7c" train_transforms.set_random_state(42) n_examples = 5 subplot_shape = [3, n_examples] fig, axes = plt.subplots(*subplot_shape, figsize=(25, 15), facecolor="white") items = np.random.choice(len(train_ds), size=len(train_ds), replace=False) example = 0 for item in items: data = train_ds[ item ] # this fetches training data with random augmentations image, label = data["image"].to(device).unsqueeze(0), data["label"][1] y_pred = model_3d(image) pred_label = y_pred.argmax(1).item() # Only display tumours images if label != 1 or label != pred_label: continue img = image.detach().cpu().numpy()[..., the_slice] name = "actual: " name += "lesion" if label == 1 else "non-lesion" name += "\npred: " name += "lesion" if pred_label == 1 else "non-lesion" name += f"\nlesion: {y_pred[0,1]:.3}" name += f"\nnon-lesion: {y_pred[0,0]:.3}" # run CAM cam_result = cam(x=image, class_idx=None) cam_result = cam_result[..., the_slice] # run occlusion occ_result, _ = occ_sens(x=image, b_box=occ_sens_b_box) occ_result = occ_result[..., pred_label] for row, (im, title) in enumerate( zip( [img, cam_result, occ_result], [name, "CAM", "Occ. sens."], ) ): cmap = "gray" if row == 0 else "jet" ax = axes[row, example] if isinstance(im, torch.Tensor): im = im.cpu().detach() im_show = ax.imshow(im[0][0], cmap=cmap) ax.set_title(title, fontsize=25) ax.axis("off") fig.colorbar(im_show, ax=ax) example += 1 if example == n_examples: break # + with SummaryWriter(log_dir="logs") as writer: plot_2d_or_3d_image(img, step=0, writer=writer, tag="Input") plot_2d_or_3d_image(cam_result, step=0, writer=writer, tag="CAM") plot_2d_or_3d_image(occ_result, step=0, writer=writer, tag="OccSens") # - # %load_ext tensorboard # %tensorboard --logdir logs
modules/interpretability/class_lung_lesion.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/nathanfjohnson/External-Display-Manager/blob/master/nat_gan.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="8etcEx5to2Io" tags=[] # # Pre-work # + id="whX1VAArSsC2" #@title Mount Drive { form-width: "200px", display-mode: "form" } def mount_drive(): from IPython import display import os, sys from google.colab import drive drive.mount("/content/gdrive", force_remount=False) if os.path.isdir("/content/gdrive"): print("mounted") working_dir = "/content/gdrive/MyDrive/nat_gan" else: print("not mounted") working_dir = "content" return working_dir working_dir = mount_drive() # + id="C5UGZuxMljWU" #@title Common { form-width: "200px", display-mode: "form" } import torch from torch import nn def download_common_stuff(): if not file_exists("common_libraries_installed"): print_step("updating apt...") #make_system_command("sudo apt update") print_step("installing pip libraries...") make_system_command("sudo apt install imagemagick -y") make_system_command("sudo apt install exempi -y") make_system_command("sudo pip install wand imgtag") make_system_command("sudo touch common_libraries_installed") def print_step(step_text): from IPython.display import clear_output clear_output(wait=True) print(f"{step_text}") def make_system_command(command): import os debug = False # @param {type:"boolean"} if debug: # !{command} else: print(command) os.system(command) def file_exists(filename): from os.path import exists return exists(filename) def show_image(image, title="", scale=0.7, clear=True): from IPython.display import clear_output import matplotlib.pyplot as plt if clear: clear_output(wait=True) plt.style.use('dark_background') (fig, ax) = plt.subplots() m = ax.imshow(image) fig.set_dpi(272 * scale) ax.axis('off') #ax.set_title(title) plt.show() print(title) def add_xmp_data(i, filename, user_args, prompts): from imgtag import ImgTag import libxmp formatted_user_args = f"{user_args}".replace(",",",\n") data = { 'title': f"{(' | '.join(prompts))}", 'creator': f"Nat_A_Cyborg", "description":f"{formatted_user_args}", "rights":"Copyright <NAME>", 'i': f"{i+1}", "args": f"{user_args}", "software":"Nat-GAN", "camera":"camera", "source":"source", "CreateDate":"CreateDate", "contributor":"contributor", "coverage":"coverage", "date":"date", "format":"format", "identifier":"identifier", "language":"language", "publisher":"publisher", "relation":"relation", "type":"type" } # https://www.adobe.com/devnet/xmp.html # https://exiv2.org/tags-xmp-dc.html imagen = ImgTag(filename=filename) for key, value in data.items(): imagen.xmp.append_array_item(libxmp.consts.XMP_NS_DC, key, value, {'prop_array_is_ordered': False, 'prop_value_is_array': True}) imagen.close() def make_wand_image(img): from wand.image import Image as WandImage from PIL import Image import numpy if type(img) is WandImage: image = img elif type(img) is Image.Image: #PIL.Image.Image image = WandImage.from_array(numpy.array(img)) else: size = img.shape[0] reshaped = numpy.reshape(numpy.ravel(numpy.array(img), order='A'), (size, size, 3), order='F') image = WandImage.from_array(reshaped) return image def make_image_filename(i, working_dir, run_name, name_override = None , subfolder="", suffix=None, include_latest = False): import os directory = f"{working_dir}/output/{run_name}" if subfolder is not "": directory += f"/{subfolder}" if name_override is not None: filename = f"{directory}/{name_override}{'_' + suffix if suffix else ''}.png" else: filename = f"{directory}/{run_name}{'_' + suffix if suffix else ''}_{i:05}.png" return filename def save_image(i, working_dir, img, run_name, user_args, prompts, name_override = None , subfolder="", suffix=None, include_latest = False): filename = make_image_filename(i, working_dir, run_name, name_override, subfolder, suffix, include_latest) image = make_wand_image(img) # image = make_watermarked_image(image) image.save(filename=filename) add_xmp_data(i, filename, user_args, prompts) if include_latest: make_annotated_image(filename, user_args["latest_image_location"]) return filename def get_video_frame(in_filename, frame_num): out, err = ( ffmpeg .input(in_filename) .filter('select', 'gte(n,{})'.format(frame_num)) .output('pipe:', vframes=1, format='image2', vcodec='mjpeg') .run(capture_stdout=True) ) return WandImage(blob=out) # + id="P0VNk50nD1MG" # @title <h1>Run Parameters</h1> { display-mode: "form" } def build_run_args(): # @markdown Name of files and directory (no / or spaces) run_name = 'refactor' # @param {type:"string"} continuous_vqgan = False # @param {type:"boolean"} vqgan_1_runs = 0# @param {type:"integer"} diff_1_runs = 1# @param {type:"integer"} vqgan_2_runs = 0# @param {type:"integer"} diff_2_runs = 0# @param {type:"integer"} vqgan_3_runs = 0# @param {type:"integer"} end_frame = 1000# @param {type:"integer"} latest_image_location = "" # @param {type:"string"} save_mid_steps = False # @param {type:"boolean"} seed = 112291 # @param {type:"number"} ramdom_seed = True # @param {type:"boolean"} args = { "run_name" : run_name, "continuous_vqgan" : continuous_vqgan, "diff_1_runs" : diff_1_runs, "diff_2_runs" : diff_2_runs, "vqgan_1_runs" : vqgan_1_runs, "vqgan_2_runs" : vqgan_2_runs, "vqgan_3_runs" : vqgan_3_runs, "ramdom_seed" : ramdom_seed, "save_mid_steps" : save_mid_steps, "seed" : seed, "end_frame" : end_frame, "latest_image_location" : latest_image_location, } return args # + id="WoK1xgM5Eco2" # @title <h1>Prompting</h1> { display-mode: "form" } def build_prompt_args(): import json text_prompts = "[{\"frames\": [0,99999],\"prompt\": \"vibrant electric refactor digital painting\",\"values\": [1,1]}]" # @param {type:"string"} modifier_postpend = "" # @param {type:"string"} image_prompt = "" # @param {type:"string"} initial_image = '/content/gdrive/MyDrive/nat_gan/assets/Used/IMG_0412.png' # @param {type:"string"} add_random_adjectives = False # @param {type:"boolean"} add_random_noun = False # @param {type:"boolean"} add_random_styles = False # @param {type:"boolean"} random_image_directory = "" # @param {type:"string"} use_video_frames = "" # @param {type:"string"} prompt_args = { "initial_image" : initial_image, "text_prompts" : json.loads(text_prompts), "add_random_adjectives" : add_random_adjectives, "add_random_noun" : add_random_noun, "add_random_styles" : add_random_styles, "modifier_postpend" : modifier_postpend, "image_prompt" : image_prompt, "random_image_directory" : random_image_directory, "use_video_frames" : use_video_frames, } return prompt_args def get_prompts_for_i(i, args): prepend = None if args["add_random_adjectives"]: prepend = random_adjectives() postpend = args["modifier_postpend"] if args["add_random_styles"]: if postpend is not "": postpend = f"{postpend} {random_styles()}" else: postpend = random_styles() if args["add_random_noun"]: postpend = f"{random_noun()} {postpend}" text_prompts = get_prompts_and_values(args["text_prompts"], i, prepend = prepend, postpend=postpend) text_prompts = [phrase.strip() for phrase in text_prompts.split("|")] if text_prompts == [""]: text_prompts = [] return list(filter(filter_zero_prompts, text_prompts)) def random_adjectives(): adjective = random.choice(open("/content/gdrive/MyDrive/nat_gan/assets/prompts/adjectives.txt").read().splitlines()) while random.randint(0, 4) == 0: add_adjective = random.choice(open("/content/gdrive/MyDrive/nat_gan/assets/prompts/adjectives.txt").read().splitlines()) adjective = f"{adjective} {add_adjective}" return adjective def random_noun(): # also try https://pypi.org/project/essential-generators/ if random.randint(0, 1) > 0: noun = random.choice(open("/content/gdrive/MyDrive/nat_gan/assets/prompts/nouns.txt").read().splitlines()) else: # https://pypi.org/project/Random-Word/ # https://developer.wordnik.com/docs#!/words/getRandomWord noun = randomWords.get_random_word(hasDictionaryDef="true", includePartOfSpeech="noun", minCorpusCount=10000, minDictionaryCount=2, ) print(f"from service: {noun}") if noun == None: print(f"noun is None") noun = random.choice(open("/content/gdrive/MyDrive/nat_gan/assets/prompts/nouns.txt").read().splitlines()) return noun def random_styles(): style = random.choice(open("/content/gdrive/MyDrive/nat_gan/assets/prompts/styles.txt").read().splitlines()) while random.randint(0, 3) == 0: add_style = random.choice(open("/content/gdrive/MyDrive/nat_gan/assets/prompts/styles.txt").read().splitlines()) style = f"{style} {add_style}" return style def filter_zero_prompts(x): return '0.0' not in x def get_prompts_and_values(prompts, frame_i, prepend=None, postpend=None): full_prompts = "" for prompt in prompts: prompt_string = prompt["prompt"] if "frames" in prompt and "values" in prompt: prompt_frames = prompt["frames"] prompt_values = prompt["values"] for frames_i in range(len(prompt_frames)-1): first_frame = prompt_frames[frames_i] next_frame = prompt_frames[frames_i+1] if first_frame <= frame_i < next_frame: first_value = prompt_values[frames_i] next_value = prompt_values[frames_i+1] value_difference = next_value - first_value range_size = next_frame - first_frame step_size = value_difference/range_size frame_value = first_value + (step_size*(frame_i-first_frame)) elif frame_i <= prompt_frames[0]: frame_value = prompt_values[0] elif frame_i >= prompt_frames[-1]: frame_value = prompt_values[-1] else: frame_value = 0 if prepend is not None and prepend is not "": prompt_string = f"{prepend} {prompt_string}" if postpend is not None and postpend is not "": prompt_string = f"{prompt_string}{postpend}" if frame_value > 0.0: full_prompts += f"{prompt_string}:{frame_value}|" break elif frame_value < 0.0: full_prompts += f"{prompt_string}:{frame_value}|" break else: full_prompts += f"{prompt_string}|" full_prompts = full_prompts[:-1] return full_prompts def parse_number_value(string_def, frame_i, integer=False): import json try: parsed = json.loads(string_def) if "frames" in parsed and "values" in parsed: frames = parsed["frames"] values = parsed["values"] for frames_i in range(len(frames)-1): first_frame = frames[frames_i] next_frame = frames[frames_i+1] if first_frame <= frame_i < next_frame: first_value = values[frames_i] next_value = values[frames_i+1] value_difference = next_value - first_value range_size = next_frame - first_frame step_size = value_difference/range_size value = first_value + (step_size*(frame_i-first_frame)) elif frame_i <= frames[0]: value = values[0] elif frame_i >= frames[-1]: value = values[-1] if integer: return int(value) return float(value) except Exception as e: if integer: return int(string_def) return float(string_def) # + id="5VsylcN5Em8s" # @title <h1>Image Manipulation</h1> { display-mode: "form" } def build_manipulste_args(output_path): # @markdown <h2>Image Overlay</h2> copy_overlay_image = "" # @param {type:"string"} overlay_operator = "normal" #@param ["normal","bumpmap","color_burn","color_dodge","darken","darken_intensity","hard_light","lighten","lighten_intensity","linear_burn","linear_dodge","linear_light","modulus_subtract","multiply","overlay","pegtop_light","pin_light","screen","soft_light","vivid_light"] # @markdown <h2>Blur Mask</h2> # @markdown https://legacy.imagemagick.org/Usage/compose/#light blur_mask_filename = "" # @param {type:"string"} # @markdown <h2>Image Effects</h2> blur = "0" # @param {type:"string"} flip = False # @param {type:"boolean"} flop = False # @param {type:"boolean"} shake = False # @param {type:"boolean"} kaleidoscope = True # @param {type:"boolean"} scale_x = "1" # @param {type:"string"} scale_y = "1" # @param {type:"string"} angle = "72" # @param {type:"string"} origin_x = "0.5" # @param {type:"string"} origin_y = "0.5" # @param {type:"string"} translate_x = "0" # @param {type:"string"} # @markdown **positives moves it down a percentage of the height** translate_y = "0" # @param {type:"string"} swirl = "0" # @param {type:"string"} wobble_angle = "0" # @param {type:"string"} wobble_distance = "0" # @param {type:"string"} # @markdown <h2>Barrel Distort</h2> # @markdown <p>barrel zoom: 1 is nothing. 0.9 is zoom in, 1.1 is zoom out (very sensitive)</p> barrel_zoom = "1" # @param {type:"string"} # @markdown **barrel distort:** 0 is nothing. negative is edges out, positive edges in. barrel_distort = "0" # @param {type:"string"} barrel_origin_x = "0.5" # @param {type:"string"} barrel_origin_y = "0.5" # @param {type:"string"} # @markdown <h2>Fred Script</h2> fred_script = "" # @param {type:"string"} overlay_path = f"{output_path}/overlay.png" if copy_overlay_image is not "": try: shutil.copyfile(overlay_image_filename, overlay_path) except: pass elif not file_exists(overlay_path): from wand.image import Image as WandImage with WandImage(width=1000, height=1000) as img: img.save(filename=overlay_path) overlay_image_filename = overlay_path manipulste_args = { "scale_x" : scale_x, "scale_y" : scale_y, "shake" : shake, "wobble_angle" : wobble_angle, "wobble_distance" : wobble_distance, "translate_x" : translate_x, "translate_y" : translate_y, "angle" : angle, "barrel_distort" : barrel_distort, "barrel_origin_x" : barrel_origin_x, "barrel_origin_y" : barrel_origin_y, "barrel_zoom" : barrel_zoom, "flip" : flip, "flop" : flop, "fred_script" : fred_script, "swirl" : swirl, "kaleidoscope" : kaleidoscope, "blur" : blur, "blur_mask_filename" : blur_mask_filename, "origin_x" : origin_x, "origin_y" : origin_y, "overlay_image_filename" : overlay_image_filename, "overlay_operator" : overlay_operator, } return manipulste_args def manipulate_image(wandImage, args, i): from wand.image import Image as WandImage angle=parse_number_value(args["angle"], i) barrel_distort=parse_number_value(args["barrel_distort"], i) barrel_origin_x=parse_number_value(args["barrel_origin_x"], i) barrel_origin_y=parse_number_value(args["barrel_origin_y"], i) barrel_zoom=parse_number_value(args["barrel_zoom"], i) blur=parse_number_value(args["blur"], i) blur_mask_filename=args["blur_mask_filename"] flip=args["flip"] flop=args["flop"] fred_script=args["fred_script"] kaleidoscope=args["kaleidoscope"] origin_x=parse_number_value(args["origin_x"], i) origin_y=parse_number_value(args["origin_y"], i) overlay_operator=args["overlay_operator"] scale_x=parse_number_value(args["scale_x"], i) scale_y=parse_number_value(args["scale_y"], i) shake=args["shake"] translate_x=parse_number_value(args["translate_x"], i) translate_y=parse_number_value(args["translate_y"], i) overlay_image_filename=args["overlay_image_filename"] swirl=parse_number_value(args["swirl"], i) wobble_angle=parse_number_value(args["wobble_angle"], i) wobble_distance=parse_number_value(args["wobble_distance"], i) wandImage=wandImage something_changed = False changes = "" width = wandImage.width height = wandImage.height if not wobble_distance == 0 and not wobble_angle == 0: current_angle = (wobble_angle*i) % 360 current_angle_rad = math.radians(current_angle) changes += f"total angle {current_angle}\n" changes += f"total angle rad {current_angle_rad}\n" x_vector = wobble_distance*math.cos(current_angle_rad) y_vector = wobble_distance*math.sin(current_angle_rad) changes += f"x_vector {x_vector}\n" changes += f"y_vector {y_vector}\n" translate_x += x_vector translate_y += y_vector if shake: changes += f"SHAKE!" wandImage.virtual_pixel = 'dither' # https://legacy.imagemagick.org/Usage/misc/#virtual-pixel translate_x += float(random.randrange(0, 200)-100)/2000 translate_y += float(random.randrange(0, 200)-100)/2000 random_scale = float(random.randrange(0, 200)-100)/1000 scale_x += random_scale scale_y += random_scale angle += float(random.randrange(0, 200)-100)/10 # barrel if not barrel_distort == 0 or not barrel_zoom == 1: changes += f"barrel_distort {barrel_distort}\n" changes += f"barrel_zoom {barrel_zoom}\n" something_changed = True barrel_args = ( barrel_distort, 0.0, 0.0, barrel_zoom, # we do zoom with the scale too width * barrel_origin_x, #X height * barrel_origin_y, #Y ) wandImage.distort('barrel', barrel_args) # FLIP-FLOP if flip and flop: something_changed = True # alternate flip/flop if i % 2 == 0: changes += "flip\n" wandImage.flip() else: changes += "flop\n" wandImage.flop() elif flip: changes += "just flip\n" something_changed = True wandImage.flip() elif flop: changes += "just flop\n" something_changed = True wandImage.flop() if kaleidoscope: wandImage.virtual_pixel = 'mirror' # https://legacy.imagemagick.org/Usage/misc/#virtual-pixel quadrant = i % 4 if quadrant == 1: changes += "kaleidoscope - flip\n" wandImage.flip() elif quadrant == 2: changes += "kaleidoscope - flop\n" wandImage.flop() elif quadrant == 3: changes += "kaleidoscope - flip flop\n" wandImage.flip() wandImage.flop() else: changes += "kaleidoscope\n" something_changed = True scale_rotate_args = ( 0, 0, 1, 1, 0, width/2, height/2, ) wandImage.distort('scale_rotate_translate', scale_rotate_args) scale_rotate_args = ( 0, 0, 1, 1, 0, -width/2, -height/2, ) wandImage.distort('scale_rotate_translate', scale_rotate_args) # scale rotate if not scale_x == 1 or not scale_y == 1 or not angle == 0 or not translate_x == 0 or not translate_y == 0: changes += f"srt: scale_x {scale_x*100}% ({(width*scale_x)-width}px)\n" changes += f"srt: scale_y {scale_y*100}% ({(height*scale_y)-height}px)\n" changes += f"srt: angle {angle}\n" changes += f"srt: translate_x {translate_x*100}% ({(translate_x*width)}px)\n" changes += f"srt: translate_y {translate_y*100}% ({(translate_y*height)}px)\n" changes += f"srt: origin_x {origin_x*100}%\n" changes += f"srt: origin_y {origin_y*100}%\n" something_changed = True scale_rotate_args = ( width*origin_x, height*origin_y, scale_x, #ScaleX scale_y, #ScaleY angle, #Angle (width*origin_x)+(translate_x*-width), (height*origin_y)+(translate_y*height), ) wandImage.virtual_pixel = 'black' # https://legacy.imagemagick.org/Usage/misc/#virtual-pixel wandImage.distort('scale_rotate_translate', scale_rotate_args) # Text #draw = Drawing() #draw.font_size = 50 #draw.text_under_color = "#ffffff" #draw.text(10, 10, "A") #draw(wandImage) #TODO: https://legacy.imagemagick.org/Usage/mapping/#distort #TODO: http://www.fmwconcepts.com/imagemagick/index.php if swirl != 0: changes += f"swirl {swirl}\n" something_changed = True wandImage.swirl(swirl) if fred_script != "": something_changed = True wandImage = run_script_on_image(i, wandImage, fred_script) # Blur if blur > 0: changes += f"blur {blur}\n" something_changed = True wandImage.blur(radius=blur, sigma=blur) # Overlay Image if overlay_image_filename != "": changes += f"overlay_image_filename {overlay_image_filename}\n" something_changed = True overlay = WandImage(filename = overlay_image_filename) overay_angle = (i*0.25)*-1 scale_rotate_args = ( overlay.width*0.5, overlay.height*0.5, 1, #ScaleX 1, #ScaleY overay_angle, #Angle ) overlay.virtual_pixel = 'mirror' # overlay.distort('scale_rotate_translate', scale_rotate_args) overlay.resize(width=int(wandImage.width*1),height=int(wandImage.height*1)) if overlay_operator == "normal": changes += f"normal\n" wandImage.composite(overlay, left=int((wandImage.width-overlay.width)/2), top=int((wandImage.height-overlay.height)/2)) else: changes += f"overlay_operator: {overlay_operator}\n" wandImage.composite(operator = overlay_operator, left = 0, top = 0, image = overlay) # https://docs.wand-py.org/en/0.6.7/guide/draw.html#composite # https://legacy.imagemagick.org/Usage/compose # Blur Mask if blur_mask_filename != "": changes += f"blur_mask_filename {blur_mask_filename}\n" something_changed = True overlay = WandImage(filename = blur_mask_filename) wandImage.composite_channel('default_channels', overlay, 'blur', left = 0, top = 0, arguments = "10" ) if not something_changed: return None show_image(wandImage,changes) return wandImage def run_script_on_image(i, wand_image, script): scratch_in = "/content/gdrive/MyDrive/nat_gan/fred/scratch_in.png" scratch_out = "/content/gdrive/MyDrive/nat_gan/fred/scratch_out.png" wand_image.save(filename=scratch_in) make_system_command(f"bash {script} {scratch_in} {scratch_out}") return WandImage(filename = scratch_out) # + id="UiCFCEgFCwjS" # @title <h1>CLIP</h1> { display-mode: "form" } def build_clip_args(): # @markdown <p>VQGAN and Diffusion methods use this</p> clip_model= "ViT-B/32" # @param ["ViT-B/16","ViT-B/32"] cut_pow=0.5 # @param {type:"number"} # @markdown <br/><h4>Controls how many crops to take from the image. Increase for higher quality.</h4> cutn= 64 # @param {type:"number"} clip_args = { "cutn" : cutn, "cut_pow" : cut_pow, "clip_model" : clip_model, } return clip_args def download_CLIP(device, working_dir, clip_model): import sys if not file_exists("CLIP_libraries_installed"): print_step("Cloning CLIP...") make_system_command(f"git clone https://github.com/openai/CLIP {working_dir}/downloads/CLIP") make_system_command("sudo pip install ftfy") make_system_command("sudo touch CLIP_libraries_installed") sys.path.append(f"{working_dir}/downloads/CLIP") import clip return clip.load(clip_model, jit=False)[0].eval().requires_grad_(False).to(device) class MakeCutouts(nn.Module): def __init__( self, cut_size, cutn, cut_pow ): super().__init__() self.cut_size = cut_size self.cutn = cutn self.cut_pow = cut_pow self.augs = nn.Sequential() #not in diffusion code self.noise_fac = 0.1 #not in diffusion code def forward(self, input): sideY, sideX = input.shape[2:4] max_size = min(sideX, sideY) min_size = min(sideX, sideY, self.cut_size) cutouts = [] def forward(self, input): from torch.nn import functional as F (sideY, sideX) = input.shape[2:4] max_size = min(sideX, sideY) min_size = min(sideX, sideY, self.cut_size) cutouts = [] if True: #diffuse stuff for _ in range(self.cutn): size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size) offsetx = torch.randint(0, sideX - size + 1, ()) offsety = torch.randint(0, sideY - size + 1, ()) cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size] cutouts.append(F.adaptive_avg_pool2d(cutout, self.cut_size)) return torch.cat(cutouts) else: #old stuff for _ in range(self.cutn): size = int(torch.rand([]) ** self.cut_pow * (max_size - min_size) + min_size) offsetx = torch.randint(0, sideX - size + 1, ()) offsety = torch.randint(0, sideY - size + 1, ()) cutout = input[:, :, offsety:offsety + size, offsetx: offsetx + size] cutouts.append(resample(cutout, (self.cut_size, self.cut_size))) batch = self.augs(torch.cat(cutouts, dim=0)) if self.noise_fac: facs = batch.new_empty([self.cutn, 1, 1, 1]).uniform_(0, self.noise_fac) batch = batch + facs * torch.randn_like(batch) return batch # + id="dfMrFSp__KZb" # @title <h1>VQGAN+CLIP</h1> { display-mode: "form" } def build_vqgan_args(model_dir): yaml_path, ckpt_path, model_name = get_model(model_dir) iterations_per_frame = "15" # @param {type:"string"} step_size = "0.1" # @param {type:"string"} init_weight = 0. # @param {type:"number"} look_back = False # @param {type:"boolean"} stop_early = False # @param {type:"boolean"} vqgan_args = { "look_back" : look_back, "step_size" : step_size, "init_weight" : init_weight, "stop_early" : stop_early, "iterations_per_frame" : iterations_per_frame, "vqgan_checkpoint" : ckpt_path, "vqgan_config" : yaml_path, "model_name": model_name, } return vqgan_args def load_vqgan_model(config_path, checkpoint_path, working_dir): import sys download_VQGAN(working_dir) sys.path.append(f"{working_dir}/downloads/taming-transformers") from omegaconf import OmegaConf from taming.models import cond_transformer, vqgan config = OmegaConf.load(config_path) if config.model.target == "taming.models.vqgan.VQModel": model = vqgan.VQModel(**config.model.params) model.eval().requires_grad_(False) model.init_from_ckpt(checkpoint_path) elif config.model.target == "taming.models.cond_transformer.Net2NetTransformer": parent_model = cond_transformer.Net2NetTransformer(**config.model.params) parent_model.eval().requires_grad_(False) parent_model.init_from_ckpt(checkpoint_path) model = parent_model.first_stage_model elif config.model.target == 'taming.models.vqgan.GumbelVQ': model = vqgan.GumbelVQ(**config.model.params) model.eval().requires_grad_(False) model.init_from_ckpt(checkpoint_path) else: raise ValueError(f"unknown model type: {config.model.target}") del model.loss return model def download_VQGAN(working_dir): import sys if not file_exists("VQGAN_libraries_installed"): print_step("Cloning taming-transformers...") make_system_command(f"git clone https://github.com/CompVis/taming-transformers {working_dir}/downloads/taming-transformers") sys.path.append(f"{working_dir}/downloads/taming-transformers") make_system_command("sudo pip install omegaconf pytorch-lightning einops") make_system_command("sudo touch VQGAN_libraries_installed") def get_model(model_dir): import os model = "ImageNet 16384" #@param ["ImageNet 16384", "ImageNet 1024", "WikiArt 1024", "WikiArt 16384", "COCO-Stuff", "FacesHQ", "S-FLCKR", "Gumbel 8192", "Ade20k", "FFHQ", "CelebA-HQ"] model_names={ "ImageNet 16384":{ "ymal_url":"https://heibox.uni-heidelberg.de/d/a7530b09fed84f80a887/files/?p=%2Fconfigs%2Fmodel.yaml&dl=1", "ckpt_url":"https://heibox.uni-heidelberg.de/d/a7530b09fed84f80a887/files/?p=%2Fckpts%2Flast.ckpt&dl=1", "name":"vqgan_imagenet_f16_16384"}, "ImageNet 1024":{ "ymal_url":"https://heibox.uni-heidelberg.de/d/8088892a516d4e3baf92/files/?p=%2Fconfigs%2Fmodel.yaml&dl=1", "ckpt_url":"https://heibox.uni-heidelberg.de/d/8088892a516d4e3baf92/files/?p=%2Fckpts%2Flast.ckpt&dl=1", "name":"vqgan_imagenet_f16_1024"}, "WikiArt 1024":{ "ymal_url":"http://mirror.io.community/blob/vqgan/wikiart.yaml", #???? "ckpt_url":"http://mirror.io.community/blob/vqgan/wikiart.ckpt", #???? "name":"wikiart_1024"}, "WikiArt 16384":{ "ymal_url":"http://eaidata.bmk.sh/data/Wikiart_16384/wikiart_f16_16384_8145600.yaml", "ckpt_url":"http://eaidata.bmk.sh/data/Wikiart_16384/wikiart_f16_16384_8145600.ckpt", "name":"wikiart_16384"}, "COCO-Stuff":{ "ymal_url":"https://dl.nmkd.de/ai/clip/coco/coco.yaml", "ckpt_url":"https://dl.nmkd.de/ai/clip/coco/coco.ckpt", "name":"coco"}, "FacesHQ":{ "ymal_url":"https://drive.google.com/uc?export=download&id=1fHwGx_hnBtC8nsq7hesJvs-Klv-P0gzT", "ckpt_url":"https://app.koofr.net/content/links/a04deec9-0c59-4673-8b37-3d696fe63a5d/files/get/last.ckpt?path=%2F2020-11-13T21-41-45_faceshq_transformer%2Fcheckpoints%2Flast.ckpt", "name":"faceshq"}, "S-FLCKR":{ "ymal_url":"https://heibox.uni-heidelberg.de/d/73487ab6e5314cb5adba/files/?p=%2Fconfigs%2F2020-11-09T13-31-51-project.yaml&dl=1", "ckpt_url":"https://heibox.uni-heidelberg.de/d/73487ab6e5314cb5adba/files/?p=%2Fcheckpoints%2Flast.ckpt&dl=1", "name":"sflckr"}, "Gumbel 8192":{ # OpenImages 8912 ???? "ymal_url":"https://heibox.uni-heidelberg.de/d/2e5662443a6b4307b470/files/?p=%2Fconfigs%2Fmodel.yaml&dl=1", "ckpt_url":"https://heibox.uni-heidelberg.de/d/2e5662443a6b4307b470/files/?p=%2Fckpts%2Flast.ckpt&dl=1", "name":"Gumbel_8192"}, "Ade20k":{ "ymal_url":"https://static.miraheze.org/intercriaturaswiki/b/bf/Ade20k.txt", "ckpt_url":"https://app.koofr.net/content/links/0f65c2cd-7102-4550-a2bd-07fd383aac9e/files/get/last.ckpt?path=%2F2020-11-20T21-45-44_ade20k_transformer%2Fcheckpoints%2Flast.ckpt", "name":"ADE20K"}, "FFHQ":{ "ymal_url":"https://app.koofr.net/content/links/0fc005bf-3dca-4079-9d40-cdf38d42cd7a/files/get/2021-04-23T18-19-01-project.yaml?path=%2F2021-04-23T18-19-01_ffhq_transformer%2Fconfigs%2F2021-04-23T18-19-01-project.yaml&force", "ckpt_url":"https://app.koofr.net/content/links/0fc005bf-3dca-4079-9d40-cdf38d42cd7a/files/get/last.ckpt?path=%2F2021-04-23T18-19-01_ffhq_transformer%2Fcheckpoints%2Flast.ckpt&force", "name":"FFHQ"}, "CelebA-HQ":{ "ymal_url":"https://app.koofr.net/content/links/6dddf083-40c8-470a-9360-a9dab2a94e96/files/get/2021-04-23T18-11-19-project.yaml?path=%2F2021-04-23T18-11-19_celebahq_transformer%2Fconfigs%2F2021-04-23T18-11-19-project.yaml&force", "ckpt_url":"https://app.koofr.net/content/links/6dddf083-40c8-470a-9360-a9dab2a94e96/files/get/last.ckpt?path=%2F2021-04-23T18-11-19_celebahq_transformer%2Fcheckpoints%2Flast.ckpt&force", "name":"CelebA-HQ"} } if not os.path.isdir(f"{model_dir}"): make_system_command(f"sudo mkdir -p {model_dir}") print("model directory created") model_dict = model_names.get(model) model_name = model_dict.get("name") model_ymal_url = model_dict.get("ymal_url") model_ckpt_url = model_dict.get("ckpt_url") print(f"*** {model} ***") ckpt_path = f"{model_dir}/{model_name}.ckpt" if not file_exists(ckpt_path): print(f"downloading {model} checkpoint from {model_ckpt_url}") # TODO: use urllib2 instead of curl make_system_command(f"sudo curl -L -o {ckpt_path} -C - '{model_ckpt_url}'") else: print(f"{model} checkpoint exists, skipping download") yaml_path = f"{model_dir}/{model_name}.yaml" if not file_exists(yaml_path): print(f"downloading {model} model from {model_ymal_url}") # TODO: use urllib2 instead of wget make_system_command(f"sudo curl -L -o {yaml_path} -C - '{model_ymal_url}'") else: print(f"{model} model exists, skipping download") return yaml_path, ckpt_path, model_name def run_vq_step(i, prompts, run, args, clip_model, cutouts, normalize, start_image, iterations, working_dir, device): import queue, numpy, clip from torch import optim from tqdm.notebook import tqdm vqgan_model = load_vqgan_model(args["vqgan_config"], args["vqgan_checkpoint"],working_dir).to(device) start_image = make_wand_image(start_image) #start_image.resize(720, 720) start_image.resize(736, 736) title = f"\n\nVQGAN start {i}\n" comp_distance = 25 recents = queue.Queue() recents.maxsize = 10 last_i_count = 0 # look_back = args['look_back'] and iterations_per_frame > recents.maxsize/2 look_back = args["look_back"] and iterations >= 5 z = z_from_img(start_image, vqgan_model, device) if look_back: title += f"smooth count: {smooth_count}\n" seed_image = wand_image_from_z(z, vqgan_model) z.requires_grad_(True) step_size = parse_number_value(args["step_size"], i) opt = optim.Adam([z], lr=step_size) title += f"step size: {step_size}\n" pMs = [] for prompt in prompts: txt, weight, stop = parse_prompt(prompt) embed = clip_model.encode_text(clip.tokenize(txt).to(device)).float() pMs.append(Prompt(embed, weight, stop).to(device)) title += f"prompt: {txt}\nweight: {weight}\n" print(title) max_comp = 0 last_max = 0 prev_i = numpy.array(wand_image_from_z(z, vqgan_model)) if look_back: iterations += recents.maxsize for j in tqdm(range(iterations)): last_i_count = j #torch.cuda.empty_cache() title = f"\ {' | '.join(prompts)}\n\ {run['run_name']} ({i}) ipf {iterations}\n\ last_i_count: {last_i_count}" train(i, opt, z, normalize, pMs, args['init_weight'], title, cutouts, vqgan_model, clip_model) if look_back: if recents.full(): recents.get() recents.put(wand_image_from_z(z)) if not args['stop_early']: continue if j == 0: prev_comp_image = numpy.array(wand_image_from_z(z)) if j % comp_distance == 0 and j >= comp_distance: comp_image = numpy.array(wand_image_from_z(z)) comp = comp_images(prev_comp_image, comp_image) prev_comp_image = comp_image new_max = max(max_comp, comp) if new_max is not max_comp: last_max = j print(f"max*({j}): {round(comp.real, 5)}") max_comp = new_max else: print(f"nope({j}): {round(comp.real, 5)}") if (j - last_max) >= (comp_distance * 2): break if look_back: out = synth(z) img = img_from_z(out) best_image = recents.get() seed_image_array = numpy.array(seed_image) comp = comp_images(seed_image_array, numpy.array(best_image)) max_comp = comp print("start") no_count = 0 for prev_image in recents.queue: comp = comp_images(seed_image_array, numpy.array(prev_image)) if comp > max_comp: max_comp = comp best_image = prev_image print("yes") smooth_count += 1 no_count = 0 else: no_count += 1 print("no") # if no_count > 3: # break out = synth(z, vqgan_model) img = img_from_z(out) show_image(img, "finished vqgan", scale=0.7) return img def comp_images(a, b): # https://github.com/andrewekhalel/sewar comp = msssim(a, b) return comp def img_from_z(synthed): import numpy z_array = ( synthed .mul(255) .clamp(0, 255) [0] .cpu() .detach() .numpy() .astype(numpy.uint8) ) one = numpy.array(z_array)[:, :, :] img = numpy.transpose(z_array, (1, 2, 0)) return img def z_from_img(img, vqgan_model, device): from torchvision.transforms import functional as TF import numpy four = numpy.array(img) three = TF.to_tensor(four) two = three.to(device) one = two.unsqueeze(0) * 2 - 1 z, *_ = vqgan_model.encode(one) return z def wand_image_from_z(z, vqgan_model): import numpy from wand.image import Image as WandImage z_array = ( synth(z, vqgan_model).movedim(3, 2) .mul(255) .clamp(0, 255) [0] .cpu() .detach() .numpy() .astype(numpy.uint8) ) numpy_array = numpy.asarray(z_array) width = numpy_array.shape[1] height = numpy_array.shape[2] reshaped = numpy.reshape(numpy_array,(width, height, 3), order='F') return WandImage.from_array(reshaped) def synth(z, vqgan_model): movedim = z.movedim(1, 3) weight = vqgan_model.quantize.embedding.weight z_q = vector_quantize(movedim, weight).movedim(3, 1) grad = vqgan_model.decode(z_q).add(1).div(2) clamp_with_grad = ClampWithGrad.apply clamp = clamp_with_grad(grad, 0, 1) return clamp def vector_quantize(x, codebook): from torch.nn import functional as F d = x.pow(2).sum(dim=-1, keepdim=True) + codebook.pow(2).sum(dim=1) \ - 2 * x @codebook.T indices = d.argmin(-1) x_q = F.one_hot(indices, codebook.shape[0]).to(d.dtype) @codebook replace_grad = ReplaceGrad.apply return replace_grad(x_q, x) class ReplaceGrad(torch.autograd.Function): @staticmethod def forward(ctx, x_forward, x_backward): ctx.shape = x_backward.shape return x_forward @staticmethod def backward(ctx, grad_in): return (None, grad_in.sum_to_size(ctx.shape)) class ClampWithGrad(torch.autograd.Function): @staticmethod def forward( ctx, input, min, max, ): ctx.min = min ctx.max = max ctx.save_for_backward(input) return input.clamp(min, max) @staticmethod def backward(ctx, grad_in): (input, ) = ctx.saved_tensors return (grad_in * (grad_in * (input - input.clamp(ctx.min, ctx.max)) >= 0), None, None) class Prompt(nn.Module): def __init__( self, embed, weight=1., stop=float('-inf'), ): super().__init__() self.register_buffer('embed', embed) self.register_buffer('weight', torch.as_tensor(weight)) self.register_buffer('stop', torch.as_tensor(stop)) def forward(self, input): from torch.nn import functional as F input_normed = F.normalize(input.unsqueeze(1), dim=2) embed_normed = F.normalize(self.embed.unsqueeze(0), dim=2) dists = \ input_normed.sub(embed_normed).norm(dim=2).div(2).arcsin().pow(2).mul(2) dists = dists * self.weight.sign() replace_grad = ReplaceGrad.apply return self.weight.abs() * replace_grad(dists, torch.maximum(dists, self.stop)).mean() def train(i, opt, z, normalize, pMs, init_weight, title, cutouts, vqgan_model, clip_model): opt.zero_grad() losses = ascend_txt(i, z, normalize, pMs, init_weight, cutouts, vqgan_model, clip_model) loss = sum(losses) loss.backward() opt.step() z_min = vqgan_model.quantize.embedding.weight.min(dim=0).values[None, :, None, None] z_max = vqgan_model.quantize.embedding.weight.max(dim=0).values[None, :, None, None] with torch.no_grad(): z.copy_(z.maximum(z_min).minimum(z_max)) def ascend_txt(i, z, normalize, pMs, init_weight, cutouts, vqgan_model, clip_model): out = synth(z, vqgan_model) iii = clip_model.encode_image(normalize(cutouts(out))).float() result = [] if init_weight: result.append(F.mse_loss(z, z_orig) * init_weight / 2) for prompt in pMs: result.append(prompt(iii)) return result # + id="zvftTgM0_Xd8" #@title <h1>CLIP Guided Diffusion</h1> { display-mode: "form" } exec(open(f'{working_dir}/downloads/modules/clip-diffusion.py').read()) def build_diffusion_args(model_dir): d_checkpoint = "512x512_diffusion_uncond_finetune_008100" #@param ["512x512_diffusion", "512x512_diffusion_uncond_finetune_008100"] # https://github.com/afiaka87/clip-guided-diffusion # https://github.com/openai/guided-diffusion # https://github.com/crowsonkb/v-diffusion-pytorch # https://thisnameismine.com/programming/360diffusion-real-esrgan-integrated-clip-guided-diffusion/ # https://github.com/crowsonkb/guided-diffusion diff_use_init = False # @param {type:"boolean"} # @markdown <br/><h4>Controls the starting point along the diffusion timesteps. # @markdown Higher values make the output look more like the init.</h4> skip_timesteps_1 = "400" # @param {type:"string"} skip_timesteps_2 = "0" # @param {type:"string"} mid_run_save = 0# @param {type:"number"} mid_run_show = 10 # @param {type:"number"} # @markdown <br/><h4>the batch size (default: 1)</h4> batch_size = 1 # @param {type:"number"} # @markdown <br/><h4>Diffusion steps (default: 1000)</h4> diffusion_steps = 1000 # @param {type:"number"} # @markdown <br/><h4>Timestep respacing (default: 1000)</h4> timestep_respacing = "1000" # @param {type:"string"} # @markdown <br/><h4>Scale for CLIP spherical distance loss. Values will need tinkering for different settings. (default: 1000)</h4> clip_guidance_scale = 1000 # @param {type:"number"} # @markdown <br/><h4>(optional) Perceptual loss scale for init image. Good at 1000?(default: 0)</h4> init_scale = 0# @param {type:"number"} # @markdown <br/><h4>Controls the smoothness of the final output. (default:150.0)</h4> tv_scale = 150 # @param {type:"number"} # @markdown <br/><h4>range_scaleControls how far out of RGB range values may get.(default: 50.0)</h4> range_scale = 50# @param {type:"number"} # @markdown <br/><h4>Specify noise schedule. Either 'linear' or 'cosine'.(default: linear)</h4> noise_schedule = "linear" #@param ["linear","cosine"] # @markdown <br/><h4>Accumulate CLIP gradient from multiple batches of cuts. Can help with OOM errors / Low VRAM. (default: 2)</h4> cutn_batches = 1 # @param {type:"number"} # @markdown <br/><h4>n_batches ?? </h4> n_batches = 1 # @param {type:"number"} diffusion_args = { "d_checkpoint_url_path" : get_checkpoints(model_dir, d_checkpoint), "diff_use_init" : diff_use_init, "n_batches" : n_batches, "batch_size" : batch_size, "cutn_batches" : cutn_batches, "clip_guidance_scale" : clip_guidance_scale, "tv_scale" : tv_scale, "range_scale" : range_scale, "init_scale" : init_scale, "mid_run_save" : mid_run_save, "mid_run_show" : mid_run_show, "diffusion_steps" : diffusion_steps, "timestep_respacing" : timestep_respacing, "noise_schedule" : noise_schedule, "skip_timesteps_1" : skip_timesteps_1, "skip_timesteps_2" : skip_timesteps_2, } return diffusion_args # + [markdown] id="wFUjjTFDX4aD" # # Begin # + id="GqvIPS0R0gWr" #@title <h1>Begin Sequence</h1> { form-width: "200px", display-mode: "form" } def prepare_run(working_dir): import json download_common_stuff() replace_yaml = True # @param {type:"boolean"} model_dir = f"{working_dir}/downloads/models" prompt_args = build_prompt_args() run_args = build_run_args() vqgan_args = build_vqgan_args(model_dir) output_path = f'{working_dir}/output/{run_args["run_name"]}' make_system_command(f"sudo mkdir --parents {output_path}") json_path = f'{output_path}/params.json' manipulste_args = build_manipulste_args(output_path) clip_args = build_clip_args() diffusion_args = build_diffusion_args(model_dir) user_args = { "prompt" : prompt_args, "run" : run_args, "CLIP" : clip_args, "VQGAN" : vqgan_args, "diffusion" : diffusion_args, "manipulate" : manipulste_args, } if replace_yaml or not file_exists(json_path): with open(json_path, 'w') as fp: json.dump(user_args, fp, sort_keys=True, indent=4) else: with open(json_path) as json_file: user_args = json.load(json_file) return output_path, user_args def next_i(i, end_frame, path, run_name): return i + 1 def extract_int(image_filename): frame_i = None try: frame_i = int(image_filename[-9:-4]) except: frame_i = int(image_filename[-13:-8]) pass return frame_i list_of_images = glob.glob(f"{path}/*{run_name}*.png") arr = list(map(extract_int, list_of_images)) if end_frame-1 not in arr: return end_frame-1 arr.sort() n = len(arr) max1 = -sys.maxsize - 1 max_value = 0 for i in range(1, n): if (abs(arr[i] - arr[i-1]) > max1): max1 = abs(arr[i] - arr[i-1]) half = max1/2 next_int = int(arr[i-1]+half) max_value = arr[i] if half == 0.5: next_int = max_value + 1 #_resume_from_latest = False # @param {type:"boolean"} #if _resume_from_latest: # list_of_files = glob.glob(f"{output_path}/*.png") # if len(list_of_files) > 0: # latest_file = max(list_of_files, key=os.path.getctime) # _initial_image = latest_file # substring = latest_file[-9:-4] # if substring.isdigit(): # _start_frame = int(substring)+1 # print(f"resuming from latest! file: {latest_file} frame: {_start_frame}") # else: # print(f"no files in {output_path} ?: {list_of_files}") print(f"next i: {next_int}") return next_int def next_start_image(i, end_frame, run_name, working_dir, prompt_args): import random import os from wand.image import Image as WandImage if prompt_args["use_video_frames"] is not "": next_start_image = get_video_frame(prompt_args["use_video_frames"],i) elif prompt_args["random_image_directory"] == "": if i == 0: next_start_image = WandImage(filename = prompt_args["initial_image"]) else: previous_file = make_image_filename(i-1, working_dir, run_name) next_start_image = WandImage(filename = previous_file) elif prompt_args["random_image_directory"] != "": relevant_path = prompt_args["random_image_directory"] included_extensions = ["jpg", "jpeg", "bmp", "png", "gif"] file_names = [ fn for fn in os.listdir(relevant_path) if any(fn.endswith(ext) for ext in included_extensions) ] seed_image_filename = random.choice(file_names) seed_image_path = ( f"{prompt_args['random_image_directory']}/{seed_image_filename}" ) prompt_args["initial_image"] = seed_image_filename print(f"random image: {seed_image_path}") next_start_image = (WandImage(filename=seed_image_path)) return next_start_image def begin_art(working_dir): from IPython.display import clear_output import random, gc, json, os # Delete memory from previous runs make_system_command(f"nvidia-smi -caa") gc.collect() torch.cuda.empty_cache() device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('Using device:', device) # !nvidia-smi output_path, user_args = prepare_run(working_dir) last_i_count = 0 itteration_count = 0 frame_count = 0 smooth_count = 0 make_system_command(f"nvidia-smi -caa") gc.collect() torch.cuda.empty_cache() i = 0 stop_on_next_loop = False while i <= user_args["run"]["end_frame"]: if stop_on_next_loop: break try: with open(f'{output_path}/params.json') as json_file: user_args = json.load(json_file) run_name = user_args["run"]["run_name"] while file_exists(make_image_filename(i, working_dir, run_name)): i = next_i(i, user_args["run"]["end_frame"],f'{output_path}/',run_name) if user_args["run"]["ramdom_seed"]: import random random.seed(None) user_args["run"]["seed"] = random.randint(1, 99999999) seed = user_args["run"]['seed'] random.seed(seed) import numpy numpy.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True os.environ['PYTHONHASHSEED'] = str(seed) print(f"seed: {seed}") clip_model = download_CLIP(device, working_dir, user_args["CLIP"]["clip_model"]) if "cutouts" not in locals(): cutouts = MakeCutouts(clip_model.visual.input_resolution, user_args["CLIP"]["cutn"], user_args["CLIP"]["cut_pow"]) from torchvision import transforms normalize = transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]) prompts = get_prompts_for_i(i, user_args["prompt"]) name_override = None if user_args["prompt"]["add_random_adjectives"] or user_args["prompt"]["add_random_noun"] or user_args["prompt"]["add_random_styles"]: name_override = "" for prompt in prompts: txt, _, _ = parse_prompt(prompt) name_override += f"[{txt}]" name_override = None latest_image = next_start_image(i, user_args["run"]["end_frame"],run_name,working_dir, user_args["prompt"]) iterations = parse_number_value(user_args["VQGAN"]["iterations_per_frame"], i, integer=True) show_image(latest_image, f"start step {i}") if iterations > 4: wandImage = make_wand_image(latest_image) wandImage.alpha_channel = False manipulated = manipulate_image(wandImage, user_args['manipulate'],i) if manipulated is not None: latest_image = manipulated try: save_image(i,latest_image,run_name,name_override=name_override,include_latest=False) except: pass steps_taken = "" if user_args["run"]["continuous_vqgan"]: print("continuous_vqgan") overlay_path = user_args['manipulate']["overlay_image_filename"] latest_edit_time = os.path.getmtime(overlay_path) + os.path.getmtime(f'{output_path}/params.json') while(os.path.getmtime(overlay_path) + os.path.getmtime(f'{output_path}/params.json') == latest_edit_time): latest_edit_time = os.path.getmtime(overlay_path) + os.path.getmtime(f'{output_path}/params.json') latest_image = run_vq_step(i, prompts, user_args["run"], user_args["VQGAN"], cutouts, latest_image, iterations) save_image(i,latest_image,run_name,name_override=name_override,include_latest=False) for _ in range(user_args["run"]["vqgan_1_runs"]): steps_taken += "[vqgan]" latest_image = run_vq_step(i, prompts, user_args["run"], user_args["VQGAN"], clip_model, cutouts, normalize, latest_image, iterations, working_dir, device) if user_args["run"]["save_mid_steps"]: save_image(i,latest_image,run_name,subfolder=steps_taken,name_override=name_override,include_latest=False,suffix=steps_taken) for _ in range(user_args["run"]["diff_1_runs"]): steps_taken += "[diff]" skip_timesteps = parse_number_value(user_args["diffusion"]["skip_timesteps_1"], i, integer=True) latest_image = run_d_step(i, device, prompts, user_args["diffusion"], user_args["prompt"], user_args["CLIP"], user_args["run"], clip_model, cutouts, normalize, skip_timesteps, latest_image, steps_taken) if user_args["run"]["save_mid_steps"]: save_image(i,latest_image,run_name,subfolder=steps_taken,name_override=name_override,include_latest=False,suffix=steps_taken) for _ in range(user_args["run"]["vqgan_2_runs"]): steps_taken += "[vqgan]" latest_image = run_vq_step(i, prompts, user_args["run"], user_args["VQGAN"], clip_model, cutouts, normalize, latest_image, iterations, working_dir, device) if user_args["run"]["save_mid_steps"]: save_image(i,latest_image,run_name,subfolder=steps_taken,name_override=name_override,include_latest=False,suffix=steps_taken) for _ in range(user_args["run"]["diff_2_runs"]): steps_taken += "[diff]" skip_timesteps = parse_number_value(user_args["diffusion"]["skip_timesteps_2"], i, integer=True) latest_image = run_d_step(i, device, prompts, user_args["diffusion"], user_args["prompt"], user_args["CLIP"], user_args["run"], clip_model, cutouts, normalize, skip_timesteps, latest_image, steps_taken) if user_args["run"]["save_mid_steps"]: save_image(i,latest_image,run_name,subfolder=steps_taken,name_override=name_override,include_latest=False,suffix=steps_taken) for _ in range(user_args["run"]["vqgan_3_runs"]): steps_taken += "[vqgan]" latest_image = run_vq_step(i, prompts, user_args["run"], user_args["VQGAN"], clip_model, cutouts, normalize, latest_image, iterations, working_dir, device) if user_args["run"]["save_mid_steps"]: save_image(i,latest_image,run_name,subfolder=steps_taken,name_override=name_override,include_latest=False,suffix=steps_taken) save_image(i, working_dir, latest_image,run_name, user_args, prompts ,name_override=name_override,include_latest=False) clear_output(wait=True) i = next_i(i, user_args["run"]["end_frame"],f'{output_path}/',run_name) except KeyboardInterrupt: stop_on_next_loop = True print("STOP REQUESTED!") pass clear_output(wait=True) show_image(latest_image, f"DONE! ({i})") begin_art(working_dir)
nat_gan.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: visualization-curriculum-gF8wUgMm # language: python # name: visualization-curriculum-gf8wugmm # --- # + [markdown] papermill={"duration": 0.013052, "end_time": "2020-04-06T06:11:21.811879", "exception": false, "start_time": "2020-04-06T06:11:21.798827", "status": "completed"} tags=[] # # COVID-19 Deaths Per Capita # > Comparing death rates adjusting for population size. # # - comments: true # - author: <NAME> & <NAME> # - categories: [growth, compare, interactive] # - hide: false # - image: images/covid-permillion-trajectories.png # - permalink: /covid-compare-permillion/ # + papermill={"duration": 0.633946, "end_time": "2020-04-06T06:11:22.455579", "exception": false, "start_time": "2020-04-06T06:11:21.821633", "status": "completed"} tags=[] #hide import numpy as np import pandas as pd import matplotlib.pyplot as plt import altair as alt # %config InlineBackend.figure_format = 'retina' chart_width = 550 chart_height= 400 # + [markdown] papermill={"duration": 0.009328, "end_time": "2020-04-06T06:11:22.475945", "exception": false, "start_time": "2020-04-06T06:11:22.466617", "status": "completed"} tags=[] # ## Deaths Per Million Of Inhabitants # + [markdown] papermill={"duration": 0.012002, "end_time": "2020-04-06T06:11:22.497263", "exception": false, "start_time": "2020-04-06T06:11:22.485261", "status": "completed"} tags=[] # Since reaching at least 1 death per million # # > Tip: Click (Shift+ for multiple) on countries in the legend to filter the visualization. # + papermill={"duration": 5.67385, "end_time": "2020-04-06T06:11:28.180422", "exception": false, "start_time": "2020-04-06T06:11:22.506572", "status": "completed"} tags=[] #hide data = pd.read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv", error_bad_lines=False) data = data.drop(columns=["Lat", "Long"]) data = data.melt(id_vars= ["Province/State", "Country/Region"]) data = pd.DataFrame(data.groupby(['Country/Region', "variable"]).sum()) data.reset_index(inplace=True) data = data.rename(columns={"Country/Region": "location", "variable": "date", "value": "total_cases"}) data['date'] =pd.to_datetime(data.date) data = data.sort_values(by = "date") data.loc[data.location == "US","location"] = "United States" data.loc[data.location == "Korea, South","location"] = "South Korea" data_pwt = pd.read_stata("https://www.rug.nl/ggdc/docs/pwt91.dta") filter1 = data_pwt["year"] == 2017 data_pop = data_pwt[filter1] data_pop = data_pop[["country","pop"]] data_pop.loc[data_pop.country == "Republic of Korea","country"] = "South Korea" data_pop.loc[data_pop.country == "Iran (Islamic Republic of)","country"] = "Iran" # per habitant data_pc = data.copy() countries = ["China", "Italy", "Spain", "France", "United Kingdom", "Germany", "Portugal", "United States", "Singapore", "South Korea", "Japan", "Brazil", "Iran", 'Netherlands', 'Belgium', 'Sweden', 'Switzerland', 'Norway', 'Denmark', 'Austria', 'Slovenia', 'Greece', 'Cyprus'] data_countries = [] data_countries_pc = [] MIN_DEATHS = 10 filter_min_dead = data_pc.total_cases < MIN_DEATHS data_pc = data_pc.drop(data_pc[filter_min_dead].index) # compute per habitant for i in countries: data_pc.loc[data_pc.location == i,"total_cases"] = data_pc.loc[data_pc.location == i,"total_cases"]/float(data_pop.loc[data_pop.country == i, "pop"]) # get each country time series filter1 = data_pc["total_cases"] > 1 for i in countries: filter_country = data_pc["location"]== i data_countries_pc.append(data_pc[filter_country & filter1]) # + papermill={"duration": 29.895182, "end_time": "2020-04-06T06:11:58.085274", "exception": false, "start_time": "2020-04-06T06:11:28.190092", "status": "completed"} tags=[] #hide_input # Stack data to get it to Altair dataframe format data_countries_pc2 = data_countries_pc.copy() for i in range(0,len(countries)): data_countries_pc2[i] = data_countries_pc2[i].reset_index() data_countries_pc2[i]['n_days'] = data_countries_pc2[i].index data_countries_pc2[i]['log_cases'] = np.log(data_countries_pc2[i]["total_cases"]) data_plot = data_countries_pc2[0] for i in range(1, len(countries)): data_plot = pd.concat([data_plot, data_countries_pc2[i]], axis=0) data_plot["trend_2days"] = np.log(2)/2*data_plot["n_days"] data_plot["trend_4days"] = np.log(2)/4*data_plot["n_days"] data_plot["trend_12days"] = np.log(2)/12*data_plot["n_days"] data_plot["trend_2days_label"] = "Doubles every 2 days" data_plot["trend_4days_label"] = "Doubles evey 4 days" data_plot["trend_12days_label"] = "Doubles every 12 days" # Plot it using Altair source = data_plot scales = alt.selection_interval(bind='scales') selection = alt.selection_multi(fields=['location'], bind='legend') base = alt.Chart(source, title = "COVID-19 Deaths Per Million of Inhabitants").encode( x = alt.X('n_days:Q', title = "Days passed since reaching 1 death per million"), y = alt.Y("log_cases:Q",title = "Log of deaths per million"), color = alt.Color('location:N', legend=alt.Legend(title="Country", labelFontSize=15, titleFontSize=17), scale=alt.Scale(scheme='tableau20')), opacity = alt.condition(selection, alt.value(1), alt.value(0.1)) ) lines = base.mark_line().add_selection( scales ).add_selection( selection ).properties( width=chart_width, height=chart_height ) trend_2d = alt.Chart(source).encode( x = "n_days:Q", y = alt.Y("trend_2days:Q", scale=alt.Scale(domain=(0, max(data_plot["log_cases"])))), ).mark_line(color="grey", strokeDash=[3,3]) labels = pd.DataFrame([{'label': 'Doubles every 2 days', 'x_coord': 6, 'y_coord': 4}, {'label': 'Doubles every 4 days', 'x_coord': 16, 'y_coord': 3.5}, {'label': 'Doubles every 12 days', 'x_coord': 25, 'y_coord': 1.8}, ]) trend_label = (alt.Chart(labels) .mark_text(align='left', dx=-55, dy=-15, fontSize=12, color="grey") .encode(x='x_coord:Q', y='y_coord:Q', text='label:N') ) trend_4d = alt.Chart(source).mark_line(color="grey", strokeDash=[3,3]).encode( x = "n_days:Q", y = alt.Y("trend_4days:Q", scale=alt.Scale(domain=(0, max(data_plot["log_cases"])))), ) trend_12d = alt.Chart(source).mark_line(color="grey", strokeDash=[3,3]).encode( x = "n_days:Q", y = alt.Y("trend_12days:Q", scale=alt.Scale(domain=(0, max(data_plot["log_cases"])))), ) plot1= ( (trend_2d + trend_4d + trend_12d + trend_label + lines) .configure_title(fontSize=20) .configure_axis(labelFontSize=15,titleFontSize=18) ) plot1.save(("../images/covid-permillion-trajectories.png")) plot1 # + [markdown] papermill={"duration": 0.013462, "end_time": "2020-04-06T06:11:58.111592", "exception": false, "start_time": "2020-04-06T06:11:58.098130", "status": "completed"} tags=[] # Last Available Total Deaths By Country: # + papermill={"duration": 0.05173, "end_time": "2020-04-06T06:11:58.177017", "exception": false, "start_time": "2020-04-06T06:11:58.125287", "status": "completed"} tags=[] #hide_input label = 'Deaths' temp = pd.concat([x.copy() for x in data_countries_pc]).loc[lambda x: x.date >= '3/1/2020'] metric_name = f'{label} per Million' temp.columns = ['Country', 'date', metric_name] # temp.loc[:, 'month'] = temp.date.dt.strftime('%Y-%m') temp.loc[:, f'Log of {label} per Million'] = temp[f'{label} per Million'].apply(lambda x: np.log(x)) temp.groupby('Country').last() # + papermill={"duration": 4.983829, "end_time": "2020-04-06T06:12:03.173372", "exception": false, "start_time": "2020-04-06T06:11:58.189543", "status": "completed"} tags=[] #hide # Get data and clean it data = pd.read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv", error_bad_lines=False) data = data.drop(columns=["Lat", "Long"]) data = data.melt(id_vars= ["Province/State", "Country/Region"]) data = pd.DataFrame(data.groupby(['Country/Region', "variable"]).sum()) data.reset_index(inplace=True) data = data.rename(columns={"Country/Region": "location", "variable": "date", "value": "total_cases"}) data['date'] =pd.to_datetime(data.date) data = data.sort_values(by = "date") data.loc[data.location == "US","location"] = "United States" data.loc[data.location == "Korea, South","location"] = "South Korea" # Population data (last year is 2017 which is what we use) data_pwt = pd.read_stata("https://www.rug.nl/ggdc/docs/pwt91.dta") filter1 = data_pwt["year"] == 2017 data_pop = data_pwt[filter1] data_pop = data_pop[["country","pop"]] data_pop.loc[data_pop.country == "Republic of Korea","country"] = "South Korea" data_pop.loc[data_pop.country == "Iran (Islamic Republic of)","country"] = "Iran" # per habitant data_pc = data.copy() # I can add more countries if needed countries = ["China", "Italy", "Spain", "France", "United Kingdom", "Germany", "Portugal", "United States", "Singapore","South Korea", "Japan", "Brazil","Iran"] data_countries = [] data_countries_pc = [] # compute per habitant for i in countries: data_pc.loc[data_pc.location == i,"total_cases"] = data_pc.loc[data_pc.location == i,"total_cases"]/float(data_pop.loc[data_pop.country == i, "pop"]) # get each country time series filter1 = data_pc["total_cases"] > 1 for i in countries: filter_country = data_pc["location"]== i data_countries_pc.append(data_pc[filter_country & filter1]) # + [markdown] papermill={"duration": 0.012084, "end_time": "2020-04-06T06:12:03.200589", "exception": false, "start_time": "2020-04-06T06:12:03.188505", "status": "completed"} tags=[] # ## Appendix # # > Warning: The following chart, "Cases Per Million of Habitants" is biased depending on how widely a country administers tests. Please read with caution. # + [markdown] papermill={"duration": 0.012101, "end_time": "2020-04-06T06:12:03.226538", "exception": false, "start_time": "2020-04-06T06:12:03.214437", "status": "completed"} tags=[] # ### Cases Per Million of Habitants # # + papermill={"duration": 0.254933, "end_time": "2020-04-06T06:12:03.494069", "exception": false, "start_time": "2020-04-06T06:12:03.239136", "status": "completed"} tags=[] #hide_input # Stack data to get it to Altair dataframe format data_countries_pc2 = data_countries_pc.copy() for i in range(0,len(countries)): data_countries_pc2[i] = data_countries_pc2[i].reset_index() data_countries_pc2[i]['n_days'] = data_countries_pc2[i].index data_countries_pc2[i]['log_cases'] = np.log(data_countries_pc2[i]["total_cases"]) data_plot = data_countries_pc2[0] for i in range(1, len(countries)): data_plot = pd.concat([data_plot, data_countries_pc2[i]], axis=0) data_plot["trend_2days"] = np.log(2)/2*data_plot["n_days"] data_plot["trend_4days"] = np.log(2)/4*data_plot["n_days"] data_plot["trend_12days"] = np.log(2)/12*data_plot["n_days"] data_plot["trend_2days_label"] = "Doubles every 2 days" data_plot["trend_4days_label"] = "Doubles evey 4 days" data_plot["trend_12days_label"] = "Doubles every 12 days" # Plot it using Altair source = data_plot scales = alt.selection_interval(bind='scales') selection = alt.selection_multi(fields=['location'], bind='legend') base = alt.Chart(source, title = "COVID-19 Confirmed Cases Per Million of Inhabitants").encode( x = alt.X('n_days:Q', title = "Days passed since reaching 1 case per million"), y = alt.Y("log_cases:Q",title = "Log of confirmed cases per million"), color = alt.Color('location:N', legend=alt.Legend(title="Country", labelFontSize=15, titleFontSize=17), scale=alt.Scale(scheme='tableau20')), opacity = alt.condition(selection, alt.value(1), alt.value(0.1)) ).properties( width=chart_width, height=chart_height ) lines = base.mark_line().add_selection( scales ).add_selection( selection ) trend_2d = alt.Chart(source).encode( x = "n_days:Q", y = alt.Y("trend_2days:Q", scale=alt.Scale(domain=(0, max(data_plot["log_cases"])))), ).mark_line( strokeDash=[3,3], color="grey") labels = pd.DataFrame([{'label': 'Doubles every 2 days', 'x_coord': 10, 'y_coord': 6}, {'label': 'Doubles every 4 days', 'x_coord': 28, 'y_coord': 6}, {'label': 'Doubles every 12 days', 'x_coord': 45, 'y_coord': 3}, ]) trend_label = (alt.Chart(labels) .mark_text(align='left', dx=-55, dy=-15, fontSize=12, color="grey") .encode(x='x_coord:Q', y='y_coord:Q', text='label:N') ) trend_4d = alt.Chart(source).mark_line(color="grey", strokeDash=[3,3]).encode( x = "n_days:Q", y = alt.Y("trend_4days:Q", scale=alt.Scale(domain=(0, max(data_plot["log_cases"])))), ) trend_12d = alt.Chart(source).mark_line(color="grey", strokeDash=[3,3]).encode( x = "n_days:Q", y = alt.Y("trend_12days:Q", scale=alt.Scale(domain=(0, max(data_plot["log_cases"])))), ) ( (trend_2d + trend_4d + trend_12d + trend_label + lines) .configure_title(fontSize=20) .configure_axis(labelFontSize=15,titleFontSize=18) ) # + [markdown] papermill={"duration": 0.01655, "end_time": "2020-04-06T06:12:03.526600", "exception": false, "start_time": "2020-04-06T06:12:03.510050", "status": "completed"} tags=[] # Last Available Cases Per Million By Country: # + papermill={"duration": 0.053026, "end_time": "2020-04-06T06:12:03.595112", "exception": false, "start_time": "2020-04-06T06:12:03.542086", "status": "completed"} tags=[] #hide_input label = 'Cases' temp = pd.concat([x.copy() for x in data_countries_pc]).loc[lambda x: x.date >= '3/1/2020'] metric_name = f'{label} per Million' temp.columns = ['Country', 'date', metric_name] # temp.loc[:, 'month'] = temp.date.dt.strftime('%Y-%m') temp.loc[:, f'Log of {label} per Million'] = temp[f'{label} per Million'].apply(lambda x: np.log(x)) temp.groupby('Country').last() # + [markdown] papermill={"duration": 0.015821, "end_time": "2020-04-06T06:12:03.627327", "exception": false, "start_time": "2020-04-06T06:12:03.611506", "status": "completed"} tags=[] # This analysis was conducted by [<NAME>](http://jbduarte.com). Assitance with creating visualizations were provided by [<NAME>](https://twitter.com/HamelHusain). Relevant sources are listed below: # # # 1. ["2019 Novel Coronavirus COVID-19 (2019-nCoV) Data Repository by Johns Hopkins CSSE"](https://systems.jhu.edu/research/public-health/ncov/) [GitHub repository](https://github.com/CSSEGISandData/COVID-19). # # 2. [Feenstra, <NAME>., <NAME> and <NAME> (2015), "The Next Generation of the Penn World Table" American Economic Review, 105(10), 3150-3182](https://www.rug.nl/ggdc/productivity/pwt/related-research) # + papermill={"duration": 0.015527, "end_time": "2020-04-06T06:12:03.658788", "exception": false, "start_time": "2020-04-06T06:12:03.643261", "status": "completed"} tags=[]
_notebooks/2020-03-19-cases-and-deaths-per-million.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="1pIo4r_Y8cMo" colab_type="text" # # DAIN Colab # + [markdown] id="iGPHW5SOpPe3" colab_type="text" # *DAIN Colab, v1.6.0* # # Based on the [original Colab file](https://github.com/baowenbo/DAIN/issues/44) by btahir. # # Enhancements by [Styler00Dollar](https://github.com/styler00dollar) aka "sudo rm -rf / --no-preserve-root#8353" on discord and [Alpha](https://github.com/AlphaGit), (Alpha#6137 on Discord). Please do not run this command in your linux terminal. It's rather meant as a joke. # # [Styler00Dollar's fork](https://github.com/styler00dollar/DAIN) / [Alpha's fork](https://github.com/AlphaGit/DAIN) / [Edgars' fork](https://github.com/edgarsi/DAIN) # # A simple guide: # - Upload this ` .ipynb` file to your Google Colab. # - Create a folder inside of Google Drive named "DAIN" # - Change the configurations in the next cell # - Run cells one by one # # Stuff that should be improved: # - Alpha channel will be removed automatically and won't be added back. Anything related to alpha will be converted to black. # - Adding configuration to select speed # - Auto-resume # - Copy `start_frame` - `end_frame` audio from original input to final output # # + id="enKoi0TR2fOD" colab_type="code" colab={} cellView="form" ################# Required Configurations ############################ #@markdown # Required Configuration #@markdown Use the values in here to configure what you'd like DAIN to do. #@markdown ## Input file #@markdown Path (relative to the root of your Google Drive) to the input file. For instance, if you save your `example.mkv` file in your Google Drive, inside a `videos` folder, the path would be: `videos/example.mkv`. Currenly videos and gifs are supported. INPUT_FILEPATH = "DAIN/input.mp4" #@param{type:"string"} #@markdown ## Output file #@markdown Output file path: path (relative to the root of your Google Drive) for the output file. It will also determine the filetype in the destination. `.mp4` is recommended for video input, `.gif` for gif inputs. OUTPUT_FILE_PATH = "DAIN/output.mp4" #@param{type:"string"} ################# Optional configurations ############################ #@markdown # Optional Configuration #@markdown Parameters below can be left with their defaults, but feel free to adapt them to your needs. #@markdown ## Target FPS #@markdown how many frames per second should the result have. This will determine how many intermediate images are interpolated. TARGET_FPS = 60 #@param{type:"number"} #@markdown ## Frame input directory #@markdown A path, relative to your GDrive root, where you already have the list of frames in the format 00001.png, 00002.png, etc. FRAME_INPUT_DIR = '/content/DAIN/input_frames' #@param{type:"string"} #@markdown ## Frame output directory #@markdown A path, relative to your GDrive root, where you want the generated frame. FRAME_OUTPUT_DIR = '/content/DAIN/output_frames' #@param{type:"string"} #@markdown ## Frame mixer #@markdown Normally we interpolate between two adjacent frames. You can try to experiment with other mixers. Claymation mixer can give smoother outputs when animation only moves every second frame at times. FRAME_MIXER = "normal" #@param ["normal", "claymation"] {type:"string"} #@markdown ## Start Frame #@markdown First frame to consider from the video when processing. START_FRAME = 1 #@param{type:"number"} #@markdown ## End Frame #@markdown Last frame to consider from the video when processing. To use the whole video use `-1`. END_FRAME = -1 #@param{type:"number"} #@markdown ## Seamless playback #@markdown Creates a seamless loop by using the first frame as last one as well. Set this to True this if loop is intended. SEAMLESS = False #@param{type:"boolean"} #@markdown ## Detect scene changes #@markdown Detects sharp changes in video, avoiding interpolating over scene changes. Slide this all the way to 1 not use scene detection at all. SCENE_CHANGE_THRESHOLD = 0.2 #@param {type:"slider", min:0, max:1, step:0.01} #@markdown ## Resize hotfix #@markdown DAIN frames are a bit "shifted / smaller" compared to original input frames. This can partly be mitigated with resizing DAIN frames to the resolution +2px and cropping the result to the original resoultion with the starting point (1,1). Without this fix, DAIN tends to make "vibrating" output and it is pretty noticible with static elements like text. #@markdown #@markdown This hotfix tries to make such effects less visible for a smoother video playback. I do not know what DAINAPP uses as a fix for this problem, but the original does show such behaviour with the default test images. More advanced users can change the interpolation method. The methods cv2.INTER_CUBIC and cv2.INTER_LANCZOS4 are recommended. The current default value is cv2.INTER_LANCZOS4. RESIZE_HOTFIX = True #@param{type:"boolean"} #@markdown ## Auto-remove PNG directory #@markdown Auto-delete output PNG dir after ffmpeg video creation. Set this to `False` if you want to keep the PNG files. AUTO_REMOVE = True #@param{type:"boolean"} # + id="N9cGwalNeyk9" colab_type="code" colab={} # Connect Google Drive from google.colab import drive drive.mount('/content/gdrive') print('Google Drive connected.') # + id="irzjv1x4e3S4" colab_type="code" colab={} # Check your current GPU # If you are lucky, you get 16GB VRAM. If you are not lucky, you get less. VRAM is important. The more VRAM, the higher the maximum resolution will go. # 16GB: Can handle 720p. 1080p will procude an out-of-memory error. # 8GB: Can handle 480p. 720p will produce an out-of-memory error. # !nvidia-smi --query-gpu=gpu_name,driver_version,memory.total --format=csv # + [markdown] id="UYHTTP91oMvh" colab_type="text" # # Install dependencies. # # This next step may take somewhere between 15-20 minutes. Run this only once at startup. # # Look for the "Finished installing dependencies" message. # + id="XunYRBtyPZf_" colab_type="code" colab={} # Install known used versions of PyTorch and SciPy # !pip install torch==1.4.0+cu100 torchvision==0.5.0+cu100 -f https://download.pytorch.org/whl/torch_stable.html # !pip install scipy==1.1.0 # !CUDA_VISIBLE_DEVICES=0 # !sudo apt-get install imagemagick imagemagick-doc print("Finished installing dependencies.") # + id="-mRVRXIGPk9I" colab_type="code" colab={} # Clone DAIN sources # %cd /content # !git clone -b master --depth 1 https://github.com/baowenbo/DAIN /content/DAIN # %cd /content/DAIN # !git log -1 # + id="e5AHGetTRacZ" colab_type="code" colab={} # This takes a while. Just wait. ~15 minutes. # Building DAIN. # %cd /content/DAIN/my_package/ # !./build.sh print("Building #1 done.") # + id="UeaU8um5-2NS" colab_type="code" colab={} # Wait again. ~5 minutes. # Building DAIN PyTorch correlation package. # %cd /content/DAIN/PWCNet/correlation_package_pytorch1_0 # !./build.sh print("Building #2 done.") # + id="InjqMYIyXCZs" colab_type="code" colab={} # Downloading pre-trained model # %cd /content/DAIN # !mkdir model_weights # !wget -O model_weights/best.pth http://vllab1.ucmerced.edu/~wenbobao/DAIN/best.pth # + id="zm5kn6vTncL4" colab_type="code" colab={} # Detecting FPS of input file. # %shell yes | cp -f /content/gdrive/My\ Drive/{INPUT_FILEPATH} /content/DAIN/ import os filename = os.path.basename(INPUT_FILEPATH) import cv2 cap = cv2.VideoCapture(f'/content/DAIN/{filename}') fps = cap.get(cv2.CAP_PROP_FPS) print(f"Input file has {fps} fps") if(fps/TARGET_FPS>0.5): print("Define a higher fps, because there is not enough time for new frames. (Old FPS)/(New FPS) should be lower than 0.5. Interpolation will fail if you try.") # + id="9YNva-GuKq4Y" colab_type="code" colab={} # ffmpeg extract - Generating individual frame PNGs from the source file. # %shell rm -rf '{FRAME_INPUT_DIR}' # %shell mkdir -p '{FRAME_INPUT_DIR}' if (END_FRAME==-1): # %shell ffmpeg -i '/content/DAIN/{filename}' -vf 'select=gte(n\,{START_FRAME}-1),setpts=PTS-STARTPTS' '{FRAME_INPUT_DIR}/%05d.png' else: # %shell ffmpeg -i '/content/DAIN/{filename}' -vf 'select=between(n\,{START_FRAME}-1\,{END_FRAME}-1),setpts=PTS-STARTPTS' '{FRAME_INPUT_DIR}/%05d.png' from IPython.display import clear_output clear_output() # png_generated_count_command_result = %shell ls '{FRAME_INPUT_DIR}' | wc -l frame_count = int(png_generated_count_command_result.output.strip()) import shutil if SEAMLESS: frame_count += 1 first_frame = f"{FRAME_INPUT_DIR}/00001.png" new_last_frame = f"{FRAME_INPUT_DIR}/{frame_count.zfill(5)}.png" shutil.copyfile(first_frame, new_last_frame) print(f"{frame_count} frame PNGs generated.") # + id="M74tIdzSne3x" colab_type="code" colab={} # Checking if PNGs do have alpha import subprocess as sp # %cd {FRAME_INPUT_DIR} channels = sp.getoutput('identify -format %[channels] 00001.png') print (f"{channels} detected") # Removing alpha if detected if "a" in channels: print("Alpha channel detected and will be removed.") print(sp.getoutput('find . -name "*.png" -exec convert "{}" -alpha off PNG24:"{}" \;')) # - # !rm -f /content/DAIN/scene_frames.log if SCENE_CHANGE_THRESHOLD != 1: scene_frames = ! \ ffmpeg -i '{FRAME_INPUT_DIR}/%05d.png' \ -filter:v "showinfo,select='gt(scene,{SCENE_CHANGE_THRESHOLD})',showinfo" \ -f null - 2>&1 | grep Parsed_showinfo_2.*n: -B 1 | grep Parsed_showinfo_0 | sed -E 's/.*n: *([0-9]+).*/\1/' \ | tee /content/DAIN/scene_frames.log # %shell pip install ipyplot # + import ipyplot def frame_image(frame): return f'{FRAME_INPUT_DIR}/{frame:0>5d}.png' # Output the frame before and the frame after the first few scene changes, for manual inspection frames = [int(i) for i in scene_frames[:100]] for f in frames: images = frame_image(f), frame_image(f+1) ipyplot.plot_images(images, img_width=150, force_b64=True) # + id="W3rrE7L824gL" colab_type="code" colab={} # Interpolation # %shell mkdir -p '{FRAME_OUTPUT_DIR}' # %cd /content/DAIN # !python -W ignore colab_interpolate.py --netName DAIN_slowmotion --mixer={FRAME_MIXER} --time_step {fps/TARGET_FPS} --start_frame 1 --end_frame {frame_count} --frame_input_dir '{FRAME_INPUT_DIR}' --frame_output_dir '{FRAME_OUTPUT_DIR}' --resize_hotfix {RESIZE_HOTFIX} # + id="TKREDli2IDMV" colab_type="code" colab={} # Create output video # %cd {FRAME_OUTPUT_DIR} # %shell ffmpeg -y -r {TARGET_FPS} -f image2 -pattern_type glob -i '*.png' '/content/gdrive/My Drive/{OUTPUT_FILE_PATH}' # + id="UF5TEo5N374o" colab_type="code" colab={} if(AUTO_REMOVE): # !rm -rf {FRAME_OUTPUT_DIR}/* # + id="uCBHIXNN-JYu" colab_type="code" colab={} # [Experimental] Create video with sound # Only run this, if the original had sound. # %cd {FRAME_OUTPUT_DIR} # %shell ffmpeg -i '/content/DAIN/{filename}' -acodec copy output-audio.aac # %shell ffmpeg -y -r {TARGET_FPS} -f image2 -pattern_type glob -i '*.png' -i output-audio.aac -shortest '/content/gdrive/My Drive/{OUTPUT_FILE_PATH}' if (AUTO_REMOVE): # !rm -rf {FRAME_OUTPUT_DIR}/* # !rm -rf output-audio.aac
Colab_DAIN.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/manav88/VAKSH-DOC/blob/main/Vaksh_Doc.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="xnoAkFlu8bjU" import pandas as pd import numpy as np from sklearn.datasets import load_breast_cancer cancer_dataset = load_breast_cancer() # + id="4igou_ZD82js" cancer_df = pd.DataFrame(np.c_[cancer_dataset['data'],cancer_dataset['target']], columns = np.append(cancer_dataset['feature_names'], ['target'])) # + colab={"base_uri": "https://localhost:8080/"} id="AGEC2QJz9II-" outputId="f3f6959c-fbbd-4651-ea49-1039bfab46ae" cancer_df.info() # + colab={"base_uri": "https://localhost:8080/", "height": 399} id="dBQz2qQt9MYi" outputId="65f7eab6-a851-4f29-d67f-e9db2dae7b8e" cancer_df.describe() # + id="8DmAhE5M9aZr" X = cancer_df.drop(['target'], axis = 1) y = cancer_df['target'] from sklearn.metrics import confusion_matrix, classification_report, accuracy_score # + id="b3RXuoRJ-EE1" 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= 5) # + id="AxRH6zig-d7S" from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train_sc = sc.fit_transform(X_train) X_test_sc = sc.transform(X_test) # + colab={"base_uri": "https://localhost:8080/"} id="FvLjGNLI-BsA" outputId="9bfadc7d-2cee-4bc6-b55c-98ff06d193a1" from sklearn.svm import SVC svc_classifier2 = SVC() svc_classifier2.fit(X_train_sc, y_train) y_pred_svc_sc = svc_classifier2.predict(X_test_sc) accuracy_score(y_test, y_pred_svc_sc) # + colab={"base_uri": "https://localhost:8080/"} id="OM-pjx8C-sBo" outputId="8a17883e-6697-4a6d-9c8b-a568dd5d0742" from sklearn.ensemble import RandomForestClassifier rf_classifier = RandomForestClassifier(n_estimators = 20, criterion = 'entropy', random_state = 51) rf_classifier.fit(X_train, y_train) y_pred_rf = rf_classifier.predict(X_test) accuracy_score(y_test, y_pred_rf) # + colab={"base_uri": "https://localhost:8080/"} id="1CU2xLsR-1Ms" outputId="fbd926b4-ef34-40a1-9578-949970abc46e" from xgboost import XGBClassifier xgb_classifier = XGBClassifier() xgb_classifier.fit(X_train, y_train) y_pred_xgb = xgb_classifier.predict(X_test) accuracy_score(y_test, y_pred_xgb) # + id="xrBi3lxs_D8m" xgb_classifier_mn = XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bynode=1, colsample_bytree=0.4, gamma=0.2, learning_rate=0.1, max_delta_step=0, max_depth=15, min_child_weight=1, missing=None, n_estimators=100, n_jobs=1, nthread=None, objective='binary:logistic', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=None, subsample=1, verbosity=1) xgb_classifier_mn.fit(X_train, y_train) y_pred_xgb_mn = xgb_classifier_mn.predict(X_test) # + colab={"base_uri": "https://localhost:8080/"} id="CBp-ws-a_HjQ" outputId="4683d9cf-8a33-4a62-8a88-c6f2c290fd00" accuracy_score(y_test, y_pred_xgb_mn) # + colab={"base_uri": "https://localhost:8080/"} id="8-PxW3T6_LN9" outputId="3b2b166b-1670-42b6-c150-eb60fd5fae5a" print(classification_report(y_test, y_pred_xgb_mn)) # + colab={"base_uri": "https://localhost:8080/"} id="xUtJXRFi_blg" outputId="403eb9f9-3199-4dad-8428-9f03cb8433f5" import pickle pickle.dump(xgb_classifier_pt, open('vaksh.pickle', 'wb')) breast_cancer_detector_model = pickle.load(open('vaksh.pickle', 'rb')) y_pred = breast_cancer_detector_model.predict(X_test) print('Confusion matrix of XGBoost model: \n',confusion_matrix(y_test, y_pred),'\n') print('Accuracy of XGBoost model = ',accuracy_score(y_test, y_pred))
Vaksh_Doc.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd from plotnine import * import re df = pd.read_csv('data/df_filled.csv') df.head() df_seoul = df.copy(deep=True) df_seoul = df_seoul.ix[(df_seoul['address'].str.contains('서울특별시'))] df_seoul.loc[~(df_seoul['address'].str.contains('서울'))] df_seoul['area'] = df_seoul['address'].str.extract(r'([가-힣|0-9]+[동|가])[^종로구]') df_seoul['area'][165426] = '개봉동' df_seoul.loc[df_seoul['area'].isnull()] df_seoul['area'].isnull().sum() df_seoul = df_seoul.groupby('area').count() df_seoul # + seoul_area = {} for area in df_seoul['area']: if area not in seoul_area.keys(): seoul_area[area] = 1 else: seoul_area[area] += 1 seoul_area # - seoul = pd.DataFrame() seoul['area'] = seoul_area.keys() seoul.info year = 2007 df_2007 = df_seoul.loc[(df_seoul['영업자시작년도'] <= year) & ((df_seoul['폐업년도'] > year) | (df_seoul['폐업년도'].isnull()))] df_2007.head() df_2007.columns df_2007 = df_2007.drop(['address', 'lat', 'lng', '구', '년도', '업소명', '업종명', '업태명'], axis=1) area_counts = {} for area in df_2007['area']: if area not in area_counts.keys(): area_counts[area] = 1 else: area_counts[area] += 1 area_counts pd.DataFrame({'수색동': 11, '응암동': 82, '신사동': 698, '녹번동': 32, '갈현동': 75, '역촌동': 42, '불광동': 45, '대조동': 70, '구산동': 17, '증산동': 13, '진관동': 7, '인사동': 7, '계동': 4, '공평동': 6, '재동': 3, '혜화동': 9, '원남동': 2, '평창동': 17, '명륜4가': 16, '관훈동': 11, '연건동': 8, '창신동': 37, '종로3가': 3, '청진동': 24, '평동': 1, '연지동': 6, '수송동': 15, '낙원동': 12, '묘동': 9, '인의동': 13, '무악동': 6, '화동': 2, '봉익동': 8, '종로6가': 7, '동숭동': 21, '명륜2가': 20, '필운동': 5, '종로2가': 16, '삼청동': 14, '내수동': 19, '당주동': 8, '구기동': 12, '종로5가': 14, '운니동': 5, '와룡동': 4, '교남동': 5, '홍파동': 1, '적선동': 9, '중학동': 1, '통의동': 5, '신문로2가': 6, '장사동': 2, '숭인동': 20, '원서동': 2, '서린동': 2, '부암동': 9, '홍지동': 4, '돈의동': 7, '도렴동': 6, '소격동': 7, '종로4가': 4, '권농동': 2, '청운동': 2, '신문로1가': 6, '효제동': 9, '체부동': 3, '종로1가': 10, '관철동': 15, '관수동': 7, '교북동': 3, '명륜3가': 2, '안국동': 3, '견지동': 1, '명륜1가': 1, '문정동': 300, '방이동': 482, '석촌동': 354, '거여동': 245, '마천동': 284, '신천동': 182, '잠실동': 729, '송파동': 321, '가락동': 607, '오금동': 254, '풍납동': 220, '삼전동': 251, '장지동': 13, '신정동': 752, '목동': 815, '신월동': 604, '문래동3가': 97, '여의도동': 777, '양평동4가': 82, '신길동': 630, '영등포동': 134, '대림동': 545, '영등포동7가': 107, '당산동4가': 60, '양평동6가': 16, '영등포동3가': 163, '당산동5가': 41, '도림동': 151, '문래동1가': 28, '문래동6가': 29, '양평동1가': 92, '문래동4가': 35, '당산동6가': 70, '양평동2가': 47, '영등포동4가': 115, '당산동': 38, '당산동3가': 113, '양평동3가': 37, '영등포동6가': 69, '영등포동1가': 23, '당산동1가': 98, '영등포동2가': 119, '당산동2가': 46, '양평동5가': 17, '문래동5가': 11, '영등포동8가': 41, '영등포동5가': 95, '문래동2가': 46, '양평동': 1, '양화동': 3, '신영동': 3, '선유동': 1, '중화동': 65, '면목동': 197, '망우동': 66, '신내동': 41, '묵동': 37, '상봉동': 74, '도곡동': 229, '논현동': 564, '개포동': 238, '역삼동': 982, '청담동': 323, '대치동': 571, '일원동': 87, '삼성동': 488, '압구정동': 120, '수서동': 68, '율현동': 8, '세곡동': 6, '화곡동': 1192, '등촌동': 403, '공항동': 197, '내발산동': 190, '가양동': 130, '염창동': 101, '방화동': 449, '과해동': 11, '마곡동': 29, '외발산동': 18, '개화동': 2, '번동': 252, '수유동': 630, '미아동': 759, '우이동': 71, '도선동': 78, '둔촌동': 165, '명일동': 338, '상일동': 114, '길동': 422, '성내동': 757, '암사동': 326, '고덕동': 122, '천호동': 685, '강일동': 21, '신림동': 1669, '남현동': 114, '봉천동': 1235, '충무로2가': 13, '인현동1가': 6, '북창동': 10, '태평로2가': 10, '남대문로5가': 18, '다동': 16, '장충동2가': 19, '명동2가': 28, '저동2가': 9, '쌍림동': 5, '충무로3가': 7, '예관동': 4, '오장동': 6, '인현동2가': 5, '충무로4가': 5, '충무로1가': 31, '만리동1가': 3, '신당동': 94, '회현동1가': 9, '저동1가': 6, '광희동1가': 10, '을지로1가': 3, '장교동': 5, '황학동': 25, '순화동': 14, '수하동': 2, '남창동': 6, '서소문동': 5, '묵정동': 4, '장충동1가': 4, '무교동': 7, '을지로3가': 3, '회현동2가': 3, '필동1가': 4, '을지로2가': 11, '주교동': 7, '초동': 3, '무학동': 6, '남산동2가': 10, '수표동': 2, '남대문로3가': 2, '필동2가': 7, '을지로6가': 23, '흥인동': 7, '중림동': 30, '산림동': 3, '봉래동1가': 3, '태평로1가': 4, '정동': 4, '남산동1가': 3, '남대문로2가': 4, '충무로5가': 2, '만리동2가': 6, '소공동': 17, '예장동': 1, '회현동3가': 1, '을지로4가': 2, '필동3가': 4, '명동1가': 6, '남산동3가': 1, '광희동2가': 1, '남대문로4가': 3, '입정동': 2, '충정로1가': 1, '구로동': 1317, '신도림동': 150, '오류동': 242, '개봉동': 408, '천왕동': 6, '가리봉동': 175, '고척동': 323, '온수동': 52, '궁동': 52, '항동': 7, '창동': 609, '도봉동': 383, '방학동': 490, '쌍문동': 345, '독산동': 885, '가산동': 327, '시흥동': 806, '화양동': 284, '자양동': 551, '구의동': 468, '군자동': 146, '중곡동': 424, '능동': 48, '광장동': 99, '상계동': 923, '공릉동': 345, '하계동': 117, '월계동': 260, '중계동': 416, '갈월동': 12, '한남동': 40, '후암동': 7, '원효로3가': 5, '한강로2가': 34, '청파동2가': 10, '청파동3가': 8, '한강로3가': 42, '용산동2가': 11, '용산동3가': 3, '이촌동': 18, '이태원동': 41, '청파동1가': 2, '용문동': 9, '동빙고동': 2, '원효로2가': 8, '신계동': 10, '서계동': 6, '남영동': 15, '동자동': 18, '보광동': 12, '원효로1가': 5, '도원동': 2, '원효로4가': 1, '한강로1가': 7, '산천동': 3, '문배동': 2, '효창동': 1, '답십리동': 360, '회기동': 204, '용두동': 356, '청량리동': 212, '장안동': 665, '전농동': 389, '제기동': 357, '이문동': 279, '휘경동': 190, '신설동': 115, '노량진동': 325, '신대방동': 288, '흑석동': 197, '상도1동': 66, '사당동': 578, '동작동': 15, '상도동': 472, '대방동': 156, '본동': 45, '서교동': 533, '염리동': 132, '공덕동': 289, '도화동': 264, '망원동': 250, '창전동': 65, '연남동': 81, '마포동': 35, '동교동': 180, '용강동': 106, '합정동': 200, '신수동': 115, '성산동': 211, '상수동': 84, '대흥동': 155, '아현동': 191, '노고산동': 170, '상암동': 100, '신공덕동': 73, '중동': 25, '현석동': 8, '구수동': 14, '토정동': 2, '서초동': 1237, '방배동': 812, '반포동': 610, '양재동': 607, '잠원동': 335, '신원동': 22, '우면동': 46, '창천동': 422, '연희동': 174, '대현동': 238, '북아현동': 210, '홍제동': 299, '남가좌동': 499, '홍은동': 236, '북가좌동': 211, '미근동': 41, '냉천동': 40, '대신동': 38, '합동': 4, '영천동': 25, '충정로3가': 73, '충정로2가': 49, '신촌동': 39, '옥천동': 7, '현저동': 10, '천연동': 11, '봉원동': 1, '길음동': 222, '성북동': 57, '동선동4가': 38, '종암동': 183, '석관동': 223, '하월곡동': 269, '장위동': 408, '삼선동5가': 32, '동선동2가': 46, '동선동3가': 17, '정릉동': 321, '삼선동4가': 28, '삼선동2가': 52, '보문동4가': 22, '삼선동1가': 30, '상월곡동': 41, '안암동5가': 134, '동소문동3가': 10, '동소문동7가': 12, '보문동5가': 14, '성북동1가': 9, '동소문동5가': 37, '동선동5가': 14, '보문동2가': 10, '보문동7가': 24, '동선동1가': 106, '돈암동': 69, '안암동4가': 12, '보문동6가': 6, '동소문동1가': 12, '동소문동2가': 35, '보문동1가': 21, '안암동2가': 7, '동소문동4가': 9, '동소문동6가': 13, '안암동1가': 6, '삼선동3가': 6, '안암동3가': 5, '보문동3가': 2, '성수동2가': 353, '금호동3가': 59, '금호동2가': 78, '마장동': 110, '하왕십리동': 116, '용답동': 149, '옥수동': 90, '홍익동': 51, '금호동1가': 61, '행당동': 271, '성수동1가': 194, '금호동4가': 67, '상왕십리동': 70, '응봉동': 25, '송정동': 26, '사근동': 14, '당인동': 1, '원지동': 26, '내곡동': 25, '염곡동': 6, '가회동': 2, 'nan': 3, '경운동': 1, '익선동': 1, '옥인동': 2, '누하동': 1, '창성동': 1 }) # df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) seoul_area = {} for area in df_2007['area']: if area not in seoul_area.keys(): seoul_area[area] = 1 else: seoul_area[area] += 1 seoul.merge(df_2007, on='area') def seoul_shops(df, year, result): df_year = df.loc[(df['영업자시작년도'] <= year) & ((df['폐업년도'] > year) | (df['폐업년도'].isnull()))] seoul_area = {} for area in df_year['area']: if area not in seoul_area.keys(): seoul_area[area] = 1 else: seoul_area[area] += 1 result2 = result.merge(df_year, on='area') return result2 # + for year in range(2007, 2008): result = seoul_shops(df_seoul, year, seoul) result # - for year in range(2008, 2009): seoul_shops(df_seoul, year, seoul) seoul.head() # + import seaborn as sns import matplotlib as plt sns.set(font="NanumGothic") plt.pyplot.subplots(figsize=(80,600)) ax = sns.heatmap(seoul, cmap='Blues') ax.figure.savefig("output_increase.png") # - def seoul_dataframe(df, year): df_year = df.loc[(df['영업자시작년도'] <= year) & ((df['폐업년도'] > year) | df['폐업년도'].isnull())] seoul_area = {} for area in df_year['area']: if area not in seoul_area.keys(): seoul_area[area] = 0 else: seoul_area[area] += 1 seoul = pd.DataFrame() seoul['area'] = seoul_area.keys() seoul[str(year)] = seoul_area.values() return seoul seoul_dataframe(df, 2008) # + df_seoul_2007 = seoul_map(df, 2007) (ggplot(df_seoul_2007[['lng', 'lat']]) + aes(x='lng', y='lat') + geom_point(size=0.01, alpha=0.01, color='red') + ggtitle('2007년 서울') + theme(text=element_text(family=font_name)) ) # + df_seoul_2017 = seoul_map(df, 2017) (ggplot(df_seoul_2017[['lng', 'lat']]) + aes(x='lng', y='lat') + geom_point(size=0.01, alpha=0.01, color='red') + ggtitle('2017년 서울') + theme(text=element_text(family=font_name)) ) # + df_dj_2007 = seoul_map(df, 2007, area='동작구') (ggplot(df_dj_2007[['lng', 'lat']]) + aes(x='lng', y='lat') + geom_point(size=0.01, alpha=0.1, color='red') + ggtitle('2007년 서울 동작구') + theme(text=element_text(family=font_name)) ) # + df_dj_2017 = seoul_map(df, 2017, area='동작구') (ggplot(df_dj_2017[['lng', 'lat']]) + aes(x='lng', y='lat') + geom_point(size=0.01, alpha=0.1, color='red') + ggtitle('2017년 서울 동작구') + theme(text=element_text(family=font_name)) ) # + df_yn_2007 = seoul_map(df, 2007, place='연남동') (ggplot(df_yn_2007[['lng', 'lat']]) + aes(x='lng', y='lat') + geom_point(size=0.01, alpha=0.1, color='red') + ggtitle('2007년 서울 연남동') + theme(text=element_text(family=font_name)) ) # + df_yn_2017 = seoul_map(df, 2017, place='연남동') (ggplot(df_yn_2017[['lng', 'lat']]) + aes(x='lng', y='lat') + geom_point(size=0.01, alpha=0.1, color='red') + ggtitle('2017년 서울 연남동') + theme(text=element_text(family=font_name)) ) # -
code/.ipynb_checkpoints/seoul_closed_shops_soryeong_ver05-checkpoint.ipynb