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
1. Crie uma classe Bola cujos atributos são cor e raio. Crie um método que imprime a cor da bola. Crie um método para calcular a área dessa bola. Crie um método para calcular o volume da bola. Crie um objeto dessa classe e calcule a área e o volume, imprimindo ambos em seguida. Obs.: Área da esfera = 4 * 3.14 * ...
class Bola: ''' Cria a representação de uma bola ''' def __init__(self, cor, raio): ''' Construtor Parâmetros ---------- cor : str cor associada a bola raio : float raio da bola ''' self.cor = cor self.raio =...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
2. Crie uma classe Retângulo cujos atributos são lado_a e lado_b. Crie um método para calcular a área desse retângulo. Crie um objeto dessa classe e calcule a área e a imprima em seguida.
class Retângulo: ''' Cria a representação de um retângulo ''' def __init__(self, lado_a, lado_b): ''' Construtor Parâmetros ---------- lado_a : float medida do primeiro lado do retângulo lado_b : float medida do segundo lado do retâ...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
3. Crie uma classe Funcionario cujos atributos são nome e e-mail. Guarde as horas trabalhadas em um dicionário cujas chaves são o mês em questão e, em outro dicionário, guarde o salário por hora relativo ao mês em questão. Crie um método que retorna o salário mensal do funcionário.
class Funcionario: ''' Cria uma representação do funcionário ''' def __init__(self,nome,email): ''' Construtor Parâmetros ---------- nome : str nome do funcionário email : str email do funcionário ''' self.nome = nom...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
4. Crie uma classe Televisor cujos atributos são: a. fabricante; b. modelo; c. canal atual; d. lista de canais; e e. volume. Faça métodos para aumentar/diminuir volume, trocar o canal e sintonizar um novo canal, que adiciona um novo canal à lista de canais (somente se esse canal não...
class Televisor: ''' Cria uma representação de Televisor ''' def __init__(self, fabricante, modelo): ''' Construtor Parâmetros --------- fabricante : str nome do fabricante do televisor modelo : str modelo do televisor ...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
5. Crie uma classe ControleRemoto cujo atributo é televisão (isso é, recebe um objeto da classe do exercício 4). Crie métodos para aumentar/diminuir volume, trocar o canal e sintonizar um novo canal, que adiciona um novo canal à lista de canais (somente se esse canal não estiver nessa lista).
class ControleRemoto: ''' Cria uma representação do controle remoto ''' def __init__(self, Televisor): ''' Construtor Parâmetros ---------- Televisor : objeto da classe Televisor ''' self.fabricante = Televisor.fabricante self.mode...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
6. O módulo time possui a função time.sleep(x), que faz seu programa “dormir” por x segundos. Utilizando essa função, crie uma classe Cronômetro e faça um programa que cronometre o tempo.
from time import sleep class cronometro: def __init__(self): self.hora = 0 self.minuto = 0 self.segundo = 0 def contagem_progressiva(self): flag = True while flag == True: if self.segundo < 60: self.segundo = self.segundo + 1 ...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
7. Crie uma modelagem de classes para uma agenda capaz de armazenar contatos. Através dessa agenda é possível incluir, remover, buscar e listar contatos já cadastrados.
class Contato: def __init__(self, nome, email, telefone, endereco): ''' Construtor Parâmetros ---------- nome : str nome do contato email : str email do contato telefone : str telefone do contato endereço : ...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
8. Crie uma classe Cliente cujos atributos são nome, idade e e-mail. Construa um método que imprima as informações tal como abaixo: Nome: Fulano de Tal Idade: 40 E-mail: fulano@mail.com
class Cliente: ''' Cria a representação de um cliente ''' def __init__(self, nome, idade, email): ''' Construtor Parâmetros ---------- nome : str nome do cliente idade : int idade do cliente email : str ...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
9. Com base no exercício anterior, crie um sistema de cadastro e a classe Cliente. Seu programa deve perguntar se o usuário quer cadastrar um novo cliente, alterar um cadastro ou sair.Dica: Você pode fazer esse exercício criando uma classe Sistema, que irá controlar o sistema de cadastros. Essa classe deve ter o atrib...
class Cliente: ''' Cria a representação de um cliente ''' def __init__(self, nome, idade, email): ''' Construtor Parâmetros ---------- nome : str nome do cliente idade : int idade do cliente email : str ...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
10. Crie uma classe ContaCorrente com os atributos cliente (que deve ser um objeto da classe Cliente) e saldo. Crie métodos para depósito, saque e transferência. Os métodos de saque e transferência devem verificar se é possível realizar a transação.
class Cliente: ''' Cria representação de um cliente ''' def __init__(self, nome, cpf): ''' Construtor Parâmetro --------- nome : str nome do cliente cpf : str cpf do cliente ''' self.nome = nome.capitalize()...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
11. Crie uma classe Fração cujos atributos são numerador (número de cima) e denominador (número de baixo). Implemente os métodos de adição, subtração, multiplicação, divisão que retornam objetos do tipo Fração.Implemente também o método _ repr _.Implemente métodos para comparação: igualdade (==) e desigualdades (!=, =...
class Fracao: ''' Cria a representação de uma fração ''' def __init__(self, numerador, denominador): ''' Construtor Parâmetros --------- numerador : int numerador da fração denominador : int denominador da fração ''...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
12. Crie uma classe Data cujos atributos são dia, mês e ano. Implemente métodos _ repr _ e para comparação: igualdade (==) e desigualdades (!=, =, ).
class Data: def __init__(self, dia, mes, ano): self.dia = dia self.mes = mes self.ano = ano def __repr__(self): return f'{self.dia}/{self.mes}/{self.ano}' def __eq__(self, other): if (self.dia == other.dia) and (self.mes == other.mes) and (self.ano == other....
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
13. Nos exercícios 1, 2, 3, 4 e 6, implemente o método _ repr _ para exibir as informações desejadas de cada uma das classes.
# Questão 1 class Bola: ''' Cria a representação de uma bola ''' def __init__(self, cor, raio): ''' Construtor Parâmetros ---------- cor : str cor associada a bola raio : float raio da bola ''' self.cor = cor ...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
14. Faça uma classe ContaVip que difere da ContaCorrente por ter cheque especial (novo atributo) e é filha da classe ContaCorrente. Você precisa implementar os métodos para saque, transferência ou depósito?
class Cliente: ''' Cria representação de um cliente ''' def __init__(self, nome, cpf): ''' Construtor Parâmetro --------- nome : str nome do cliente cpf : str cpf do cliente ''' self.nome = nome.capitalize()...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
15. Crie uma classe Quadrado, filha da classe Retângulo do exercício 2.
class Retângulo: ''' Cria a representação de um retângulo ''' def __init__(self, lado_a, lado_b): ''' Construtor Parâmetros ---------- lado_a : float medida do primeiro lado do retângulo lado_b : float medida do segundo lado do retâ...
_____no_output_____
MIT
POO/Lista_Exercicios_POO.ipynb
augustojardim/Degree_DS_Tecnicas_Programacao_I
US Production Data for RBC Modeling
import pandas as pd import numpy as np import fredpy as fp import matplotlib.pyplot as plt plt.style.use('classic') %matplotlib inline pd.plotting.register_matplotlib_converters() # Load API key fp.api_key = fp.load_api_key('fred_api_key.txt') # Download nominal GDP, nominal personal consumption expenditures, nominal ...
Hours units: Index 2012=100 Deflator units: Index 2012=100
MIT
Data/Code/business_cycle_data.ipynb
letsgoexploring/econ126
Next, compute the quarterly capital stock series for the US using the perpetual inventory method. The discrete-time Solow growth model is given by:\begin{align}Y_t & = A_tK_t^{\alpha}L_t^{1-\alpha} \tag{1}\\C_t & = (1-s)Y_t \tag{2}\\Y_t & = C_t + I_t \tag{3}\\K_{t+1} & = I_t + (1-\delta)K_t \tag{4}\\A_{t+1} & = (1+g)A_...
# Set the capital share of income alpha = 0.35 # Average saving rate s = np.mean(invest.data/gdp.data) # Average quarterly labor hours growth rate n = (hours.data[-1]/hours.data[0])**(1/(len(hours.data)-1)) - 1 # Average quarterly real GDP growth rate g = ((gdp.data[-1]/gdp.data[0])**(1/(len(gdp.data)-1)) - 1) - n ...
_____no_output_____
MIT
Data/Code/business_cycle_data.ipynb
letsgoexploring/econ126
Reading QoS analysis raw infoTemporarily, this info is saved in a CSV file but it will be in the database**qos_analysis_13112018.csv**- columns = ['url','protocol','code','start','end','duration','runid']- First try of qos analysis.- It was obtained from 50 repetitions of each of 3921 eepsites gathered. - Just one i2r...
# File for processing it qos_file = 'qos_analysis_13112018.csv' path_to_file = 'data/' + qos_file columns = ['url','protocol','code','start','end','duration','runid'] df_qos = pd.read_csv(path_to_file,names=columns,delimiter="|") # File for processing it - local router qos_file = 'qos_analysis_29112018_local.csv' pat...
_____no_output_____
MIT
notebooks/qos_analysis.ipynb
Abellan09/tfg_crawler_i2p
Availability study
HTTP_RESPONSE_CODES = {200:'OK', 301:'Moved Permanently', 302:'Found (Previously "Moved temporarily")', 400:'Bad Request', 401:'Unauthorized', 403:'Forbidden', 429:'Too Many Requ...
_____no_output_____
MIT
notebooks/qos_analysis.ipynb
Abellan09/tfg_crawler_i2p
Distributed Training of Mask-RCNN in Amazon SageMaker using EFSThis notebook is a step-by-step tutorial on distributed training of [Mask R-CNN](https://arxiv.org/abs/1703.06870) implemented in [TensorFlow](https://www.tensorflow.org/) framework. Mask R-CNN is also referred to as heavy weight object detection model and...
import boto3 session = boto3.session.Session() aws_region = session.region_name s3_bucket = # your-s3-bucket-name try: s3_client = boto3.client('s3') response = s3_client.get_bucket_location(Bucket=s3_bucket) print(f"Bucket region: {response['LocationConstraint']}") except: print(f"Access Error: Che...
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Stage COCO 2017 dataset in Amazon S3We use [COCO 2017 dataset](http://cocodataset.org/home) for training. We download COCO 2017 training and validation dataset to this notebook instance, extract the files from the dataset archives, and upload the extracted files to your Amazon [S3 bucket](https://docs.aws.amazon.com/A...
!cat ./prepare-s3-bucket.sh
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Using your *Amazon S3 bucket* as argument, run the cell below. If you have already uploaded COCO 2017 dataset to your Amazon S3 bucket, you may skip this step.
%%time !./prepare-s3-bucket.sh {s3_bucket}
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Copy COCO 2017 dataset from S3 to Amazon EFSNext, we copy COCO 2017 dataset from S3 to EFS file-system. The ```prepare-efs.sh``` script executes this step.
!cat ./prepare-efs.sh
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
If you have already copied COCO 2017 dataset from S3 to your EFS file-system, skip this step.
%%time !./prepare-efs.sh {s3_bucket}
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Build and push SageMaker training imagesFor this step, the [IAM Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) attached to this notebook instance needs full access to Amazon ECR service. If you created this notebook instance using the ```./stack-sm.sh``` script in this repository, the IAM Role a...
!cat ./container-script-mode/build_tools/build_and_push.sh %%time ! ./container-script-mode/build_tools/build_and_push.sh {aws_region}
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Set ```tensorpack_image``` below to Amazon ECR URI of the image you pushed above.
tensorpack_image = #<amazon-ecr-uri>
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
AWS Samples Mask R-CNNUse ```./container-optimized-script-mode/build_tools/build_and_push.sh``` script to build and push the AWS Samples Mask R-CNN training image to Amazon ECR.
!cat ./container-optimized-script-mode/build_tools/build_and_push.sh
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Using your *AWS region* as argument, run the cell below.
%%time ! ./container-optimized-script-mode/build_tools/build_and_push.sh {aws_region}
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Set ```aws_samples_image``` below to Amazon ECR URI of the image you pushed above.
aws_samples_image = #<amazon-ecr-uri>
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Upgrade SageMaker Python SDKIf needed, upgrade SageMaker Python SDK.
!pip install --upgrade pip !pip install sagemaker
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
SageMaker Initialization We have staged the data and we have built and pushed the training docker image to Amazon ECR. Now we are ready to start using Amazon SageMaker.
%%time import os import time import sagemaker from sagemaker import get_execution_role from sagemaker.tensorflow.estimator import TensorFlow role = get_execution_role() # provide a pre-existing role ARN as an alternative to creating a new role print(f'SageMaker Execution Role:{role}') client = boto3.client('sts') acc...
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Next, we set the Amazon ECR image URI used for training. You saved this URI in a previous step.
training_image = # set to tensorpack_image or aws_samples_image print(f'Training image: {training_image}')
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Define SageMaker Data ChannelsNext, we define the *train* and *log* data channels using EFS file-system. To do so, we need to specify the EFS file-system id, which is shown in the output of the command below.
notebook_attached_efs=!df -kh | grep 'fs-' | sed 's/\(fs-[0-9a-z]*\).*/\1/' print(f"SageMaker notebook attached EFS: {notebook_attached_efs}")
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
In the cell below, we define the `train` data input channel.
from sagemaker.inputs import FileSystemInput # Specify EFS file system id. file_system_id = notebook_attached_efs[0] print(f"EFS file-system-id: {file_system_id}") # Specify directory path for input data on the file system. # You need to provide normalized and absolute path below. file_system_directory_path = '/mask...
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Below we create the log output directory and define the `log` data output channel.
# Specify directory path for log output on the EFS file system. # You need to provide normalized and absolute path below. # For example, '/mask-rcnn/sagemaker/output/log' # Log output directory must not exist file_system_directory_path = f'/mask-rcnn/sagemaker/output/log-{int(time.time())}' # Create the log output dir...
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Next, we define the model output location in S3. Set ```s3_bucket``` to your S3 bucket name prior to running the cell below. The model checkpoints, logs and Tensorboard events will be written to the log output directory on the EFS file system you created above. At the end of the model training, they will be copied from...
prefix = "mask-rcnn/sagemaker" #prefix in your bucket s3_output_location = f's3://{s3_bucket}/{prefix}/output' print(f'S3 model output location: {s3_output_location}')
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Configure Hyper-parametersNext we define the hyper-parameters. Note, some hyper-parameters are different between the two implementations. The batch size per GPU in TensorPack Faster-RCNN/Mask-RCNN is fixed at 1, but is configurable in AWS Samples Mask-RCNN. The learning rate schedule is specified in units of steps in ...
hyperparameters = { "mode_fpn": "True", "mode_mask": "True", "eval_period": 1, "batch_norm": "FreezeBN" }
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Define Training MetricsNext, we define the regular expressions that SageMaker uses to extract algorithm metrics from training logs and send them to [AWS CloudWatch metrics](https://docs.aws.amazon.com/en_pv/AmazonCloudWatch/latest/monitoring/working_with_metrics.html). These algorithm metrics are visualized in SageMak...
metric_definitions=[ { "Name": "fastrcnn_losses/box_loss", "Regex": ".*fastrcnn_losses/box_loss:\\s*(\\S+).*" }, { "Name": "fastrcnn_losses/label_loss", "Regex": ".*fastrcnn_losses/label_loss:\\s*(\\S+).*" }...
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Define SageMaker Training JobNext, we use SageMaker [Tensorflow](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/sagemaker.tensorflow.html) API to define a SageMaker Training Job that uses SageMaker script mode. Select scriptIn script-mode, first we have to select an entry point script that acts as i...
script= # "tensorpack-mask-rcnn.py" or "aws-mask-rcnn.py"
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Select distribution modeWe use Message Passing Interface (MPI) to distribute the training job across multiple hosts. The ```custom_mpi_options``` below is only used by [AWS Samples Mask R-CNN](https://github.com/aws-samples/mask-rcnn-tensorflow) model, and can be safely commented out for [TensorPack Faster-RCNN/Mask-R...
mpi_distribution={'mpi': { 'enabled': True, "custom_mpi_options" : "-x TENSORPACK_FP16=1 " } }
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Define SageMaker Tensorflow EstimatorWe recommned using 32 GPUs, so we set ```instance_count=4``` and ```instance_type='ml.p3.16xlarge'```, because there are 8 Tesla V100 GPUs per ```ml.p3.16xlarge``` instance. We recommend using 100 GB [Amazon EBS](https://aws.amazon.com/ebs/) storage volume with each training instan...
# Give Amazon SageMaker Training Jobs Access to FileSystem Resources in Your Amazon VPC. security_group_ids = # ['sg-xxxxxxxx'] subnets = # [ 'subnet-xxxxxxx'] sagemaker_session = sagemaker.session.Session(boto_session=session) mask_rcnn_estimator = TensorFlow(image_uri=training_image, ...
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Launch training jobFinally, we launch the SageMaker training job. See ```Training Jobs``` in SageMaker console to monitor the training job.
import time job_name=f'mask-rcnn-efs-script-mode-{int(time.time())}' print(f"Launching Training Job: {job_name}") # set wait=True below if you want to print logs in cell output mask_rcnn_estimator.fit(inputs=data_channels, job_name=job_name, logs="All", wait=False)
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-scriptmode-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Exercise 03 - Booleans and Conditionals 1. Simple Function with ConditionalsMany programming languages have [sign](https://en.wikipedia.org/wiki/Sign_function) available as a built-in function. Python does not, but we can define our own!In the cell below, define a function called `sign` which takes a numerical argume...
# Your code goes here. Define a function called 'sign' def sign(num) { return num % 1 }
_____no_output_____
MIT
python-for-data/.ipynb_checkpoints/Ex03 - Booleans and Conditionals-checkpoint.ipynb
cnhhoang850/atom-assignments
2. Singular vs Plural NounsWe've decided to add "print" to our `to_smash` function from Exercise 02
def to_smash(total_candies): """Return the number of leftover candies that must be smashed after distributing the given number of candies evenly between 3 friends. >>> to_smash(91) 1 """ print("Splitting", total_candies, "candies") return total_candies % 3 to_smash(91)
_____no_output_____
MIT
python-for-data/.ipynb_checkpoints/Ex03 - Booleans and Conditionals-checkpoint.ipynb
cnhhoang850/atom-assignments
What happens if we call it with `total_candies = 1`?
to_smash(1)
_____no_output_____
MIT
python-for-data/.ipynb_checkpoints/Ex03 - Booleans and Conditionals-checkpoint.ipynb
cnhhoang850/atom-assignments
**Wrong grammar there!**Modify the definition in the cell below to correct the grammar of our print statement.**Your Task:**> If there's only one candy, we should use the singular "candy" instead of the plural "candies"
def to_smash(total_candies): """Return the number of leftover candies that must be smashed after distributing the given number of candies evenly between 3 friends. >>> to_smash(91) 1 """ print("Splitting", total_candies, "candies") return total_candies % 3 to_smash(91) to_smash(1)
_____no_output_____
MIT
python-for-data/.ipynb_checkpoints/Ex03 - Booleans and Conditionals-checkpoint.ipynb
cnhhoang850/atom-assignments
3. Checking weather againIn the main lesson we talked about deciding whether we're prepared for the weather. I said that I'm safe from today's weather if...- I have an umbrella...- or if the rain isn't too heavy and I have a hood...- otherwise, I'm still fine unless it's raining *and* it's a workdayThe function below ...
def prepared_for_weather(have_umbrella, rain_level, have_hood, is_workday): # Don't change this code. Our goal is just to find the bug, not fix it! return have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday # Change the values of these inputs so they represent a case where prepar...
_____no_output_____
MIT
python-for-data/.ipynb_checkpoints/Ex03 - Booleans and Conditionals-checkpoint.ipynb
cnhhoang850/atom-assignments
4. Start being lazy...The function `is_negative` below is implemented correctly - It returns True if the given number is negative and False otherwise.However, it's more verbose than it needs to be. We can actually reduce the number of lines of code in this function by *75%* while keeping the same behaviour. **Your tas...
def is_negative(number): if number < 0: return True else: return False def concise_is_negative(number): pass # Your code goes here (try to keep it to one line!)
_____no_output_____
MIT
python-for-data/.ipynb_checkpoints/Ex03 - Booleans and Conditionals-checkpoint.ipynb
cnhhoang850/atom-assignments
5. Adding ToppingsThe boolean variables `ketchup`, `mustard` and `onion` represent whether a customer wants a particular topping on their hot dog. We want to implement a number of boolean functions that correspond to some yes-or-no questions about the customer's order. For example:
def onionless(ketchup, mustard, onion): """Return whether the customer doesn't want onions. """ return not onion
_____no_output_____
MIT
python-for-data/.ipynb_checkpoints/Ex03 - Booleans and Conditionals-checkpoint.ipynb
cnhhoang850/atom-assignments
**Your task:**> For each of the remaining functions, fill in the body to match the English description in the docstring.
def wants_all_toppings(ketchup, mustard, onion): """Return whether the customer wants "the works" (all 3 toppings) """ pass def wants_plain_hotdog(ketchup, mustard, onion): """Return whether the customer wants a plain hot dog with no toppings. """ pass def exactly_one_sauce(ketchup, mustard, o...
_____no_output_____
MIT
python-for-data/.ipynb_checkpoints/Ex03 - Booleans and Conditionals-checkpoint.ipynb
cnhhoang850/atom-assignments
6. 🌶️We’ve seen that calling `bool()` on an integer returns `False` if it’s equal to 0 and `True` otherwise. What happens if we call `int()` on a bool? Try it out in the notebook cell below.Can you take advantage of this to write a succinct function that corresponds to the English sentence "*Does the customer want ex...
def exactly_one_topping(ketchup, mustard, onion): """Return whether the customer wants exactly one of the three available toppings on their hot dog. """ pass
_____no_output_____
MIT
python-for-data/.ipynb_checkpoints/Ex03 - Booleans and Conditionals-checkpoint.ipynb
cnhhoang850/atom-assignments
&nbsp; Day 5: Optimal Mind ControlWelcome to Day 5! Now that we can simulate a model network of conductance-based neurons, we discuss the limitations of our approach and attempts to work around these issues. Memory ManagementUsing Python and TensorFlow allowed us to write code that is readable, parallizable and sca...
#@markdown Import required files and code from previous tutorials !wget --no-check-certificate \ "https://raw.githubusercontent.com/neurorishika/PSST/master/Tutorial/Day%205%20Optimal%20Mind%20Control/tf_integrator.py" \ -O "tf_integrator.py" !wget --no-check-certificate \ "https://raw.githubusercontent.com/neur...
_____no_output_____
MIT
Tutorial/Day 5 Optimal Mind Control/Day 5.ipynb
technosap/PSST
Recall the ModelFor implementing a Batch system, we do not need to change how we construct our model only how we execute it. Step 1: Initialize Parameters and Dynamical Equations; Define Input
n_n = 3 # Number of simultaneous neurons to simulate sim_res = 0.01 # Time Resolution of the Simulation sim_time = 700 # Length of the Simulation t = np.arange(0,sim_time,sim_res) # Time points at which to simulate the network # Acetylcholine ach_ma...
_____no_output_____
MIT
Tutorial/Day 5 Optimal Mind Control/Day 5.ipynb
technosap/PSST
Step 2: Define the Initial Condition of the Network and Add some Noise to the initial conditions
# Initializing the State Vector and adding 1% noise state_vector = [-71]*n_n+[0,0,0]*n_n+[0]*n_ach+[0]*n_gaba+[-9999999]*n_n state_vector = np.array(state_vector) state_vector = state_vector + 0.01*state_vector*np.random.normal(size=state_vector.shape)
_____no_output_____
MIT
Tutorial/Day 5 Optimal Mind Control/Day 5.ipynb
technosap/PSST
Step 3: Splitting Time Series into independent batches and Run Each Batch SequentiallySince we will be dividing the computation into batches, we have to split the time array such that for each new call, the final state vector of the last batch will be the initial condition for the current batch. The function $np.array...
# Define the Number of Batches n_batch = 2 # Split t array into batches using numpy t_batch = np.array_split(t,n_batch) # Iterate over the batches of time array for n,i in enumerate(t_batch): # Inform start of Batch Computation print("Batch",(n+1),"Running...",end="") # In np.array_split(), the ...
Batch 1 Running...Finished Batch 2 Running...Finished
MIT
Tutorial/Day 5 Optimal Mind Control/Day 5.ipynb
technosap/PSST
Putting the Output TogetherThe output from our batch implementation is a set of binary files that store parts of our total simulation. To get the overall output we have to stitch them back together.
overall_state = [] # Iterate over the generated output files for n,i in enumerate(["part_"+str(n+1)+".npy" for n in range(n_batch)]): # Since the first element in the series was the last output, we remove them if n>0: overall_state.append(np.load(i)[1:,:]) else: overall_state.append(np...
_____no_output_____
MIT
Tutorial/Day 5 Optimal Mind Control/Day 5.ipynb
technosap/PSST
Visualizing the Overall DataFinally, we plot the same voltage traces of the 3 neurons from Day 4 as a Voltage vs Time heatmap. While this visualization may seem unnecessary for just 3 neurons, it becomes an useful tool when on visualizes the dynamics of a large network of neurons as illustrated in the Example Implemen...
# Plot the voltage traces of the three neurons plt.figure(figsize=(12,6)) sns.heatmap(overall_state[::100,:3].T,xticklabels=100,yticklabels=5,cmap='RdBu_r') plt.xlabel("Time (in ms)") plt.ylabel("Neuron Number") plt.title("Voltage vs Time Heatmap for Projection Neurons (PNs)") plt.tight_layout() plt.show()
_____no_output_____
MIT
Tutorial/Day 5 Optimal Mind Control/Day 5.ipynb
technosap/PSST
By this method, we have maximized the usage of our available memory but we can go further and develop a method to allow indefinitely long simulation. The issue behind this entire algorithm is that the memory is not cleared until the python kernel finishes. One way to overcome this is to save the parameters of the model...
!python call.py
Batch 1 Running...Finished Batch 2 Running...Finished
MIT
Tutorial/Day 5 Optimal Mind Control/Day 5.ipynb
technosap/PSST
Combining all DataJust like we merged all the batches, we merge all the sub-batches and batches.
n_splits = 2 n_batch = 2 overall_state = [] # Iterate over the generated output files for n,i in enumerate(["batch"+str(x+1) for x in range(n_splits)]): for m,j in enumerate(["_part_"+str(x+1)+".npy" for x in range(n_batch)]): # Since the first element in the series was the last output, we remove the...
_____no_output_____
MIT
Tutorial/Day 5 Optimal Mind Control/Day 5.ipynb
technosap/PSST
II - Wavefronts and optical systemsFirst let's import HCIPy, and a few supporting libraries:
from hcipy import * import numpy as np import matplotlib.pyplot as plt %matplotlib inline
_____no_output_____
MIT
doc/getting_started/2_wavefronts_optical_systems.ipynb
rahulbhadani/hcipy
Wavefronts in HCIPy are monochromatic. They consist of an electric field (as an HCIP `Field`), and a wavelength. If broadband images are needed, multiple `Wavefront`s must be constructed and propagated through the optical system, sampling the required wavelength range. Let us construct a `Wavefront`.
pupil_grid = make_pupil_grid(1024) aperture = circular_aperture(1)(pupil_grid) wavefront = Wavefront(aperture, 1)
_____no_output_____
MIT
doc/getting_started/2_wavefronts_optical_systems.ipynb
rahulbhadani/hcipy
A note must be made at this point regarding units. HCIPy is averse w.r.t. the used units. If the user fills in all quantities in SI, then all calculations in HCIPy will be returned in SI units. This allows the user to use any unit he/she wants, while still being able to seamlessly use dimensionless quantities. Ie. the ...
focal_grid = make_focal_grid(pupil_grid, 8, 16)
_____no_output_____
MIT
doc/getting_started/2_wavefronts_optical_systems.ipynb
rahulbhadani/hcipy
This constructs a `Grid` with 8 samples per $\lambda/D$ and a 16 $\lambda/D$ radius field of view (so 32 $\lambda/D$ diameter field of view). Now we can construct a Fraunhofer propagator that can actually propagate the light to the focal plane.
prop = FraunhoferPropagator(pupil_grid, focal_grid) img = prop.forward(wavefront) imshow_field(np.log10(img.intensity / img.intensity.max()), vmin=-5) plt.colorbar() plt.show()
_____no_output_____
MIT
doc/getting_started/2_wavefronts_optical_systems.ipynb
rahulbhadani/hcipy
All Fourier transforms concerning the propagation are done internally. In this case a Matrix Fourier transform was used, as it was deemed quicker than a Fast Fourier transform in this case. Also note that when defining the propagator, we didn't pass the wavelength of the wavefront. This wavelength is taken from the `Wa...
pupil_grid_2 = make_pupil_grid(1024, 0.015) aperture_2 = circular_aperture(0.01)(pupil_grid_2) fresnel_prop = FresnelPropagator(pupil_grid_2, 2) wf = Wavefront(aperture_2, 500e-9) img = fresnel_prop(wf) imshow_field(img.intensity) plt.show()
_____no_output_____
MIT
doc/getting_started/2_wavefronts_optical_systems.ipynb
rahulbhadani/hcipy
The propagators shown previously are part of a larger group of optical elements. All `OpticalElement`s can propagate a `Wavefront` through them. Examples include simple `Apodizer`s, which act as an infinitely-thin screen with a (complex) transmission. A little more complicated example is `SurfaceAberration`, which simu...
aberration = SurfaceAberration(pupil_grid, 0.25, 1) wf = Wavefront(aperture) img = prop(aberration(wf)) imshow_field(np.log10(img.intensity / img.intensity.max()), vmin=-5) plt.colorbar() plt.show()
c:\users\emiel por\documents\github\hcipy\hcipy\optics\aberration.py:39: RuntimeWarning: divide by zero encountered in power res = Field(grid.as_('polar').r**exponent, grid)
MIT
doc/getting_started/2_wavefronts_optical_systems.ipynb
rahulbhadani/hcipy
These simple optical elements can be combined into more complicated optical systems. These include full wavefront sensor implementations and coronagraphs. Both of these will be handled in later sections.To convert a `Wavefront` into an observed image, one can simply use the `Wavefront.power` attribute, which is the `Wa...
flat_field = 0.01 dark = 10 detector = NoisyDetector(focal_grid, dark_current_rate=dark, flat_field=flat_field) wf.total_power = 5000 img = prop(aberration(wf)) detector.integrate(img, 0.5) image = detector.read_out() imshow_field(np.log10(image), vmax=np.log10(image).max(), vmin=0) plt.colorbar() plt.show()
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:11: RuntimeWarning: divide by zero encountered in log10 # This is added back by InteractiveShellApp.init_path()
MIT
doc/getting_started/2_wavefronts_optical_systems.ipynb
rahulbhadani/hcipy
📝 Exercise M6.03This exercise aims at verifying if AdaBoost can over-fit.We will make a grid-search and check the scores by varying thenumber of estimators.We will first load the California housing dataset and split it into atraining and a testing set.
from sklearn.datasets import fetch_california_housing from sklearn.model_selection import train_test_split data, target = fetch_california_housing(return_X_y=True, as_frame=True) target *= 100 # rescale the target in k$ data_train, data_test, target_train, target_test = train_test_split( data, target, random_stat...
_____no_output_____
CC-BY-4.0
notebooks/M6-ensemble_ex_03.ipynb
datagistips/scikit-learn-mooc
NoteIf you want a deeper overview regarding this dataset, you can refer to theAppendix - Datasets description section at the end of this MOOC. Then, create an `AdaBoostRegressor`. Use the function`sklearn.model_selection.validation_curve` to get training and test scoresby varying the number of estimators. Use the mean ...
# Write your code here. from sklearn.ensemble import AdaBoostRegressor from sklearn.model_selection import validation_curve import pandas as pd import numpy as np n_estimators = np.arange(1, 100, 2) n_estimators model = AdaBoostRegressor() model.get_params() train_scores, test_scores = validation_curve( model, dat...
_____no_output_____
CC-BY-4.0
notebooks/M6-ensemble_ex_03.ipynb
datagistips/scikit-learn-mooc
Plot both the mean training and test errors. You can also plot thestandard deviation of the errors.*Hint: you can use `plt.errorbar`.*
# Write your code here. from matplotlib import pyplot as plt plt.errorbar(n_estimators, train_errors.mean(axis=1), yerr=train_errors.std(axis=1), label="Training error") plt.errorbar(n_estimators, test_errors.mean(axis=1), yerr=train_errors.std(axis=1), label="Testing error")
_____no_output_____
CC-BY-4.0
notebooks/M6-ensemble_ex_03.ipynb
datagistips/scikit-learn-mooc
Plotting the validation curve, we can see that AdaBoost is not immune againstoverfitting. Indeed, there is an optimal number of estimators to be found.Adding too many estimators is detrimental for the statistical performance ofthe model. Repeat the experiment using a random forest instead of an AdaBoost regressor.
# Write your code here. from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor() train_scores, test_scores = validation_curve( model, data, target, param_name="n_estimators", param_range=n_estimators, cv=5, scoring="neg_mean_absolute_error", n_jobs=2) # PLOT plt.errorbar(n_estimators, t...
_____no_output_____
CC-BY-4.0
notebooks/M6-ensemble_ex_03.ipynb
datagistips/scikit-learn-mooc
SmallPebble[![](https://github.com/sradc/smallpebble/workflows/Python%20package/badge.svg)](https://github.com/sradc/smallpebble/commits/) **Project status: unstable.**SmallPebble is a minimal automatic differentiation and deep learning library written from scratch in [Python](https://www.python.org/), using [NumPy](h...
import matplotlib.pyplot as plt import numpy as np from tqdm.notebook import tqdm import smallpebble as sp from smallpebble.misc import load_data
_____no_output_____
Apache-2.0
README.ipynb
malleshi-9025/SmallPebble
Training a neural network to classify handwritten digits (MNIST)
"Load the dataset, and create a validation set." X_train, y_train, _, _ = load_data('mnist') # load / download from openml.org X_train = X_train/255 # normalize # Seperate out data for validation. X = X_train[:50_000, ...] y = y_train[:50_000] X_eval = X_train[50_000:60_000, ...] y_eval = y_train[50_000:60_000] "Pl...
_____no_output_____
Apache-2.0
README.ipynb
malleshi-9025/SmallPebble
Training a convolutional neural network on CIFAR-10, using CuPyThis was run on [Google Colab](https://colab.research.google.com/), with a GPU.
"Load the CIFAR dataset." X_train, y_train, _, _ = load_data('cifar') # load/download from openml.org X_train = X_train/255 # normalize """Plot, to check it's the right data. (This cell's code is from: https://www.tensorflow.org/tutorials/images/cnn#verify_the_data) """ class_names = ['airplane', 'automobile', 'bi...
_____no_output_____
Apache-2.0
README.ipynb
malleshi-9025/SmallPebble
Train the model.
NUM_ITERS = 3000 BATCH_SIZE = 128 eval_batch = sp.batch(X_eval, y_eval, BATCH_SIZE) adam = sp.Adam() for i, (xbatch, ybatch) in tqdm(enumerate(sp.batch(X, y, BATCH_SIZE)), total=NUM_ITERS): if i >= NUM_ITERS: break xbatch_images = xbatch.reshape([-1, 32, 32, 3]) X_in.assign_value(sp.Variable(xbatc...
_____no_output_____
Apache-2.0
README.ipynb
malleshi-9025/SmallPebble
It looks like we could improve our results by training for longer (and we could improve our model architecture). --- Brief guide to using SmallPebbleSmallPebble provides the following building blocks to make models with:- `sp.Variable`- Operations, such as `sp.add`, `sp.mul`, etc.- `sp.get_gradients`- `sp.Lazy`- `sp.Pl...
import cupy import numpy import smallpebble as sp # Switch to CuPy sp.use(cupy) print(sp.array_library.library.__name__) # should be 'cupy' # Switch back to NumPy: sp.use(numpy) print(sp.array_library.library.__name__) # should be 'numpy'
cupy numpy
Apache-2.0
README.ipynb
malleshi-9025/SmallPebble
sp.Variable & sp.get_gradients With SmallPebble, you can:- Wrap NumPy arrays in `sp.Variable`- Apply SmallPebble operations (e.g. `sp.matmul`, `sp.add`, etc.)- Compute gradients with `sp.get_gradients`
a = sp.Variable(np.random.random([2, 2])) b = sp.Variable(np.random.random([2, 2])) c = sp.Variable(np.random.random([2])) y = sp.mul(a, b) + c print('y.array:\n', y.array) gradients = sp.get_gradients(y) grad_a = gradients[a] grad_b = gradients[b] grad_c = gradients[c] print('grad_a:\n', grad_a) print('grad_b:\n', gr...
y.array: [[1.32697776 1.24689392] [1.25317932 1.05037433]] grad_a: [[0.50232192 0.99209074] [0.42936606 0.19027664]] grad_b: [[0.95442445 0.34679685] [0.94471809 0.7753676 ]] grad_c: [2. 2.]
Apache-2.0
README.ipynb
malleshi-9025/SmallPebble
Note that `y` is computed straight away, i.e. the (forward) computation happens immediately.Also note that `y` is a sp.Variable and we could continue to carry out SmallPebble operations on it. sp.Lazy & sp.PlaceholderLazy graphs are constructed using `sp.Lazy` and `sp.Placeholder`.
lazy_node = sp.Lazy(lambda a, b: a + b)(1, 2) print(lazy_node) print(lazy_node.run()) a = sp.Lazy(lambda a: a)(2) y = sp.Lazy(lambda a, b, c: a * b + c)(a, 3, 4) print(y) print(y.run())
<smallpebble.smallpebble.Lazy object at 0x7f15db26ea50> 10
Apache-2.0
README.ipynb
malleshi-9025/SmallPebble
Forward computation does not happen immediately - only when .run() is called.
a = sp.Placeholder() b = sp.Variable(np.random.random([2, 2])) y = sp.Lazy(sp.matmul)(a, b) a.assign_value(sp.Variable(np.array([[1,2], [3,4]]))) result = y.run() print('result.array:\n', result.array)
result.array: [[1.96367495 2.26668698] [3.94895132 5.3053362 ]]
Apache-2.0
README.ipynb
malleshi-9025/SmallPebble
You can use .run() as many times as you like. Let's change the placeholder value and re-run the graph:
a.assign_value(sp.Variable(np.array([[10,20], [30,40]]))) result = y.run() print('result.array:\n', result.array)
result.array: [[19.63674952 22.6668698 ] [39.48951324 53.053362 ]]
Apache-2.0
README.ipynb
malleshi-9025/SmallPebble
Finally, let's compute gradients:
gradients = sp.get_gradients(result)
_____no_output_____
Apache-2.0
README.ipynb
malleshi-9025/SmallPebble
Note that `sp.get_gradients` is called on `result`, which is a `sp.Variable`, not on `y`, which is a `sp.Lazy` instance. sp.learnable & sp.get_learnablesUse `sp.learnable` to flag parameters as learnable, allowing them to be extracted from a lazy graph with `sp.get_learnables`.This enables a workflow of: building a mo...
a = sp.Placeholder() b = sp.learnable(sp.Variable(np.random.random([2, 1]))) y = sp.Lazy(sp.matmul)(a, b) y = sp.Lazy(sp.add)(y, sp.learnable(sp.Variable(np.array([5])))) learnables = sp.get_learnables(y) for learnable in learnables: print(learnable)
<smallpebble.smallpebble.Variable object at 0x7f157a263b10> <smallpebble.smallpebble.Variable object at 0x7f15d2a4ccd0>
Apache-2.0
README.ipynb
malleshi-9025/SmallPebble
In this exercise we will try to re-create the decision tree from data![](figures/play_tennis.png)
import pandas as pd from sklearn import tree from sklearn.tree import export_text data = pd.read_csv("data/PlayTennis.csv")
_____no_output_____
MIT
41-warmup-blank_introduction_to_machine_learning.ipynb
hanisaf/advanced-data-management-and-analytics
Train a decision tree using the data and then print the tree*Note* You will need to change the values from string to numbers before training the tree
data.head()
_____no_output_____
MIT
41-warmup-blank_introduction_to_machine_learning.ipynb
hanisaf/advanced-data-management-and-analytics
---author: - Elizabeth Czarniak (CZARNIA_ELIZ@bentley.edu) - Nathan Carter (ncarter@bentley.edu)--- We're going to use some fake data here by generating random numbers, but you can replace our fake data with your real data in the code below.
# Replace this with your data, such as a variable or column in a DataFrame import numpy as np values = np.random.normal(0, 1, 50) # 50 random values
_____no_output_____
MIT
database/tasks/How to create a QQ-plot/Python, using SciPy.ipynb
nathancarter/how2data
If the data is normally distributed, then we expect that the QQ plot will show the observed values (blue dots) falling very clsoe to the red line (the quantiles for the normal distribution).
from scipy import stats import matplotlib.pyplot as plt stats.probplot(values, dist="norm", plot=plt) plt.show()
_____no_output_____
MIT
database/tasks/How to create a QQ-plot/Python, using SciPy.ipynb
nathancarter/how2data
ChainerRL Quickstart GuideThis is a quickstart guide for users who just want to try ChainerRL for the first time.If you have not yet installed ChainerRL, run the command below to install it:
%%bash pip install chainerrl
Collecting chainerrl Downloading chainerrl-0.2.0.tar.gz (56kB) Collecting cached-property (from chainerrl) Downloading cached_property-1.3.1-py2.py3-none-any.whl Requirement already satisfied: chainer>=2.0.0 in /home/shunta/.pyenv/versions/anaconda3-4.4.0/lib/python3.6/site-packages (from chainerrl) Collecting futu...
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
If you have already installed ChainerRL, let's begin!First, you need to import necessary modules. The module name of ChainerRL is `chainerrl`. Let's import `gym` and `numpy` as well since they are used later.
import chainer import chainer.functions as F import chainer.links as L import chainerrl import gym import numpy as np
_____no_output_____
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
ChainerRL can be used for any problems if they are modeled as "environments". [OpenAI Gym](https://github.com/openai/gym) provides various kinds of benchmark environments and defines the common interface among them. ChainerRL uses a subset of the interface. Specifically, an environment must define its observation space...
env = gym.make('CartPole-v0') print('observation space:', env.observation_space) print('action space:', env.action_space) obs = env.reset() env.render(close=True) print('initial observation:', obs) action = env.action_space.sample() obs, r, done, info = env.step(action) print('next observation:', obs) print('reward:'...
[2017-09-23 05:17:39,776] Making new env: CartPole-v0
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
Now you have defined your environment. Next, you need to define an agent, which will learn through interactions with the environment.ChainerRL provides various agents, each of which implements a deep reinforcement learning algorithm.To use [DQN (Deep Q-Network)](http://dx.doi.org/10.1038/nature14236), you need to defin...
class QFunction(chainer.Chain): def __init__(self, obs_size, n_actions, n_hidden_channels=50): super().__init__( l0=L.Linear(obs_size, n_hidden_channels), l1=L.Linear(n_hidden_channels, n_hidden_channels), l2=L.Linear(n_hidden_channels, n_actions)) def __call__(self...
_____no_output_____
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
If you want to use CUDA for computation, as usual as in Chainer, call `to_gpu`.
# Uncomment to use CUDA # q_func.to_gpu(0)
_____no_output_____
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
You can also use ChainerRL's predefined Q-functions.
_q_func = chainerrl.q_functions.FCStateQFunctionWithDiscreteAction( obs_size, n_actions, n_hidden_layers=2, n_hidden_channels=50)
_____no_output_____
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
As in Chainer, `chainer.Optimizer` is used to update models.
# Use Adam to optimize q_func. eps=1e-2 is for stability. optimizer = chainer.optimizers.Adam(eps=1e-2) optimizer.setup(q_func)
_____no_output_____
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
A Q-function and its optimizer are used by a DQN agent. To create a DQN agent, you need to specify a bit more parameters and configurations.
# Set the discount factor that discounts future rewards. gamma = 0.95 # Use epsilon-greedy for exploration explorer = chainerrl.explorers.ConstantEpsilonGreedy( epsilon=0.3, random_action_func=env.action_space.sample) # DQN uses Experience Replay. # Specify a replay buffer and its capacity. replay_buffer = chaine...
_____no_output_____
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
Now you have an agent and an environment. It's time to start reinforcement learning!In training, use `agent.act_and_train` to select exploratory actions. `agent.stop_episode_and_train` must be called after finishing an episode. You can get training statistics of the agent via `agent.get_statistics`.
n_episodes = 200 max_episode_len = 200 for i in range(1, n_episodes + 1): obs = env.reset() reward = 0 done = False R = 0 # return (sum of rewards) t = 0 # time step while not done and t < max_episode_len: # Uncomment to watch the behaviour # env.render() action = agent...
episode: 10 R: 12.0 statistics: [('average_q', 0.0077787917633448615), ('average_loss', 0)] episode: 20 R: 43.0 statistics: [('average_q', 0.013923729594215806), ('average_loss', 0)] episode: 30 R: 10.0 statistics: [('average_q', 0.04999595856865319), ('average_loss', 0.15626195506060395)] episode: 40 R: 10.0 statistic...
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
Now you finished training the agent. How good is the agent now? You can test it by using `agent.act` and `agent.stop_episode` instead. Exploration such as epsilon-greedy is not used anymore.
for i in range(10): obs = env.reset() done = False R = 0 t = 0 while not done and t < 200: env.render(close=True) action = agent.act(obs) obs, r, done, _ = env.step(action) R += r t += 1 print('test episode:', i, 'R:', R) agent.stop_episode()
test episode: 0 R: 200.0 test episode: 1 R: 200.0 test episode: 2 R: 200.0 test episode: 3 R: 200.0 test episode: 4 R: 200.0 test episode: 5 R: 200.0 test episode: 6 R: 200.0 test episode: 7 R: 200.0 test episode: 8 R: 200.0 test episode: 9 R: 200.0
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
If test scores are good enough, the only remaining task is to save the agent so that you can reuse it. What you need to do is to simply call `agent.save` to save the agent, then `agent.load` to load the saved agent.
# Save an agent to the 'agent' directory agent.save('agent') # Uncomment to load an agent from the 'agent' directory # agent.load('agent')
_____no_output_____
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
RL completed!But writing code like this every time you use RL might be boring. So, ChainerRL has utility functions that do these things.
# Set up the logger to print info messages for understandability. import logging import sys gym.undo_logger_setup() # Turn off gym's default logger settings logging.basicConfig(level=logging.INFO, stream=sys.stdout, format='') chainerrl.experiments.train_agent_with_evaluation( agent, env, steps=2000, ...
outdir:result step:86 episode:0 R:86.0 statistics:[('average_q', 20.728489019516747), ('average_loss', 0.13604925025581077)] outdir:result step:286 episode:1 R:200.0 statistics:[('average_q', 20.671014208079793), ('average_loss', 0.14984728771766473)] outdir:result step:396 episode:2 R:110.0 statistics:[('average_q', 2...
MIT
6_dqn_cartpole.ipynb
yuhonghong66/chainer-notebooks
Introduction to Kubernetes **Learning Objectives** * Create GKE cluster from command line * Deploy an application to your cluster * Cleanup, delete the cluster OverviewKubernetes is an open source project (available on [kubernetes.io](kubernetes.io)) which can run on many different environments, from laptops to high...
import os CLUSTER_NAME = "asl-cluster" ZONE = "us-central1-a" os.environ["CLUSTER_NAME"] = CLUSTER_NAME os.environ["ZONE"] = ZONE
_____no_output_____
Apache-2.0
notebooks/docker_and_kubernetes/labs/2_intro_k8s.ipynb
ctivanovich/asl-ml-immersion
We'll set our default compute zone to `us-central1-a` and use `gcloud container clusters create ...` to create the GKE cluster. Let's first look at all the clusters we currently have.
!gcloud container clusters list
NAME LOCATION MASTER_VERSION MASTER_IP MACHINE_TYPE NODE_VERSION NUM_NODES STATUS cluster-1 us-central1-a 1.19.14-gke.1900 35.193.84.252 custom-2-4352 1.19.14-gke.1900 2 RUNNING
Apache-2.0
notebooks/docker_and_kubernetes/labs/2_intro_k8s.ipynb
ctivanovich/asl-ml-immersion
**Exercise**Use `gcloud container clusters create` to create a new cluster using the `CLUSTER_NAME` we set above. This takes a few minutes...
%%bash gcloud container clusters create $CLUSTER_NAME --zone $ZONE
NAME LOCATION MASTER_VERSION MASTER_IP MACHINE_TYPE NODE_VERSION NUM_NODES STATUS asl-cluster us-central1-a 1.20.10-gke.1600 34.71.2.241 e2-medium 1.20.10-gke.1600 3 RUNNING
Apache-2.0
notebooks/docker_and_kubernetes/labs/2_intro_k8s.ipynb
ctivanovich/asl-ml-immersion