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 |
|---|---|---|---|---|---|
Slices | a = np.arange(15)
a = a.reshape((3,5))
a
# Just a copy of the array
a[:]
a[:, 0]
a[1, :]
a[2, :] = (np.arange(5) + 1) * 10
a
a < 10
a[a < 12]
np.where(a < 12)
xs, ys = np.where(a < 20)
a[xs, ys] | _____no_output_____ | MIT | lecture1/NumPy_crash_course.ipynb | HSE-LaMBDA/modern-technologies-for-ml-and-big-data |
Matplotlib | import matplotlib.pyplot as plt
# Don't forget this magic expression if want to show plots in notebook
%matplotlib inline
xs = np.arange(100)
ys = np.cumsum(np.random.standard_normal(size=100)) | _____no_output_____ | MIT | lecture1/NumPy_crash_course.ipynb | HSE-LaMBDA/modern-technologies-for-ml-and-big-data |
Line plot | plt.figure()
plt.plot(xs, ys)
plt.show()
# A little bit of options
plt.figure()
plt.plot(xs, ys, label="1st series", color="green")
plt.plot(xs, ys.max() - ys, label="2nd series", color="red")
plt.legend(loc="upper right")
plt.xlabel("Time, sec")
plt.ylabel("Something")
plt.title("Just two random series")
plt.show() | _____no_output_____ | MIT | lecture1/NumPy_crash_course.ipynb | HSE-LaMBDA/modern-technologies-for-ml-and-big-data |
Bar plot | plt.figure()
plt.bar(xs, ys)
plt.show()
plt.figure()
h, bins, patches = plt.hist(ys)
plt.show() | _____no_output_____ | MIT | lecture1/NumPy_crash_course.ipynb | HSE-LaMBDA/modern-technologies-for-ml-and-big-data |
Scatter plot | xs1 = np.random.standard_normal(size=100)
ys1 = np.random.standard_normal(size=100)
xs2 = np.random.standard_normal(size=100) + 3
ys2 = np.random.standard_normal(size=100)
plt.scatter(xs1, ys1, label="class1", color="green")
plt.scatter(xs2, ys2, label="class2", color="red")
plt.plot([1.5, 1.5], [-4, 4], linewidth=3)
... | _____no_output_____ | MIT | lecture1/NumPy_crash_course.ipynb | HSE-LaMBDA/modern-technologies-for-ml-and-big-data |
Images | means=np.array([[-1, 1], [-1, 1]])
stds = np.array([1, 1.1])
@np.vectorize
def normal_density(mx, my, std, x, y):
return np.exp(
-((x - mx) ** 2 + (y - my) ** 2) / 2.0 / std / std
) / std / std
@np.vectorize
def f(x, y):
return np.sum(
normal_density(means[0, :], means[1, :], stds, x, y... | _____no_output_____ | MIT | lecture1/NumPy_crash_course.ipynb | HSE-LaMBDA/modern-technologies-for-ml-and-big-data |
Data engineeringIn this section we'll explore the climate data for Hawaii by:+ checking for missing data (null values)+ checking for duplicates ResultsNo duplicate data was found in either the station data nor in the measurements data.There was about 7.4 % of null values found in the measurements data (1447 rows on a ... | # Dependencies
import pandas as pd
import os
# Load files into dataframe
## Measurement file
input_file_m = input("Enter the name of the measurement file you want to analyze (without extension): ") + ".csv"
filepath_m = os.path.join('Resources', input_file_m)
measurement_df = pd.read_csv(filepath_m)
## Station file
inp... | _____no_output_____ | ADSL | Hawaii vacation/data_engineering.ipynb | tardis123/Hawaii-vacation |
Shallow Parsing - Chunking | # Do imports
import nltk
data = "The authority did not permit giving of fishing permit."
tokens = nltk.word_tokenize(data)
print(tokens)
tag = nltk.pos_tag(tokens)
print(tag)
grammar = "NP: {<DT>?<JJ>*<NN>}"
cp =nltk.RegexpParser(grammar)
result = cp.parse(tag)
print(result)
result.draw() # It will draw the pat... | _____no_output_____ | MIT | l5-syntax/syntax exploration.ipynb | biplav-s/course-nl |
# Required Libraries
import numpy as np
import pandas as pd
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
from keras.layers import LSTM, Dense, TimeDistributed, Embedding, Bidirectional
from keras.models import Model, Input
from keras_contrib.layers import CRF
from keras... | _____no_output_____ | MIT | NER_LSTM.ipynb | piyushsharma1812/recurrent-neural-networks | |
please use keras==2.2.4 | # Evaluation
y_pred = model.predict(X_test)
y_pred = np.argmax(y_pred, axis=-1)
y_test_true = np.argmax(y_test, -1)
# Convert the index to tag
y_pred = [[idx2tag[i] for i in row] for row in y_pred]
y_test_true = [[idx2tag[i] for i in row] for row in y_test_true]
print("F1-score is : {:.1%}".format(f1_score(y_test_true,... | _____no_output_____ | MIT | NER_LSTM.ipynb | piyushsharma1812/recurrent-neural-networks |
虚谷号WebGPIO应用(客户端Python版)虚谷号和手机(App inventor)如何互动控制?虚谷号和掌控板如何互动控制?为了让虚谷号和其他开源硬件、编程语言快速互动,虚谷号的WebGPIO应运而生。简单的说,只要在虚谷号上运行一个python文件,就可以用WebAPI的形式来与虚谷号互动,可以获取虚谷号板载Arduino的所有引脚的电平,也可以控制所有引脚。 1.接口介绍要在虚谷号上运行“webgpio.py”。也可以将“webgpio.py”文件更名为“main.py”,复制到vvBoard的Python目录,只要一开机,虚谷号就会执行。下载地址:https://github.com/vvlink/vvBoard-d... | import requests
vvboardip='192.168.3.42'
pin='D13'
value=1
t=1
payload = {"pin":pin,'value':value,'type':t}
re = requests.post(url='http://'+ vvboardip +':1024/',params=payload)
if (re.status_code==200):
r=re.json()
print('成功发送控制命令:'+ r["msg"])
print('返回的信息为:')
print(re.text) | 成功发送控制命令:success,set D13 to 1 with 1 mode
返回的信息为:
{
"error_code": 0,
"msg": "success,set D13 to 1 with 1 mode",
"pin": "D13"
}
| MIT | 课程汇集/虚谷号内置课程目录/1.虚谷号GPIO/WebGPIO/虚谷号WebGPIO应用(客户端Python版) .ipynb | xiezuoru/vvBoard-docs |
2.2. 调用GET方法,读取A0号引脚的电平。在该案例中可以修改的参数有: - url:设置成虚谷号的IP地址 - pin:对应的引脚 A0-A5,D0-D13 注意:该方法需要外接传感器,否则数字口默认返回为低电平,模拟口返回随机数。 | import requests
vvboardip='192.168.3.42'
pin='A0'
payload = {"pin":pin}
re = requests.get(url='http://'+ vvboardip +':1024/',params=payload)
if (re.status_code==200):
r=re.json()
print('成功获取引脚'+ r["pin"] + '的状态:'+ r["msg"])
print('返回的原始信息为:')
print(re.text) | 成功获取引脚A0的状态:393
返回的原始信息为:
{
"error_code": 0,
"msg": "393",
"pin": "A0"
}
| MIT | 课程汇集/虚谷号内置课程目录/1.虚谷号GPIO/WebGPIO/虚谷号WebGPIO应用(客户端Python版) .ipynb | xiezuoru/vvBoard-docs |
Toy EnvironmentIn this exercise we will learn how to implement a simple Toy environment using Python. The environment is illustrated in figure. It is composed of 3 states and 2 actions. The initial state is state 1.The goal of this exercise is to implement a class Environment with a ... | from typing import Tuple
class Environment:
def __init__(self):
"""
Constructor of the Environment class.
"""
self._initial_state = 1
self._allowed_actions = [0, 1] # 0: A, 1: B
self._states = [1, 2, 3]
self._current_state = self._initial_state
def step(... | Initial state is 1
From state 1 to state 2 with action 0, reward: 1
From state 2 to state 1 with action 0, reward: 0
From state 1 to state 3 with action 1, reward: 10
From state 3 to state 3 with action 1, reward: 10
From state 3 to state 2 with action 0, reward: 0
From state 2 to state 3 with action 1, reward: 1
| MIT | Chapter01/Exercise01_01/Exercise01_01.ipynb | adityashah95/The-Reinforcement-Learning-Workshop |
The second example shows how to set up a power-law spectral source, as well as how to add two sets of photons together.This example will also briefly show how to set up a mock dataset "in memory" using yt. For more details on how to do this, check out [the yt docs on in-memory datasets](http://yt-project.org/doc/examin... | %matplotlib inline
import matplotlib
matplotlib.rc("font", size=18, family="serif")
import yt
import numpy as np
import matplotlib.pyplot as plt
from yt.utilities.physical_ratios import cm_per_kpc, K_per_keV
from yt.units import mp
import pyxsim | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
The cluster we set up will be a simple isothermal $\beta$-model system, with a temperature of 4 keV. We'll set it up on a uniform grid of 2 Mpc and 256 cells on a side. The parameters of the model are: | R = 1000. # radius of cluster in kpc
r_c = 100. # scale radius of cluster in kpc
rho_c = 1.673e-26 # scale density in g/cm^3
beta = 1. # beta parameter
kT = 4. # cluster temperature in keV
nx = 256
ddims = (nx,nx,nx) | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
and we set up the density and temperature arrays: | x, y, z = np.mgrid[-R:R:nx*1j,
-R:R:nx*1j,
-R:R:nx*1j]
r = np.sqrt(x**2+y**2+z**2)
dens = np.zeros(ddims)
dens[r <= R] = rho_c*(1.+(r[r <= R]/r_c)**2)**(-1.5*beta)
dens[r > R] = 0.0
temp = kT*K_per_keV*np.ones(ddims) | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
Next, we will take the density and temperature arrays and put them into a dictionary with their units, where we will also set up velocity fields set to zero. Then, we'll call the yt function `load_uniform_grid` to set this up as a full-fledged yt dataset. | data = {}
data["density"] = (dens, "g/cm**3")
data["temperature"] = (temp, "K")
data["velocity_x"] = (np.zeros(ddims), "cm/s")
data["velocity_y"] = (np.zeros(ddims), "cm/s")
data["velocity_z"] = (np.zeros(ddims), "cm/s")
bbox = np.array([[-0.5, 0.5], [-0.5, 0.5], [-0.5, 0.5]]) # The bounding box of the domain in code ... | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
The next thing we have to do is specify a derived field for the normalization of the power-law emission. This could come from a variety of sources, for example, relativistic cosmic-ray electrons. For simplicity, we're not going to assume a specific model, except that we will only specify that the source of the power la... | norm = yt.YTQuantity(1.0e-19, "photons/s/keV")
def _power_law_emission(field, data):
return norm*data["cell_mass"]/mp
ds.add_field(("gas","power_law_emission"), function=_power_law_emission, units="photons/s/keV") | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
where we have normalized the field arbitrarily. Note that the emission field for a power-law model is a bit odd in that it is technically a specific *luminosity* for the cell. This is done primarily for simplicity in designing the underlying algorithm. Now, let's set up a sphere to collect photons from: | sp = ds.sphere("c", (0.5, "Mpc")) | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
And set the parameters for the initial photon sample: | A = yt.YTQuantity(500., "cm**2")
exp_time = yt.YTQuantity(1.0e5, "s")
redshift = 0.03 | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
Set up two source models, a thermal model and a power-law model: | thermal_model = pyxsim.ThermalSourceModel("apec", 0.01, 80.0, 80000, Zmet=0.3)
plaw_model = pyxsim.PowerLawSourceModel(1.0, 0.01, 80.0, "power_law_emission", 1.0) | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
Now, generate the photons for each source model. After we've generated the photons for both, we'll add them together. | thermal_photons = pyxsim.PhotonList.from_data_source(sp, redshift, A, exp_time, thermal_model)
plaw_photons = pyxsim.PhotonList.from_data_source(sp, redshift, A, exp_time, plaw_model)
photons = thermal_photons + plaw_photons | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
Now, we want to project the photons along a line of sight. We'll specify the `"wabs"` model for foreground galactic absorption. We'll create events from the total set of photons as well as the power-law only set, to see the difference between the two. | events = photons.project_photons("x", (30.0, 45.0), absorb_model="wabs", nH=0.02)
plaw_events = plaw_photons.project_photons("x", (30.0, 45.0), absorb_model="wabs", nH=0.02) | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
Finally, create energy spectra for both sets of events. We won't bother convolving with instrument responses here, because we just want to see what the spectra look like. | events.write_spectrum("all_spec.fits", 0.1, 80.0, 8000, overwrite=True)
plaw_events.write_spectrum("plaw_spec.fits", 0.1, 80.0, 8000, overwrite=True) | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
To visualize the spectra, we'll load them up using [AstroPy's FITS I/O](http://docs.astropy.org/en/stable/io/fits/) and use [Matplotlib](http://matplotlib.org) to plot the spectra: | import astropy.io.fits as pyfits
f1 = pyfits.open("all_spec.fits")
f2 = pyfits.open("plaw_spec.fits")
plt.figure(figsize=(9,7))
plt.loglog(f2["SPECTRUM"].data["ENERGY"], f2["SPECTRUM"].data["COUNTS"])
plt.loglog(f1["SPECTRUM"].data["ENERGY"], f1["SPECTRUM"].data["COUNTS"])
plt.xlim(0.1, 50)
plt.ylim(1, 2.0e4)
plt.xlabe... | _____no_output_____ | BSD-3-Clause | doc/source/cookbook/Power_Law.ipynb | NegriAndrea/pyxsim |
This is a markdown cellYou can format text here in markdown. You can have subheadings- You can have bullet points1. numbered lists$and \ more$There are lots of markdown resources on the web you can use to learn markdown. Here's a starting point: https://guides.github.com/features/mastering-markdown/ More on Anaconda ... | #This is a code cell You can run code here. Try running the code cells
print('Hello World')
a = 2+3
print(a) | _____no_output_____ | MIT | Session-1/Assignments/Assignment-1A/first_notebook.ipynb | Madhuparna04/ML-Series |
While attempting to compare limma's results for log-transformed an non-transformed data, it was noticed (and brought up by Dr Tim) That the values of logFC produced by limma for non-transformed data are of wrong order of magnitude. I have investigated the issue, following the limma calculations for non-transformed data... | indexed_by_target_path = 'data/clean/protein/indexed_by_target.csv'
clinical_path = 'data/clean/protein/clinical_data_ordered_to_match_proteins_matrix.csv'
clinical = read_csv(clinical_path, index_col=0)
raw_protein_matrix = read_csv(indexed_by_target_path, index_col=0)
by_condition = clinical.Meningitis
tb_lysozyme = ... | _____no_output_____ | MIT | analyses/notes/Limma_expects_log_transformed_data.ipynb | krassowski/meningitis-integration |
While for the transformed data: | from numpy import log10
log10(tb_lysozyme)
log10(hc_lysozyme)
log10(tb_lysozyme) / log10(hc_lysozyme)
protein_matrix = raw_protein_matrix.apply(log10)
%%R -i protein_matrix -i by_condition
import::here(space_to_dot, dot_to_space, .from='helpers/utilities.R')
import::here(
limma_fit, limma_diff_ebayes, full_table,
... | [1] 61798.2
| MIT | analyses/notes/Limma_expects_log_transformed_data.ipynb | krassowski/meningitis-integration |
We can trace it back to: | %%R
fit = limma_fit(
data=raw_protein_matrix, conditions_vector=by_condition,
a='Tuberculosis', b='Healthy control'
)
%%R
fit$coefficients['Lysozyme', ] | [1] 61798.2
| MIT | analyses/notes/Limma_expects_log_transformed_data.ipynb | krassowski/meningitis-integration |
It changes when using using only the data from TB and HC, though it continues to produce large values: | %%R
fit = limma_fit(
data=raw_protein_matrix, conditions_vector=by_condition,
a='Tuberculosis', b='Healthy control', use_all=F
)
%%R
fit$coefficients['Lysozyme', ] | Intercept Group
59749.21 30899.10
| MIT | analyses/notes/Limma_expects_log_transformed_data.ipynb | krassowski/meningitis-integration |
Getting back to the previous version, we can see that the meansare correctly calculated: | %%R
design <- design_from_conditions(by_condition)
fit <- calculate_means(raw_protein_matrix, design)
%%R
fit$coefficients['Lysozyme', ]
tb_lysozyme, hc_lysozyme
%%R
contrast_specification <- paste(
space_to_dot('Tuberculosis'),
space_to_dot('Healthy control'),
sep='-'
)
contrast.matrix <- limma::makeContra... | Contrasts
Levels Tuberculosis-Healthy.control
Intercept 0
Healthy.control -1
Tuberculosis 1
Viral 0
| MIT | analyses/notes/Limma_expects_log_transformed_data.ipynb | krassowski/meningitis-integration |
There is only one step more:> fit <- limma::contrasts.fit(fit, contrast.matrix)so the problem must be here | %%R
fit_contrasted <- limma::contrasts.fit(fit, contrast.matrix)
fit_contrasted$coefficients['Lysozyme', ] | [1] 61798.2
| MIT | analyses/notes/Limma_expects_log_transformed_data.ipynb | krassowski/meningitis-integration |
Note the result we got: 61798.20 is: | tb_lysozyme - hc_lysozyme
%%R
final_fit = limma::eBayes(fit_contrasted, trend=T, robust=T)
final_fit$coefficients['Lysozyme', ] | [1] 61798.2
| MIT | analyses/notes/Limma_expects_log_transformed_data.ipynb | krassowski/meningitis-integration |
AVGN TutorialThis tutorial walks you through getting started with AVGN on a sample dataset, so you can figure out how to use it on your own data. If you're not too familiar with Python, make sure you've first familiarized yourself with Jupyter notebooks and installing pyhton packages. Then come back and try the tutori... | from avgn.downloading.download import download_tqdm
from avgn.utils.paths import DATA_DIR
from avgn.utils.general import unzip_file
from tqdm.autonotebook import tqdm
# where the files are located online (url, filename)
data_urls = [
('https://ndownloader.figshare.com/articles/3470165/versions/1', 'all_files.zip'),... | _____no_output_____ | MIT | tutorial/0.0-Start-Here.ipynb | xingjeffrey/avgn_paper |
Getting the data into a usable formatNow that the data is saved, we want to get the annotations into the same format as all of the other datasets. The format we use is JSON, which just holds a dictionary of information about the dataset. For each .WAV file, we will create a JSON that looks something like this:```{ ... | from datetime import datetime
import avgn.utils
import numpy as np
RAW_DATASET_LOC = output_loc/"zip_contents"
RAW_DATASET_LOC
# first we create a name for our dataset
DATASET_ID = 'koumura_bengalese_finch'
# create a unique datetime identifier for the files output by this notebook
DT_ID = datetime.now().strftime("%Y-... | _____no_output_____ | MIT | tutorial/0.0-Start-Here.ipynb | xingjeffrey/avgn_paper |
Now, for each wav file, we want to generate a JSON, using information from the XML.Lets take a look inside an XML first, to see what's in there. It might be useful to take a look at this XML file in your web browser to get a better idea of what's in there as well. | import xml.etree.ElementTree
import xml.dom.minidom
# print a sample of the XML
parssed = xml.dom.minidom.parse(annotation_files[0].as_posix())
pretty_xml_as_string = dom.toprettyxml()
print(pretty_xml_as_string[:400] + '...') | <?xml version="1.0" ?>
<Sequences>
<NumSequence>1350</NumSequence>
<Sequence>
<WaveFileName>0.wav</WaveFileName>
<Position>32000</Position>
<Length>64832</Length>
<NumNote>15</NumNote>
<Note>
<Position>5056</Position>
<Length>1440</Length>
<Label>0</Label>
</Note>
<Note>
<Position>8512</Posi... | MIT | tutorial/0.0-Start-Here.ipynb | xingjeffrey/avgn_paper |
Parse XML Before we create a JSON, we can create a pandas dataframe with all the relevant info from the XML. This is all very specific to this dataset, but hopefully it gives you an idea of what you need to do for your dataset. | import pandas as pd
song_df = pd.DataFrame(
columns=[
"bird",
"WaveFileName",
"Position",
"Length",
"NumNote",
"NotePositions",
"NoteLengths",
"NoteLabels",
]
)
song_df
# loop through XML annotation files... | _____no_output_____ | MIT | tutorial/0.0-Start-Here.ipynb | xingjeffrey/avgn_paper |
Now we can generate a JSON from that pandas dataframe | from avgn.utils.audio import get_samplerate
import librosa
from avgn.utils.json import NoIndent, NoIndentEncoder
# for each bird
for bird in tqdm(np.unique(song_df.bird)):
# grab that bird's annotations
bird_df = song_df[song_df.bird == bird]
# for each wav file produced by that bird
for wfn in tqd... | {
"species": "Lonchura striata domestica",
"common_name": "Bengalese finch",
"wav_loc": "/mnt/cube/tsainbur/Projects/github_repos/avgn_paper/data/raw/koumura/zip_contents/Bird9/Wave/216.wav",
"samplerate_hz": 32000,
"length_s": 11.124,
"indvs": {
"Bird9": {
"notes": {
"start_times": [1.158... | MIT | tutorial/0.0-Start-Here.ipynb | xingjeffrey/avgn_paper |
First BigQuery ML models for Taxifare PredictionIn this notebook, we will use BigQuery ML to build our first models for taxifare prediction.BigQuery ML provides a fast way to build ML models on large structured and semi-structured datasets. Learning Objectives1. Choose the correct BigQuery ML model type and specify op... | import os | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/first_model.ipynb | jonesevan007/training-data-analyst |
Set environment variables | %%bash
export PROJECT=$(gcloud config list project --format "value(core.project)")
echo "Your current GCP Project Name is: "$PROJECT
PROJECT = "your-gcp-project-here" # REPLACE WITH YOUR PROJECT NAME
REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
# Do not change these
os.environ["BUCKET"] = ... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/first_model.ipynb | jonesevan007/training-data-analyst |
Create a BigQuery Dataset and Google Cloud Storage BucketA BigQuery dataset is a container for tables, views, and models built with BigQuery ML. Let's create one called __serverlessml__ if we have not already done so in an earlier lab. We'll do the same for a GCS bucket for our project too. | %%bash
## Create a BigQuery dataset for serverlessml if it doesn't exist
datasetexists=$(bq ls -d | grep -w serverlessml)
if [ -n "$datasetexists" ]; then
echo -e "BigQuery dataset already exists, let's not recreate it."
else
echo "Creating BigQuery dataset titled: serverlessml"
bq --location=US mk --dat... | BigQuery dataset already exists, let's not recreate it.
Bucket exists, let's not recreate it.
| Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/first_model.ipynb | jonesevan007/training-data-analyst |
Model 1: Raw dataLet's build a model using just the raw data. It's not going to be very good, but sometimes it is good to actually experience this.The model will take a minute or so to train. When it comes to ML, this is blazing fast. | %%bigquery
CREATE OR REPLACE MODEL
serverlessml.model1_rawdata
OPTIONS(input_label_cols=['fare_amount'],
model_type='linear_reg') AS
SELECT
(tolls_amount + fare_amount) AS fare_amount,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/first_model.ipynb | jonesevan007/training-data-analyst |
Once the training is done, visit the [BigQuery Cloud Console](https://console.cloud.google.com/bigquery) and look at the model that has been trained. Then, come back to this notebook. Note that BigQuery automatically split the data we gave it, and trained on only a part of the data and used the rest for evaluation. We ... | %%bigquery
SELECT * FROM ML.EVALUATE(MODEL serverlessml.model1_rawdata) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/first_model.ipynb | jonesevan007/training-data-analyst |
Let's report just the error we care about, the Root Mean Squared Error (RMSE) | %%bigquery
SELECT
SQRT(mean_squared_error) AS rmse
FROM
ML.EVALUATE(MODEL serverlessml.model1_rawdata) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/first_model.ipynb | jonesevan007/training-data-analyst |
We told you it was not going to be good! Recall that our heuristic got 8.13, and our target is $6. Note that the error is going to depend on the dataset that we evaluate it on.We can also evaluate the model on our own held-out benchmark/test dataset, but we shouldn't make a habit of this (we want to keep our benchmark... | %%bigquery
SELECT
SQRT(mean_squared_error) AS rmse
FROM
ML.EVALUATE(MODEL serverlessml.model1_rawdata, (
SELECT
(tolls_amount + fare_amount) AS fare_amount,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude ... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/first_model.ipynb | jonesevan007/training-data-analyst |
Model 2: Apply data cleanupRecall that we did some data cleanup in the previous lab. Let's do those before training.This is a dataset that we will need quite frequently in this notebook, so let's extract it first. | %%bigquery
CREATE OR REPLACE TABLE
serverlessml.cleaned_training_data AS
SELECT
(tolls_amount + fare_amount) AS fare_amount,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude AS dropofflat,
passenger_count*1.0 AS passengers
FROM
... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/first_model.ipynb | jonesevan007/training-data-analyst |
Model 3: More sophisticated modelsWhat if we try a more sophisticated model? Let's try Deep Neural Networks (DNNs) in BigQuery: DNNTo create a DNN, simply specify __dnn_regressor__ for the model_type and add your hidden layers. | %%bigquery
-- This model type is in alpha, so it may not work for you yet.
-- This training takes on the order of 15 minutes.
CREATE OR REPLACE MODEL
serverlessml.model3b_dnn
OPTIONS(input_label_cols=['fare_amount'],
model_type='dnn_regressor', hidden_units=[32, 8]) AS
SELECT
*
FROM
serverlessml.c... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/first_model.ipynb | jonesevan007/training-data-analyst |
Nice! Evaluate DNN on benchmark datasetLet's use the same validation dataset to evaluate -- remember that evaluation metrics depend on the dataset. You can not compare two models unless you have run them on the same withheld data. | %%bigquery
SELECT
SQRT(mean_squared_error) AS rmse
FROM
ML.EVALUATE(MODEL serverlessml.model3b_dnn, (
SELECT
(tolls_amount + fare_amount) AS fare_amount,
pickup_datetime,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/first_model.ipynb | jonesevan007/training-data-analyst |
PlottingHere you can explore the different possibilities that the hep_spt package offers for plotting. | %matplotlib inline
import hep_spt
hep_spt.set_style()
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.stats import norm | _____no_output_____ | MIT | docs/notebooks/plotting.ipynb | mramospe/hepspt |
Plotting a (non)weighted sampleUse the function "errorbar_hist" to plot the same sample without and with weights. In the non-weighted case, we will ask for frequentist poissonian errors, so we will get asymmetric error bars for low values of the number of entries. | # Create a random sample
size = 200
smp = np.random.normal(0, 3, size)
wgts = np.random.uniform(0, 1, size)
fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(10, 5))
# Make the non-weighted plot
values, edges, ex, ey = hep_spt.errorbar_hist(smp, bins=10, range=(-7, 7), uncert='freq')
centers = (edges[1:] + edges[:-1])/2... | _____no_output_____ | MIT | docs/notebooks/plotting.ipynb | mramospe/hepspt |
Calculating the pull of a distributionSometimes we want to calculate the distance in terms of standard deviations from a curve to our measurements. This example creates a random sample of events following a normal distribution and overlies it with the original curve. The pull plot is shown below. | # Create the samples
size=5e3
sample = norm.rvs(size=int(size))
values, edges, ex, ey = hep_spt.errorbar_hist(sample, 40, range=(-4, 4), uncert='freq')
centers = (edges[1:] + edges[:-1])/2.
# Extract the PDF values in each center, and make the pull
ref = norm.pdf(centers)
ref *= size/ref.sum()
pull, perr = hep_spt... | _____no_output_____ | MIT | docs/notebooks/plotting.ipynb | mramospe/hepspt |
Plotting efficienciesLet's suppose we build two histograms from the same sample, one of them after having applied some requirements. The first histogram will follow a gaussian distribution with center at 0 and standard deviation equal to 2, with 1000 entries. The second, with only 100 entries, will have the same cent... | # Create a random sample
raw = np.random.normal(0, 2, 1000)
cut = np.random.normal(0, 0.5, 100)
# Create the histograms (we do not care about the errors for the moment). Note that the two
# histograms have the same number of bins and range.
h_raw, edges = np.histogram(raw, bins=10, range=(-2, 2))
h_cut, _ = np.his... | _____no_output_____ | MIT | docs/notebooks/plotting.ipynb | mramospe/hepspt |
Displaying the correlation between variables on a sampleThe hep_spt package also provides a way to easily plot the correlation among the variables on a given sample. Let's create a sample composed by 5 variables, two being independent and three correlated with them, and plot the results. Note that we must specify the ... | # Create a random sample
a = np.random.uniform(0, 1, 1000)
b = np.random.normal(0, 1, 1000)
c = a + np.random.uniform(0, 1, 1000)
ab = a*b
abc = ab + c
smp = np.array([a, b, c, ab, abc])
# Calculate the correlation
corr = np.corrcoef(smp)
# Plot the results
fig = plt.figure()
hep_spt.corr_hist2d(corr, ['a', '... | _____no_output_____ | MIT | docs/notebooks/plotting.ipynb | mramospe/hepspt |
Plotting a 2D profileWhen making 2D histograms, it is often useful to plot the profile in X or Y of the given distribution. This can be done as follows: | # Create a random sample
s = 10000
x = np.random.normal(0, 1, s)
y = np.random.normal(0, 1, s)
# Make the figure
fig = plt.figure()
ax = fig.gca()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
h, xe, ye, im = ax.hist2d(x, y, (40, 40), range=[(-2.5, +2.5), (-2.5, +2.5)])
... | _____no_output_____ | MIT | docs/notebooks/plotting.ipynb | mramospe/hepspt |
```Copyright 2021 IBM CorporationLicensed 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.0Unless required by applicable law or agreed to in writing, softwaredistrib... | cd ../../
CACHE_DIR='cache-dir'
import numpy as np
import time
from datasets import CreditCardFraud
from sklearn.tree import DecisionTreeClassifier
from snapml import DecisionTreeClassifier as SnapDecisionTreeClassifier
from sklearn.metrics import roc_auc_score as score
dataset = CreditCardFraud(cache_dir=CACHE_DIR)
X_... | Speed-up: 34.8 x
Relative diff. in score: 0.0130
| Apache-2.0 | examples/training/decision_tree/example_credit_card_fraud.ipynb | LaudateCorpus1/snapml-examples |
DisclaimerPerformance results always depend on the hardware and software environment. Information regarding the environment that was used to run this notebook are provided below: | import utils
environment = utils.get_environment()
for k,v in environment.items():
print("%15s: %s" % (k, v)) | platform: Linux-4.15.0-136-generic-x86_64-with-glibc2.10
cpu_count: 16
cpu_freq_min: 1200.0
cpu_freq_max: 3200.0
total_memory: 62.825439453125
snapml_version: 1.7.0
sklearn_version: 0.24.1
| Apache-2.0 | examples/training/decision_tree/example_credit_card_fraud.ipynb | LaudateCorpus1/snapml-examples |
Record StatisticsFinally, we record the enviroment and performance statistics for analysis outside of this standalone notebook. | import scrapbook as sb
sb.glue("result", {
'dataset': dataset.name,
'n_examples_train': X_train.shape[0],
'n_examples_test': X_test.shape[0],
'n_features': X_train.shape[1],
'n_classes': len(np.unique(y_train)),
'model': type(model).__name__,
'score': score.__name__,
't_fit_sklearn': t_f... | _____no_output_____ | Apache-2.0 | examples/training/decision_tree/example_credit_card_fraud.ipynb | LaudateCorpus1/snapml-examples |
In this notebook you will apply what you have just learned about cqasm and Quantum Inspire. We will consider a simple quantum algorithm, the quantum approximate optimization algorithm (QAOA), for which you will code the circuit in cqasm and send some jobs to real quantum hardware on the Quantum Inspire platform. 1. Re... | # Just some function to draw graphs
def draw_cc_graph(G,node_color='b',fig_size=4):
plt.figure(figsize=(fig_size,fig_size))
nx.draw(G, G.pos,
node_color= node_color,
with_labels=True,
node_size=1000,font_size=14)
plt.show()
# Define the objective function
def maxcut_obj(x,G):
cu... | _____no_output_____ | Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
Test instances | w2 = np.matrix([
[0, 1],
[1, 0]])
G2 = nx.from_numpy_matrix(w2)
positions = nx.circular_layout(G2)
G2.pos=positions
print('G2:')
draw_cc_graph(G2)
w3 = np.matrix([
[0, 1, 1],
[1, 0, 1],
[1, 1, 0]])
G3 = nx.from_numpy_matrix(w3)
positions = nx.circular_layout(G3)
G3.pos=positions
print('G3:')
draw_cc_graph(G3) | G2:
| Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
3. Circuit generators We provide you with an example written in qiskit. You have to write the one for cqasm yourself. Qiskit generators | class Qiskit(object):
# Cost operator:
def get_cost_operator_circuit(G, gamma):
N = G.number_of_nodes()
qc = QuantumCircuit(N,N)
for i, j in G.edges():
qc.cx(i,j)
qc.rz(2*gamma, j)
qc.cx(i,j)
return qc
# Mixing operator
def get... | _____no_output_____ | Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
cqasm generators Now it is up to you to apply what we have learned about cqasm to write the script for the cost and mixing operators: | class Cqasm(object):
### We give them this part
def get_qasm_header(N_qubits):
"""
Create cQASM header for `N_qubits` qubits and prepare all in |0>-state.
"""
header = f"""
version 1.0
qubits {N_qubits}
prep_z q[0:{N_qubits-1}]
"""
return header
def get_cost... | _____no_output_____ | Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
4. Hybrid-quantum classical optimization Since QAOA is usually adopted as a hybrid quantum-classical algorithm, we need to construct an outer loop which optimizes the estimated $\bra{\gamma,\beta}H\ket{\gamma,\beta}$. | # Black-box function that describes the energy output of the QAOA quantum circuit
def get_black_box_objective(G, p, SDK = 'qiskit', backend = None, shots=2**10):
if SDK == 'cqasm':
if not backend:
backend = 'QX single-node simulator'
backend_type = qi.get_backend_type_by_name(backend... | _____no_output_____ | Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
5. A simple instance on the quantum inspire platform: 2-qubit case Let us first consider the most simple MAXCUT instance. We have just two nodes, and an optimal cut with objective value 1 would be to place both nodes in its own set. | G=G2
max_costs_bf, max_sol_bf,costs = brute_force(G)
print("brute force method best cut: ",max_costs_bf)
print("best string brute force method:",max_sol_bf)
colors = ['red' if x == '0' else 'b' for x in max_sol_bf]
draw_cc_graph(G,node_color = colors) | brute force method best cut: 1
best string brute force method: 01
| Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
Using qiskit, the circuit would look the following: | # Test and show circuit for some beta,gamma
p = 1
beta = np.random.rand(p)*np.pi
gamma = np.random.rand(p)*2*np.pi
qc = Qiskit.get_qaoa_circuit(G,beta, gamma)
qc.draw(output='mpl') | _____no_output_____ | Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
Now let's run our hybrid-quantum algorithm simulation using qiskit: | # Parameters that can be changed:
p = 1
lb = np.zeros(2*p)
ub = np.hstack([np.full(p, np.pi), np.full(p, 2*np.pi)])
init_point = np.random.uniform(lb, ub, 2*p)
shots = 2**10
optimiser = 'COBYLA'
max_iter = 100
# Training of the parameters beta and gamma
obj = get_black_box_objective(G,p,SDK='qiskit',shots=shots)
# Low... | Probability of measuring the optimal solution is 1.0
| Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
Now that we have obtained some good values for $\beta$ and $\gamma$ through classical simulation, let's see what Starmon-5 would give us. The figure below shows the topology of Starmon-5. Since q0 is not connected to q1, we have to relabel the nodes. Networkx as such an option, by using 'nx.relabel_nodes(G,{1:2}' we ca... | Image(filename='Starmon5.png')
qc_Cqasm = Cqasm.get_qaoa_circuit(nx.relabel_nodes(G, {1: 2}), optimal_theta[:p], optimal_theta[p:])
print(qc_Cqasm) |
version 1.0
qubits 5
prep_z q[0:4]
{H q[0] | H q[2]}
.U_gamma_1
CNOT q[0], q[2]
Rz q[2], 1.5828114789648722
CNOT q[0], q[2]
.U_beta_1
{Rx q[0], -0.798661078152829 | Rx q[2], -0.798661078152829}
measure_all
| Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
Now we run the Cqasm-circuit on the Starmon-5 Hardware. | authentication = get_authentication()
QI.set_authentication(authentication, QI_URL)
qiapi = QuantumInspireAPI(QI_URL, authentication)
result = qiapi.execute_qasm(qc_Cqasm, backend_type=qiapi.get_backend_type('Starmon-5'), number_of_shots=2**10)
counts_QI = result['histogram'] | _____no_output_____ | Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
Inspecting 'counts_QI', we see that it returns the integer corresponding to the bit string result of the measurement | counts_QI | _____no_output_____ | Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
Note that we measure more than just the two relevant qubits, since we had the 'measure all' command in the the cqasm code. The distribution over the strings looks the following: | counts_bin = {}
for k,v in counts_QI.items():
counts_bin[f'{int(k):05b}'] = v
print(counts_bin)
plt.bar(counts_bin.keys(), counts_bin.values())
plt.xlabel('State')
plt.ylabel('Measurement probability')
plt.xticks(rotation='vertical')
plt.show() | {'00000': 0.056640625, '00001': 0.4208984375, '00010': 0.005859375, '00011': 0.021484375, '00100': 0.3994140625, '00101': 0.0283203125, '00110': 0.0234375, '00111': 0.001953125, '01000': 0.001953125, '01001': 0.0068359375, '01100': 0.015625, '01101': 0.001953125, '10001': 0.0009765625, '10100': 0.0078125, '10110': 0.00... | Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
Let's create another counts dictionary with only the relevant qubits, which are q0 and q2: | counts_bin_red = defaultdict(float)
for string in counts_bin:
q0 = string[-1]
q1 = string[-3]
counts_bin_red[(q0+q1)]+=counts_bin[string]
counts_bin_red | _____no_output_____ | Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
We now plot all distributions (qiskit, Starmon-5, and random guessing) in a single plot. | #Determine the approximation ratio:
print('Approximation ratio on the hardware is',-compute_maxcut_energy(counts_bin_red,G)/max_costs_bf)
# Random guessing distribution
RG_dist = random_guessing_dist(G)
# Measurement distribution
E_dist_S5 = defaultdict(int)
for k, v in counts_bin_red.items():
E_dist_S5[maxcut_o... | Approximation ratio on the hardware is 0.9033203125
| Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
6. Compilation issues: the triangle graph For the graph with just two nodes we already had some minor compilation issues, but this was easily fixed by relabeling the nodes. We will now consider an example for which relabeling is simply not good enough to get it mapped to the Starmon-5 toplogy. | G=G3
max_costs_bf, max_sol_bf,costs = brute_force(G)
print("brute force method best cut: ",max_costs_bf)
print("best string brute force method:",max_sol_bf)
colors = ['red' if x == '0' else 'b' for x in max_sol_bf]
draw_cc_graph(G,node_color = colors) | brute force method best cut: 2
best string brute force method: 001
| Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
Due to the topology of Starmon-5 this graph cannot be executed without any SWAPS. Therefore, we ask you to write a new circuit generator that uses SWAPS in order to make the algorithm work with the Starmon-5 topology. Let's also swap back to the original graph configuration, so that we can in the end measure only the q... | def QAOA_triangle_circuit_cqasm(graph, beta, gamma):
circuit_str = Cqasm.get_qasm_header(5)
circuit_str += "{" + ' | '.join([f"H q[{i}]" for i in graph.nodes()]) + "}\n\n"
def get_triangle_cost_operator(graph, gamma, p):
layer_list = graph.number_of_edges() * [None]
for n, edge in enume... | _____no_output_____ | Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
We now run the same procedure as before to obtain good parameter values | # Parameters that can be changed:
p = 1
lb = np.zeros(2*p)
ub = np.hstack([np.full(p, np.pi), np.full(p, 2*np.pi)])
init_point = np.random.uniform(lb, ub, 2*p)
shots = 2**10
optimiser = 'COBYLA'
max_iter = 100
# Training of the parameters beta and gamma
obj = get_black_box_objective(G,p,SDK='qiskit',shots=shots)
# Low... | _____no_output_____ | Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
Let's run it on Starmon-5 again! | # Extract the optimal values for beta and gamma and run a new circuit with these parameters
optimal_theta = res['x']
qasm_circuit = QAOA_triangle_circuit_cqasm(G, optimal_theta[:p], optimal_theta[p:])
qiapi = QuantumInspireAPI(QI_URL, authentication)
result = qiapi.execute_qasm(qasm_circuit, backend_type=qiapi.get_back... | Approximation ratio on the hardware is 0.8984375
| Apache-2.0 | docs/notebooks/eqtc_workshop/EQTC_workshop_QAOA_tutorial_solution.ipynb | QuTech-Delft/quantum-inspire-examples |
Detection and Location Chain **Abstract**: This hackathon project represents our effort to combine our existing machine learning and photogrametry efforts and further combine those efforts with both Cloud and Edge based solutions based upon Xilinx FPGA acceleration. The Trimble team decided that the Xilinx hackathon w... | ## Imports
import cv2
import json
import matplotlib.pyplot as pyplot
import numpy
import matplotlib.patches as patches
import pynq.overlays.base
import pynq.lib.arduino as arduino
import pynq.lib.video as video
import requests
import scipy
import sys
import PIL
## Config
gAWS_TENSORFLOW_INSTANCE = 'http://34.202.159.... | _____no_output_____ | BSD-3-Clause | teams/team_trimble/Trimble.ipynb | AbinMM/PYNQ_Hackathon_2017 |
Turn on the HDMI coming off the pink board. This is used in a fashion that is different than their primary test notes and may be difficult to complete during the time period. Specifically, the hdmi out is used without the input | base = pynq.overlays.base.BaseOverlay("base.bit")
hdmi_in = base.video.hdmi_in
hdmi_out = base.video.hdmi_out
v = video.VideoMode(1920,1080,24)
hdmi_out.configure(v, video.PIXEL_BGR)
hdmi_out.start()
outframe = hdmi_out.newframe() | _____no_output_____ | BSD-3-Clause | teams/team_trimble/Trimble.ipynb | AbinMM/PYNQ_Hackathon_2017 |
Using Pillow, pull in the chosen image for Camera 0 | # Read images
image0BGR = cv2.imread(gCAMERA0_IMAGE)
image1BGR = cv2.imread(gCAMERA1_IMAGE)
image0 = image0BGR[...,::-1]
image1 = image1BGR[...,::-1] | _____no_output_____ | BSD-3-Clause | teams/team_trimble/Trimble.ipynb | AbinMM/PYNQ_Hackathon_2017 |
Do exactly the same for the second image of the overlapping pair from camera 1 To send one of these to the HDMI, we are going to have to reformat it to fit the provided HDMI display | # Show image 0 on HDMI
# Need to resize it first
outframe[:] = cv2.resize(image0BGR, (1920, 1080));
hdmi_out.writeframe(outframe) | _____no_output_____ | BSD-3-Clause | teams/team_trimble/Trimble.ipynb | AbinMM/PYNQ_Hackathon_2017 |
We will also display Young-Jin to the LCD screen. Why ? Because Young Jin does awesome work and deserves to be famous and also because I can | ## Show image on LCD
# Open LCD object and clear
lcd = arduino.Arduino_LCD18(base.ARDUINO)
lcd.clear()
# Write image to disk
nw = 160
nl = 128
cv2.imwrite("/home/xilinx/small.jpg", cv2.resize(image0BGR, (nw,nl)))
# Display!
lcd.display("/home/xilinx/small.jpg",x_pos=0,y_pos=127,orientation=3,background=[255,255,255]... | _____no_output_____ | BSD-3-Clause | teams/team_trimble/Trimble.ipynb | AbinMM/PYNQ_Hackathon_2017 |
We now need to classify the images. This runs the remote version of TensorFlow on the image to get the bounding box. The following routine wraps this for simplicity. The spun up AWS TensorFlow instance is expecting to get besent a JPEG and will classify and send back the results as JSON.The IP address of the spun up AW... | def RemoteTensorFlowClassify(image_name_string):
f = open(image_name_string,'rb')
r = requests.put(gAWS_TENSORFLOW_INSTANCE, data=f)
return json.loads(r.content.decode()) | _____no_output_____ | BSD-3-Clause | teams/team_trimble/Trimble.ipynb | AbinMM/PYNQ_Hackathon_2017 |
Actually call the defined function on images from camera 1 and camera 2. | #Return the object that camera zero sees with the maximum score
cam0_json_return = RemoteTensorFlowClassify(gCAMERA0_IMAGE)
json0 = cam0_json_return["image_detection"]
max = 0.0
out = []
for var in json0['object']:
if (var['score'] > max):
out = var
json0 = out
json0
#Return the object that camera one sees ... | _____no_output_____ | BSD-3-Clause | teams/team_trimble/Trimble.ipynb | AbinMM/PYNQ_Hackathon_2017 |
The AWS tensorflow reports the bounding boxes for the required object. | def DrawRect(the_json,the_image, x1, x2, y1, y2 ):
# Currently offline until the TesnorFlow net is fixed
#x1 = int(the_json["xmin"])
#y1 = int(the_json["ymin"])
#x2 = int(the_json["xmax"])
#y2 = int(the_json["ymax"])
fig, ax = pyplot.subplots(1)
ax.imshow(the_image)
rect = pat... | _____no_output_____ | BSD-3-Clause | teams/team_trimble/Trimble.ipynb | AbinMM/PYNQ_Hackathon_2017 |
Full mesh triangularization is off line until we reconsile the camera calibration. There was an issue discovered during the hackathon that needs to be examined in teh lab setup s the code below this will not function until we reconsile the camera calibration config. | # Triangulate points
# We need projection matrices for camera 0 and camera 1
f = 8.350589e+000 / 3.45E-3
cx = -3.922872e-002 / 3.45E-3
cy = -1.396717e-004 / 3.45E-3
K_C0 = numpy.transpose(numpy.asarray([[f, 0, 0], [0, f, 0], [cx, cy, 1]]))
k_C0 = numpy.asarray([1.761471e-003, -2.920431e-005, -8.341438e-005, -9.470247e... | _____no_output_____ | BSD-3-Clause | teams/team_trimble/Trimble.ipynb | AbinMM/PYNQ_Hackathon_2017 |
Real single ray These are the real single ray operands. Real raytracing is exact raytracing without paraxial approximation. | import pandas as pd
import itables
from itables import init_notebook_mode, show
import itables.options as opt
init_notebook_mode(all_interactive=True)
opt.lengthMenu = [50, 100, 200, 500]
#opt.classes = ["display", "cell-border"]
#opt.classes = ["display", "nowrap"]
opt.columnDefs = [{"className": "dt-left", "target... | _____no_output_____ | MIT | _build/jupyter_execute/KDP-2_operands_real_single_ray.ipynb | Jonas231/OpticalDesignDocu_o |
Write a Python program that displays your full name, student number, age, and course | class Student():
def __init__(self, fullname, studentnumber, age, course):
self.fullname = fullname
self.studentnumber = studentnumber
self.age = age
self.course = course
def name(self):
return self.fullname
def number(self):
return self.studentnumber
def ageko(self):
return self.... | My Full Name is Jeremiah Manalang
My Student Number is 202010993
My Age is 20
My Course is Computer Engineering
| Apache-2.0 | Prelim_Exam.ipynb | jeremayaaa/OOP-58001 |
6 - Pivot TableIn this sixth step I'll show you how to reshape your data using a pivot table.This will provide a nice condensed version. We'll reshape the data so that we can see how much each customer spent in each category. | import pandas as pd
import numpy as np
df = pd.read_json("customer_data.json", convert_dates=False)
df.head() | _____no_output_____ | BSD-3-Clause | 6 - Pivot Table.ipynb | NickScherer/example-NickScherer.github.io |
Taking a quick look using the .head() function, we can see all of the columns, and the first few rows of the data.For this example, let's just use the first 50 rows of the data. | df_subset = df[0:50]
df_subset | _____no_output_____ | BSD-3-Clause | 6 - Pivot Table.ipynb | NickScherer/example-NickScherer.github.io |
Let's take a look at the types for each column using the .dtypes method. | df_subset.dtypes | _____no_output_____ | BSD-3-Clause | 6 - Pivot Table.ipynb | NickScherer/example-NickScherer.github.io |
The amount column should be a numeric type, but Pandas thinks it's an object. Let's go ahead and change that column to a numeric float type using the .astype() method. | df_subset["amount"] = df_subset["amount"].astype(float)
df_subset.dtypes | C:\Users\NickScherer\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#i... | BSD-3-Clause | 6 - Pivot Table.ipynb | NickScherer/example-NickScherer.github.io |
Now we can see that the amount column is a numeric float type. We don't need all of the columns, just the customer_id, category, and amount columns.Here's what that smaller dataframe would look like. | df_subset[["customer_id", "category", "amount"]] | _____no_output_____ | BSD-3-Clause | 6 - Pivot Table.ipynb | NickScherer/example-NickScherer.github.io |
Let's finish up by creating our pivot_table.We'll set the index to customer_id, the columns to category, and the values to amount. This will reshape the data so that we can see how much each customer spent in each category. Let's create this using a new dataframe called df_pivot.The final important point before we resh... | # pivot table; aggregation function "sum"
df_pivot = df_subset.pivot_table(index="customer_id", columns="category", values="amount", aggfunc=np.sum)
print(df_pivot) | category appliances clothing electronics house household outdoor
customer_id
100102 NaN NaN NaN 70.66 NaN NaN
100103 NaN NaN 78.61 NaN NaN NaN
100105 NaN ... | BSD-3-Clause | 6 - Pivot Table.ipynb | NickScherer/example-NickScherer.github.io |
Wandb> Integration with [Weights & Biases](https://docs.wandb.com/library/integrations/fastai) First thing first, you need to install wandb with```pip install wandb```Create a free account then run ``` wandb login```in your terminal. Follow the link to get an API token that you will need to paste, then you're all set... | #export
import wandb
from wandb.wandb_config import ConfigError
#export
class WandbCallback(Callback):
"Saves model topology, losses & metrics"
toward_end,remove_on_fetch,run_after = True,True,FetchPredsCallback
# Record if watch has been called previously (even in another instance)
_wandb_watch_called ... | _____no_output_____ | Apache-2.0 | nbs/70_callback.wandb.ipynb | tyoc213-contrib/fastai2 |
Optionally logs weights and or gradients depending on `log` (can be "gradients", "parameters", "all" or None), sample predictions if ` log_preds=True` that will come from `valid_dl` or a random sample pf the validation set (determined by `seed`). `n_preds` are logged in this case.If used in combination with `SaveModelC... | #export
def _make_plt(img):
"Make plot to image resolution"
# from https://stackoverflow.com/a/13714915
my_dpi = 100
fig = plt.figure(frameon=False, dpi=my_dpi)
h, w = img.shape[:2]
fig.set_size_inches(w / my_dpi, h / my_dpi)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig... | _____no_output_____ | Apache-2.0 | nbs/70_callback.wandb.ipynb | tyoc213-contrib/fastai2 |
Example of use:Once your have defined your `Learner`, before you call to `fit` or `fit_one_cycle`, you need to initialize wandb:```import wandbwandb.init()```To use Weights & Biases without an account, you can call `wandb.init(anonymous='allow')`.Then you add the callback to your `learner` or call to `fit` methods, po... | #hide
#slow
from fastai.vision.all import *
path = untar_data(URLs.MNIST_TINY)
items = get_image_files(path)
tds = Datasets(items, [PILImageBW.create, [parent_label, Categorize()]], splits=GrandparentSplitter()(items))
dls = tds.dataloaders(after_item=[ToTensor(), IntToFloatTensor()])
os.environ['WANDB_MODE'] = 'dryr... | _____no_output_____ | Apache-2.0 | nbs/70_callback.wandb.ipynb | tyoc213-contrib/fastai2 |
Export - | #hide
from nbdev.export import *
notebook2script() | Converted 00_torch_core.ipynb.
Converted 01_layers.ipynb.
Converted 02_data.load.ipynb.
Converted 03_data.core.ipynb.
Converted 04_data.external.ipynb.
Converted 05_data.transforms.ipynb.
Converted 06_data.block.ipynb.
Converted 07_vision.core.ipynb.
Converted 08_vision.data.ipynb.
Converted 09_vision.augment.ipynb.
Co... | Apache-2.0 | nbs/70_callback.wandb.ipynb | tyoc213-contrib/fastai2 |
Detecting Payment Card FraudIn this section, we'll look at a credit card fraud detection dataset, and build a binary classification model that can identify transactions as either fraudulent or valid, based on provided, *historical* data. In a [2016 study](https://nilsonreport.com/upload/content_promo/The_Nilson_Report... | import io
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import boto3
import sagemaker
from sagemaker import get_execution_role
%matplotlib inline | _____no_output_____ | MIT | Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb | simonmijares/ML-case-studies |
I'm storing my **SageMaker variables** in the next cell:* sagemaker_session: The SageMaker session we'll use for training models.* bucket: The name of the default S3 bucket that we'll use for data storage.* role: The IAM role that defines our data and model permissions. | # sagemaker session, role
sagemaker_session = sagemaker.Session()
role = sagemaker.get_execution_role()
# S3 bucket name
bucket = sagemaker_session.default_bucket()
| _____no_output_____ | MIT | Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb | simonmijares/ML-case-studies |
Loading and Exploring the DataNext, I am loading the data and unzipping the data in the file `creditcardfraud.zip`. This directory will hold one csv file of all the transaction data, `creditcard.csv`.As in previous notebooks, it's important to look at the distribution of data since this will inform how we develop a fr... | # only have to run once
!wget https://s3.amazonaws.com/video.udacity-data.com/topher/2019/January/5c534768_creditcardfraud/creditcardfraud.zip
!unzip creditcardfraud
# read in the csv file
local_data = 'creditcard.csv'
# print out some data
transaction_df = pd.read_csv(local_data)
print('Data shape (rows, cols): ', t... | Data shape (rows, cols): (284807, 31)
| MIT | Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb | simonmijares/ML-case-studies |
EXERCISE: Calculate the percentage of fraudulent dataTake a look at the distribution of this transaction data over the classes, valid and fraudulent. Complete the function `fraudulent_percentage`, below. Count up the number of data points in each class and calculate the *percentage* of the data points that are fraudul... | transaction_df[transaction_df['Class']==1].count()[0]
# Calculate the fraction of data points that are fraudulent
def fraudulent_percentage(transaction_df):
'''Calculate the fraction of all data points that have a 'Class' label of 1; fraudulent.
:param transaction_df: Dataframe of all transaction data points... | _____no_output_____ | MIT | Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb | simonmijares/ML-case-studies |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.