markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Prepare for trainingThis next section of code performs the following tasks:* Specify GS bucket, create output directory for model checkpoints and eval results.* Specify task and download training data.* Specify ALBERT pretrained model
#Download GLUE data !git clone https://github.com/nyu-mll/GLUE-baselines download_glue GLUE_DIR='glue_data' !python download_glue/download_glue_data.py --data_dir $GLUE_DIR --tasks all # Please find the full list of tasks and their fintuning hyperparameters # here https://github.com/google-research/albert/blob/master/run_glue.sh BUCKET = "luanps" #@param { type: "string" } TASK = 'RTE' #@param {type:"string"} # Available pretrained model checkpoints: # base, large, xlarge, xxlarge ALBERT_MODEL = 'base' #@param {type:"string"} TASK_DATA_DIR = 'glue_data' BASE_DIR = "gs://" + BUCKET if not BASE_DIR or BASE_DIR == "gs://": raise ValueError("You must enter a BUCKET.") DATA_DIR = os.path.join(BASE_DIR, "data") MODELS_DIR = os.path.join(BASE_DIR, "models") OUTPUT_DIR = 'gs://{}/albert-tfhub/models/{}'.format(BUCKET, TASK) tf.gfile.MakeDirs(OUTPUT_DIR) print('***** Model output directory: {} *****'.format(OUTPUT_DIR)) # Download glue data. #! test -d download_glue_repo || git clone https://gist.github.com/60c2bdb54d156a41194446737ce03e2e.git download_glue_repo #!python download_glue_repo/download_glue_data.py --data_dir=$TASK_DATA_DIR --tasks=$TASK #print('***** Task data directory: {} *****'.format(TASK_DATA_DIR)) ALBERT_MODEL_HUB = 'https://tfhub.dev/google/albert_' + ALBERT_MODEL + '/3'
***** Model output directory: gs://luanps/albert-tfhub/models/RTE *****
Apache-2.0
albert_finetune_optimization.ipynb
luanps/albert
Now let's run the fine-tuning scripts. If you use the default MRPC task, this should be finished in around 10 mintues and you will get an accuracy of around 86.5. Choose hyperparameters using [Optuna](https://optuna.readthedocs.io/en/stable/index.html)
#Install Optuna optimzation lib !pip install optuna import optuna import uuid def get_last_acc_from_file(result_file): f = open(result_file,'r') results = f.readlines() result_dict = dict() for r in results: if 'eval_accuracy' in r: k,v = r.split(' = ') return float(v) def objective(trial): #hyperparameter setting: RTE task warmup_steps = trial.suggest_int('warmup_steps', 100, 500,100) train_steps = trial.suggest_int('train_steps', 400, 2000,100) learning_rate = trial.suggest_loguniform("learning_rate", 1e-5, 5e-5) batch_size = trial.suggest_int('batch_size', 16, 128,16) #Tmp config id = str(uuid.uuid4()).split('-')[0] OUTPUT_TMP = f'{OUTPUT_DIR}/{id}' os.environ['TFHUB_CACHE_DIR'] = OUTPUT_TMP !python -m albert.run_classifier \ --data_dir="glue_data/" \ --output_dir=$OUTPUT_TMP \ --albert_hub_module_handle=$ALBERT_MODEL_HUB \ --spm_model_file="from_tf_hub" \ --do_train=True \ --do_eval=True \ --do_predict=False \ --max_seq_length=512 \ --optimizer=adamw \ --task_name=$TASK \ --warmup_step=$warmup_steps \ --learning_rate=$learning_rate \ --train_step=$train_steps \ --save_checkpoints_steps=100 \ --train_batch_size=$batch_size\ --tpu_name=$TPU_ADDRESS \ --use_tpu=True #Download results and load model accuracy !mkdir $id !gsutil cp $OUTPUT_TMP/eval_results.txt $id model_acc = get_last_acc_from_file(f'{id}/eval_results.txt') return model_acc #Run Optuna optimization study = optuna.create_study(direction='maximize',study_name=TASK) study.optimize(objective, n_trials=20) #Pack Optuna results and save to Bucket import joblib study_file = f'{TASK}_study.pkl' !rm $study_file joblib.dump(study, study_file) !gsutil cp $study_file $OUTPUT_DIR study.trials_dataframe()
_____no_output_____
Apache-2.0
albert_finetune_optimization.ipynb
luanps/albert
Analyzing Optimization Results
#Download pkl file from GCP import joblib study_file = f'{TASK}_study.pkl' !gsutil cp $OUTPUT_DIR/$study_file . study = joblib.load(study_file) study.trials_dataframe() import optuna from optuna.visualization import plot_contour from optuna.visualization import plot_edf from optuna.visualization import plot_intermediate_values from optuna.visualization import plot_optimization_history from optuna.visualization import plot_parallel_coordinate from optuna.visualization import plot_param_importances from optuna.visualization import plot_slice plot_optimization_history(study) plot_parallel_coordinate(study) plot_contour(study) plot_slice(study) plot_param_importances(study) plot_edf(study)
_____no_output_____
Apache-2.0
albert_finetune_optimization.ipynb
luanps/albert
Bernoulli BanditWe are going to implement several exploration strategies for simplest problem - bernoulli bandit.The bandit has $K$ actions. Action produce 1.0 reward $r$ with probability $0 \le \theta_k \le 1$ which is unknown to agent, but fixed over time. Agent's objective is to minimize regret over fixed number $T$ of action selections:$$\rho = T\theta^* - \sum_{t=1}^T r_t$$Where $\theta^* = \max_k\{\theta_k\}$**Real-world analogy:**Clinical trials - we have $K$ pills and $T$ ill patient. After taking pill, patient is cured with probability $\theta_k$. Task is to find most efficient pill.A research on clinical trials - https://arxiv.org/pdf/1507.08025.pdf
class BernoulliBandit: def __init__(self, n_actions=5): self._probs = np.random.random(n_actions) @property def action_count(self): return len(self._probs) def pull(self, action): if np.any(np.random.random() > self._probs[action]): return 0.0 return 1.0 def optimal_reward(self): """ Used for regret calculation """ return np.max(self._probs) def step(self): """ Used in nonstationary version """ pass def reset(self): """ Used in nonstationary version """ class AbstractAgent(metaclass=ABCMeta): def init_actions(self, n_actions): self._successes = np.zeros(n_actions) self._failures = np.zeros(n_actions) self._total_pulls = 0 @abstractmethod def get_action(self): """ Get current best action :rtype: int """ pass def update(self, action, reward): """ Observe reward from action and update agent's internal parameters :type action: int :type reward: int """ self._total_pulls += 1 if reward == 1: self._successes[action] += 1 else: self._failures[action] += 1 @property def name(self): return self.__class__.__name__ class RandomAgent(AbstractAgent): def get_action(self): return np.random.randint(0, len(self._successes))
_____no_output_____
MIT
Informatics/Reinforcement Learning/Practical RL - HSE/week6_exploration/bandits.ipynb
MarcosSalib/Cocktail_MOOC
Epsilon-greedy agent**for** $t = 1,2,...$ **do**   **for** $k = 1,...,K$ **do**       $\hat\theta_k \leftarrow \alpha_k / (\alpha_k + \beta_k)$   **end for**    $x_t \leftarrow argmax_{k}\hat\theta$ with probability $1 - \epsilon$ or random action with probability $\epsilon$   Apply $x_t$ and observe $r_t$   $(\alpha_{x_t}, \beta_{x_t}) \leftarrow (\alpha_{x_t}, \beta_{x_t}) + (r_t, 1-r_t)$**end for**Implement the algorithm above in the cell below:
class EpsilonGreedyAgent(AbstractAgent): def __init__(self, epsilon=0.01): self._epsilon = epsilon def get_action(self): # <YOUR CODE> alpha = self._successes beta = self._failures theta_ = alpha / (alpha + beta) if np.random.random() < self._epsilon: return np.random.randint(0, len(alpha)) else: return np.argmax(theta_) @property def name(self): return self.__class__.__name__ + "(epsilon={})".format(self._epsilon)
_____no_output_____
MIT
Informatics/Reinforcement Learning/Practical RL - HSE/week6_exploration/bandits.ipynb
MarcosSalib/Cocktail_MOOC
UCB AgentEpsilon-greedy strategy heve no preference for actions. It would be better to select among actions that are uncertain or have potential to be optimal. One can come up with idea of index for each action that represents otimality and uncertainty at the same time. One efficient way to do it is to use UCB1 algorithm:**for** $t = 1,2,...$ **do**&nbsp;&nbsp; **for** $k = 1,...,K$ **do**&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $w_k \leftarrow \alpha_k / (\alpha_k + \beta_k) + \sqrt{2log\ t \ / \ (\alpha_k + \beta_k)}$&nbsp;&nbsp; **end for** &nbsp;&nbsp; **end for** $x_t \leftarrow argmax_{k}w$&nbsp;&nbsp; Apply $x_t$ and observe $r_t$&nbsp;&nbsp; $(\alpha_{x_t}, \beta_{x_t}) \leftarrow (\alpha_{x_t}, \beta_{x_t}) + (r_t, 1-r_t)$**end for**__Note:__ in practice, one can multiply $\sqrt{2log\ t \ / \ (\alpha_k + \beta_k)}$ by some tunable parameter to regulate agent's optimism and wilingness to abandon non-promising actions.More versions and optimality analysis - https://homes.di.unimi.it/~cesabian/Pubblicazioni/ml-02.pdf
class UCBAgent(AbstractAgent): def __init__(self, gamma=0.01): self._gamma = gamma def get_action(self): # <YOUR CODE> alpha = self._successes beta = self._failures t = self._total_pulls omega_ = alpha / (alpha + beta) + self._gamma * np.sqrt(2*np.log(t) / (alpha+beta)) return np.argmax(omega_) @property def name(self): return self.__class__.__name__ + "(gamma={})".format(self._gamma)
_____no_output_____
MIT
Informatics/Reinforcement Learning/Practical RL - HSE/week6_exploration/bandits.ipynb
MarcosSalib/Cocktail_MOOC
Thompson samplingUCB1 algorithm does not take into account actual distribution of rewards. If we know the distribution - we can do much better by using Thompson sampling:**for** $t = 1,2,...$ **do**&nbsp;&nbsp; **for** $k = 1,...,K$ **do**&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Sample $\hat\theta_k \sim beta(\alpha_k, \beta_k)$&nbsp;&nbsp; **end for** &nbsp;&nbsp; $x_t \leftarrow argmax_{k}\hat\theta$&nbsp;&nbsp; Apply $x_t$ and observe $r_t$&nbsp;&nbsp; $(\alpha_{x_t}, \beta_{x_t}) \leftarrow (\alpha_{x_t}, \beta_{x_t}) + (r_t, 1-r_t)$**end for** More on Thompson Sampling:https://web.stanford.edu/~bvr/pubs/TS_Tutorial.pdf
class ThompsonSamplingAgent(AbstractAgent): def get_action(self): # <YOUR CODE> alpha = self._successes beta = self._failures theta_ = np.random.beta(alpha+1, beta+1) return np.argmax(theta_) from collections import OrderedDict def get_regret(env, agents, n_steps=5000, n_trials=50): scores = OrderedDict({ agent.name: [0.0 for step in range(n_steps)] for agent in agents }) for trial in range(n_trials): env.reset() for a in agents: a.init_actions(env.action_count) for i in range(n_steps): optimal_reward = env.optimal_reward() for agent in agents: action = agent.get_action() reward = env.pull(action) agent.update(action, reward) scores[agent.name][i] += optimal_reward - reward env.step() # change bandit's state if it is unstationary for agent in agents: scores[agent.name] = np.cumsum(scores[agent.name]) / n_trials return scores def plot_regret(agents, scores): for agent in agents: plt.plot(scores[agent.name]) plt.legend([agent.name for agent in agents]) plt.ylabel("regret") plt.xlabel("steps") plt.show() # Uncomment agents agents = [ EpsilonGreedyAgent(), UCBAgent(0.1), UCBAgent(0.2), ThompsonSamplingAgent() ] regret = get_regret(BernoulliBandit(), agents, n_steps=10000, n_trials=10) plot_regret(agents, regret)
/home/x/anaconda3/envs/rl/lib/python3.7/site-packages/ipykernel_launcher.py:10: RuntimeWarning: invalid value encountered in true_divide # Remove the CWD from sys.path while we load stuff. /home/x/anaconda3/envs/rl/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in true_divide # This is added back by InteractiveShellApp.init_path() /home/x/anaconda3/envs/rl/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: divide by zero encountered in log # This is added back by InteractiveShellApp.init_path() /home/x/anaconda3/envs/rl/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in sqrt # This is added back by InteractiveShellApp.init_path() /home/x/anaconda3/envs/rl/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: divide by zero encountered in true_divide # This is added back by InteractiveShellApp.init_path()
MIT
Informatics/Reinforcement Learning/Practical RL - HSE/week6_exploration/bandits.ipynb
MarcosSalib/Cocktail_MOOC
Submit to coursera
from submit import submit_bandits submit_bandits(agents, regret, '', '')
Submitted to Coursera platform. See results on assignment page!
MIT
Informatics/Reinforcement Learning/Practical RL - HSE/week6_exploration/bandits.ipynb
MarcosSalib/Cocktail_MOOC
Realizar:1. Crear una lista de enteros en Python y realizar la suma con recursividad, el caso base es cuando la lista este vacía.2. Hacer un contador regresivo con recursión.3. Sacar de un ADT pila el valor en la posición media.
class Pila: def __init__(self): self.items = [] def imprimirCompleto(self): for x in range(0,len(self.items),1): print(self.items[x],end=",") def estaVacia(self): return self.items == [] def incluir(self, item): self.items.append(item) def extraerPrimero(self): return self.items.pop(0) def extraerUltimo(self): return self.items.pop() def inspeccionarUltimo(self): return self.items[len(self.items)-1] def tamano(self): return len(self.items) def sumaRec(lista,longitud,suma = 0): if longitud != 0: suma += lista[longitud-1] print(suma) sumaRec(lista,longitud-1,suma) def contador(maximo): if maximo != 0: print(maximo) contador(maximo-1) def posicionRec(pila): lon = pila.tamano() if lon == 1: print("\nEl elemento de la posicicon media es: ",pila.inspeccionarUltimo()) else: pila.extraerPrimero() pila.extraerUltimo() posicionRec(pila) def main(): print("1. Crear una lista de enteros en Python y realizar \nla suma con recursividad, el caso base es cuando \nla lista este vacía.") listNum = [1,2,3,4,5,6,7,8,9] print(listNum) sumaRec(listNum,len(listNum)) print("2. Hacer un contador regresivo con recursión.") print("INICIA CONTEO REGRESIVO") contador(30) print("FINALIZA CONTEO REGRESIVO") print("3. Sacar de un ADT pila el valor en la posición media") p = Pila() p.incluir(1) p.incluir(2) p.incluir(3) p.incluir(4) p.incluir(5) p.incluir(6) p.incluir(7) p.incluir(8) p.incluir(9) p.imprimirCompleto() try: posicionRec(p) except: print("La lista no tiene posicion Media") main()
1. Crear una lista de enteros en Python y realizar la suma con recursividad, el caso base es cuando la lista este vacía. [1, 2, 3, 4, 5, 6, 7, 8, 9] 9 17 24 30 35 39 42 44 45 2. Hacer un contador regresivo con recursión. INICIA CONTEO REGRESIVO 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 FINALIZA CONTEO REGRESIVO 3. Sacar de un ADT pila el valor en la posición media 1,2,3,4,5,6,7,8,9, El elemento de la posicicon media es: 5
MIT
Tarea_7_Recursividad.ipynb
Sahp59/daa_2021_1
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-getting-started.png) Azure Machine Learning Pipelines: Getting Started OverviewA common scenario when using machine learning components is to have a data workflow that includes the following steps:- Preparing/preprocessing a given dataset for training, followed by- Training a machine learning model on this data, and then- Deploying this trained model in a separate environment, and finally- Running a batch scoring task on another data set, using the trained model.Azure's Machine Learning pipelines give you a way to combine multiple steps like these into one configurable workflow, so that multiple agents/users can share and/or reuse this workflow. Machine learning pipelines thus provide a consistent, reproducible mechanism for building, evaluating, deploying, and running ML systems.To get more information about Azure machine learning pipelines, please read our [Azure Machine Learning Pipelines](https://aka.ms/pl-concept) overview, or the [readme article](https://aka.ms/pl-readme).In this notebook, we provide a gentle introduction to Azure machine learning pipelines. We build a pipeline that runs jobs unattended on different compute clusters; in this notebook, you'll see how to use the basic Azure ML SDK APIs for constructing this pipeline. Prerequisites and Azure Machine Learning BasicsIf 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 ImportsIn this first code cell, we import key Azure Machine Learning modules that we will use below.
import os import azureml.core from azureml.core import Workspace, Experiment, Datastore from azureml.widgets import RunDetails # Check core SDK version number print("SDK version:", azureml.core.VERSION)
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
Pipeline-specific SDK importsHere, we import key pipeline modules, whose use will be illustrated in the examples below.
from azureml.pipeline.core import Pipeline from azureml.pipeline.steps import PythonScriptStep print("Pipeline SDK-specific imports completed")
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
Initialize WorkspaceInitialize a [workspace](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.workspace(class%29) object from persisted configuration.
ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\n') # Default datastore def_blob_store = ws.get_default_datastore() # The following call GETS the Azure Blob Store associated with your workspace. # Note that workspaceblobstore is **the name of this store and CANNOT BE CHANGED and must be used as is** def_blob_store = Datastore(ws, "workspaceblobstore") print("Blobstore's name: {}".format(def_blob_store.name))
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
Required data and script files for the the tutorialSample files required to finish this tutorial are already copied to the corresponding source_directory locations. Even though the .py provided in the samples does not 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. Datastore conceptsA [Datastore](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.datastore.datastore?view=azure-ml-py) is a place where data can be stored that is then made accessible to a compute either by means of mounting or copying the data to the compute target. A Datastore can either be backed by an Azure File Storage (default) or by an Azure Blob Storage.In this next step, we will upload the training and test set into the workspace's default storage (File storage), and another piece of data to Azure Blob Storage. When to use [Azure Blobs](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction), [Azure Files](https://docs.microsoft.com/en-us/azure/storage/files/storage-files-introduction), or [Azure Disks](https://docs.microsoft.com/en-us/azure/virtual-machines/linux/managed-disks-overview) is [detailed here](https://docs.microsoft.com/en-us/azure/storage/common/storage-decide-blobs-files-disks).**Please take good note of the concept of the datastore.** Upload data to default datastoreDefault datastore on workspace is the Azure File storage. The workspace has a Blob storage associated with it as well. Let's upload a file to each of these storages.
# get_default_datastore() gets the default Azure Blob Store associated with your workspace. # Here we are reusing the def_blob_store object we obtained earlier def_blob_store.upload_files(["./20news.pkl"], target_path="20newsgroups", overwrite=True) print("Upload call completed")
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
(Optional) See your files using Azure PortalOnce you successfully uploaded the files, you can browse to them (or upload more files) using [Azure Portal](https://portal.azure.com). At the portal, make sure you have selected your subscription (click *Resource Groups* and then select the subscription). Then look for your **Machine Learning Workspace** name. It has a link to your storage. Click on the storage link. It will take you to a page where you can see [Blobs](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction), [Files](https://docs.microsoft.com/en-us/azure/storage/files/storage-files-introduction), [Tables](https://docs.microsoft.com/en-us/azure/storage/tables/table-storage-overview), and [Queues](https://docs.microsoft.com/en-us/azure/storage/queues/storage-queues-introduction). We have uploaded a file each to the Blob storage and to the File storage in the above step. You should be able to see both of these files in their respective locations. Compute TargetsA compute target specifies where to execute your program such as a remote Docker on a VM, or a cluster. A compute target needs to be addressable and accessible by you.**You need at least one compute target to send your payload to. We are planning to use Azure Machine Learning Compute exclusively for this tutorial for all steps. However in some cases you may require multiple compute targets as some steps may run in one compute target like Azure Machine Learning Compute, and some other steps in the same pipeline could run in a different compute target.***The example belows show creating/retrieving/attaching to an Azure Machine Learning Compute instance.* List of Compute Targets on the workspace
cts = ws.compute_targets for ct in cts: print(ct)
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
Retrieve or create a Azure Machine Learning computeAzure Machine Learning Compute is a service for provisioning and managing clusters of Azure virtual machines for running machine learning workloads. Let's create a new Azure Machine Learning Compute in the current workspace, if it doesn't already exist. We will then run the training script on this compute target.If we could not find the compute with the given name in the previous cell, then we will create a new compute here. We will create an Azure Machine Learning Compute containing **STANDARD_D2_V2 CPU VMs**. This process is broken down into the following steps:1. Create the configuration2. Create the Azure Machine Learning compute**This process will take about 3 minutes and is providing only sparse output in the process. Please make sure to wait until the call returns before moving to the next cell.**
from azureml.core.compute import ComputeTarget, AmlCompute 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("Azure Machine Learning 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())
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
**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. **Now that we have completed learning the basics of Azure Machine Learning (AML), let's go ahead and start understanding the Pipeline concepts.** Creating a Step in a PipelineA Step is a unit of execution. Step typically needs a target of execution (compute target), a script to execute, and may require script arguments and inputs, and can produce outputs. The step also could take a number of other parameters. Azure Machine Learning Pipelines provides the following built-in Steps:- [**PythonScriptStep**](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.python_script_step.pythonscriptstep?view=azure-ml-py): Adds a step to run a Python script in a Pipeline.- [**AdlaStep**](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.adla_step.adlastep?view=azure-ml-py): Adds a step to run U-SQL script using Azure Data Lake Analytics.- [**DataTransferStep**](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.data_transfer_step.datatransferstep?view=azure-ml-py): Transfers data between Azure Blob and Data Lake accounts.- [**DatabricksStep**](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.databricks_step.databricksstep?view=azure-ml-py): Adds a DataBricks notebook as a step in a Pipeline.- [**HyperDriveStep**](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.hyper_drive_step.hyperdrivestep?view=azure-ml-py): Creates a Hyper Drive step for Hyper Parameter Tuning in a Pipeline.- [**AzureBatchStep**](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.azurebatch_step.azurebatchstep?view=azure-ml-py): Creates a step for submitting jobs to Azure Batch- [**EstimatorStep**](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.estimator_step.estimatorstep?view=azure-ml-py): Adds a step to run Estimator in a Pipeline.- [**MpiStep**](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.mpi_step.mpistep?view=azure-ml-py): Adds a step to run a MPI job in a Pipeline.- [**AutoMLStep**](https://docs.microsoft.com/en-us/python/api/azureml-train-automl/azureml.train.automl.automlstep?view=azure-ml-py): Creates a AutoML step in a Pipeline.The following code will create a PythonScriptStep to be executed in the Azure Machine Learning Compute we created above using train.py, one of the files already made available in the `source_directory`.A **PythonScriptStep** is a basic, built-in step to run a Python Script on a compute target. It takes a script name and optionally other parameters like arguments for the script, compute target, inputs and outputs. If no compute target is specified, default compute target for the workspace is used. You can also use a [**RunConfiguration**](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.runconfiguration?view=azure-ml-py) to specify requirements for the PythonScriptStep, such as conda dependencies and docker image.> 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.
# Uses default values for PythonScriptStep construct. source_directory = './train' print('Source directory for the step is {}.'.format(os.path.realpath(source_directory))) # Syntax # PythonScriptStep( # script_name, # name=None, # arguments=None, # compute_target=None, # runconfig=None, # inputs=None, # outputs=None, # params=None, # source_directory=None, # allow_reuse=True, # version=None, # hash_paths=None) # This returns a Step step1 = PythonScriptStep(name="train_step", script_name="train.py", compute_target=aml_compute, source_directory=source_directory, allow_reuse=True) print("Step1 created")
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
**Note:** In the above call to PythonScriptStep(), the flag *allow_reuse* determines whether the step should reuse previous results when run with the same settings/inputs. This flag's default value is *True*; the default is set to *True* because, when inputs and parameters have not changed, we typically do not want to re-run a given pipeline step. If *allow_reuse* is set to *False*, a new run will always be generated for this step during pipeline execution. The *allow_reuse* flag can come in handy in situations where you do *not* want to re-run a pipeline step. Running a few steps in parallelHere we are looking at a simple scenario where we are running a few steps (all involving PythonScriptStep) in parallel. Running nodes in **parallel** is the default behavior for steps in a pipeline.We already have one step defined earlier. Let's define few more steps.
# For this step, we use a different source_directory source_directory = './compare' print('Source directory for the step is {}.'.format(os.path.realpath(source_directory))) # All steps use the same Azure Machine Learning compute target as well step2 = PythonScriptStep(name="compare_step", script_name="compare.py", compute_target=aml_compute, source_directory=source_directory) # Use a RunConfiguration to specify some additional requirements for this step. 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']) # For this step, we use yet another source_directory source_directory = './extract' print('Source directory for the step is {}.'.format(os.path.realpath(source_directory))) step3 = PythonScriptStep(name="extract_step", script_name="extract.py", compute_target=aml_compute, source_directory=source_directory, runconfig=run_config) # list of steps to run steps = [step1, step2, step3] print("Step lists created")
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
Build the pipelineOnce we have the steps (or steps collection), we can build the [pipeline](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-core/azureml.pipeline.core.pipeline.pipeline?view=azure-ml-py). By deafult, all these steps will run in **parallel** once we submit the pipeline for run.A pipeline is created with a list of steps and a workspace. Submit a pipeline using [submit](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.experiment(class)?view=azure-ml-pysubmit-config--tags-none----kwargs-). When submit is called, a [PipelineRun](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-core/azureml.pipeline.core.pipelinerun?view=azure-ml-py) is created which in turn creates [StepRun](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-core/azureml.pipeline.core.steprun?view=azure-ml-py) objects for each step in the workflow.
# Syntax # Pipeline(workspace, # steps, # description=None, # default_datastore_name=None, # default_source_directory=None, # resolve_closure=True, # _workflow_provider=None, # _service_endpoint=None) pipeline1 = Pipeline(workspace=ws, steps=steps) print ("Pipeline is built")
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
Validate the pipelineYou have the option to [validate](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-core/azureml.pipeline.core.pipeline.pipeline?view=azure-ml-pyvalidate--) the pipeline prior to submitting for run. The platform runs validation steps such as checking for circular dependencies and parameter checks etc. even if you do not explicitly call validate method.
pipeline1.validate() print("Pipeline validation complete")
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
Submit the pipeline[Submitting](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-core/azureml.pipeline.core.pipeline.pipeline?view=azure-ml-pysubmit) the pipeline involves creating an [Experiment](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.experiment?view=azure-ml-py) object and providing the built pipeline for submission.
# Submit syntax # submit(experiment_name, # pipeline_parameters=None, # continue_on_step_failure=False, # regenerate_outputs=False) pipeline_run1 = Experiment(ws, 'Hello_World1').submit(pipeline1, regenerate_outputs=False) print("Pipeline is submitted for execution")
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
**Note:** If regenerate_outputs is set to True, a new submit will always force generation of all step outputs, and disallow data reuse for any step of this run. Once this run is complete, however, subsequent runs may reuse the results of this run. Examine the pipeline run Use RunDetails WidgetWe are going to use the RunDetails widget to examine the run of the pipeline. You can click each row below to get more details on the step runs.
RunDetails(pipeline_run1).show()
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
Use Pipeline SDK objectsYou can cycle through the node_run objects and examine job logs, stdout, and stderr of each of the steps.
step_runs = pipeline_run1.get_children() for step_run in step_runs: status = step_run.get_status() print('Script:', step_run.name, 'status:', status) # Change this if you want to see details even if the Step has succeeded. if status == "Failed": joblog = step_run.get_job_log() print('job log:', joblog)
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
Get additonal run detailsIf you wait until the pipeline_run is finished, you may be able to get additional details on the run. **Since this is a blocking call, the following code is commented out.**
#pipeline_run1.wait_for_completion() #for step_run in pipeline_run1.get_children(): # print("{}: {}".format(step_run.name, step_run.get_metrics()))
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
Running a few steps in sequenceNow let's see how we run a few steps in sequence. We already have three steps defined earlier. Let's *reuse* those steps for this part.We will reuse step1, step2, step3, but build the pipeline in such a way that we chain step3 after step2 and step2 after step1. Note that there is no explicit data dependency between these steps, but still steps can be made dependent by using the [run_after](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-core/azureml.pipeline.core.builder.pipelinestep?view=azure-ml-pyrun-after-step-) construct.
step2.run_after(step1) step3.run_after(step2) # Try a loop #step2.run_after(step3) # Now, construct the pipeline using the steps. # We can specify the "final step" in the chain, # Pipeline will take care of "transitive closure" and # figure out the implicit or explicit dependencies # https://www.geeksforgeeks.org/transitive-closure-of-a-graph/ pipeline2 = Pipeline(workspace=ws, steps=[step3]) print ("Pipeline is built") pipeline2.validate() print("Simple validation complete") pipeline_run2 = Experiment(ws, 'Hello_World2').submit(pipeline2) print("Pipeline is submitted for execution") RunDetails(pipeline_run2).show()
_____no_output_____
MIT
how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb
alla15747/MachineLearningNotebooks
DCGAN Tutorial==============**Author**: `Nathan Inkawhich `__ Introduction------------This tutorial will give an introduction to DCGANs through an example. Wewill train a generative adversarial network (GAN) to generate newcelebrities after showing it pictures of many real celebrities. Most ofthe code here is from the dcgan implementation in`pytorch/examples `__, and thisdocument will give a thorough explanation of the implementation and shedlight on how and why this model works. But don’t worry, no priorknowledge of GANs is required, but it may require a first-timer to spendsome time reasoning about what is actually happening under the hood.Also, for the sake of time it will help to have a GPU, or two. Letsstart from the beginning.Generative Adversarial Networks-------------------------------What is a GAN?~~~~~~~~~~~~~~GANs are a framework for teaching a DL model to capture the trainingdata’s distribution so we can generate new data from that samedistribution. GANs were invented by Ian Goodfellow in 2014 and firstdescribed in the paper `Generative AdversarialNets `__.They are made of two distinct models, a *generator* and a*discriminator*. The job of the generator is to spawn ‘fake’ images thatlook like the training images. The job of the discriminator is to lookat an image and output whether or not it is a real training image or afake image from the generator. During training, the generator isconstantly trying to outsmart the discriminator by generating better andbetter fakes, while the discriminator is working to become a betterdetective and correctly classify the real and fake images. Theequilibrium of this game is when the generator is generating perfectfakes that look as if they came directly from the training data, and thediscriminator is left to always guess at 50% confidence that thegenerator output is real or fake.Now, lets define some notation to be used throughout tutorial startingwith the discriminator. Let $x$ be data representing an image.$D(x)$ is the discriminator network which outputs the (scalar)probability that $x$ came from training data rather than thegenerator. Here, since we are dealing with images the input to$D(x)$ is an image of CHW size 3x64x64. Intuitively, $D(x)$should be HIGH when $x$ comes from training data and LOW when$x$ comes from the generator. $D(x)$ can also be thought ofas a traditional binary classifier.For the generator’s notation, let $z$ be a latent space vectorsampled from a standard normal distribution. $G(z)$ represents thegenerator function which maps the latent vector $z$ to data-space.The goal of $G$ is to estimate the distribution that the trainingdata comes from ($p_{data}$) so it can generate fake samples fromthat estimated distribution ($p_g$).So, $D(G(z))$ is the probability (scalar) that the output of thegenerator $G$ is a real image. As described in `Goodfellow’spaper `__,$D$ and $G$ play a minimax game in which $D$ tries tomaximize the probability it correctly classifies reals and fakes($logD(x)$), and $G$ tries to minimize the probability that$D$ will predict its outputs are fake ($log(1-D(G(x)))$).From the paper, the GAN loss function is\begin{align}\underset{G}{\text{min}} \underset{D}{\text{max}}V(D,G) = \mathbb{E}_{x\sim p_{data}(x)}\big[logD(x)\big] + \mathbb{E}_{z\sim p_{z}(z)}\big[log(1-D(G(z)))\big]\end{align}In theory, the solution to this minimax game is where$p_g = p_{data}$, and the discriminator guesses randomly if theinputs are real or fake. However, the convergence theory of GANs isstill being actively researched and in reality models do not alwaystrain to this point.What is a DCGAN?~~~~~~~~~~~~~~~~A DCGAN is a direct extension of the GAN described above, except that itexplicitly uses convolutional and convolutional-transpose layers in thediscriminator and generator, respectively. It was first described byRadford et. al. in the paper `Unsupervised Representation Learning WithDeep Convolutional Generative AdversarialNetworks `__. The discriminatoris made up of strided`convolution `__layers, `batchnorm `__layers, and`LeakyReLU `__activations. The input is a 3x64x64 input image and the output is ascalar probability that the input is from the real data distribution.The generator is comprised of`convolutional-transpose `__layers, batch norm layers, and`ReLU `__ activations. Theinput is a latent vector, $z$, that is drawn from a standardnormal distribution and the output is a 3x64x64 RGB image. The stridedconv-transpose layers allow the latent vector to be transformed into avolume with the same shape as an image. In the paper, the authors alsogive some tips about how to setup the optimizers, how to calculate theloss functions, and how to initialize the model weights, all of whichwill be explained in the coming sections.
from __future__ import print_function #%matplotlib inline import argparse import os import random import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data import torchvision.datasets as dset import torchvision.transforms as transforms import torchvision.utils as vutils import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from IPython.display import HTML # Set random seed for reproducibility manualSeed = 999 #manualSeed = random.randint(1, 10000) # use if you want new results print("Random Seed: ", manualSeed) random.seed(manualSeed) torch.manual_seed(manualSeed)
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
Inputs------Let’s define some inputs for the run:- **dataroot** - the path to the root of the dataset folder. We will talk more about the dataset in the next section- **workers** - the number of worker threads for loading the data with the DataLoader- **batch_size** - the batch size used in training. The DCGAN paper uses a batch size of 128- **image_size** - the spatial size of the images used for training. This implementation defaults to 64x64. If another size is desired, the structures of D and G must be changed. See `here `__ for more details- **nc** - number of color channels in the input images. For color images this is 3- **nz** - length of latent vector- **ngf** - relates to the depth of feature maps carried through the generator- **ndf** - sets the depth of feature maps propagated through the discriminator- **num_epochs** - number of training epochs to run. Training for longer will probably lead to better results but will also take much longer- **lr** - learning rate for training. As described in the DCGAN paper, this number should be 0.0002- **beta1** - beta1 hyperparameter for Adam optimizers. As described in paper, this number should be 0.5- **ngpu** - number of GPUs available. If this is 0, code will run in CPU mode. If this number is greater than 0 it will run on that number of GPUs
# Root directory for dataset dataroot = "data/celeba" # Number of workers for dataloader workers = 2 # Batch size during training batch_size = 128 # Spatial size of training images. All images will be resized to this # size using a transformer. image_size = 64 # Number of channels in the training images. For color images this is 3 nc = 3 # Size of z latent vector (i.e. size of generator input) nz = 100 # Size of feature maps in generator ngf = 64 # Size of feature maps in discriminator ndf = 64 # Number of training epochs num_epochs = 5 # Learning rate for optimizers lr = 0.0002 # Beta1 hyperparam for Adam optimizers beta1 = 0.5 # Number of GPUs available. Use 0 for CPU mode. ngpu = 1
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
Data----In this tutorial we will use the `Celeb-A Facesdataset `__ which canbe downloaded at the linked site, or in `GoogleDrive `__.The dataset will download as a file named *img_align_celeba.zip*. Oncedownloaded, create a directory named *celeba* and extract the zip fileinto that directory. Then, set the *dataroot* input for this notebook tothe *celeba* directory you just created. The resulting directorystructure should be::: /path/to/celeba -> img_align_celeba -> 188242.jpg -> 173822.jpg -> 284702.jpg -> 537394.jpg ...This is an important step because we will be using the ImageFolderdataset class, which requires there to be subdirectories in thedataset’s root folder. Now, we can create the dataset, create thedataloader, set the device to run on, and finally visualize some of thetraining data.
# We can use an image folder dataset the way we have it setup. # Create the dataset dataset = dset.ImageFolder(root=dataroot, transform=transforms.Compose([ transforms.Resize(image_size), transforms.CenterCrop(image_size), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ])) # Create the dataloader dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=workers) # Decide which device we want to run on device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu") # Plot some training images real_batch = next(iter(dataloader)) plt.figure(figsize=(8,8)) plt.axis("off") plt.title("Training Images") plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=2, normalize=True).cpu(),(1,2,0)))
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
Implementation--------------With our input parameters set and the dataset prepared, we can now getinto the implementation. We will start with the weigth initializationstrategy, then talk about the generator, discriminator, loss functions,and training loop in detail.Weight Initialization~~~~~~~~~~~~~~~~~~~~~From the DCGAN paper, the authors specify that all model weights shallbe randomly initialized from a Normal distribution with mean=0,stdev=0.02. The ``weights_init`` function takes an initialized model asinput and reinitializes all convolutional, convolutional-transpose, andbatch normalization layers to meet this criteria. This function isapplied to the models immediately after initialization.
# custom weights initialization called on netG and netD def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0)
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
Generator~~~~~~~~~The generator, $G$, is designed to map the latent space vector($z$) to data-space. Since our data are images, converting$z$ to data-space means ultimately creating a RGB image with thesame size as the training images (i.e. 3x64x64). In practice, this isaccomplished through a series of strided two dimensional convolutionaltranspose layers, each paired with a 2d batch norm layer and a reluactivation. The output of the generator is fed through a tanh functionto return it to the input data range of $[-1,1]$. It is worthnoting the existence of the batch norm functions after theconv-transpose layers, as this is a critical contribution of the DCGANpaper. These layers help with the flow of gradients during training. Animage of the generator from the DCGAN paper is shown below... figure:: /_static/img/dcgan_generator.png :alt: dcgan_generatorNotice, the how the inputs we set in the input section (*nz*, *ngf*, and*nc*) influence the generator architecture in code. *nz* is the lengthof the z input vector, *ngf* relates to the size of the feature mapsthat are propagated through the generator, and *nc* is the number ofchannels in the output image (set to 3 for RGB images). Below is thecode for the generator.
# Generator Code class Generator(nn.Module): def __init__(self, ngpu): super(Generator, self).__init__() self.ngpu = ngpu self.main = nn.Sequential( # input is Z, going into a convolution nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False), nn.BatchNorm2d(ngf * 8), nn.ReLU(True), # state size. (ngf*8) x 4 x 4 nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 4), nn.ReLU(True), # state size. (ngf*4) x 8 x 8 nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 2), nn.ReLU(True), # state size. (ngf*2) x 16 x 16 nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf), nn.ReLU(True), # state size. (ngf) x 32 x 32 nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False), nn.Tanh() # state size. (nc) x 64 x 64 ) def forward(self, input): return self.main(input)
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
Now, we can instantiate the generator and apply the ``weights_init``function. Check out the printed model to see how the generator object isstructured.
# Create the generator netG = Generator(ngpu).to(device) # Handle multi-gpu if desired if (device.type == 'cuda') and (ngpu > 1): netG = nn.DataParallel(netG, list(range(ngpu))) # Apply the weights_init function to randomly initialize all weights # to mean=0, stdev=0.2. netG.apply(weights_init) # Print the model print(netG)
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
Discriminator~~~~~~~~~~~~~As mentioned, the discriminator, $D$, is a binary classificationnetwork that takes an image as input and outputs a scalar probabilitythat the input image is real (as opposed to fake). Here, $D$ takesa 3x64x64 input image, processes it through a series of Conv2d,BatchNorm2d, and LeakyReLU layers, and outputs the final probabilitythrough a Sigmoid activation function. This architecture can be extendedwith more layers if necessary for the problem, but there is significanceto the use of the strided convolution, BatchNorm, and LeakyReLUs. TheDCGAN paper mentions it is a good practice to use strided convolutionrather than pooling to downsample because it lets the network learn itsown pooling function. Also batch norm and leaky relu functions promotehealthy gradient flow which is critical for the learning process of both$G$ and $D$. Discriminator Code
class Discriminator(nn.Module): def __init__(self, ngpu): super(Discriminator, self).__init__() self.ngpu = ngpu self.main = nn.Sequential( # input is (nc) x 64 x 64 nn.Conv2d(nc, ndf, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf) x 32 x 32 nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 2), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*2) x 16 x 16 nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 4), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*4) x 8 x 8 nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 8), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*8) x 4 x 4 nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False), nn.Sigmoid() ) def forward(self, input): return self.main(input)
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
Now, as with the generator, we can create the discriminator, apply the``weights_init`` function, and print the model’s structure.
# Create the Discriminator netD = Discriminator(ngpu).to(device) # Handle multi-gpu if desired if (device.type == 'cuda') and (ngpu > 1): netD = nn.DataParallel(netD, list(range(ngpu))) # Apply the weights_init function to randomly initialize all weights # to mean=0, stdev=0.2. netD.apply(weights_init) # Print the model print(netD)
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
Loss Functions and Optimizers~~~~~~~~~~~~~~~~~~~~~~~~~~~~~With $D$ and $G$ setup, we can specify how they learnthrough the loss functions and optimizers. We will use the Binary CrossEntropy loss(`BCELoss `__)function which is defined in PyTorch as:\begin{align}\ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad l_n = - \left[ y_n \cdot \log x_n + (1 - y_n) \cdot \log (1 - x_n) \right]\end{align}Notice how this function provides the calculation of both log componentsin the objective function (i.e. $log(D(x))$ and$log(1-D(G(z)))$). We can specify what part of the BCE equation touse with the $y$ input. This is accomplished in the training loopwhich is coming up soon, but it is important to understand how we canchoose which component we wish to calculate just by changing $y$(i.e. GT labels).Next, we define our real label as 1 and the fake label as 0. Theselabels will be used when calculating the losses of $D$ and$G$, and this is also the convention used in the original GANpaper. Finally, we set up two separate optimizers, one for $D$ andone for $G$. As specified in the DCGAN paper, both are Adamoptimizers with learning rate 0.0002 and Beta1 = 0.5. For keeping trackof the generator’s learning progression, we will generate a fixed batchof latent vectors that are drawn from a Gaussian distribution(i.e. fixed_noise) . In the training loop, we will periodically inputthis fixed_noise into $G$, and over the iterations we will seeimages form out of the noise.
# Initialize BCELoss function criterion = nn.BCELoss() # Create batch of latent vectors that we will use to visualize # the progression of the generator fixed_noise = torch.randn(64, nz, 1, 1, device=device) # Establish convention for real and fake labels during training real_label = 1. fake_label = 0. # Setup Adam optimizers for both G and D optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999)) optimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
Training~~~~~~~~Finally, now that we have all of the parts of the GAN framework defined,we can train it. Be mindful that training GANs is somewhat of an artform, as incorrect hyperparameter settings lead to mode collapse withlittle explanation of what went wrong. Here, we will closely followAlgorithm 1 from Goodfellow’s paper, while abiding by some of the bestpractices shown in `ganhacks `__.Namely, we will “construct different mini-batches for real and fake”images, and also adjust G’s objective function to maximize$logD(G(z))$. Training is split up into two main parts. Part 1updates the Discriminator and Part 2 updates the Generator.**Part 1 - Train the Discriminator**Recall, the goal of training the discriminator is to maximize theprobability of correctly classifying a given input as real or fake. Interms of Goodfellow, we wish to “update the discriminator by ascendingits stochastic gradient”. Practically, we want to maximize$log(D(x)) + log(1-D(G(z)))$. Due to the separate mini-batchsuggestion from ganhacks, we will calculate this in two steps. First, wewill construct a batch of real samples from the training set, forwardpass through $D$, calculate the loss ($log(D(x))$), thencalculate the gradients in a backward pass. Secondly, we will constructa batch of fake samples with the current generator, forward pass thisbatch through $D$, calculate the loss ($log(1-D(G(z)))$),and *accumulate* the gradients with a backward pass. Now, with thegradients accumulated from both the all-real and all-fake batches, wecall a step of the Discriminator’s optimizer.**Part 2 - Train the Generator**As stated in the original paper, we want to train the Generator byminimizing $log(1-D(G(z)))$ in an effort to generate better fakes.As mentioned, this was shown by Goodfellow to not provide sufficientgradients, especially early in the learning process. As a fix, weinstead wish to maximize $log(D(G(z)))$. In the code we accomplishthis by: classifying the Generator output from Part 1 with theDiscriminator, computing G’s loss *using real labels as GT*, computingG’s gradients in a backward pass, and finally updating G’s parameterswith an optimizer step. It may seem counter-intuitive to use the reallabels as GT labels for the loss function, but this allows us to use the$log(x)$ part of the BCELoss (rather than the $log(1-x)$part) which is exactly what we want.Finally, we will do some statistic reporting and at the end of eachepoch we will push our fixed_noise batch through the generator tovisually track the progress of G’s training. The training statisticsreported are:- **Loss_D** - discriminator loss calculated as the sum of losses for the all real and all fake batches ($log(D(x)) + log(D(G(z)))$).- **Loss_G** - generator loss calculated as $log(D(G(z)))$- **D(x)** - the average output (across the batch) of the discriminator for the all real batch. This should start close to 1 then theoretically converge to 0.5 when G gets better. Think about why this is.- **D(G(z))** - average discriminator outputs for the all fake batch. The first number is before D is updated and the second number is after D is updated. These numbers should start near 0 and converge to 0.5 as G gets better. Think about why this is.**Note:** This step might take a while, depending on how many epochs yourun and if you removed some data from the dataset.
# Training Loop # Lists to keep track of progress img_list = [] G_losses = [] D_losses = [] iters = 0 print("Starting Training Loop...") # For each epoch for epoch in range(num_epochs): # For each batch in the dataloader for i, data in enumerate(dataloader, 0): ############################ # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z))) ########################### ## Train with all-real batch netD.zero_grad() # Format batch real_cpu = data[0].to(device) b_size = real_cpu.size(0) label = torch.full((b_size,), real_label, dtype=torch.float, device=device) # Forward pass real batch through D output = netD(real_cpu).view(-1) # Calculate loss on all-real batch errD_real = criterion(output, label) # Calculate gradients for D in backward pass errD_real.backward() D_x = output.mean().item() ## Train with all-fake batch # Generate batch of latent vectors noise = torch.randn(b_size, nz, 1, 1, device=device) # Generate fake image batch with G fake = netG(noise) label.fill_(fake_label) # Classify all fake batch with D output = netD(fake.detach()).view(-1) # Calculate D's loss on the all-fake batch errD_fake = criterion(output, label) # Calculate the gradients for this batch errD_fake.backward() D_G_z1 = output.mean().item() # Add the gradients from the all-real and all-fake batches errD = errD_real + errD_fake # Update D optimizerD.step() ############################ # (2) Update G network: maximize log(D(G(z))) ########################### netG.zero_grad() label.fill_(real_label) # fake labels are real for generator cost # Since we just updated D, perform another forward pass of all-fake batch through D output = netD(fake).view(-1) # Calculate G's loss based on this output errG = criterion(output, label) # Calculate gradients for G errG.backward() D_G_z2 = output.mean().item() # Update G optimizerG.step() # Output training stats if i % 50 == 0: print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f' % (epoch, num_epochs, i, len(dataloader), errD.item(), errG.item(), D_x, D_G_z1, D_G_z2)) # Save Losses for plotting later G_losses.append(errG.item()) D_losses.append(errD.item()) # Check how the generator is doing by saving G's output on fixed_noise if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len(dataloader)-1)): with torch.no_grad(): fake = netG(fixed_noise).detach().cpu() img_list.append(vutils.make_grid(fake, padding=2, normalize=True)) iters += 1
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
Results-------Finally, lets check out how we did. Here, we will look at threedifferent results. First, we will see how D and G’s losses changedduring training. Second, we will visualize G’s output on the fixed_noisebatch for every epoch. And third, we will look at a batch of real datanext to a batch of fake data from G.**Loss versus training iteration**Below is a plot of D & G’s losses versus training iterations.
plt.figure(figsize=(10,5)) plt.title("Generator and Discriminator Loss During Training") plt.plot(G_losses,label="G") plt.plot(D_losses,label="D") plt.xlabel("iterations") plt.ylabel("Loss") plt.legend() plt.show()
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
**Visualization of G’s progression**Remember how we saved the generator’s output on the fixed_noise batchafter every epoch of training. Now, we can visualize the trainingprogression of G with an animation. Press the play button to start theanimation.
#%%capture fig = plt.figure(figsize=(8,8)) plt.axis("off") ims = [[plt.imshow(np.transpose(i,(1,2,0)), animated=True)] for i in img_list] ani = animation.ArtistAnimation(fig, ims, interval=1000, repeat_delay=1000, blit=True) HTML(ani.to_jshtml())
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
**Real Images vs. Fake Images**Finally, lets take a look at some real images and fake images side byside.
# Grab a batch of real images from the dataloader real_batch = next(iter(dataloader)) # Plot the real images plt.figure(figsize=(15,15)) plt.subplot(1,2,1) plt.axis("off") plt.title("Real Images") plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=5, normalize=True).cpu(),(1,2,0))) # Plot the fake images from the last epoch plt.subplot(1,2,2) plt.axis("off") plt.title("Fake Images") plt.imshow(np.transpose(img_list[-1],(1,2,0))) plt.show()
_____no_output_____
MIT
PyTorch/Visual-Audio/Torchscript/dcgan_faces_tutorial.ipynb
MitchellTesla/Quantm
MSDS
def msds(N,arr): w_e = 0 e_e = 0 n_e = 0 s_e = 0 nw_e = 0 ne_e = 0 sw_e = 0 se_e = 0 for row in range(arr.shape[0] // N): for col in range(arr.shape[1] // N): f_block = arr[row * N : (row + 1) * N, col * N : (col + 1) * N] # w if col == 0: w_block = np.fliplr(f_block) else: w_block = arr[row * N : (row + 1) * N, (col - 1) * N : col * N] # e if col == arr.shape[1] // N - 1: e_block = np.fliplr(f_block) else: e_block = arr[row * N : (row + 1) * N, (col + 1) * N : (col + 2) * N] # n if row == 0: n_block = np.flipud(f_block) else: n_block = arr[(row - 1) * N : row * N, col * N : (col + 1) * N] # s if row == arr.shape[0] // N - 1: s_block = np.flipud(f_block) else: s_block = arr[(row + 1) * N : (row + 2) * N, col * N : (col + 1) * N] w_d1 = f_block[:, 0] - w_block[:, N-1] e_d1 = f_block[:, N-1] - e_block[:, 0] n_d1 = f_block[0, :] - n_block[N-1, :] s_d1 = f_block[N-1, :] - s_block[0, :] w_d2 = (w_block[:, N-1] - w_block[:, N-2] + f_block[:, 1] - f_block[:, 0]) / 2 e_d2 = (e_block[:, 1] - e_block[:, 0] + f_block[:, N-1] - f_block[:, N-2]) / 2 n_d2 = (n_block[N-1, :] - n_block[N-2, :] + f_block[1, :] - f_block[0, :]) / 2 s_d2 = (s_block[1, :] - s_block[0, :] + f_block[N-1, :] - f_block[N-2, :]) / 2 w_e += np.sum((w_d1 - w_d2) ** 2 ) e_e += np.sum((e_d1 - e_d2) ** 2 ) n_e += np.sum((n_d1 - n_d2) ** 2) s_e += np.sum((s_d1 - s_d2) ** 2) # nw if row == 0 or col == 0: nw_block = np.flipud(np.fliplr(f_block)) else: nw_block = arr[(row - 1) * N : row * N, (col - 1) * N : col * N] # ne if row == 0 or col == arr.shape[1] // N - 1: ne_block = np.flipud(np.fliplr(f_block)) else: ne_block = arr[(row-1) * N : row * N, (col + 1) * N : (col + 2) * N] # sw if row == arr.shape[0] // N -1 or col == 0: sw_block = np.flipud(np.fliplr(f_block)) else: sw_block = arr[row * N : (row+1) * N, (col-1) * N : col * N] # se if row == arr.shape[0]//N-1 or col == arr.shape[0] // N -1: se_block = np.flipud(np.fliplr(f_block)) else: se_block = arr[(row + 1) * N : (row + 2) * N, (col+1) * N : (col + 2) * N] nw_g1 = f_block[0, 0] - nw_block[N-1, N-1] ne_g1 = f_block[0, N-1] - ne_block[N-1, 0] sw_g1 = f_block[N-1, 0] - sw_block[0, N-1] se_g1 = f_block[N-1, N-1] - se_block[0, 0] nw_g2 = (nw_block[N-1,N-1] - nw_block[N-2,N-2] + f_block[1,1] - f_block[0,0])/2 ne_g2 = (ne_block[N-1,0] - ne_block[N-2,1] + f_block[1,N-2] - f_block[0,N-1])/2 sw_g2 = (sw_block[0,N-1] - nw_block[1,N-2] + f_block[N-2,1] - f_block[N-1,0])/2 se_g2 = (nw_block[0,0] - nw_block[1,1] + f_block[N-2,N-2] - f_block[N-1,N-1])/2 nw_e += (nw_g1 - nw_g2) ** 2 ne_e += (ne_g1 - ne_g2) ** 2 sw_e += (sw_g1 - sw_g2) ** 2 se_e += (se_g1 - se_g2) ** 2 MSDSt = (w_e + e_e + n_e + s_e + nw_e + ne_e + sw_e + se_e)/ ((arr.shape[0]/N)**2) MSDS1 = (w_e + e_e + n_e + s_e)/ ((arr.shape[0]/N)**2) MSDS2 = (nw_e + ne_e + sw_e + se_e)/ ((arr.shape[0]/N)**2) return MSDSt, MSDS1, MSDS2 class DMLCT: def __init__(self, n_bar, N): self.n_bar = n_bar self.N = N self.x_l = (2 * np.arange(N) + 1) / (2 * N) self.s_l = np.arange(n_bar) / (n_bar - 1) self.xi = (np.arange(n_bar + 1) - 0.5) / (n_bar - 1) self.lambda_kh = self.get_lambda_kh(self.n_bar) self.w_k_j = self.get_w_k_j(self.n_bar, self.N) self.W_L_k_kh = self.get_W_L_k_kh(self.n_bar, self.N) self.W_k_kh = self.get_W_k_kh(self.n_bar, self.N) self.W_R_k_kh = self.get_W_R_k_kh(self.n_bar, self.N) def Lagrange_j(self, j): x = sympy.Symbol("x") L_x = 1.0 for l in range(self.n_bar): if l != j: L_x *= (x - self.s_l[l]) / (self.s_l[j] - self.s_l[l]) return sympy.integrate(L_x) def get_lambda_kh(self, n_bar): lambda_kh = np.ones(n_bar) lambda_kh[0] = np.sqrt(1 / 2) return lambda_kh def get_w_k_j(self, n_bar, N): L_j = np.zeros((n_bar, N)) x = sympy.Symbol("x") for j in range(n_bar): temp = [] Lj = self.Lagrange_j(j) for k in range(N): temp.append(Lj.subs(x, self.x_l[k])) L_j[j] = np.array(temp) w_k_j = np.zeros((n_bar, N)) for j in range(n_bar): w_k_j[j] = scipy.fftpack.dct(L_j[j], norm="ortho") return w_k_j def get_W_L_k_kh(self, n_bar, N): W_L_k_kh = np.zeros((n_bar - 1, N)) lambda_kh = self.get_lambda_kh(n_bar) for kh in range(n_bar - 1): W_L_k_kh[kh] = ( (1 - n_bar) * np.sqrt(2 / N) * lambda_kh[kh] * np.cos(np.pi * kh * (self.xi[0] + 1)) * self.w_k_j[0] ) return W_L_k_kh def get_W_k_kh(self, n_bar, N): W_k_kh = np.zeros((n_bar - 1, N)) for kh in range(n_bar - 1): sum_sin = np.zeros(N) for j in range(1, n_bar - 2 + 1): sum_sin += np.sin(np.pi * kh * self.s_l[j]) * self.w_k_j[j] W_k_kh[kh] = ( (n_bar - 1) * np.sqrt(2 / N) * self.lambda_kh[kh] * ( np.cos(np.pi * kh * self.xi[1]) * (self.w_k_j[0] - (-1) ** (kh) * self.w_k_j[n_bar - 1]) - 2 * np.sin((np.pi * kh) / (2 * (n_bar - 1))) * sum_sin ) ) return W_k_kh def get_W_R_k_kh(self, n_bar, N): W_R_k_kh = np.zeros((n_bar - 1, N)) for kh in range(n_bar - 1): W_R_k_kh[kh] = ( (n_bar - 1) * np.sqrt(2 / N) * self.lambda_kh[kh] * np.cos(np.pi * kh * (self.xi[n_bar] - 1)) * self.w_k_j[n_bar - 1] ) return W_R_k_kh def get_F_L_k_horizontal(arr, N, row, col): # w if col == 0: # w_block = np.zeros(N) w_block = arr[row, col * N : (col + 1) * N] else: w_block = arr[row, (col - 1) * N : col * N] return w_block def get_F_R_k_horizontal(arr, N, row, col): # e if col == arr.shape[1] // N - 1: # e_block = np.zeros(N) e_block = arr[row, col * N : (col + 1) * N] else: e_block = arr[row, (col + 1) * N : (col + 2) * N] return e_block def get_F_L_k_vertical(arr, N, row, col): # n if row == 0: # n_block = np.zeros(N) n_block = arr[row * N : (row + 1) * N, col] else: n_block = arr[(row - 1) * N : row * N, col] return n_block def get_F_R_k_vertical(arr, N, row, col): # s if row == arr.shape[0] // N - 1: # s_block = np.zeros(N) s_block = arr[row * N : (row + 1) * N, col] else: s_block = arr[(row + 1) * N : (row + 2) * N, col] return s_block # dmlct = DMLCT(n_bar, N) IMG = AIRPLANE # IMG = ImageLoader(MONO_DIR_PATH + "LENNA.bmp") Fk = np.zeros(IMG.img.shape)
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
順変換 縦方向 DCT
for row in range(IMG.img.shape[0] // N): for col in range(IMG.img.shape[1]): eight_points = IMG.img[N * row : N * (row + 1), col] c = scipy.fftpack.dct(eight_points, norm="ortho") Fk[N * row : N * (row + 1), col] = c
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
残差
dmlct = DMLCT(n_bar, N) for row in range(IMG.img.shape[0] // N): for col in range(IMG.img.shape[1]): # ビューなら直接いじっちゃう F = Fk[N * row : N * (row + 1), col] F_L = get_F_L_k_vertical(Fk, N, row, col) F_R = get_F_R_k_vertical(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range(n_bar - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) # n_bar = 4 なら 0,1,2は残す 3,4,5,6,7を書き換える F[n_bar - 2 + 1 :] -= U_k_n_bar[n_bar - 2 + 1 :] # 0を残す for k in reversed(range(1, n_bar - 2 + 1)): dmlct = DMLCT(k+1, N) for row in range(IMG.img.shape[0] // N): for col in range(IMG.img.shape[1]): # ビューなら直接いじっちゃう F = Fk[N * row : N * (row + 1), col] F_L = get_F_L_k_vertical(Fk, N, row, col) F_R = get_F_R_k_vertical(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range((k + 1) - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) F[k] -= U_k_n_bar[k]
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
横方向 DCT
for row in range(Fk.shape[0]): for col in range(Fk.shape[1] // N): eight_points = Fk[row, N * col : N * (col + 1)] c = scipy.fftpack.dct(eight_points, norm="ortho") Fk[row, N * col : N * (col + 1)] = c
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
残差
dmlct = DMLCT(n_bar, N) for row in range(IMG.img.shape[0]): for col in range(IMG.img.shape[1] // N): F = Fk[row, N * col : N * (col + 1)] F_L = get_F_L_k_horizontal(Fk, N, row, col) F_R = get_F_R_k_horizontal(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range(n_bar - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) # n_bar = 4 なら 0,1,2は残す 3,4,5,6,7を書き換える F[n_bar - 2 + 1 :] -= U_k_n_bar[n_bar - 2 + 1 :] # 0を残す for k in reversed(range(1, n_bar - 2 + 1)): dmlct = DMLCT(k+1, N) for row in range(IMG.img.shape[0]): for col in range(IMG.img.shape[1] // N): F = Fk[row, N * col : N * (col + 1)] F_L = get_F_L_k_horizontal(Fk, N, row, col) F_R = get_F_R_k_horizontal(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range((k + 1) - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) F[k] -= U_k_n_bar[k] plt.imshow(Fk) pd.DataFrame(Fk).to_csv("DMLCT_lenna_hiroya_coef.csv",header=False,index=False)
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
係数の確保
Fk_Ori = np.copy(Fk)
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
逆変換
recover = np.zeros(IMG.img.shape)
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
横方向 残差
for k in range(1, n_bar - 2 + 1): dmlct = DMLCT(k+1, N) for row in range(IMG.img.shape[0]): for col in range(IMG.img.shape[1] // N): F = Fk[row, N * col : N * (col + 1)] F_L = get_F_L_k_horizontal(Fk, N, row, col) F_R = get_F_R_k_horizontal(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range((k + 1) - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) F[k] += U_k_n_bar[k] dmlct = DMLCT(n_bar, N) for row in range(IMG.img.shape[0]): for col in range(IMG.img.shape[1] // N): F = Fk[row, N * col : N * (col + 1)] F_L = get_F_L_k_horizontal(Fk, N, row, col) F_R = get_F_R_k_horizontal(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range(n_bar - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) # n_bar = 4 なら 0,1,2は残す 3,4,5,6,7を書き換える F[n_bar - 2 + 1 :] += U_k_n_bar[n_bar - 2 + 1 :]
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
IDCT
for row in range(Fk.shape[0]): for col in range(Fk.shape[1] // N): F = Fk[row, N * col : N * col + N] data = scipy.fftpack.idct(F, norm="ortho") # Fkに代入した後、縦方向に対して処理 Fk[row, N * col : N * col + N] = data
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
縦方向 残差
for k in range(1, n_bar - 2 + 1): dmlct = DMLCT(k+1, N) for row in range(IMG.img.shape[0] // N): for col in range(IMG.img.shape[1]): # ビューなら直接いじっちゃう F = Fk[N * row : N * (row + 1), col] F_L = get_F_L_k_vertical(Fk, N, row, col) F_R = get_F_R_k_vertical(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range((k + 1) - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) F[k] += U_k_n_bar[k] dmlct = DMLCT(n_bar, N) for row in range(IMG.img.shape[0] // N): for col in range(IMG.img.shape[1]): # ビューなら直接いじっちゃう F = Fk[N * row : N * (row + 1), col] F_L = get_F_L_k_vertical(Fk, N, row, col) F_R = get_F_R_k_vertical(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range(n_bar - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) # n_bar = 4 なら 0,1,2は残す 3,4,5,6,7を書き換える F[n_bar - 2 + 1 :] += U_k_n_bar[n_bar - 2 + 1 :]
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
IDCT
for row in range(Fk.shape[0] // N): for col in range(Fk.shape[1]): F = Fk[N * row : N * (row + 1), col] data = scipy.fftpack.idct(F, norm="ortho") # 復元画像 recover[N * row : N * (row + 1), col] = data plt.imshow(recover.astype("u8"), cmap="gray")
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
もどった...! 量子化テーブル
Q50_Luminance = np.array( [ [16, 11, 10, 16, 24, 40, 51, 61], [12, 12, 14, 19, 26, 58, 60, 55], [14, 13, 16, 24, 40, 57, 69, 56], [14, 17, 22, 29, 51, 87, 80, 62], [18, 22, 37, 56, 68, 109, 103, 77], [24, 35, 55, 64, 81, 104, 113, 92], [49, 64, 78, 87, 103, 121, 120, 101], [72, 92, 95, 98, 112, 100, 103, 99], ] ) for i in tqdm_notebook(np.arange(1,10000,1)): Q = i / 100 Q_Luminance = np.copy(Q50_Luminance) if Q < 50: Q_Luminance = Q_Luminance * 50 / Q Q_Luminance = np.where(Q_Luminance > 255, 255, Q_Luminance) else: Q_Luminance = (100 - Q) * Q50_Luminance / 50 Q_Luminance = np.where(Q_Luminance < 1, 1, Q_Luminance)
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
量子化
Fk = np.copy(Fk_Ori) Q_Fk = np.zeros(Fk.shape) for row in range(IMG.img.shape[0] // N): for col in range(IMG.img.shape[1] // N): block = Fk[row * N : (row + 1) * N, col * N : (col + 1) * N] # 量子化 block = np.round(block / Q_Luminance) # 逆量子化 block = block * Q_Luminance Q_Fk[row * N : (row+1)*N, col * N : (col+1)*N] = block Fk = np.copy(Q_Fk) Q_recover = np.zeros(Q_Fk.shape)
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
横方向 残差
for k in range(1, n_bar - 2 + 1): dmlct = DMLCT(k+1, N) for row in range(IMG.img.shape[0]): for col in range(IMG.img.shape[1] // N): F = Fk[row, N * col : N * (col + 1)] F_L = get_F_L_k_horizontal(Fk, N, row, col) F_R = get_F_R_k_horizontal(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range((k + 1) - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) F[k] += U_k_n_bar[k] dmlct = DMLCT(n_bar, N) for row in range(IMG.img.shape[0]): for col in range(IMG.img.shape[1] // N): F = Fk[row, N * col : N * (col + 1)] F_L = get_F_L_k_horizontal(Fk, N, row, col) F_R = get_F_R_k_horizontal(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range(n_bar - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) # n_bar = 4 なら 0,1,2は残す 3,4,5,6,7を書き換える F[n_bar - 2 + 1 :] += U_k_n_bar[n_bar - 2 + 1 :]
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
IDCT
for row in range(Fk.shape[0]): for col in range(Fk.shape[1] // N): F = Fk[row, N * col : N * col + N] data = scipy.fftpack.idct(F, norm="ortho") # Fkに代入した後、縦方向に対して処理 Fk[row, N * col : N * col + N] = data
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
縦方向 残差
for k in range(1, n_bar - 2 + 1): dmlct = DMLCT(k+1, N) for row in range(IMG.img.shape[0] // N): for col in range(IMG.img.shape[1]): # ビューなら直接いじっちゃう F = Fk[N * row : N * (row + 1), col] F_L = get_F_L_k_vertical(Fk, N, row, col) F_R = get_F_R_k_vertical(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range((k + 1) - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) F[k] += U_k_n_bar[k] dmlct = DMLCT(n_bar, N) for row in range(IMG.img.shape[0] // N): for col in range(IMG.img.shape[1]): # ビューなら直接いじっちゃう F = Fk[N * row : N * (row + 1), col] F_L = get_F_L_k_vertical(Fk, N, row, col) F_R = get_F_R_k_vertical(Fk, N, row, col) U_k_n_bar = np.zeros(N) for kh in range(n_bar - 2 + 1): U_k_n_bar += ( F_L[kh] * dmlct.W_L_k_kh[kh] + F[kh] * dmlct.W_k_kh[kh] + F_R[kh] * dmlct.W_R_k_kh[kh] ) # n_bar = 4 なら 0,1,2は残す 3,4,5,6,7を書き換える F[n_bar - 2 + 1 :] += U_k_n_bar[n_bar - 2 + 1 :]
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
IDCT
for row in range(Fk.shape[0] // N): for col in range(Fk.shape[1]): F = Fk[N * row : N * (row + 1), col] data = scipy.fftpack.idct(F, norm="ortho") # 復元画像 Q_recover[N * row : N * (row + 1), col] = data Q_recover = np.round(Q_recover) plt.imshow(Q_recover, cmap="gray") plt.imsave("DMLCT_8x8_n"+str(n_bar)+ "_LENNA.png",Q_recover,cmap="gray")
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
情報量
qfk = pd.Series(Q_Fk.flatten()) pro = qfk.value_counts() / qfk.value_counts().sum() pro.head() S = 0 for pi in pro: S -= pi * np.log2(pi) S
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
PSNR
MSE = np.sum(np.sum(np.power((IMG.img - Q_recover),2)))/(Q_recover.shape[0] * Q_recover.shape[1]) PSNR = 10 * np.log10(255 * 255 / MSE) PSNR
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
MSSIM
MSSIM = ssim(IMG.img,Q_recover.astype(IMG.img.dtype),gaussian_weights=True,sigma=1.5,K1=0.01,K2=0.03) MSSIM dmlct = DMLCT(n_bar, N)
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
MSDS
MSDSt, MSDS1, MSDS2 = msds(N,Q_recover) MSDS1 MSDS2
_____no_output_____
MIT
DMLCT/8x8/DMLCT.ipynb
Hiroya-W/Python_DCT
Line Charts------ Tutorial---
# mounting drive from google.colab import drive drive.mount("/content/drive") # Importing libraries import pandas as pd pd.plotting.register_matplotlib_converters() import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns # Loading Data spotify_data = pd.read_csv("/content/drive/MyDrive/Colab Notebooks/Kaggle_Courses/03 Data Visualization/spotify.csv", index_col="Date", parse_dates=True) spotify_data
_____no_output_____
MIT
02 Line charts.ipynb
Bluelord/DataCamp_courses
Plot the data
# Sixe of plot plt.figure(figsize=(15,8)) # Line chart showing daily global streams of each song sns.lineplot(data=spotify_data)
_____no_output_____
MIT
02 Line charts.ipynb
Bluelord/DataCamp_courses
As you can see above, the line of code is relatively short and has two main components:- `sns.lineplot` tells the notebook that we want to create a line chart. - _Every command that you learn about in this course will start with `sns`, which indicates that the command comes from the [seaborn](https://seaborn.pydata.org/) package. For instance, we use `sns.lineplot` to make line charts. Soon, you'll learn that we use `sns.barplot` and `sns.heatmap` to make bar charts and heatmaps, respectively._- `data=spotify_data` selects the data that will be used to create the chart.Note that you will always use this same format when you create a line chart, and **_the only thing that changes with a new dataset is the name of the dataset_**. So, if you were working with a different dataset named `financial_data`, for instance, the line of code would appear as follows:```sns.lineplot(data=financial_data)```Sometimes there are additional details we'd like to modify, like the size of the figure and the title of the chart. Each of these options can easily be set with a single line of code.
# Set the width and height of the figure plt.figure(figsize=(14,6)) # Add title plt.title("Daily Global Streams of Popular Songs in 2017-2018") # Line chart showing daily global streams of each song sns.lineplot(data=spotify_data)
_____no_output_____
MIT
02 Line charts.ipynb
Bluelord/DataCamp_courses
The first line of code sets the size of the figure to `14` inches (in width) by `6` inches (in height). To set the size of _any figure_, you need only copy the same line of code as it appears. Then, if you'd like to use a custom size, change the provided values of `14` and `6` to the desired width and height.The second line of code sets the title of the figure. Note that the title must *always* be enclosed in quotation marks (`"..."`)! Plot a subset of the dataSo far, you've learned how to plot a line for _every_ column in the dataset. In this section, you'll learn how to plot a _subset_ of the columns.We'll begin by printing the names of all columns. This is done with one line of code and can be adapted for any dataset by just swapping out the name of the dataset (in this case, `spotify_data`).
list(spotify_data.columns) # Set the width and height of the figure plt.figure(figsize=(14,6)) # Add title plt.title("Daily Global Streams of Popular Songs in 2017-2018") # Line chart showing daily global streams of 'Shape of You' sns.lineplot(data=spotify_data['Shape of You'], label="Shape of You") # Line chart showing daily global streams of 'Despacito' sns.lineplot(data=spotify_data['Despacito'], label="Despacito") # Add label for horizontal axis plt.xlabel("Date")
_____no_output_____
MIT
02 Line charts.ipynb
Bluelord/DataCamp_courses
Exercise ---
data = pd.read_csv("/content/drive/MyDrive/Colab Notebooks/Kaggle_Courses/03 Data Visualization/museum_visitors.csv", index_col="Date", parse_dates=True) # Print the last five rows of the data data.tail(5) # How many visitors did the Chinese American Museum # receive in July 2018? ca_museum_jul18 = 2620 # In October 2018, how many more visitors did Avila # Adobe receive than the Firehouse Museum? avila_oct18 = 19280-4622 # Line chart showing the number of visitors to each museum over time plt.figure(figsize = (12,5)) # Title plt.title('Line chart showing the number of visitors') sns.lineplot(data=data) # Line plot showing the number of visitors to Avila Adobe over time plt.figure(figsize = (12,5)) sns.lineplot(data = data['Avila Adobe']) plt.title('number of visitors to Avila Adobe') plt.xlabel('Date') plt.ylabel('No. of Visitors') plt.show()
_____no_output_____
MIT
02 Line charts.ipynb
Bluelord/DataCamp_courses
Numpy template* Cells before the ` [[nbplot]] template` are ignored.* Cells starting with ` [[nbplot]] ignore` are also ignored.* Some variables are substituted in every cell: * `${root_path}`: the working directory when `nbplot` was called. Input files will be relative to this.* Some variables are subtituted in the `[[nbplot]] for i,input in enumerate(inputs)` blocks: * `${i}`: index of the input in the list * `${input.pretty_name}`: truncated path of the file, or 'stdin' * `${input.rel_path}`: path of the file relative to the `root_path`, or `stdin` * `${input.abs_path_or_io}`: full filepath or StringIO when the data comes from stdin * `${input.guessed_sep}`: separator guessed by nbplot for this file. Usually space or comma.
# [[nbplot]] template # Note: don't change that first line, it tells nbplot that the notebook below is a template # This cell will be executed and the metadata dictionary loaded, but not included in the output. template_metadata = { 'name': 'numpy', 'format_version': '0.1' } import io, math, os, sys from base64 import b64decode # for stdin from pathlib import Path import matplotlib.pyplot as plt import numpy as np import mplcursors # for interactive plot cursors # Transform x,y into a smooth x,y with splines (similar to gnuplot csplines) # Sample usage: ax.plot(*csplines(x,y)) # Don't forget the * to expand the output (x,y) tuple! def csplines(x,y): from scipy.interpolate import make_interp_spline spl = make_interp_spline(x, y, 3) x_smooth = np.linspace(x[0], x[len(x)-1], max(300, len(x)*10)) # at least 10x the number of points return x_smooth, spl(x_smooth) # None will skip multiple spaces, ' ' will not. def np_delim(delim): return None if delim == ' ' else delim
_____no_output_____
MIT
nbplot/templates/nbplot-numpy.ipynb
nburrus/nbplot
Cheatsheet gnuplot matplotlib |Gnuplot | Matplotlib|| :-- | :-- || `with lines` | `default` or `ax.plot(..., '-')` || `with linespoints` | `ax.plot(..., '.-')` || `with points` | `ax.plot(..., '.')` || `smooth csplines` | `ax.plot(*csplines(x,y))` || `using 1:2` | `ax.plot(data[:,0], data[:,1])` || `using 0:1` | `ax.plot(data[:,0])` |
# interactive mode by default %matplotlib notebook #%matplotlib inline plt.ioff() # show the figure only at the end to avoid postponing potential loading errors fig,ax = plt.subplots(figsize=(8,6), num='MyWindow') #fig.suptitle('MyPlot') #ax.set_title('My Title') #ax.set_xlabel('x') #ax.set_ylabel('y') root_path = Path("$root_path") # [[nbplot]] for i,input in enumerate(inputs) name${i} = "${input.pretty_name}"; file_or_io${i} = ${input.abs_path_or_io} data${i} = np.genfromtxt(file_or_io${i}, dtype=float, comments='#', delimiter=np_delim('${input.guessed_sep}'), skip_header=0) display(data0[:4]) x, y = (data${i}[:,0], data${i}[:,1]) if data${i}.ndim > 1 else (np.arange(0,data${i}.shape[0]), data${i}) ax.plot(x, y, label=name${i}) # [[nbplot]] endfor ax.legend() mplcursors.cursor() # enable the cursors, left click to annotate a point, right click to hide it. plt.show() # show the plot plt.ion(); # restore interactive mode
_____no_output_____
MIT
nbplot/templates/nbplot-numpy.ipynb
nburrus/nbplot
Missing Category Imputation ==> Feature-Engine What is Feature-EngineFeature-Engine is an open source python package that I created at the back of this course. - Feature-Engine includes all the feature engineering techniques described in the course- Feature-Engine works like to Scikit-learn, so it is easy to learn- Feature-Engine allows you to implement specific engineering steps to specific feature subsets- Feature-Engine can be integrated with the Scikit-learn pipeline allowing for smooth model building- **Feature-Engine allows you to design and store a feature engineering pipeline with bespoke procedures for different variable groups.**-------------------------------------------------------------------Feature-Engine can be installed via pip ==> pip install feature-engine- Make sure you have installed feature-engine before running this notebookFor more information visit:my website In this demoWe will use Feature-Engine to perform mean or median imputation using the Ames House Price Dataset.- To download the dataset visit the lecture **Datasets** in **Section 1** of the course.
import pandas as pd import numpy as np import matplotlib.pyplot as plt # to split the datasets from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline # from feature-engine from feature_engine.imputation import CategoricalImputer # let's load the dataset with a selected group of variables cols_to_use = [ 'BsmtQual', 'FireplaceQu', 'LotFrontage', 'MasVnrArea', 'GarageYrBlt', 'SalePrice' ] data = pd.read_csv('../houseprice.csv', usecols=cols_to_use) data.head() data.isnull().mean() # let's separate into training and testing set # first drop the target from the feature list cols_to_use.remove('SalePrice') X_train, X_test, y_train, y_test = train_test_split(data[cols_to_use], data['SalePrice'], test_size=0.3, random_state=0) X_train.shape, X_test.shape
_____no_output_____
BSD-3-Clause
04.20-Missing-Category-Imputation-Feature-Engine.ipynb
sri-spirited/feature-engineering-for-ml
Feature-Engine captures the categorical variables automatically
# we call the imputer from featur- engine # we don't need to specify anything imputer = CategoricalImputer() # we fit the imputer imputer.fit(X_train) # we see that the imputer found the categorical variables to # impute with the frequent category imputer.variables
_____no_output_____
BSD-3-Clause
04.20-Missing-Category-Imputation-Feature-Engine.ipynb
sri-spirited/feature-engineering-for-ml
**This imputer will replace missing data in categorical variables by 'Missing'**
# feature-engine returns a dataframe tmp = imputer.transform(X_train) tmp.head() # let's check that the numerical variables don't # contain NA any more tmp[imputer.variables].isnull().mean()
_____no_output_____
BSD-3-Clause
04.20-Missing-Category-Imputation-Feature-Engine.ipynb
sri-spirited/feature-engineering-for-ml
Feature-engine allows you to specify variable groups easily
# let's do it imputation but this time # and let's do it over 1 of the 2 categorical variables imputer = CategoricalImputer(variables=['BsmtQual']) imputer.fit(X_train) # now the imputer uses only the variables we indicated imputer.variables # transform data set tmp = imputer.transform(X_train) tmp.head() tmp[imputer.variables].isnull().mean()
_____no_output_____
BSD-3-Clause
04.20-Missing-Category-Imputation-Feature-Engine.ipynb
sri-spirited/feature-engineering-for-ml
Feature-engine can be used with the Scikit-learn pipeline
# let's check the percentage of NA in each categorical variable X_train.isnull().mean()
_____no_output_____
BSD-3-Clause
04.20-Missing-Category-Imputation-Feature-Engine.ipynb
sri-spirited/feature-engineering-for-ml
- BsmtQual: 0.023 ==> frequent category imputation- FirePlaceQu: 0.46 ==> missing category imputation
pipe = Pipeline([ ('imputer_mode', CategoricalImputer(imputation_method='frequent', variables=['BsmtQual'])), ('imputer_missing', CategoricalImputer(variables=['FireplaceQu'])), ]) pipe.fit(X_train) pipe.named_steps['imputer_mode'].variables pipe.named_steps['imputer_missing'].variables # let's transform the data with the pipeline tmp = pipe.transform(X_train) # let's check null values are gone tmp.isnull().mean()
_____no_output_____
BSD-3-Clause
04.20-Missing-Category-Imputation-Feature-Engine.ipynb
sri-spirited/feature-engineering-for-ml
Now You Code 1: NumberIn this now you code we will learn to re-factor a program into a function. This is the most common way to write a function when you are a beginner. *Re-factoring* is the act of re-writing code without changing its functionality. We commonly do re-factoring to improve performance or readability of our code.The way you do this is rather simple. First you write a program to solve the problem, then you re-write that program as a function and finally test the function to make sure it works as expected. This helps train you to think abstractly about problems, but leverages what you understand currently about programming. First we write the program Write a program to take an input string and convert to a float. If the string cannot be converted to a float it returns the string "NaN" which means "Not a Number" We did this first part for you. Step 1: Problem AnalysisInputs: Any valueOutputs: whether that value is a numberAlgorithm:1. input a value2. try to convert the value to a number3. if you can convert it, print the number4. if you cannot print 'NaN' for Not a number.
## STEP 2 : Write the program text = input("Enter a number: ") try: number = float(text) except ValueError: number = "NaN" print(number)
Enter a number: 5 5.0
MIT
content/lessons/06/Now-You-Code/NYC1-Number.ipynb
cspelz-su/Final-Project
Next we refactor it into a functionComplete this function. It should be similar to the program above, but it should not have any `input()` or `print()` functions as those are reserved for the main program. Functions should take variables as input and return a variable as output. When the function executes, the variables are replaced with actual values. Our function in question takes `text` as input and returns `number` as output.
# Step 3: write the function ## Function: Number ## Argument (input): text value ## Returns (output): float of text value or "NaN" def number(text): # TODO Write code here
_____no_output_____
MIT
content/lessons/06/Now-You-Code/NYC1-Number.ipynb
cspelz-su/Final-Project
Rewrite the program to use the functionFinally re-write the original program to use the new function. The program now works the same as STEP1 but it now uses a function!
## Step 4: write the program from step 2 again, but this time use the function
_____no_output_____
MIT
content/lessons/06/Now-You-Code/NYC1-Number.ipynb
cspelz-su/Final-Project
SelfBuildingModel[www.vexpower.com](www.vexpower.com)
# Set the right folder import sys import os if not os.path.isdir("mmm"): module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import mmm import pandas as pd pd.set_option('display.float_format', lambda x: '%.3f' % x) # suppress scientific notation # Load dataset file_name = "GoolyBib-ABT - Sheet1.csv" data = pd.read_csv('../data/'+file_name) data.head() from IPython.display import display from mmm.clean import make_column_index from mmm.engineer import add_constant from mmm.select import get_all_X_labels, guess_date_column, guess_y_column, guess_media_columns, backwards_feature_elimination, find_best_feature from mmm.build import run_regression, create_results_df, create_pred_df from mmm.validate import calculate_r2 from mmm.display import display_accuracy_chart, save_model, display_contrib_chart, display_decomp_chart class SelfBuildingModel(): def __init__(self, file_name): # load data self.df = pd.read_csv('../data/'+file_name) # Guess labels self.date_label = guess_date_column(self.df) make_column_index(self.df, self.date_label) add_constant(self.df) self.y_label = guess_y_column(self.df) self.X_labels = get_all_X_labels(self.df, self.y_label) self.media_labels = guess_media_columns(self.df) self.base_labels = [l for l in self.X_labels if l not in self.media_labels] # Set placeholders self.coefficients = None self.p_values = None self.error_label = "R2" self.error_func = calculate_r2 self.error_value = None self.y_actual = None self.y_pred = None self.pred_df = None # Self-build model self._ffs() def _ffs(self): self.find() y_label, error_value, X_labels, coefficients = self.fit() save_model(y_label, error_value, X_labels, coefficients) self.show() def find(self): # bfe on base variables base_keep = backwards_feature_elimination(self.df, self.y_label, self.base_labels) # find best adstock and diminishing return rate of each media variable best_media_labels = [] for m in self.media_variables: adstock_columns = add_adstocks(self.df, m) best_adstock_column = find_best_feature(self.df, self.y_label, adstock_columns, base_keep) diminishing_columns = add_diminishing_returns(self.df, best_adstock_column) best_diminishing_column = find_best_feature(self.df, self.y_label, diminishing_columns, base_keep) best_media_labels.append(best_diminishing_column) self.best_X_labels = base_keep + best_media_labels def fit(self): y_actual, y_pred, coefficients, p_values = run_regression(self.df, self.y_label, self.best_X_labels) self.y_actual, self.y_pred, self.coefficients, self.p_values = y_actual, y_pred, coefficients, p_values self.error_value = self.error_func(self.y_actual, self.y_pred) self.results_df = create_results_df(self.X_labels, self.coefficients, self.p_values) self.pred_df = create_pred_df(self.df, self.results_df) return self.y_label, self.error_value, self.X_labels, self.coefficients def show(self): display(self.results_df) display_accuracy_chart(self.y_actual, self.y_pred, self.y_label, accuracy=(self.error_label, self.error_value)) display_contrib_chart(self.pred_df) display_decomp_chart(self.pred_df)
_____no_output_____
MIT
notebooks/SelfBuildingModel.ipynb
hammer-mt/VEX-MMM
pytorch-yolo2 ref: https://github.com/longcw/yolo2-pytorch get model
from darknet import Darknet cfgfile = './cfg/yolo-pose.cfg' weightfile = './backup/cargo/model_backup.weights' weightfile2 = './backup/cargo/model.weights' m = Darknet(cfgfile) m2 = Darknet(cfgfile) m.load_weights(weightfile) m2.load_weights(weightfile2) print('Loading weights from %s... Done!' % (weightfile)) print('Loading weights from %s... Done!' % (weightfile2))
_____no_output_____
MIT
1.yolo2_pytorch_onnx_save_model_v2.ipynb
chenyu36/singleshot6Dpose
save detection information
import pickle op_dict = { 'num_classes':m.num_classes, 'anchors':m.anchors, 'num_anchors':m.num_anchors } pickle.dump(op_dict, open('detection_information.pkl','wb'))
_____no_output_____
MIT
1.yolo2_pytorch_onnx_save_model_v2.ipynb
chenyu36/singleshot6Dpose
use Onnx to convert model ref: https://github.com/onnx/tutorials/blob/master/tutorials/PytorchOnnxExport.ipynb
import torch.onnx from torch.autograd import Variable # Standard ImageNet input - 3 channels, 224x224, # values don't matter as we care about network structure. # But they can also be real inputs. dummy_input = Variable(torch.randn(1, 3, 416, 416)) # Obtain your model, it can be also constructed in your script explicitly model = m model2 = m2 # Invoke export torch.onnx.export(model, dummy_input, "cargo_yolo2.onnx") torch.onnx.export(model2, dummy_input, "cargo_yolo2_v2.onnx")
_____no_output_____
MIT
1.yolo2_pytorch_onnx_save_model_v2.ipynb
chenyu36/singleshot6Dpose
Build TensorRT engine and serialize it
import cv2 import numpy as np from numpy import array import pycuda.driver as cuda import pycuda.autoinit import tensorrt as trt import sys, os sys.path.insert(1, os.path.join(sys.path[0], "..")) import common # You can set the logger severity higher to suppress messages (or lower to display more messages). TRT_LOGGER = trt.Logger(trt.Logger.WARNING) import matplotlib import matplotlib.pyplot as plt %matplotlib inline def get_engine(onnx_file_path, engine_file_path=""): """Attempts to load a serialized engine if available, otherwise builds a new TensorRT engine and saves it.""" def build_engine(): """Takes an ONNX file and creates a TensorRT engine to run inference with""" with trt.Builder(TRT_LOGGER) as builder, builder.create_network() as network, trt.OnnxParser(network, TRT_LOGGER) as parser: builder.max_workspace_size = 1 << 30 # 1GB builder.max_batch_size = 1 # Parse model file if not os.path.exists(onnx_file_path): print('ONNX file {} not found, please run yolov3_to_onnx.py first to generate it.'.format(onnx_file_path)) exit(0) print('Loading ONNX file from path {}...'.format(onnx_file_path)) with open(onnx_file_path, 'rb') as model: print('Beginning ONNX file parsing') parser.parse(model.read()) print('Completed parsing of ONNX file') print('Building an engine from file {}; this may take a while...'.format(onnx_file_path)) engine = builder.build_cuda_engine(network) print("Completed creating Engine") with open(engine_file_path, "wb") as f: f.write(engine.serialize()) return engine if os.path.exists(engine_file_path): # If a serialized engine exists, use it instead of building an engine. print("Reading engine from file {}".format(engine_file_path)) with open(engine_file_path, "rb") as f, trt.Runtime(TRT_LOGGER) as runtime: return runtime.deserialize_cuda_engine(f.read()) else: return build_engine() # Try to load a previously generated yolo network graph in ONNX format: onnx_file_path = './cargo_yolo2.onnx' onnx_file_v2_path = './cargo_yolo2_v2.onnx' engine_file_path = './cargo_yolo2.trt' engine_file_v2_path = './cargo_yolo2_v2.trt' input_image_path = './cargo_sample.jpg' def preprosess_img(img_path): frame = cv2.imread(img_path,0) img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) yolo_img =cv2.resize(img, (416, 416), interpolation=cv2.INTER_AREA) plt.imshow(img) return yolo_img # Do inference with TensorRT trt_outputs = [] with get_engine(onnx_file_v2_path, engine_file_v2_path) as engine, engine.create_execution_context() as context: inputs, outputs, bindings, stream = common.allocate_buffers(engine) print(type(engine)) img = preprosess_img(input_image_path) # Do inference print('Running inference on image {}...'.format(input_image_path)) # Set host input to the image. The common.do_inference function will copy the input to the GPU before executing. inputs[0].host = img trt_outputs = common.do_inference(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream) print(trt_outputs) print(type(trt_outputs)) plt.imshow(img) output_shapes = [(1,20,13,13)] #trt_outputs = [output.reshape(shape) for output, shape in zip(trt_outputs, output_shapes)] trt_outputs = array(trt_outputs).reshape(1,20,13,13) # print('trt_outputs type', type(trt_outputs)) print('trt outputs shape ', trt_outputs.shape)
trt outputs shape (1, 20, 13, 13)
MIT
1.yolo2_pytorch_onnx_save_model_v2.ipynb
chenyu36/singleshot6Dpose
Automatic Feature SelectionOften we collected many features that might be related to a supervised prediction task, but we don't know which of them are actually predictive. To improve interpretability, and sometimes also generalization performance, we can use automatic feature selection to select a subset of the original features. There are several types of feature selection methods available, which we'll explain in order of increasing complexity.For a given supervised model, the best feature selection strategy would be to try out each possible subset of the features, and evaluate generalization performance using this subset. However, there are exponentially many subsets of features, so this exhaustive search is generally infeasible. The strategies discussed below can be thought of as proxies for this infeasible computation. Univariate statisticsThe simplest method to select features is using univariate statistics, that is by looking at each feature individually and running a statistical test to see whether it is related to the target. This kind of test is also known as analysis of variance (ANOVA).We create a synthetic dataset that consists of the breast cancer data, with an addition of 50 completely random features.
from sklearn.datasets import load_breast_cancer, load_digits from sklearn.model_selection import train_test_split cancer = load_breast_cancer() # get deterministic random numbers rng = np.random.RandomState(42) noise = rng.normal(size=(len(cancer.data), 50)) # add noise features to the data # the first 30 features are from the dataset, the next 50 are noise X_w_noise = np.hstack([cancer.data, noise]) X_train, X_test, y_train, y_test = train_test_split( X_w_noise, cancer.target, random_state=0, test_size=.5)
_____no_output_____
CC0-1.0
notebooks/20 Feature Selection.ipynb
jlgorman/scipy-2016-sklearn
We have to define a threshold on the p-value of the statistical test to decide how many features to keep. There are several strategies implemented in scikit-learn, a straight-forward one being ``SelectPercentile``, which selects a percentile of the original features (we select 50% below):
from sklearn.feature_selection import SelectPercentile # use f_classif (the default) and SelectPercentile to select 50% of features: select = SelectPercentile(percentile=50) select.fit(X_train, y_train) # transform training set: X_train_selected = select.transform(X_train) print(X_train.shape) print(X_train_selected.shape)
_____no_output_____
CC0-1.0
notebooks/20 Feature Selection.ipynb
jlgorman/scipy-2016-sklearn
We can also use the test statistic directly to see how relevant each feature is. As the breast cancer dataset is a classification task, we use f_classif, the F-test for classification. Below we plot the p-values associated with each of the 80 features (30 original features + 50 noise features). Low p-values indicate informative features.
from sklearn.feature_selection import f_classif, f_regression, chi2 F, p = f_classif(X_train, y_train) plt.figure() plt.plot(p, 'o')
_____no_output_____
CC0-1.0
notebooks/20 Feature Selection.ipynb
jlgorman/scipy-2016-sklearn
Clearly most of the first 30 features have very small p-values.Going back to the SelectPercentile transformer, we can obtain the features that are selected using the ``get_support`` method:
mask = select.get_support() print(mask) # visualize the mask. black is True, white is False plt.matshow(mask.reshape(1, -1), cmap='gray_r')
_____no_output_____
CC0-1.0
notebooks/20 Feature Selection.ipynb
jlgorman/scipy-2016-sklearn
Nearly all of the original 30 features were recovered.We can also analize the utility of the feature selection by training a supervised model on the data.It's important to learn the feature selection only on the training set!
from sklearn.linear_model import LogisticRegression # transform test data: X_test_selected = select.transform(X_test) lr = LogisticRegression() lr.fit(X_train, y_train) print("Score with all features: %f" % lr.score(X_test, y_test)) lr.fit(X_train_selected, y_train) print("Score with only selected features: %f" % lr.score(X_test_selected, y_test))
_____no_output_____
CC0-1.0
notebooks/20 Feature Selection.ipynb
jlgorman/scipy-2016-sklearn
Model-based Feature SelectionA somewhat more sophisticated method for feature selection is using a supervised machine learning model, and selecting features based on how important they were deemed by the model. This requires the model to provide some way to rank the features by importance. This can be done for all tree-based models (which implement ``get_feature_importances``) and all linear models, for which the coefficients can be used to determine how much influence a feature has on the outcome.Any of these models can be made into a transformer that does feature selection by wrapping it with the ``SelectFromModel`` class:
from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import RandomForestClassifier select = SelectFromModel(RandomForestClassifier(n_estimators=100, random_state=42), threshold="median") select.fit(X_train, y_train) X_train_rf = select.transform(X_train) print(X_train.shape) print(X_train_rf.shape) mask = select.get_support() # visualize the mask. black is True, white is False plt.matshow(mask.reshape(1, -1), cmap='gray_r') X_test_rf = select.transform(X_test) LogisticRegression().fit(X_train_rf, y_train).score(X_test_rf, y_test)
_____no_output_____
CC0-1.0
notebooks/20 Feature Selection.ipynb
jlgorman/scipy-2016-sklearn
This method builds a single model (in this case a random forest) and uses the feature importances from this model.We can do a somewhat more elaborate search by training multiple models on subsets of the data. One particular strategy is recursive feature elimination: Recursive Feature EliminationRecursive feature elimination builds a model on the full set of features, and similar to the method above selects a subset of features that are deemed most important by the model. However, usually only a single feature is dropped from the dataset, and a new model is build on the remaining features. The process of dropping features and model building is repeated until there are only a pre-specified number of features left:
from sklearn.feature_selection import RFE select = RFE(RandomForestClassifier(n_estimators=100, random_state=42), n_features_to_select=40) select.fit(X_train, y_train) # visualize the selected features: mask = select.get_support() plt.matshow(mask.reshape(1, -1), cmap='gray_r') X_train_rfe = select.transform(X_train) X_test_rfe = select.transform(X_test) LogisticRegression().fit(X_train_rfe, y_train).score(X_test_rfe, y_test) select.score(X_test, y_test)
_____no_output_____
CC0-1.0
notebooks/20 Feature Selection.ipynb
jlgorman/scipy-2016-sklearn
Exercises Plot the "XOR" dataset which is created like this:
xx, yy = np.meshgrid(np.linspace(-3, 3, 50), np.linspace(-3, 3, 50)) rng = np.random.RandomState(0) X = rng.randn(200, 2) Y = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0)
_____no_output_____
CC0-1.0
notebooks/20 Feature Selection.ipynb
jlgorman/scipy-2016-sklearn
Demo: Wrapped single_run_processThe basic steps to set up an OpenCLSim simulation are:* Import libraries* Initialise simpy environment* Define object classes* Create objects * Create sites * Create vessels * Create activities* Register processes and run simpy----This notebook provides an example of a single_run_process. In the single_run_process a typical "loading-sailing full-unloading-sailing empty" is pre-packed in a while activity. 0. Import libraries
import datetime, time import simpy import shapely.geometry import pandas as pd import openclsim.core as core import openclsim.model as model import openclsim.plot as plot
_____no_output_____
MIT
notebooks/09_wrapped_single_run_process.ipynb
TUDelft-CITG/Hydraulic-Infrastructure-Realisation
1. Initialise simpy environment
# setup environment simulation_start = 0 my_env = simpy.Environment(initial_time=simulation_start)
_____no_output_____
MIT
notebooks/09_wrapped_single_run_process.ipynb
TUDelft-CITG/Hydraulic-Infrastructure-Realisation
2. Define object classes
# create a Site object based on desired mixin classes Site = type( "Site", ( core.Identifiable, core.Log, core.Locatable, core.HasContainer, core.HasResource, ), {}, ) # create a TransportProcessingResource object based on desired mixin classes TransportProcessingResource = type( "TransportProcessingResource", ( core.Identifiable, core.Log, core.ContainerDependentMovable, core.Processor, core.HasResource, core.LoadingFunction, core.UnloadingFunction, ), {}, )
_____no_output_____
MIT
notebooks/09_wrapped_single_run_process.ipynb
TUDelft-CITG/Hydraulic-Infrastructure-Realisation
3. Create objects 3.1. Create site object(s)
# prepare input data for from_site location_from_site = shapely.geometry.Point(4.18055556, 52.18664444) data_from_site = {"env": my_env, "name": "from_site", "geometry": location_from_site, "capacity": 10_000, "level": 10_000 } # instantiate from_site from_site = Site(**data_from_site) # prepare input data for to_site location_to_site = shapely.geometry.Point(4.25222222, 52.11428333) data_to_site = {"env": my_env, "name": "to_site", "geometry": location_to_site, "capacity": 10_000, "level": 0 } # instantiate to_site to_site = Site(**data_to_site)
_____no_output_____
MIT
notebooks/09_wrapped_single_run_process.ipynb
TUDelft-CITG/Hydraulic-Infrastructure-Realisation
3.2. Create vessel object(s)
# prepare input data for vessel_01 data_vessel01 = {"env": my_env, "name": "vessel01", "geometry": location_from_site, "loading_rate": 1, "unloading_rate": 5, "capacity": 1_000, "compute_v": lambda x: 10 + 2 * x } # instantiate vessel_01 vessel01 = TransportProcessingResource(**data_vessel01)
_____no_output_____
MIT
notebooks/09_wrapped_single_run_process.ipynb
TUDelft-CITG/Hydraulic-Infrastructure-Realisation
3.3 Create activity/activities
# initialise registry registry = {} # create a 'while activity' that contains a pre-packed set of 'sub_processes' single_run, while_activity = model.single_run_process( name="single_run", registry={}, env=my_env, origin=from_site, destination=to_site, mover=vessel01, loader=vessel01, unloader=vessel01 )
_____no_output_____
MIT
notebooks/09_wrapped_single_run_process.ipynb
TUDelft-CITG/Hydraulic-Infrastructure-Realisation
4. Register processes and run simpy
# initate the simpy processes defined in the 'while activity' and run simpy model.register_processes([while_activity]) my_env.run()
_____no_output_____
MIT
notebooks/09_wrapped_single_run_process.ipynb
TUDelft-CITG/Hydraulic-Infrastructure-Realisation
5. Inspect results 5.1 Inspect logs
display(plot.get_log_dataframe(vessel01, [*single_run, while_activity])) display(plot.get_log_dataframe(from_site, [*single_run])) display(plot.get_log_dataframe(to_site, [*single_run]))
_____no_output_____
MIT
notebooks/09_wrapped_single_run_process.ipynb
TUDelft-CITG/Hydraulic-Infrastructure-Realisation
5.2 Visualise gantt charts
plot.get_gantt_chart([while_activity, vessel01, *single_run])
_____no_output_____
MIT
notebooks/09_wrapped_single_run_process.ipynb
TUDelft-CITG/Hydraulic-Infrastructure-Realisation
5.3 Visualise step charts
fig = plot.get_step_chart([from_site, to_site, vessel01])
_____no_output_____
MIT
notebooks/09_wrapped_single_run_process.ipynb
TUDelft-CITG/Hydraulic-Infrastructure-Realisation
a) By using Logistic Regression Algorithm Part A: Data Preprocessing Step1 : importing the libraries
import numpy as np import matplotlib.pyplot as plt import pandas as pd
_____no_output_____
MIT
Project 2/PROJECT 2.ipynb
ParadoxPD/Intro-to-machine-learning
step2: import data set
dataset=pd.read_csv('Logistic Data.csv') dataset
_____no_output_____
MIT
Project 2/PROJECT 2.ipynb
ParadoxPD/Intro-to-machine-learning
step3: to create feature matrix and dependent variable vector
a=dataset.iloc[:,:-1].values b=dataset.iloc[:,-1].values a b
_____no_output_____
MIT
Project 2/PROJECT 2.ipynb
ParadoxPD/Intro-to-machine-learning