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 |
;
# 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.