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
View the Circuit It's usually a good idea to view the ASCII diagram of your circuit to make sure it's doing what you want. This can be displayed by printing the circuit.
print(qnn)
0: ───Z──────────────────────────────────────────────────────────────── β”‚ 1: ───┼─────Z────────────────────────────────────────────────────────── β”‚ β”‚ 2: ───┼─────┼─────Z──────────────────────────────────────────────────── β”‚ β”‚ β”‚ 3: ───┼─────┼─────┼─────Z─────────────────────────────────────...
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
You can experiment with adding more layers of $ZX$ gates (or adding other kinds of transformations!) to your QNN, but we can use this simplest kind of circuit to analyze a simple toy problem, which is what we will do next. A Toy Problem: Biased Coin FlipsAs a toy problem, let's get our quantum neuron to decide whether...
def readout_expectation(state): """Takes in a specification of a state as an array of 0s and 1s and returns the expectation value of Z on ther readout qubit. Uses the XmonSimulator to calculate the wavefunction exactly.""" # A convenient representation of the state as an integer state_num = int(np.sum(st...
_____no_output_____
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
Loss and ErrorThe next functions take a list of states (each specified as an array of $0$s and $1$s as before) and a corresponding list of labels and computes the loss and error, respectively, of that list.
def loss(states, labels): loss=0 for state, label in zip(states,labels): loss += 1 - label*readout_expectation(state) return loss/(2*len(states)) def classification_error(states, labels): error=0 for state,label in zip(states,labels): error += 1 - label*np.sign(readout_expectation(state)) return ...
_____no_output_____
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
Generating Data For our toy problem we'll want to be able to generate a batch of data. Here is a helper function for that task:
def make_batch(): """Generates a set of labels, then uses those labels to generate inputs. label = -1 corresponds to majority 0 in the sate, label = +1 corresponds to majority 1. """ np.random.seed(0) # For consistency in demo labels = (-1)**np.random.choice(2, size=100) # Smaller batch sizes will speed up ...
_____no_output_____
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
TrainingNow we'll try to find the optimal weight to solve our toy problem. For illustration, we'll do both a brute force search of the paramter space as well as a stochastic gradient descent. Brute Force SearchLet's compute both the loss and error rate on a batch of data as a function of the shared weight between all...
# Using cirq.Simulator with the EigenGate implementation of ZZ, this takes # about 30s to run. Using the XmonSimulator took about 40 minutes the last # time I tried it! %%time linspace = np.linspace(start=-1, stop=1, num=80) train_losses = [] error_rates = [] for p in linspace: params = {'w': p} train_losses.append...
_____no_output_____
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
__Question__: Why are the loss and error functions periodic with period $1$ when the $ZX$ gate is periodic with period $2$? Solution This kind of "halving" of the periodicity of $\langle Y \rangle$ compared to the period of the gates itself is typical of qubit systems. We can analyze how it works mathematically in a s...
def stochastic_grad_loss(): """Generates a new data point and computes the gradient of the loss using that data point.""" # Randomly generate the data point. label = (-1)**np.random.choice(2) state = np.random.choice(2, size=INPUT_SIZE, p=[0.5-label*0.2,0.5+label*0.2]) # Compute the gradient using fin...
_____no_output_____
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
We can apply this function repeatedly to flow toward the minimum:
eta = 10**-4 # Learning rate. Try different values. params = {'w': 0} # Initialize weight. Try different values. for i in range(201): if not i%25: print('Step: {} Loss: {}'.format(i, loss(states, labels))) grad = stochastic_grad_loss() params['w'] += -eta*grad print('Final Weight: {}'.format(params['w']))
Step: 0 Loss: 0.5 Step: 25 Loss: 0.29664170142263174 Step: 50 Loss: 0.21596111725317313 Step: 75 Loss: 0.19353972657117993 Step: 100 Loss: 0.1930989919230342 Step: 125 Loss: 0.19318223176524044 Step: 150 Loss: 0.19358215024578385 Step: 175 Loss: 0.1965144828868506 Step: 200 Loss: 0.1930640292633325 Final Weight: -0.044...
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
Use Sampling Instead of Calculating from the WavefunctionOn real hardware we will have to use sampling to find results instead of computing the exact wavefunction. Rewrite the `readout_expectation` function to compute the expectation value using sampling instead. Unlike with the wavefunction calculation, we also need ...
def readout_expectation_sample(state): """Takes in a specification of a state as an array of 0s and 1s and returns the expectation value of Z on ther readout qubit. Uses the XmonSimulator to sample the final wavefunction.""" # We still need to resolve the parameters in the circuit. resolver = cirq.ParamRes...
_____no_output_____
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
Solution
def readout_expectation_sample(state): """Takes in a specification of a state as an array of 0s and 1s and returns the expectation value of Z on ther readout qubit. Uses the XmonSimulator to sample the final wavefunction.""" # We still need to resolve the parameters in the circuit. resolver = cirq.ParamRes...
_____no_output_____
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
Comparison of Sampling with the Exact Wavefunction Just to illustrate the difference between sampling and using the wavefunction, try running the two methods several times on identical input:
state = [0,0,0,1,0,1,1,0,1] # Try different initial states. params = {'w': 0.05} # Try different weights. print("Exact expectation value: {}".format(readout_expectation(state))) print("Estimates from sampling:") for _ in range(5): print(readout_expectation_sample(state))
Exact expectation value: 0.3090169429779053 Estimates from sampling: 0.308354 0.306674 0.309026 0.310854 0.30854
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
As an exercise, try repeating some of the above calculations (e.g., the SGD optimization) using `readout_expectation_sample` in place of `readout_expectation`. How many repetitions should you use? How should the hyperparameters `eps` and `eta` be adjusted in response to the number of repetitions? Optimizing For Hardwa...
print(cirq.google.Foxtail)
(0, 0)───(0, 1)───(0, 2)───(0, 3)───(0, 4)───(0, 5)───(0, 6)───(0, 7)───(0, 8)───(0, 9)───(0, 10) β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ (1, 0)───(1, 1)───(1, 2)───(1, 3)───(1...
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
The qubits are arranged in two rows of eleven qubits each, and qubits can only communicate to their nearest neighbors along the horizontal and vertial connections. That does not mesh well with the QNN we designed, where all of the data qubits need to interact with the readout qubit. There is no *in-principle* restricti...
qnn_fox = cirq.Circuit() w = 0.2 # Want an explicit numerical weight for later for i in range(10): qnn_fox.append([ZXGate(w).on(cirq.GridQubit(1,i), cirq.GridQubit(0,i)), ZXGate(w).on(cirq.GridQubit(0,i+1), cirq.GridQubit(0,i)), cirq.SWAP(cirq.GridQubit(0,i), cirq.GridQubit(0,i+1...
(0, 0): ────X───────X───────×────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── β”‚ β”‚ β”‚ (0, 1): ────┼───────Z^0.2───×───X───────X───────×─────...
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
As coded, this circuit still won't run on the Foxtail device. That's because the gates we've defined are not native gates. Cirq has a built-in method that will convert our gates to Xmon gates (which are native for the Foxtail device) and attempt to optimze the circuit by reducing the total number of gates:
cirq.google.optimized_for_xmon(qnn_fox, new_device=cirq.google.Foxtail, allow_partial_czs=True)
_____no_output_____
Apache-2.0
colabs/QNN_hands_on.ipynb
derekchen-2/physics-math-tutorials
---- Data Library for Python---- Content layer - NewsThis notebook demonstrates how to retrieve News. Learn moreTo learn more about the Refinitiv Data Library for Python please join the Refinitiv Developer Community. By [registering](https://developers.refinitiv.com/iam/register) and [logging](https://developers.refi...
import os os.environ["RD_LIB_CONFIG_PATH"] = "../../../Configuration"
_____no_output_____
Apache-2.0
Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb
Refinitiv-API-Samples/Example.DataLibrary.Python
Some Imports to start with
import refinitiv.data as rd from refinitiv.data.content import news from datetime import timedelta
_____no_output_____
Apache-2.0
Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb
Refinitiv-API-Samples/Example.DataLibrary.Python
Open the data sessionThe open_session() function creates and open sessions based on the information contained in the refinitiv-data.config.json configuration file. Please edit this file to set the session type and other parameters required for the session you want to open.
rd.open_session('platform.rdp')
_____no_output_____
Apache-2.0
Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb
Refinitiv-API-Samples/Example.DataLibrary.Python
Retrieve data Headlines Get headlines
response = news.headlines.Definition("Apple").get_data() response.data.df
_____no_output_____
Apache-2.0
Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb
Refinitiv-API-Samples/Example.DataLibrary.Python
Get headlines within a range of dates
response = news.headlines.Definition( query="Refinitiv", date_from="20.03.2021", date_to=timedelta(days=-4), count=3 ).get_data() response.data.df
_____no_output_____
Apache-2.0
Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb
Refinitiv-API-Samples/Example.DataLibrary.Python
Get a limited number of headlines
response = news.headlines.Definition(query = "Google", count = 350).get_data() response.data.df
_____no_output_____
Apache-2.0
Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb
Refinitiv-API-Samples/Example.DataLibrary.Python
Story
response = news.story.Definition("urn:newsml:reuters.com:20211003:nNRAgvhyiu:1").get_data() print(response.data.story.title, '\n') print(response.data.story.content)
Google Doodle marks birthday of Spanish ocean scientist María de los Ángeles Alvariño GonzÑlez For best results when printing this announcement, please click on link below: http://newsfile.refinitiv.com/getnewsfile/v1/story?guid=urn:newsml:reuters.com:20211003:nNRAgvhyiu&default-theme=true The Google Doodle today (...
Apache-2.0
Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb
Refinitiv-API-Samples/Example.DataLibrary.Python
Close the session
rd.close_session()
_____no_output_____
Apache-2.0
Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb
Refinitiv-API-Samples/Example.DataLibrary.Python
Statistic Inference- This is a Python base notebook- Using `rpy2` for R functionsWe saw some pattern in EDA, naturally, we would like to see if the different between feature are significantly related to the target. Import libaries
import rpy2 import rpy2.robjects as robjects from rpy2.robjects.packages import importr %load_ext rpy2.ipython %%R library(tidyverse) library(broom) library(GGally)
R[write to console]: ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ── R[write to console]: βœ” ggplot2 3.3.5 βœ” purrr 0.3.4 βœ” tibble 3.1.6 βœ” dplyr 1.0.7 βœ” tidyr 1.1.4 βœ” stringr 1.4.0 βœ” readr 2.1.1 βœ” forcats 0.5.1 R[write to console]: ── Conflicts ─────────────────...
MIT
spotify_user_behaviour_predictor/4_Stat_Infer.ipynb
MacyChan/spotify-user-behaviour-predictor
Reading the data CSVRead in the data CSV and store it as a pandas dataframe named `spotify_df`.
%%R spotify_df <- read_csv("data/spotify_data.csv") head(spotify_df)
R[write to console]: New names: * `` -> ...1
MIT
spotify_user_behaviour_predictor/4_Stat_Infer.ipynb
MacyChan/spotify-user-behaviour-predictor
Regression Data Wrangle- Remove `song_title` and `artist` for relationship study by regression. As both of them are neither numerical nor categorical features.
%%R spotify_df_num <- spotify_df[2:15] head(spotify_df_num)
# A tibble: 6 Γ— 14 acousticness danceability duration_ms energy instrumentalness key liveness <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 0.0102 0.833 204600 0.434 0.0219 2 0.165 2 0.199 0.743 326933 0.359 0.00611 ...
MIT
spotify_user_behaviour_predictor/4_Stat_Infer.ipynb
MacyChan/spotify-user-behaviour-predictor
Set up regression model Here, I am interested in determining factors associated with `target`. In particular, I will use a Multiple Linear Regression (MLR) Model to study the relation between `target` and all other features.
%%R ML_reg <- lm( target ~ ., data = spotify_df_num) |> tidy(conf.int = TRUE) ML_reg<- ML_reg |> mutate(Significant = p.value < 0.05) |> mutate_if(is.numeric, round, 3) ML_reg
# A tibble: 14 Γ— 8 term estimate std.error statistic p.value conf.low conf.high Significant <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <lgl> 1 (Interce… -0.313 0.206 -1.52 0.128 -0.717 0.09 FALSE 2 acoustic… -0.325 0.055 -5.92 0 -0.433...
MIT
spotify_user_behaviour_predictor/4_Stat_Infer.ipynb
MacyChan/spotify-user-behaviour-predictor
- We can see that a lot of features are statiscally correlated with target. They are listed in the table below.
%%R ML_reg |> filter(Significant == TRUE) |> select(term)
# A tibble: 7 Γ— 1 term <chr> 1 acousticness 2 danceability 3 duration_ms 4 instrumentalness 5 loudness 6 speechiness 7 valence
MIT
spotify_user_behaviour_predictor/4_Stat_Infer.ipynb
MacyChan/spotify-user-behaviour-predictor
GGpairsBelow is the ggpair plots to visual the correlation between different features.
%%R ggpairs(data = spotify_df_num)
_____no_output_____
MIT
spotify_user_behaviour_predictor/4_Stat_Infer.ipynb
MacyChan/spotify-user-behaviour-predictor
Migrating scripts from Framework Mode to Script ModeThis notebook focus on how to migrate scripts using Framework Mode to Script Mode. The original notebook using Framework Mode can be find here https://github.com/awslabs/amazon-sagemaker-examples/blob/4c2a93114104e0b9555d7c10aaab018cac3d7c04/sagemaker-python-sdk/tens...
import os import subprocess import sagemaker from sagemaker import get_execution_role sagemaker_session = sagemaker.Session() role = get_execution_role()
_____no_output_____
Apache-2.0
sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb
dleen/amazon-sagemaker-examples
Download the MNIST dataset
import utils from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf data_sets = input_data.read_data_sets('data', dtype=tf.uint8, reshape=False, validation_size=5000) utils.convert_to(data_sets.train, 'train', 'data') utils.convert_to(data_sets.validation, 'validation', 'data') utils.conve...
_____no_output_____
Apache-2.0
sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb
dleen/amazon-sagemaker-examples
Upload the dataWe use the ```sagemaker.Session.upload_data``` function to upload our datasets to an S3 location. The return value inputs identifies the location -- we will use this later when we start the training job.
inputs = sagemaker_session.upload_data(path='data', key_prefix='data/mnist')
_____no_output_____
Apache-2.0
sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb
dleen/amazon-sagemaker-examples
Construct an entry point script for training On this example, we assume that you aready have a Framework Mode training script named `mnist.py`:
!pygmentize 'mnist.py'
_____no_output_____
Apache-2.0
sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb
dleen/amazon-sagemaker-examples
The training script `mnist.py` include the Framework Mode functions ```model_fn```, ```train_input_fn```, ```eval_input_fn```, and ```serving_input_fn```. We need to create a entrypoint script that uses the functions above to create a ```tf.estimator```:
%%writefile train.py import argparse # import original framework mode script import mnist import tensorflow as tf if __name__ == '__main__': parser = argparse.ArgumentParser() # read hyperparameters as script arguments parser.add_argument('--training_steps', type=int) parser.add_argument('--evaluati...
_____no_output_____
Apache-2.0
sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb
dleen/amazon-sagemaker-examples
Changes in the SageMaker TensorFlow estimatorWe need to create a TensorFlow estimator pointing to ```train.py``` as the entrypoint:
from sagemaker.tensorflow import TensorFlow mnist_estimator = TensorFlow(entry_point='train.py', dependencies=['mnist.py'], role='SageMakerRole', framework_version='1.13', hyperparameters={'training_step...
_____no_output_____
Apache-2.0
sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb
dleen/amazon-sagemaker-examples
Deploy the trained model to prepare for predictionsThe deploy() method creates an endpoint (in this case locally) which serves prediction requests in real-time.
mnist_predictor = mnist_estimator.deploy(initial_instance_count=1, instance_type='local')
_____no_output_____
Apache-2.0
sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb
dleen/amazon-sagemaker-examples
Invoking the endpoint
import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) for i in range(10): data = mnist.test.images[i].tolist() predict_response = mnist_predictor.predict(data) print("========================================") ...
_____no_output_____
Apache-2.0
sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb
dleen/amazon-sagemaker-examples
Clean-upDeleting the local endpoint when you're finished is important since you can only run one local endpoint at a time.
mnist_estimator.delete_endpoint()
_____no_output_____
Apache-2.0
sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb
dleen/amazon-sagemaker-examples
The Linnerud dataset is a multi-output regression dataset. It consists of three excercise (data) and three physiological (target) variables collected from twenty middle-aged men in a fitness club:physiological - CSV containing 20 observations on 3 physiological variables:Weight, Waist and Pulse.exercise - CSV containin...
import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model, model_selection X, y = datasets.load_linnerud(return_X_y=True) print(X.shape) print(X[0])
(20, 3) [ 5. 162. 60.]
MIT
2-Regression/1-Tools/linnerud.ipynb
pr0gmtc/ML-For-Beginners
Taking Waist and Situps variables:
X = X[:, np.newaxis, 1] y = y[:, np.newaxis, 1] print(X.shape) print(y.shape) X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33) model = linear_model.LinearRegression() model.fit(X_train, y_train) y_pred = model.predict(X_test) plt.scatter(X_test, y_test, color='black') plt.plot(...
_____no_output_____
MIT
2-Regression/1-Tools/linnerud.ipynb
pr0gmtc/ML-For-Beginners
βŠ• [sanskrit-coders/indic_transliteration: Python package for indic script transliteration](https://github.com/sanskrit-coders/indic_transliteration)```pip install indic_transliterationpip install git+https://github.com/sanskrit-coders/indic_transliteration/@master ```
from indic_transliteration import sanscript from indic_transliteration.sanscript import SchemeMap, SCHEMES, transliterate data = 'idam adbhutam' print(transliterate(data, sanscript.HK, sanscript.TELUGU)) print(transliterate(data, sanscript.ITRANS, sanscript.DEVANAGARI)) scheme_map = SchemeMap(SCHEMES[sanscript.VELTHUI...
ΰ²…ΰ²Έΰ²― ಔಷಧಿಃ ಗ್ರನ್ΰ²₯ಃΰ₯€ ಎ ΰ²’ ΰ²―ΰ³†ΰ²•ΰ³ΰ²•ΰ²•ΰ³Š?
Apache-2.0
notebook/procs-hi-transliteration.ipynb
samlet/stack
![image.png](data:image/png;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCABNAI0DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QA...
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed un...
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
**Environment Preparation** **Install Java 8**Run the cell on the **Google Colab** to install jdk 1.8.**Note:** if you run this notebook on your computer, root permission is required when running the cell to install Java 8. (You may ignore this cell if Java 8 has already been set up in your computer).
# Install jdk8 !apt-get install openjdk-8-jdk-headless -qq > /dev/null import os # Set environment variable JAVA_HOME. os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64" !update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java !java -version
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
**Install Analytics Zoo** [Conda](https://docs.conda.io/projects/conda/en/latest/user-guide/install/) is needed to prepare the Python environment for running this example. **Note**: The following code cell is specific for setting up conda environment on Colab; for general conda installation, please refer to the [insta...
import sys # Get current python version version_info = sys.version_info python_version = f"{version_info.major}.{version_info.minor}.{version_info.micro}" # Install Miniconda !wget https://repo.continuum.io/miniconda/Miniconda3-4.5.4-Linux-x86_64.sh !chmod +x Miniconda3-4.5.4-Linux-x86_64.sh !./Miniconda3-4.5.4-Linux-...
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
You can install the latest pre-release version using `pip install --pre --upgrade analytics-zoo[ray]`.
# Install latest pre-release version of Analytics Zoo # Installing Analytics Zoo from pip will automatically install pyspark, bigdl, and their dependencies. !pip install --pre --upgrade analytics-zoo[ray] # Install python dependencies !pip install torch==1.7.1 torchvision==0.8.2
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
**Automated hyper-parameter search for PyTorch using Orca APIs**In this guide we will describe how to enable automated hyper-parameter search for PyTorch using Orca `AutoEstimator` in 5 simple steps.
# import necesary libraries and modules from __future__ import print_function import os import argparse from zoo.orca import init_orca_context, stop_orca_context from zoo.orca import OrcaContext
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
**Step 1: Init Orca Context**
# recommended to set it to True when running Analytics Zoo in Jupyter notebook. OrcaContext.log_output = True # (this will display terminal's stdout and stderr in the Jupyter notebook). cluster_mode = "local" if cluster_mode == "local": init_orca_context(cores=4, memory="2g", init_ray_on_spark=True) # run in loc...
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
This is the only place where you need to specify local or distributed mode. View [Orca Context](https://analytics-zoo.readthedocs.io/en/latest/doc/Orca/Overview/orca-context.html) for more details.**Note**: You should export HADOOP_CONF_DIR=/path/to/hadoop/conf/dir when you run on Hadoop YARN cluster. **Step 2: Define...
import torch import torch.nn as nn import torch.nn.functional as F class LeNet(nn.Module): def __init__(self, fc1_hidden_size=500): super(LeNet, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5, 1) self.conv2 = nn.Conv2d(20, 50, 5, 1) self.fc1 = nn.Linear(4*4*50, fc1_hidden_size) ...
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
After defining your model, you need to define a *Model Creator Function* that returns an instance of your model, and a *Optimizer Creator Function* that returns a PyTorch optimizer. Note that both the *Model Creator Function* and the *Optimizer Creator Function* should take `config` as input and get the hyper-parameter...
def model_creator(config): model = LeNet(fc1_hidden_size=config["fc1_hidden_size"]) return model def optim_creator(model, config): return torch.optim.Adam(model.parameters(), lr=config["lr"])
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
**Step 3: Define Dataset**You can define the train and validation datasets using *Data Creator Function* that has one parameter of `config` and returns a PyTorch `DataLoader`.
import torch from torchvision import datasets, transforms torch.manual_seed(0) dir = './dataset' test_batch_size = 640 def train_loader_creator(config): train_loader = torch.utils.data.DataLoader( datasets.MNIST(dir, train=True, download=True, transform=transforms.Compose([ ...
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
**Step 4: Define search space**You should define a dictionary as your hyper-parameter search space. The keys are hyper-parameter names which should be the same with those in your creators, and you can specify how you want to sample each hyper-parameter in the values of the search space. See more about [automl.hp](http...
from zoo.orca.automl import hp search_space = { "fc1_hidden_size": hp.choice([500, 600]), "lr": hp.choice([0.001, 0.003]), "batch_size": hp.choice([160, 320, 640]), }
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
**Step 5: Automatically fit and search *with* Orca AutoEstimator** First, create an AutoEstimator. You can refer to [AutoEstimator API doc](https://analytics-zoo.readthedocs.io/en/latest/doc/PythonAPI/AutoML/automl.htmlorca-automl-auto-estimator) for more details.
from zoo.orca.automl.auto_estimator import AutoEstimator auto_est = AutoEstimator.from_torch(model_creator=model_creator, optimizer=optim_creator, loss=criterion, logs_dir="/tmp/zoo_automl_logs", ...
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
Next, use the auto estimator to fit and search for the best hyper-parameter set.
auto_est.fit(data=train_loader_creator, validation_data=test_loader_creator, search_space=search_space, n_sampling=2, epochs=1, metric="accuracy")
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
Finally, you can get the best learned model and the best hyper-parameters.
best_model = auto_est.get_best_model().model # will change later best_config = auto_est.get_best_config() print(best_config)
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
You can use the best learned model and the best hyper-parameters as you want. Here, we demonstrate how to evaluate on the test dataset.
test_loader = test_loader_creator(best_config) best_model.eval() correct = 0 with torch.no_grad(): for data, target in test_loader: output = best_model(data) pred = output.data.max(1, keepdim=True)[1] correct += pred.eq(target.data.view_as(pred)).sum().numpy() accuracy = 100. * correct / len(test_loader.d...
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
You can find the accuracy of the best model has reached 98%.
# stop orca context when program finishes stop_orca_context()
_____no_output_____
Apache-2.0
docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb
EvelynQiang/analytics-zoo
DL Neuromatch Academy: Week 1, Day 2, Tutorial 1 Gradients and AutoGrad__Content creators:__ Saeed Salehi, Vladimir Haltakov, Andrew Saxe__Content reviewers:__ Polina Turishcheva, Atnafu Lambebo, Yu-Fang Yang__Content editors:__ Anoop Kulkarni__Production editors:__ Khalid Almubarak, Spiros Chavlis ---Tutorial Object...
#@markdown Tutorial slides # you should link the slides for all tutorial videos here (we will store pdfs on osf) from IPython.display import HTML HTML('<iframe src="https://docs.google.com/presentation/d/1kfWWYhSIkczYfjebhMaqQILTCu7g94Q-o_ZcWb1QAKs/embed?start=false&loop=false&delayms=3000" frameborder="0" width="960"...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
--- Setup
# Imports import numpy as np import matplotlib.pyplot as plt import torch from torch import nn import time import random from tqdm.notebook import tqdm, trange #@title Figure settings import ipywidgets as widgets # interactive display %config InlineBackend.figure_format = 'retina' plt.style.use("https://raw.gi...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
--- Section 1: Gradient Descent AlgorithmSince the goal of most learning algorithms is **minimizing the risk (cost) function**, optimization is the soul of learning! The gradient descent algorithm, along with its variations such as stochastic gradient descent, is one of the most powerful and popular optimization method...
#@title Video 1.1: Introduction from IPython.display import YouTubeVideo video = YouTubeVideo(id="PFQeUDxQFls", width=854, height=480, fs=1) print("Video available at https://youtu.be/" + video.id) video #@title Video 1.2: Gradient Descent from IPython.display import YouTubeVideo video = YouTubeVideo(id="Z3dyRLR8GbM", ...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
Gradient Descent (introduced by Augustin-Louis Cauchy in 1847) is an **iterative method** to **minimize** a **continuous** and (ideally) **differentiable function** of **many variables**. DefinitionLet $f(\mathbf{w}): \mathbb{R}^d \rightarrow \mathbb{R}$ be a differentiable function. Gradient Descent is an iterative al...
#@title Video 1.3: Computational Graph from IPython.display import YouTubeVideo video = YouTubeVideo(id="7c8iCHcVgVs", width=854, height=480, fs=1) print("Video available at https://youtu.be/" + video.id) video
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
The last function in *Exercise 1.2* is an example of how overwhelming the derivation of gradients can get, as the number of variables and nested functions increases. This function is still extremely simple compared to the loss functions of modern neural networks. So how do PyTorch and similar frameworks approach such b...
#@title Video 2.1: Automatic Differentiation from IPython.display import YouTubeVideo video = YouTubeVideo(id="h8B8Nlcz7yY", width=854, height=480, fs=1) print("Video available at https://youtu.be/" + video.id) video
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
Deep learning frameworks such as PyTorch, JAX, and TensorFlow come with a very efficient and sophisticated set of algorithms, commonly known as Automatic differentiation. AutoGrad is PyTorch's automatic differentiation engine. Here we start by covering the essentials of AutoGrad, but you will learn more in the coming d...
class SimpleGraph: def __init__(self, w=None, b=None): """Initializing the SimpleGraph Args: w (float): initial value for weight b (float): initial value for bias """ if w is None: self.w = torch.randn(1, requires_grad=True) else: self.w = torch.tensor([w], requires_grad=T...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D2_LinearDeepLearning/solutions/W1D2_Tutorial1_Solution_b9fccdbe.py) It is important to appreciate the fact that PyTorch can follow our operations as we arbitrary go through classes and functions. 2.2 Backward Propagat...
print('Gradient function for prediction =', prediction.grad_fn) print('Gradient function for loss =', square_loss.grad_fn)
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
Now let's kick off backward pass to calculate the gradients by calling the `.backward()` on the tensor we wish to initiate the backpropagation from. Often, `.backward()` is called on the loss, which is the last on the graph. Before doing that, let's calculate the loss gradients:$$\frac{\partial{loss}}{\partial{w}} = - ...
# analytical gradients (remember detaching) ana_dloss_dw = - 2 * feature * (target - prediction.detach())*(1 - prediction.detach()**2) ana_dloss_db = - 2 * (target - prediction.detach())*(1 - prediction.detach()**2) square_loss.backward() # first we should call the backward to build the graph autograd_dloss_dw = simp...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
References and more:* [A GENTLE INTRODUCTION TO TORCH.AUTOGRAD](https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html)* [AUTOMATIC DIFFERENTIATION PACKAGE - TORCH.AUTOGRAD](https://pytorch.org/docs/stable/autograd.html)* [AUTOGRAD MECHANICS](https://pytorch.org/docs/stable/notes/autograd.html)* [AUTOMATIC...
#@title Video 3.1: Putting it together from IPython.display import YouTubeVideo video = YouTubeVideo(id="rUChBWj9ihw", width=854, height=480, fs=1) print("Video available at https://youtu.be/" + video.id) video
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
In this section we will focus on training the simple neural network model from yesterday.
#@title Generate the sample dataset import sklearn.datasets # Create a dataset of 256 points with a little noise X_orig, y_orig = sklearn.datasets.make_moons(256, noise=0.1) # Plot the dataset plt.figure(figsize=(9, 7)) plt.scatter(X_orig[:,0], X_orig[:,1], s=40, c=y_orig) plt.xlabel("$x_1$") plt.ylabel("$x_2$") plt....
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
Let's define the same simple neural network model as in Day 1. This time we will not define a `train` method, but instead implement it outside of the class so we can better inspect it.
# Simple neural network with a single hidden layer class NaiveNet(nn.Module): def __init__(self): """ Initializing the NaiveNet """ super(NaiveNet, self).__init__() self.layers = nn.Sequential( nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 2), ) def forward(self, x): ...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
PyTorch provides us with ready to use neural network building blocks, such as linear or recurrent layers, activation functions and loss functions, packed in the [`torch.nn`](https://pytorch.org/docs/stable/nn.html) module. If we build a neural network using the `torch.nn` layers, the weights and biases are already in `...
# Create an instance of our network naive_model = NaiveNet().to(device) # Create a cross entropy loss function cross_entropy_loss = nn.CrossEntropyLoss() # Stochstic Gradient Descent optimizer with a learning rate of 1e-1 learning_rate = 1e-1 sgd_optimizer = torch.optim.SGD(naive_model.parameters(), lr=learning_rate)
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
The training process in PyTorch is interactive - you can perform training iterations as you wish and inspect the results after each iteration. We encourage leaving the loss function outside the explicit forward pass function, and rather calculate it on the output (prediction).Let's perform one training iteration. You c...
# Reset all gradients to 0 sgd_optimizer.zero_grad() # Forward pass (Compute the output of the model on the data) y_logits = naive_model(X) # Compute the loss loss = cross_entropy_loss(y_logits, y) print('Loss:', loss.item()) # Perform backpropagation to build the graph and compute the gradients loss.backward() # `...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
Exercise 3Following everything we learned so far, we ask you to complete the `train` function below.
def train(features, labels, model, loss_fun, optimizer, n_epochs): """Training function Args: features (torch.Tensor): features (input) with shape torch.Size([n_samples, 2]) labels (torch.Tensor): labels (targets) with shape torch.Size([n_samples, 2]) model (torch nn.Module): the neural network lo...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D2_LinearDeepLearning/solutions/W1D2_Tutorial1_Solution_364cd4e2.py)*Example output:*
#@title Video 3.2: Wrap-up from IPython.display import YouTubeVideo video = YouTubeVideo(id="zFmWs6doqhM", width=854, height=480, fs=1) print("Video available at https://youtu.be/" + video.id) video
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb
haltakov/course-content-dl
Classifying Hourly Timestamps into Day or Night
import pandas as pd import numpy as np import warnings from df2gspread import df2gspread as d2g warnings.simplefilter('ignore') ## Import Raw TTN Data from Google SpreadSheet url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRlXVQ6c3fKWvtQlFRSRUs5TI3soU7EghlypcptOM8paKXcUH8HjYv90VoJBncuEKYIZGLq477xE58C/pub?gid=0...
_____no_output_____
MIT
DataWrangling/ClassifyingTimeStamps.ipynb
diliprk/SmartCityVisualization
Importing SunTime Chart for adding Day or Night Classification Here we add Day or Night classification to Hourly Vehicle Count Data using sunrise and sunset times dataframe of Saarbrucken. These times were acquired from [timeanddate.com](https://www.timeanddate.com/sun/germany/saarbrucken) and the dataframe was manual...
# Reading SunTime Chart of SaarbrΓΌcken url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRJCZQkgUHTCcx-wvJOog87qq4EFiQ1W6T4akxLSpiqCb3KjYDf_43coltDGG0YcjjsDTxjeXE-O_NH/pub?gid=0&single=true&output=csv' df_suntimes = pd.read_csv(url) # Modified Sun Timings DataFrame df_suntimes_mod = pd.DataFrame() df_suntimes_mod...
_____no_output_____
MIT
DataWrangling/ClassifyingTimeStamps.ipynb
diliprk/SmartCityVisualization
Coding MatricesHere are a few exercises to get you started with coding matrices. The exercises start off with vectors and then get more challenging Vectors
### TODO: Assign the vector <5, 10, 2, 6, 1> to the variable v v = []
_____no_output_____
MIT
4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb
mustafa1adel/CVND_Localization_Exercises
The v variable contains a Python list. This list could also be thought of as a 1x5 matrix with 1 row and 5 columns. How would you represent this list as a matrix?
### TODO: Assign the vector <5, 10, 2, 6, 1> to the variable mv ### The difference between a vector and a matrix in Python is that ### a matrix is a list of lists. ### Hint: See the last quiz on the previous page mv = [[]]
_____no_output_____
MIT
4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb
mustafa1adel/CVND_Localization_Exercises
How would you represent this vector in its vertical form with 5 rows and 1 column? When defining matrices in Python, each row is a list. So in this case, you have 5 rows and thus will need 5 lists.As an example, this is what the vector $$$$ would look like as a 1x2 matrix in Python: ```pythonmatrix1by2 = [ [5, 7]]``...
### TODO: Assign the vector <5, 10, 2, 6, 1> to the variable vT ### vT is a 5x1 matrix vT = []
_____no_output_____
MIT
4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb
mustafa1adel/CVND_Localization_Exercises
Assigning Matrices to Variables
### TODO: Assign the following matrix to the variable m ### 8 7 1 2 3 ### 1 5 2 9 0 ### 8 2 2 4 1 m = [[]]
_____no_output_____
MIT
4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb
mustafa1adel/CVND_Localization_Exercises
Accessing Matrix Values
### TODO: In matrix m, change the value ### in the second row last column from 0 to 5 ### Hint: You do not need to rewrite the entire matrix
_____no_output_____
MIT
4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb
mustafa1adel/CVND_Localization_Exercises
Looping through Matrices to do MathCoding mathematical operations with matrices can be tricky. Because matrices are lists of lists, you will need to use a for loop inside another for loop. The outside for loop iterates over the rows and the inside for loop iterates over the columns.Here is some pseudo code```pythonfor...
### TODO: Use for loops to multiply each matrix element by 5 ### Store the answer in the r variable. This is called scalar ### multiplication ### ### HINT: First write a for loop that iterates through the rows ### one row at a time ### ### Then write another for loop within the for loop that ###...
_____no_output_____
MIT
4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb
mustafa1adel/CVND_Localization_Exercises
Printing Out a Matrix
### TODO: Write a function called matrix_print() ### that prints out a matrix in ### a way that is easy to read. ### Each element in a row should be separated by a tab ### And each row should have its own line ### You can test our your results with the m matrix ### HINT: You can use a fo...
_____no_output_____
MIT
4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb
mustafa1adel/CVND_Localization_Exercises
Test Your Results
### You can run these tests to see if you have the expected ### results. If everything is correct, this cell has no output assert v == [5, 10, 2, 6, 1] assert mv == [ [5, 10, 2, 6, 1] ] assert vT == [ [5], [10], [2], [6], [1]] assert m == [ [8, 7, 1, 2, 3], [1, 5, 2, 9, 5], ...
_____no_output_____
MIT
4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb
mustafa1adel/CVND_Localization_Exercises
Print Out Your Results
### Run this cell to print out your answers print(v) print(mv) print(vT) print(m) print(r)
_____no_output_____
MIT
4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb
mustafa1adel/CVND_Localization_Exercises
μˆ™μ œ 1======= μΌλŸ¬λ‘κΈ° :**_κΌΌκΌΌν•˜κ²Œ 읽어보기 λ°”λžλ‹ˆλ‹€_*** `prettytable` λͺ¨λ“ˆμ„ μ„€μΉ˜ν•΄μ•Ό 슀크립트λ₯Ό μ‹€ν–‰ν•  수 있음. (μ„€μΉ˜ 방법: `pip install --user prettytable`) * `flights.db` 파일이 μˆ™μ œμš© Jupyter notebookκ³Ό 같은 디렉터리에 μžˆμ–΄μ•Ό 함 (μ—†λ‹€λ©΄ [μ—¬κΈ°μ„œ](http://open.gnu.ac.kr/lecslides/2018-2-DB/Assignments1/flights.db.zip) λ‹€μš΄ λ°›κΈ°) 압좕을 ν•΄μ œν•΄μ•Ό 함. `flights.db.zip`이 μžˆλŠ” κ³³μ—μ„œ `unzip flights...
%%sql SELECT * FROM flight_delays LIMIT 1;
* sqlite:///flights.db Done.
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
ꡉμž₯히 λ§Žμ€ μ»¬λŸΌλ“€μ΄ μžˆλŠ” 것을 μ•Œ 수 μžˆλŠ”λ°, 그러면 λͺ‡ μ€„μ΄λ‚˜ λ κΉŒμš”?
%%sql SELECT COUNT(*) AS num_rows FROM flight_delays
* sqlite:///flights.db Done.
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
λ°μ΄ν„°μ˜ 양이 μƒλ‹Ήν•©λ‹ˆλ‹€! 손과 머리둜만 해닡을 μ°Ύμ§€ λͺ»ν•  것 κ°™κ΅°μš”. λ°μ΄ν„°λ² μ΄μŠ€μ— 더 λ§Žμ€ 데이터λ₯Ό 넣을 ν•„μš”λŠ” μ—†κ² κ΅°μš”. μ»¬λŸΌλ“€μ΄ μ–΄λ–€ 의미λ₯Ό κ°–λŠ”μ§€ μ•Œμ•„ 보렀면 [이 링크](https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=236)λ₯Ό 따라가기 λ°”λžλ‹ˆλ‹€. λͺ‡ 개의 좔가적인 ν…Œμ΄λΈ”λ“€μ„ 같이 포함해 λ†“μ•˜μŠ΅λ‹ˆλ‹€. 이 ν…Œμ΄λΈ”λ“€μ„ μ‚¬μš©ν•˜λ©΄ `airline_id`, `airport_id`, 그리고 `day_of_week` 을 μ‚¬λžŒμ΄ 읽기 νŽΈν•œ μ •λ³΄λ‘œ λ³€ν™˜ν•  수 μžˆμŠ΅λ‹ˆλ‹€. μ•„λž˜μ˜ 셀을 μ΄μš©ν•˜μ—¬ `airlines`κ³Ό `w...
%%sql
_____no_output_____
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
μ’‹μŠ΅λ‹ˆλ‹€. 이제 μ‹œμž‘ν•΄λ΄…μ‹œλ‹€. SQL 질의문 질의문 1: ν•­κ³΅νŽΈμ˜ 평균 μ§€μ—° μ‹œκ°„μ€? ------------------------데이터에 λŒ€ν•œ 이해λ₯Ό 돕기 μœ„ν•΄, κ°„λ‹¨ν•œ μ§ˆμ˜λ¬Έμ„ μž‘μ„±ν•΄λ΄…μ‹œλ‹€.μ•„λž˜μ˜ 셀에 2017λ…„ 7μ›”λ™μ•ˆ λͺ¨λ“  ν•­κ³΅νŽΈμ˜ 평균 μ§€μ—°μ‹œκ°„μ„ κ΅¬ν•˜λŠ” μ§ˆμ˜λ¬Έμ„ μž‘μ„±ν•΄λ΄…μ‹œλ‹€.
%%sql
_____no_output_____
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
질의문 2: κ°€μž₯ κΈ΄ μ§€μ—° μ‹œκ°„μ€?------------------------평균은 그리 크지 μ•Šκ΅°μš”. ν•˜μ§€λ§Œ _졜μž₯_ μ§€μ—° μ‹œκ°„μ€ μ–΄λ–»κ²Œ λ˜λ‚˜μš”?μ•„λž˜μ˜ 셀에 2017λ…„ 7μ›”λ™μ•ˆ κ°€μž₯ 늦게 λ„μ°©ν•œ μ‹œκ°„μ„ μ°ΎλŠ” μ§ˆμ˜λ¬Έμ„ μž‘μ„±ν•΄λ΄…μ‹œλ‹€.
%%sql
_____no_output_____
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
질의문 3: μ–΄λ–€ ν•­κ³΅νŽΈμ„ ν”Όν•˜λŠ” 것이 μ •μ‹  건강에 μ’‹μ„κΉŒμš”?------------------------μ–΄λ–€ ν•­κ³΅νŽΈμ΄ κ°€μž₯ λŠ¦μ—ˆλ‚˜μš”?μ•„λž˜μ˜ 셀에 2017λ…„ 7월에 κ°€μž₯ 늦게 λ„μ°©ν•œ 항곡사(`carrier`)와 ν•­κ³΅νŽΈ λͺ…, 좜발 λ„μ‹œ λͺ…, 도착 λ„μ‹œ λͺ…, 항곡 일정을 좜λ ₯ν•˜λŠ” μ§ˆμ˜λ¬Έμ„ μž‘μ„± λ°”λžλ‹ˆλ‹€. μ•žμ—μ„œ 얻은 정보λ₯Ό μ§ˆμ˜λ¬Έμ— μ‚½μž…ν•΄μ„œ κ³„μ‚°ν•˜μ§€ 말고 쀑첩 μ§ˆμ˜λ¬Έμ„ μ“°κΈ° λ°”λžλ‹ˆλ‹€.
%%sql
_____no_output_____
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
질의문 4: μ–΄λ–€ μš”μΌμ΄ μ—¬ν–‰ν•˜κΈ° κ°€μž₯ μ•ˆμ’‹μ€ λ‚ μΈκ°€μš”?------------------------ν•™κΈ°κ°€ μ‹œμž‘λ˜μ—ˆμœΌλ‹ˆ λ¨Ό 곳으둜 여행을 ν•  μˆ˜λŠ” μ—†μ§€λ§Œ, 좜μž₯은 κ°€μ•Όν•˜κ² μ§€μš”. λΉ„ν–‰κΈ°λ₯Ό 타기 κ°€μž₯ μ•ˆμ’‹μ€ 날은 무슨 μš”μΌμΈκ°€μš”?μ•„λž˜μ˜ 셀에 μš”μΌλ§ˆλ‹€ 평균 μ§€μ—° μ‹œκ°„μ΄ μ–΄λ–»κ²Œ λ˜λŠ”μ§€ λ‚΄λ¦Όμ°¨μˆœμœΌλ‘œ μ •λ ¬ν•˜μ—¬ κ²°κ³Όλ₯Ό 좜λ ₯ν•˜λ„λ‘ μ§ˆμ˜λ¬Έμ„ μž‘μ„±ν•˜κΈ° λ°”λžλ‹ˆλ‹€. 좜λ ₯ 결과의 μŠ€ν‚€λ§ˆλŠ” (`weekday_name`, `average_delay`)의 ν˜•νƒœλ₯Ό κ°–κ³  μžˆμ–΄μ•Ό ν•©λ‹ˆλ‹€.**Note: μš”μΌμ˜ IDλ₯Ό κ·ΈλŒ€λ‘œ 좜λ ₯ν•˜μ§€ 말기 λ°”λžλ‹ˆλ‹€.** (Hint: `weekdays` ν…Œμ΄λΈ”μ„ μ‚¬μš©ν•˜μ—¬ j...
%%sql
_____no_output_____
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
질의문 5: SFOμ—μ„œ μΆœλ°œν•˜λŠ” 항곡사 쀑 μ§€μ—° μ‹œκ°„μ΄ κ°€μž₯ κΈ΄ ν•­κ³΅μ‚¬λŠ” μ–΄λ””μž…λ‹ˆκΉŒ?------------------------μ–΄λ–€ μš”μΌμ„ ν”Όν•΄μ•Ό ν• μ§€ μ•Œμ•˜μœΌλ‹ˆ SFOμ—μ„œ μΆœλ°œν•˜λŠ” 항곡사 쀑 ν•œ 곳을 μ •ν•΄μ•Ό ν•©λ‹ˆλ‹€. μ–΄λ””λ‘œ κ°ˆμ§€λŠ” λ§ν•˜μ§€ μ•Šμ•˜μœΌλ‹ˆ, SFOμ—μ„œ μΆœλ°œν•˜λŠ” λͺ¨λ“  ν•­κ³΅μ‚¬μ˜ ν•­κ³΅νŽΈλ“€μ˜ 평균 μ§€μ—°μ‹œκ°„μ„ ꡬ해 λ΄…μ‹œλ‹€.μ•„λž˜μ˜ 셀에 2017λ…„ 7월에 SFOμ—μ„œ μΆœλ°œν•œ 각 항곡사 λ³„λ‘œ λͺ¨λ“  ν•­κ³΅νŽΈμ— λŒ€ν•΄ 평균 μ§€μ—°μ‹œκ°„μ„ λ‚΄λ¦Όμ°¨μˆœμœΌλ‘œ κ΅¬ν•˜λŠ” μ§ˆμ˜λ¬Έμ„ μž‘μ„±ν•΄λ΄…μ‹œλ‹€.**Note: 항곡사 IDλ₯Ό κ·ΈλŒ€λ‘œ 좜λ ₯ν•˜μ§€ λ§™μ‹œλ‹€.** (Hint: 쀑첩 질의문으둜 `airlines` ν…Œμ΄...
%%sql
_____no_output_____
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
질의문 6: ν•­κ³΅μ‚¬λ“€μ˜ μ§€μ—° λΉ„μœ¨μ„ μ•Œμ•„ λ΄…μ‹œλ‹€------------------------μ§€μ—°λ˜λŠ” ν•­κ³΅νŽΈμ΄ λ§ŽμŠ΅λ‹ˆλ‹€. μ–΄λ–€ 항곡사가 μ§€μ—°μ‹œκ°„μ΄ λ§Žμ€ μ•Œμ•„λ΄…μ‹œλ‹€.μ•„λž˜μ˜ 셀에 평균 10λΆ„ 이상 μ§€μ—°λ˜λŠ” ν•­κ³΅νŽΈμ΄ μžˆμ—ˆλ˜ ν•­κ³΅μ‚¬λ“€μ˜ λΉ„μœ¨μ„ κ΅¬ν•΄λ΄…μ‹œλ‹€. 전체 ν•­κ³΅μ‚¬μ˜ 수λ₯Ό μ„Έμ„œ μ§ˆμ˜λ¬Έμ— ν¬ν•¨μ‹œν‚€μ§€ 말기 λ°”λžλ‹ˆλ‹€. 그리고 μ§ˆμ˜λ¬Έμ—λŠ” μ΅œμ†Œν•œ ν•˜λ‚˜ μ΄μƒμ˜ `HAVING` μ ˆμ„ μ‚¬μš©ν•©μ‹œλ‹€.Note: sqlite 의 `COUNT(*)`λŠ” μ •μˆ˜ν˜•μ„ λ¦¬ν„΄ν•˜κΈ° λ•Œλ¬Έμ— μ‹€μˆ˜ν˜•μœΌλ‘œ κ²°κ³Όλ₯Ό 좜λ ₯ν•˜λ €λ©΄ μ΅œμ†Œν•œ ν•œ 번 이상 `SELECT CAST (COUNT(*) AS float)` λ˜λŠ” `COU...
%%sql
_____no_output_____
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
질의문 7: 좜발 지연이 도착 지연에 μ–΄λ–€ 영ν–₯을 λ―ΈμΉ˜λ‚˜μš”?------------------------λΉ„ν–‰κΈ°κ°€ μ§€μ—° μΆœλ°œν•˜λ©΄ 도착 μ‹œκ°„μ— μ–Όλ§ˆλ‚˜ 영ν–₯을 μ£ΌλŠ”μ§€ μ•Œκ³  μ‹ΆμŠ΅λ‹ˆλ‹€.[μƒ˜ν”Œ 곡뢄산](https://en.wikipedia.org/wiki/Covariance) 은 두 λ³€μˆ˜ κ°„μ˜ λΆ„μ‚°λŸ‰μ„ μΈ‘μ •ν•˜μ—¬ 상관관계가 μžˆλŠ”μ§€ μ•Œλ €μ£ΌλŠ” ν†΅κ³„μΉ˜μž…λ‹ˆλ‹€. 곡뢄산이 클수둝 상관관계가 λ†’κ³  음수인 경우 역상관관계가 μžˆμŠ΅λ‹ˆλ‹€. μƒ˜ν”Œ κ³΅λΆ„μ‚°μ˜ 계산 식은 λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€:$$Cov(X,Y) = \frac{1}{n-1} \sum_{i=1}^n (x_i-\hat{x})(y_i-\hat{y})$$...
%%sql
_____no_output_____
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
질의문 8: ν•œ μ£Όκ°€ μ—‰λ§μ΄μ—ˆμŠ΅λ‹ˆλ‹€...------------------------7μ›” μ–΄λ–€ ν•­κ³΅μ‚¬μ˜ λ§ˆμ§€λ§‰ ν•œ μ£Ό(24일 이후)의 평균 μ§€μ—° μ‹œκ°„μ΄ κ·Έ 이전 μ£Ό(24일 이전)λ“€μ˜ 평균 μ§€μ—° μ‹œκ°„λ³΄λ‹€ μ ˆλŒ€μ μœΌλ‘œ κΈΈμ—ˆλ‚˜μš”?μ•„λž˜μ˜ 셀에 1일뢀터 23μΌκΉŒμ§€μ˜ 평균 μ§€μ—° μ‹œκ°„ λŒ€λΉ„ 24일 λΆ€ν„° 31일 μ‚¬μ΄μ˜ 평균 μ§€μ—° μ‹œκ°„μ΄ μ ˆλŒ€μ μœΌλ‘œ κΈΈμ—ˆλ˜ ν•­κ³΅μ‚¬μ˜ 이름을 좜λ ₯ν•˜λŠ” μ§ˆμ˜λ¬Έμ„ μž‘μ„±ν•˜κΈ° λ°”λžλ‹ˆλ‹€.Note: [sqliteμ—μ„œ λ‚ μ§œ 닀루기](http://www.sqlite.org/lang_datefunc.html)에 따라 `day_of_month`을 μ‚¬μš©ν•˜μ—¬ μ§ˆμ˜λ¬Έμ„ μž‘μ„±ν•˜λŠ” 것...
%%sql
_____no_output_____
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
질의문 9: 진보적인 그리고 혁λͺ…적인------------------------ν¬νŠΈλžœλ“œ (PDX)와 μœ μ§„ (EUG)둜 κ°€κΈ°λ₯Ό μ›ν•˜μ§€λ§Œ, ν•œ λ²ˆμ— κ°€κΈ°κ°€ 쉽지 μ•Šκ΅°μš”. 우수 고객 λ§ˆμΌλ¦¬μ§€λ₯Ό μ±„μš°κΈ° μœ„ν•΄ 같은 ν•­κ³΅νŽΈμœΌλ‘œ 각 λ„μ‹œλ‘œ μ΄λ™ν•˜κΈ°λ₯Ό μ›ν•©λ‹ˆλ‹€. SFO -> PDF와 SFO -> EUG 둜 κ°€λŠ” 같은 항곡사가 μžˆλŠ”μ§€ μ•Œκ³  μ‹ΆμŠ΅λ‹ˆλ‹€.μ•„λž˜μ˜ 셀에 2017λ…„ 7월에 SFO -> PDX κ³Ό SFO -> EUG 을 μΆœν•­ν•œ ν•­κ³΅μ‚¬μ˜ μœ μΌν•œ 이름(쀑볡 μ—†μŒ ID κ°€ μ•„λ‹˜)을 좜λ ₯ν•˜λŠ” ν•˜λ‚˜μ˜ SQL μ§ˆμ˜λ¬Έμ„ μž‘μ„±ν•˜κΈ° λ°”λžλ‹ˆλ‹€.
%%sql
_____no_output_____
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
질의문 10: ν”Όλ‘œλ„μ™€ 등거리 κ°„μ˜ κ²°μ •------------------------μ‹œμΉ΄κ³ μ—μ„œ μΊ˜λ¦¬ν¬λ‹ˆμ•„λ‘œ μ΄λ™ν•˜λ €κ³  ν•©λ‹ˆλ‹€. Midway (MDW) λ˜λŠ” O'Hare (ORD) μ—μ„œ μƒŒν”„λž€μ‹œμŠ€μ½” (SFO), μ‚°ν˜Έμ„Έ (SJC), μ˜€ν¬λžœλ“œ (OAK)둜 λ„μ°©ν•˜λ©΄ μ’‹κ²ŸμŠ΅λ‹ˆλ‹€. λ§Œμ•½ 이 번 달이 7월이라고 ν•˜λ©΄ μ‹œμΉ΄κ³ μ—μ„œ ν˜„μ§€ μ‹œκ°„ 14μ‹œμ— μΆœλ°œν•˜λŠ” 경둜 쀑 μ§€μ—° μ‹œκ°„μ΄ κ°€μž₯ 짧은 κ²½λ‘œκ°€ μ–΄λ–€ κ²ƒμž…λ‹ˆκΉŒ?μ•„λž˜μ˜ 셀에 MDW λ˜λŠ” ORD μ—μ„œ ν˜„μ§€ μ‹œκ°„ 14μ‹œ(`crs_dep_time`)에 μΆœλ°œν•˜κ³  SFO, SJC, λ˜λŠ” OAK에 λ„μ°©ν•˜λŠ” ν•­κ³΅νŽΈλ“€μ˜ 평균 μ§€μ—° μ‹œκ°„μ„ κ΅¬ν•˜λŠ” ν•˜λ‚˜...
%%sql
_____no_output_____
MIT
Assignments1/HW1.ipynb
resourceful/lecture_db
303 Build NN QuicklyView more, visit my tutorial page: https://morvanzhou.github.io/tutorials/My Youtube Channel: https://www.youtube.com/user/MorvanZhou
import torch import torch.nn.functional as F # replace following class code with an easy sequential network class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer self.pred...
Net( (hidden): Linear(in_features=1, out_features=10, bias=True) (predict): Linear(in_features=10, out_features=1, bias=True) ) Sequential( (0): Linear(in_features=1, out_features=10, bias=True) (1): ReLU() (2): Linear(in_features=10, out_features=1, bias=True) )
MIT
tutorial-contents-notebooks/303_build_nn_quickly.ipynb
harrywang/PyTorch-Tutorial
window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-59152712-8'); Generating C code for the right-hand-side of the scalar wave equation, in ***curvilinear*** coordinates, using a reference metric formalism Author: Zach Etienne Formatting...
import sympy as sp import NRPy_param_funcs as par import indexedexp as ixp import reference_metric as rfm # reference_metric::CoordSystem can be set to Spherical, SinhSpherical, SinhSphericalv2, # Cylindrical, SinhCylindrical, SinhCylindricalv2, etc. # See reference...
contracted GammahatU[0]: -2 ─── xxβ‚€ contracted GammahatU[1]: -1 ───────────── 2 xxβ‚€ β‹…tan(xx₁) contracted GammahatU[2]: 0
BSD-2-Clause
Tutorial-ScalarWaveCurvilinear.ipynb
Steve-Hawk/nrpytutorial
Step 2: The right-hand side of the scalar wave equation in spherical coordinates, using NRPy+ \[Back to [top](toc)\]$$\label{rhs_scalarwave_spherical}$$Following our [implementation of the scalar wave equation in Cartesian coordinates](Tutorial-ScalarWave.ipynb), we will introduce a new variable $v=\partial_t u$ that ...
import NRPy_param_funcs as par import indexedexp as ixp import grid as gri import finite_difference as fin import reference_metric as rfm from outputC import * # The name of this module ("scalarwave") is given by __name__: thismodule = __name__ # Step 0: Read the spatial dimension parameter as DIM. DIM = par.parval_fr...
{ /* * NRPy+ Finite Difference Code Generation, Step 1 of 2: Read from main memory and compute finite difference stencils: */ /* * Original SymPy expressions: * "[const double uu_dD0 = invdx0*(-2*uu_i0m1_i1_i2/3 + uu_i0m2_i1_i2/12 + 2*uu_i0p1_i1_i2/3 - uu_i0p2_i1_i2/12), * const double u...
BSD-2-Clause
Tutorial-ScalarWaveCurvilinear.ipynb
Steve-Hawk/nrpytutorial
Step 3: Code Validation against `ScalarWaveCurvilinear.ScalarWaveCurvilinear_RHSs` NRPy+ Module \[Back to [top](toc)\]$$\label{code_validation}$$Here, as a code validation check, we verify agreement in the SymPy expressions for the RHSs of the Curvilinear Scalar Wave equation (i.e., uu_rhs and vv_rhs) between1. this ...
# Step 7: We already have SymPy expressions for uu_rhs and vv_rhs in # terms of other SymPy variables. Even if we reset the list # of NRPy+ gridfunctions, these *SymPy* expressions for # uu_rhs and vv_rhs *will remain unaffected*. # # Here, we will use the above-defined uu_rhs and vv_r...
Consistency check between ScalarWaveCurvilinear tutorial and NRPy+ module: uu_rhs - swcrhs.uu_rhs: 0 (should be zero) vv_rhs - swcrhs.vv_rhs: 0 (should be zero)
BSD-2-Clause
Tutorial-ScalarWaveCurvilinear.ipynb
Steve-Hawk/nrpytutorial
Step 4: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](toc)\]$$\label{latex_pdf_output}$$The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial direct...
!jupyter nbconvert --to latex --template latex_nrpy_style.tplx --log-level='WARN' Tutorial-ScalarWaveCurvilinear.ipynb !pdflatex -interaction=batchmode Tutorial-ScalarWaveCurvilinear.tex !pdflatex -interaction=batchmode Tutorial-ScalarWaveCurvilinear.tex !pdflatex -interaction=batchmode Tutorial-ScalarWaveCurvilinear.t...
[pandoc warning] Duplicate link reference `[comment]' "source" (line 23, column 1) This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded format=pdflatex) restricted \write18 enabled. entering extended mode This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded forma...
BSD-2-Clause
Tutorial-ScalarWaveCurvilinear.ipynb
Steve-Hawk/nrpytutorial
Find the top rooms ignited and the top materials in those rooms that were first ignited
import psycopg2 import pandas as pd from IPython.display import display conn = psycopg2.connect(service='nfirs') pd.options.display.max_rows = 1000 df = pd.read_sql_query("select * from codelookup where fieldid = 'PROP_USE' and length(code_value) = 3 order by code_value", conn)['code_value'] codes = list(df.values)
_____no_output_____
MIT
sources/nfirs/scripts/popular-room-ignitions.ipynb
tbuffington7/data
By property use type (batch by property type)
# Create a CSV for each property use type q = """SELECT x.prop_use, area_orig, first_ign, x.civ_inj, x.civ_death, x.flame_sprd, x.item_sprd, x.cnt FROM ( SELECT *, row_number() over (partition BY area_orig ORDER BY area_...
_____no_output_____
MIT
sources/nfirs/scripts/popular-room-ignitions.ipynb
tbuffington7/data