markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Note that the asymmetry parameter becomes negative at the reflection peak (as expected, since light is preferentially backscattered), and, as a result, the transport length has a dip in the same wavelength region.
Calculating the reflection spectrum of a core-shell particle system, with either an absorbing or non-absor... | # Example calculation for a core-shell particle system (core is polystyrene and shell is silica, in a matrix of air)
from structcol import model
# parameters for our colloidal sample
volume_fraction = sc.Quantity(0.5, '')
radius = sc.Quantity(np.array([110,120]), 'nm')
# wavelengths of interest
wavelength = sc.Quant... | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Calculating the reflection spectrum of a polydisperse system with either one species or two species of particles
We can calculate the spectrum of a polydisperse system with either one or two species of particles, meaning that there are one or two mean radii, and each species has its own size distribution. We then need ... | # Example calculation for a polydisperse system with two species of particles, each with its own size distribution
from structcol import model
# parameters for our colloidal sample
volume_fraction = sc.Quantity(0.5, '')
radius = sc.Quantity('100 nm')
# define the parameters for polydispersity
radius2 = sc.Quantity('1... | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Note that the polydisperse case has a broader and red-shifted peak compared to the monodisperse case. This trend makes sense since the polydisperse system contains 10$\%$ of larger particles than the monodisperse system.
Mie scattering module
Normally you won't need to use this model on its own, but if you want to, st... | from structcol import mie | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Form factor calculation: | wavelen = sc.Quantity('450 nm')
n_matrix = ri.n('vacuum', wavelen)
n_particle = ri.n('polystyrene', wavelen)
radius = sc.Quantity('0.4 um')
m = sc.index_ratio(n_particle, n_matrix)
x = sc.size_parameter(wavelen, n_matrix, radius)
# must explicitly state whether angles are in radians or degrees
angles = sc.Quantity(np.... | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Structure module
To use this module: | from structcol import structure | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Here is an example of calculating structure factors with the Percus-Yevick approximation. The code is fully vectorized, so we can calculate structure factors for a variety of qd values and volume fractions in parallel: | qd = np.arange(0.1, 20, 0.01)
phi = np.array([0.15, 0.3, 0.45])
# this little trick allows us to calculate the structure factor on a 2d
# grid of points (turns qd into a column vector and phi into a row vector).
# Could also use np.ogrid
s = structure.factor_py(qd.reshape(-1,1), phi.reshape(1,-1))
for i in range(len(p... | tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Google Colab interagration | %%bash
test ! -z $COLAB_GPU || exit 0 # Run only if running on Google Colab
test ! -f ampl.installed || exit 0 # Run only once
rm -rf ampl.linux-intel64
# You can install a demo bundle with all solvers:
# curl -O https://portal.ampl.com/dl/amplce/ampl.linux64.tgz && tar xzf ampl.linux64.tgz
# Or pick individual mod... | notebooks/colab_bash.ipynb | ampl/amplpy | bsd-3-clause |
Import, instantiate an ampl object and register jupyter notebook magics | from amplpy import AMPL, register_magics
ampl = AMPL()
# Store %%ampl cells in the list _ampl_cells
# Evaluate %%ampl_eval cells with ampl.eval()
register_magics(store_name='_ampl_cells', ampl_object=ampl) | notebooks/colab_bash.ipynb | ampl/amplpy | bsd-3-clause |
Import libraries | import os
from datetime import datetime
import apache_beam as beam
import numpy as np
import tensorflow.io as tf_io | notebooks/community/analytics-componetized-patterns/retail/recommendation-system/bqml-scann/02_export_bqml_mf_embeddings.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Configure GCP environment settings
Update the following variables to reflect the values for your GCP environment:
PROJECT_ID: The ID of the Google Cloud project you are using to implement this solution.
BUCKET: The name of the Cloud Storage bucket you created to use with this solution. The BUCKET value should be just ... | PROJECT_ID = "yourProject" # Change to your project.
BUCKET = "yourBucketName" # Change to the bucket you created.
REGION = "yourDataflowRegion" # Change to your Dataflow region.
BQ_DATASET_NAME = "recommendations"
!gcloud config set project $PROJECT_ID | notebooks/community/analytics-componetized-patterns/retail/recommendation-system/bqml-scann/02_export_bqml_mf_embeddings.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Export the item embedding vector data
Export the item embedding data to Cloud Storage by using a Dataflow pipeline. This pipeline does the following:
Reads the item embedding records from the item_embeddings table in BigQuery.
Writes each item embedding record to a CSV file.
Writes the item embedding CSV files to a Cl... | runner = "DataflowRunner"
timestamp = datetime.utcnow().strftime("%y%m%d%H%M%S")
job_name = f"ks-bqml-export-embeddings-{timestamp}"
bq_dataset_name = BQ_DATASET_NAME
embeddings_table_name = "item_embeddings"
output_dir = f"gs://{BUCKET}/bqml/item_embeddings"
project = PROJECT_ID
temp_location = os.path.join(output_dir... | notebooks/community/analytics-componetized-patterns/retail/recommendation-system/bqml-scann/02_export_bqml_mf_embeddings.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Parameters | # parameters of the filter
beta = 0.33
n_sps = 8 # samples per symbol
syms_per_filt = 4 # symbols per filter (plus minus in both directions)
K_filt = 2 * syms_per_filt * n_sps + 1 # length of the fir filter
# set symbol time
t_symb = 1.0
# switch for normalizing all signals in order to only loo... | nt2_ce2/vorlesung/ch_3_channels/multipath.ipynb | kit-cel/lecture-examples | gpl-2.0 |
Define Channel | # defining delays of multi-path and their weight
# NOTE: No "sanity check" if lengths correspond, so errors may occurr
# choose whether delays of multipath are
# (0) in multiples of the symbol time t_sym or
# (1) in multiples of the sampling time t_sym / n_sps
channel_factors = [ 1.0, .5, .1 ]
delay_type = 1
if de... | nt2_ce2/vorlesung/ch_3_channels/multipath.ipynb | kit-cel/lecture-examples | gpl-2.0 |
Pulse Shape and Effect of Multi-Path on Pulse Shape | rrc = get_rrc_ir( K_filt, n_sps, t_symb, beta)
r_rrc = np.convolve( rrc, h_channel )
if normalize_signals:
rrc /= np.linalg.norm( rrc )
r_rrc /= np.linalg.norm( r_rrc ) | nt2_ce2/vorlesung/ch_3_channels/multipath.ipynb | kit-cel/lecture-examples | gpl-2.0 |
show pulse and version after multi-path | plt.figure()
plt.plot( np.arange(len(rrc)), rrc, linewidth=2.0, label='$g_{\\mathrm{rrc}}(t)$')
plt.plot( np.arange(len(r_rrc)), r_rrc, linewidth=2.0, label='$r(t)$')
plt.legend(loc='upper right')
plt.grid(True)
plt.xlabel('$n/t$') | nt2_ce2/vorlesung/ch_3_channels/multipath.ipynb | kit-cel/lecture-examples | gpl-2.0 |
show spectra
Note: Both spectra are normalized to have equal energy in frequency regime | rrc_padded = np.hstack( ( rrc , np.zeros( 9*len(rrc) ) ) )
rrc_padded = np.roll( rrc_padded, -( K_filt - 1 ) // 2 )
RRC = np.fft.fft( rrc_padded )
r_rrc_padded = np.hstack( ( r_rrc , np.zeros( 10*len(rrc) - len( r_rrc ) ) ) )
r_rrc_padded = np.roll( r_rrc_padded, -( K_filt - 1 ) // 2 )
R_rrc = np.fft.fft( r_rrc_pad... | nt2_ce2/vorlesung/ch_3_channels/multipath.ipynb | kit-cel/lecture-examples | gpl-2.0 |
Note: Spectrum is shown to emphasize that pulse shape might be distorted.
Real Data Modulated Tx-signal | # number of symbols and samples per symbol
n_symb = 8
# modulation scheme and constellation points
constellation = np.array( [ 1 , -1] )
# generate random binary vector and modulate the specified modulation scheme
d = np.random.randint( 2, size = n_symb )
s = constellation[ d ]
# prepare sequence to be filtered by u... | nt2_ce2/vorlesung/ch_3_channels/multipath.ipynb | kit-cel/lecture-examples | gpl-2.0 |
show signals | plt.plot( np.arange(len(s_up)), np.max(np.abs(s_Tx)) * np.real(s_up),'vr', ms=12, label='$A_n$')
plt.plot( np.arange(len(s_Tx)), np.real(s_Tx), linewidth=2.0, label='$s(t)=\sum A_ng_{\\mathrm{rrc}}(t-nT)$')
plt.plot( np.arange(len(s_up_delayed)), np.max(np.abs(s_Tx)) * np.real(s_up_delayed),'xg', ms=18, label='$A... | nt2_ce2/vorlesung/ch_3_channels/multipath.ipynb | kit-cel/lecture-examples | gpl-2.0 |
Note I: The sybol values (except for scaling) may be obtained by sampling the signal $s(t)$ at times being delayed by $\tau_\mathrm{g}$, equaling the group delay of the pulse shaping filter.
Note II: So, in upcoming plots symbols $A_n$ (without delay) will be omitted and only $A_{n-\tau_\mathrm{g}}$ will be shown. | plt.plot( np.arange(len(s_up_delayed)), np.max(np.abs(s_Tx)) * np.real(s_up_delayed),'x', ms=18, label='$A_{n-\\tau_\mathrm{g}}$')
plt.plot( np.arange(len(s_up_delayed_delayed)), np.max(np.abs(s_Tx)) * np.real(s_up_delayed_delayed),'D', ms=12, label='$A_{n-2\\tau_\mathrm{g}}$')
plt.plot( np.arange(len(s_Tx)), ... | nt2_ce2/vorlesung/ch_3_channels/multipath.ipynb | kit-cel/lecture-examples | gpl-2.0 |
Note: If the channel is perfect, i.e, no channel is active at all, then MF at the receiver--matched to rrc--leads to signal $y_\mathrm{rrc}(t)$ whose samples with delay $2\tau_\mathrm{g}$ corresponds to the transmitted symbols. | plt.plot( np.arange(len(s_up_delayed)), np.max(np.abs(s_Tx)) * np.real(s_up_delayed),'x', ms=18, label='$A_{n-\\tau_\mathrm{g}}$')
plt.plot( np.arange(len(s_up_delayed_delayed)), np.max(np.abs(s_Tx)) * np.real(s_up_delayed_delayed),'D', ms=12, label='$A_{n-2\\tau_\mathrm{g}}$')
... | nt2_ce2/vorlesung/ch_3_channels/multipath.ipynb | kit-cel/lecture-examples | gpl-2.0 |
TB Model
We pick the following parameters:
+ hopping constant $ t= 250$ meV
+ $\Delta = 1.0 t$ so that $T_c^{MF} = 0.5 t$, and so that $\xi_0 \simeq a_0$
+ $g = -0.25$, unitless, so as to match the article's formalism, not the thesis'
+ $J = \dfrac{0.1 t}{0.89}$ so as to set $T_{KT} = 0.1 t$.
This means that we have th... | Tc_mf = meV_to_K(0.5*250)
print '$T_c^{MF} = $', Tc_mf, "K"
print r"$T_{KT} = $", Tc_mf/10.0, "K" | Notebooks/test_DOS.ipynb | dombrno/PG | bsd-2-clause |
Instantiation | T_CST = 0.25
MY_PARAMS = {"width":10, "chem_potential": 0.0,
"hopping_constant": T_CST, "J_constant": 0.1 * T_CST / 0.89,
"delta": 1.0 * T_CST,
"use_assaad": False, "broadening_delta": 0.01 * T_CST}
MY_MODEL = TbModel(MY_PARAMS) | Notebooks/test_DOS.ipynb | dombrno/PG | bsd-2-clause |
Modification | TB_PARAMS = {"width":20, "use_assaad": True}
MY_MODEL.set_params(TB_PARAMS)
print MY_MODEL | Notebooks/test_DOS.ipynb | dombrno/PG | bsd-2-clause |
DOS Computation | fig, ax = plt.subplots(figsize = (10, 8), dpi=100, frameon=False)
x_axis_ampl = 4.5
xmin = -x_axis_ampl
xmax = x_axis_ampl
ax.set_xlim([xmin, xmax])
#ax.set_ylim([0.0, 1.0])
l_xticks = np.linspace(int(xmin), int(xmax), 9,endpoint=True)
ax.set_xticks(l_xticks)
ax.set_xticklabels(['%1.1f' %elem for elem in l_xticks])
... | Notebooks/test_DOS.ipynb | dombrno/PG | bsd-2-clause |
Modification | BCS_PARAMS = {"width":20, "use_assaad": True,
"uniform_phase": True, "temperature": 1.75*145.0, "delta":1.0 * T_CST}
MY_DWAVE_MODEL.set_params(BCS_PARAMS)
print MY_DWAVE_MODEL
print "temp: ", K_to_meV(MY_DWAVE_MODEL.temperature), "meV" | Notebooks/test_DOS.ipynb | dombrno/PG | bsd-2-clause |
DOS Computation | dos_values = np.real(MY_DWAVE_MODEL.get_dos())
fig, ax = plt.subplots(figsize = (10, 8), dpi=100, frameon=False)
x_values = MY_DWAVE_MODEL.lattice.omega_mesh / T_CST
xmin = np.amin(x_values)
xmax = np.amax(x_values)
ax.set_xlim([xmin, xmax])
ax.set_xticks(np.linspace(int(xmin), int(xmax), 13,endpoint=True))
ax.plot... | Notebooks/test_DOS.ipynb | dombrno/PG | bsd-2-clause |
Modification | MC_PARAMS_MP = {"intervals": BCS_PARAMS["width"]**2 / 2,
"target_snapshots": 25,
"algorithm":"metropolis"}
MC_PARAMS_CLUSTER = {"intervals": 5,
"target_snapshots": 25,
"algorithm":"cluster"}
MY_DRIVER.set_params(MC_PARAMS_MP)
print MY_DWAVE_MODEL._uniform_phase
prin... | Notebooks/test_DOS.ipynb | dombrno/PG | bsd-2-clause |
Questions:
* What is the temp below which the correlation length should plateau?
* What should the value of such plateau be ? Why would it be different from the size of the grid for low enough T?? | a = np.array([1.125, 1.25, 1.5, 1.75, 2.0, 3.0, 4.0, 5.0])
fig, ax = plt.subplots(figsize = (10, 8), dpi=100, frameon=False)
for temp in temps:
x_data = x_datas[temp]
y_data = y_datas[temp]
ax.plot(x_data, y_data, label=str(temp))
popt, pcov = curve_fit(func, x_data, y_data)
print "temp: ", temp, ... | Notebooks/test_DOS.ipynb | dombrno/PG | bsd-2-clause |
Functions | def sample(df, n=1000, include_cats=[2, 3, 4, 5, 6, 7], random_state=1868):
"""Take a random sample of size `n` for categories
in `include_cats`.
"""
df = df.copy()
subset = df[df.Category.isin(include_cats)]
sample = subset.sample(n, random_state=random_state)
return sample
def clean_text(... | notebooks/kaggle-writeup.ipynb | juanshishido/text-classification | mit |
Data
Load | training = pd.read_csv('../data/newtrain.csv')
test = pd.read_csv('../data/newtest.csv') | notebooks/kaggle-writeup.ipynb | juanshishido/text-classification | mit |
Clean | training['text_clean'] = clean_text(training, 'Text')
test['text_clean'] = clean_text(test, 'Text') | notebooks/kaggle-writeup.ipynb | juanshishido/text-classification | mit |
Features | training = features(training)
test = features(test) | notebooks/kaggle-writeup.ipynb | juanshishido/text-classification | mit |
Split the training data | train, dev = cross_validation.train_test_split(training, test_size=0.2, random_state=1868)
train = train.append(sample(train, n=800))
train.reset_index(drop=True, inplace=True)
dev.reset_index(drop=True, inplace=True) | notebooks/kaggle-writeup.ipynb | juanshishido/text-classification | mit |
tfidf | train_matrix, dev_matrix = tfidf_matrices(train, dev) | notebooks/kaggle-writeup.ipynb | juanshishido/text-classification | mit |
Combine | train = concat_tfidf(train, train_matrix)
dev = concat_tfidf(dev, dev_matrix) | notebooks/kaggle-writeup.ipynb | juanshishido/text-classification | mit |
Training | svm = LinearSVC(dual=False, max_iter=5000)
features = train.columns[3:]
X = train[features].values
y = train['Category'].values
features_dev = dev[features].values | notebooks/kaggle-writeup.ipynb | juanshishido/text-classification | mit |
Testing on dev | svm.fit(X, y)
dev_predicted = svm.predict(features_dev)
accuracy_score(dev.Category, dev_predicted)
plt.figure(figsize=(6, 5))
plt.scatter(jitter(dev.Category, 0.15),
jitter(dev_predicted, 0.15),
color='#348ABD', alpha=0.25)
plt.title('Support Vector Classifier\n')
plt.xlabel('Ground Truth')... | notebooks/kaggle-writeup.ipynb | juanshishido/text-classification | mit |
Test Data | training = training.append(sample(training, n=1200))
training.reset_index(drop=True, inplace=True)
training_matrix, test_matrix = tfidf_matrices(training, test)
training = concat_tfidf(training, training_matrix)
test = concat_tfidf(test, test_matrix)
features = training.columns[3:]
X = training[features].values
y = ... | notebooks/kaggle-writeup.ipynb | juanshishido/text-classification | mit |
Problema Prático 2.14
Transforme a rede Y da Figura 2.51 em uma rede delta. | print("Problema Prático 2.14")
def y_delta(R1,R2,R3):
Ra = (R1*R2 + R2*R3 + R3*R1)/R1
Rb = (R1*R2 + R2*R3 + R3*R1)/R2
Rc = (R1*R2 + R2*R3 + R3*R1)/R3
return Ra,Rb,Rc
ra,rb,rc = y_delta(10,20,40)
print("Ra:",ra,"ohms")
print("Rb:",rb,"ohms")
print("Rc:",rc,"ohms") | Aula 3 - Métodos de Análise - Nodal.ipynb | GSimas/EEL7045 | mit |
Exemplo 2.15
Obtenha a resistência equivalente Rab para o circuito da Figura 2.52 e a use para encontrar
a corrente i. | print("Exemplo 2.15")
#analisando a triade 5ohms (rc) 15ohms (rb) e 20ohms (ra) como associacao em delta
r1,r2,r3 = delta_y(20,15,5)
Req1 = 12.5+r1 #em serie com resistor 12,5 ohm
Req2 = 10+r2 #em serie com resistor 10 ohm
Req3 = Req1*Req2/(Req1 + Req2) #paralelo entre Req1 e Req2
Req4 = Req3 + r3
Reqf = 30*Req4/(Req4 ... | Aula 3 - Métodos de Análise - Nodal.ipynb | GSimas/EEL7045 | mit |
Problema Prático 2.15
Para o circuito em ponte da Figura 2.54, determine Rab e i. | print("Problema Prático 2.15")
r1,r2,r3 = delta_y(50,30,20)
Req1 = 24 + r1
Req2 = 10 + r2
Req3 = Req1*Req2/(Req1 + Req2)
Req4 = Req3 + r3
Reqf = Req4 + 13
V = 240
i = V/Reqf
print("Rab:",Reqf,"ohm")
print("Corrente resultante:",i,"A") | Aula 3 - Métodos de Análise - Nodal.ipynb | GSimas/EEL7045 | mit |
Exemplo 2.16
Três lâmpadas são conectadas a uma fonte de 9 V, conforme mostrado na Figura 2.56a.
Calcule:
(a) corrente total fornecida pela fonte;
(b) corrente que passa por cada lâmpada;
(c) resistência de cada lâmpada. | print("Exemplo 2.16")
V = 9
p2 = 15 #potencia da primeira lampada
p3 = 10
p1 = 20
pt = p1 + p2 + p3
i = pt/V
i1 = p1/V
i2 = i - i1
r1 = V/i1
r2 = p2/(i2**2) # da equacao p = r*(i^2) => r = p/(i^2)
r3 = p3/(i2**2)
print("Corrente total:",i,"A")
print("Corrente na lampada 20W:",i1,"A")
print("Corrente nas lampadas 15W e ... | Aula 3 - Métodos de Análise - Nodal.ipynb | GSimas/EEL7045 | mit |
Problema Prático 2.16
Consulte a Figura 2.55 e considere a existência de dez lâmpadas que podem ser associadas em paralelo e dez que podem ser ligadas em série, cada uma das quais com potência
nominal de 40 W. Se a tensão da rede elétrica for 110 V para as ligações em série e em
paralelo, calcule a corrente através de ... | V = 110
p = 40
n = 10
pt = p*n #potencia serie
i = pt/V
print("Corrente em cada lampada em serie:",i,"A")
i = p/V
print("Corrente em cada lampada em paralelo:",i,"A") | Aula 3 - Métodos de Análise - Nodal.ipynb | GSimas/EEL7045 | mit |
Análise Nodal
A análise nodal também é
conhecida como método do
nó-tensão.
Etapas para determinar tensões nodais:
Selecione um nó como referência.
Atribua tensões v1, v2, ..., vn–1 aos n – 1 nós restantes. As tensões são medidas em relação ao nó de referência.
Aplique a LKC a cada um dos n – 1 nós que não são de refe... | print("Exemplo 3.1")
import numpy as np
#i2 + i3 = 5
#i2 + 10 = i5 + 5 => i5 = i2 + 5
#i2 = (v1-v2)/4
#i3 = v1/2
#i5 = v2/6
#(v1-v2)/4 + v1/2 = 5 => 3v1 - v2 = 20
# v2/6 = (v1-v2)/4 + 5 => 2v2 = 3v1 - 3v2 + 60 => 3v1 - 5v2 = -60
coef = np.matrix('3 -1; 3 -5')
res = np.matrix('20;-60')
V = np.linalg.inv(np.transpose(coe... | Aula 3 - Métodos de Análise - Nodal.ipynb | GSimas/EEL7045 | mit |
Problema Prático 3.1
Obtenha as tensões nodais no circuito da Figura 3.4 | print("Problema Prático 3.1")
#i1 + i3 = 3
#i3 = i2 + 12
#i1 = v1/2
#i2 = v2/7
#i3 = (v1-v2)/6
#v1/2 + (v1-v2)/6 = 3 => 4v1 - v2 = 18
#(v1-v2)/6 = v2/7 + 12 => 7v1 - 7v2 = 6v2 + 504 => 7v1 - 13v2 = 504
coef = np.matrix('4 -1; 7 -13')
res = np.matrix('18; 504')
V = np.linalg.inv(np.transpose(coef)*coef)*np.transpose(coe... | Aula 3 - Métodos de Análise - Nodal.ipynb | GSimas/EEL7045 | mit |
Exemplo 3.2
Determine as tensões na Figura 3.5a. | print("Exemplo 3.2")
#i1 + ix = 3
#ix = i2 + i3
#i1 + i2 = 2*ix
#i1 = (v1-v3)/4
#i2 = (v2-v3)/8
#i3 = v2/4
#ix = (v1-v2)/2
#(v1-v3)/4 + (v1-v2)/2 = 3 => 9v1 - 6v2 - 3v3 = 36
#(v1-v2)/2 = (v2-v3)/8 + v2/4 => 4v1 - 7v2 + v3 = 0
#(v1-v3)/4 + (v2-v3)/8 = v1 - v2 => -6v1 + 9v2 - 3v3 = ... | Aula 3 - Métodos de Análise - Nodal.ipynb | GSimas/EEL7045 | mit |
Problema Prático 3.2
Determine as tensões nos três primeiros nós que não são de referência no circuito da Figura 3.6. | print("Problema Prático 3.2")
#i2 = i1 + 4
#ix = i2 + 4*ix
#i1 + i3 + 4*ix = 0
#i1 = (v3-v1)/2
#i2 = (v1-v2)/3
#i3 = v3/6
#ix = v2/4
#(v1-v2)/3 = (v3-v1)/2 + 4 => 10v1 - 4v2 -6v3 = 48
#v2/4 = (v1-v2)/3 + v2 => 4v1 + 5v2 = 0
#(v3-v1)/2 + v3/6 + v2 = 0 => -3v1 + 6v2 + 4v3= 0
coef = np.ma... | Aula 3 - Métodos de Análise - Nodal.ipynb | GSimas/EEL7045 | mit |
Using the spin chain model
First, we simulate the quantum circuit using the Hamiltonian model LinearSpinChain. The control Hamiltonians are defined in SpinChainModel. | processor = LinearSpinChain(3)
processor.load_circuit(qc); | examples/qip-processor-DJ-algorithm.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
To quickly visualize the pulse, Processor has a method called plot_pulses. In the figure bellow, each colour represents the pulse sequence of one control Hamiltonian in the system as a function of time. In each time interval, the pulse remains constant. | processor.plot_pulses(title="Control pulse of Spin chain", figsize=(8, 4), dpi=100); | examples/qip-processor-DJ-algorithm.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
Because for the spin chain model interaction only exists between neighbouring qubits, SWAP gates are added between and after the first CNOT gate, swapping the first two qubits. The SWAP gate is decomposed into three iSWAP gates, while the CNOT is decomposed into two iSWAP gates plus additional single-qubit corrections.... | basis00 = basis([2,2], [0,0])
psi0 = basis([2,2,2], [0,0,0])
result = processor.run_state(init_state=psi0)
print("Probability of measuring state 00:")
print(np.real((basis00.dag() * ptrace(result.states[-1], [0,1]) * basis00)[0,0])) | examples/qip-processor-DJ-algorithm.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
With decoherence | processor.t1 = 100
processor.t2 = 30
psi0 = basis([2,2,2], [0,0,0])
result = processor.run_state(init_state=psi0)
print("Probability of measuring state 00:")
print(np.real((basis00.dag() * ptrace(result.states[-1], [0,1]) * basis00)[0,0])) | examples/qip-processor-DJ-algorithm.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
Using the optimal control module
This feature integrated into the sub-class OptPulseProcessor which use methods in the optimal control module to find the optimal pulse sequence for the desired gates. It can find the optimal pulse either for the whole unitary evolution or for each gate. Here we choose the second option. | setting_args = {"SNOT": {"num_tslots": 6, "evo_time": 2},
"X": {"num_tslots": 1, "evo_time": 0.5},
"CNOT": {"num_tslots": 12, "evo_time": 5}}
processor = OptPulseProcessor( # Use the control Hamiltonians of the spin chain model.
num_qubits=3, model=SpinChainModel(3, setup="linear"))... | examples/qip-processor-DJ-algorithm.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
For the optimal control model, we use the GRAPE algorithm, where control pulses are piece-wise constant functions. We provide the algorithm with the same control Hamiltonian model used for the spin chain model. In the compiled optimal signals, all controls are active (non-zero pulse amplitude) during most of the execut... | basis00 = basis([2,2], [0,0])
psi0 = basis([2,2,2], [0,0,0])
result = processor.run_state(init_state=psi0)
print("Probability of measuring state 00:")
print(np.real((basis00.dag() * ptrace(result.states[-1], [0,1]) * basis00)[0,0])) | examples/qip-processor-DJ-algorithm.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
We can see that under noisy evolution their is a none zero probability of measuring state 00.
Using the superconducting qubits model
Below, we simulate the same quantum circuit using one sub-class LinearSpinChain. It will find the pulse based on the Hamiltonian available on a quantum computer of the linear spin chain s... | processor = SCQubits(num_qubits=3)
processor.load_circuit(qc);
processor.plot_pulses(title="Control pulse of SCQubits", figsize=(8, 4), dpi=100); | examples/qip-processor-DJ-algorithm.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
For the superconducting-qubit processor, the compiled pulses have a Gaussian shape. This is crucial for superconducting qubits because the second excited level is only slightly detuned from the qubit transition energy. A smooth pulse usually prevents leakage to the non-computational subspace. Similar to the spin chain,... | basis00 = basis([3, 3], [0, 0])
psi0 = basis([3, 3, 3], [0, 0, 0])
result = processor.run_state(init_state=psi0)
print("Probability of measuring state 00:")
print(np.real((basis00.dag() * ptrace(result.states[-1], [0,1]) * basis00)[0,0])) | examples/qip-processor-DJ-algorithm.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
With decoherence | processor.t1 = 50.e3
processor.t2 = 20.e3
psi0 = basis([3, 3, 3], [0, 0, 0])
result = processor.run_state(init_state=psi0)
print("Probability of measuring state 00:")
print(np.real((basis00.dag() * ptrace(result.states[-1], [0,1]) * basis00)[0,0]))
import qutip_qip
print("qutip-qip version:", qutip_qip.version.version... | examples/qip-processor-DJ-algorithm.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
EBM with surface and atm layers | ebm = climlab.GreyRadiationModel(num_lev=1, num_lat=90)
insolation = climlab.radiation.AnnualMeanInsolation(domains=ebm.Ts.domain)
ebm.add_subprocess('insolation', insolation)
ebm.subprocess.SW.flux_from_space = ebm.subprocess.insolation.insolation
print(ebm)
# add a fixed relative humidity process
# (will only affe... | docs/source/courseware/PolarAmplification.ipynb | cjcardinale/climlab | mit |
Now with meridional heat transport | diffebm = climlab.process_like(ebm)
# thermal diffusivity in W/m**2/degC
D = 0.6
# meridional diffusivity in m**2/s
K = D / diffebm.Tatm.domain.heat_capacity * const.a**2
d = climlab.dynamics.MeridionalDiffusion(K=K, state={'Tatm': diffebm.Tatm}, **diffebm.param)
diffebm.add_subprocess('diffusion', d)
print(diffebm)
d... | docs/source/courseware/PolarAmplification.ipynb | cjcardinale/climlab | mit |
Same thing but with NO EVAPORATION | diffebm2 = climlab.process_like(diffebm)
diffebm2.remove_subprocess('LHF')
diffebm2.integrate_years(3)
co2diffebm2 = climlab.process_like(co2diffebm)
co2diffebm2.remove_subprocess('LHF')
co2diffebm2.integrate_years(3)
# With transport and no evaporation...
# No polar amplification, either of surface or air temperatur... | docs/source/courseware/PolarAmplification.ipynb | cjcardinale/climlab | mit |
A column model approach | model = climlab.GreyRadiationModel(num_lev=30, num_lat=90, abs_coeff=1.6E-4)
insolation = climlab.radiation.AnnualMeanInsolation(domains=model.Ts.domain)
model.add_subprocess('insolation', insolation)
model.subprocess.SW.flux_from_space = model.subprocess.insolation.insolation
print(model)
# Convective adjustment for... | docs/source/courseware/PolarAmplification.ipynb | cjcardinale/climlab | mit |
Now with meridional heat tranpsort! | diffmodel = climlab.process_like(model)
# thermal diffusivity in W/m**2/degC
D = 0.05
# meridional diffusivity in m**2/s
K = D / diffmodel.Tatm.domain.heat_capacity[0] * const.a**2
print(K)
d = climlab.dynamics.MeridionalDiffusion(K=K, state={'Tatm':diffmodel.Tatm}, **diffmodel.param)
diffmodel.add_subprocess('diffus... | docs/source/courseware/PolarAmplification.ipynb | cjcardinale/climlab | mit |
Same thing but with NO EVAPORATION | diffmodel2 = climlab.process_like(diffmodel)
diffmodel2.remove_subprocess('LHF')
print(diffmodel2)
diffmodel2.integrate_years(3)
co2diffmodel2 = climlab.process_like(co2diffmodel)
co2diffmodel2.remove_subprocess('LHF')
co2diffmodel2.integrate_years(3)
# With transport and no evaporation...
# No polar amplification... | docs/source/courseware/PolarAmplification.ipynb | cjcardinale/climlab | mit |
Warming effect of a DECREASE IN EVAPORATION EFFICIENCY
Take a column model that includes evaporation and heat transport, and reduce the drag coefficient by a factor of 2.
How does the surface temperature change? | diffmodel3 = climlab.process_like(diffmodel)
diffmodel3.subprocess['LHF'].Cd *= 0.5
diffmodel3.integrate_years(5.)
# Reduced evaporation gives equatorially enhanced warming of surface
# and cooling of near-surface air temperature
plt.plot(diffmodel.lat, diffmodel3.Ts - diffmodel.Ts, label='Ts')
plt.plot(diffmodel.la... | docs/source/courseware/PolarAmplification.ipynb | cjcardinale/climlab | mit |
Same calculation in a two-layer EBM | diffebm3 = climlab.process_like(diffebm)
diffebm3.subprocess['LHF'].Cd *= 0.5
diffebm3.integrate_years(5.)
# Reduced evaporation gives equatorially enhanced warming of surface
# and cooling of near-surface air temperature
plt.plot(diffebm.lat, diffebm3.Ts - diffebm.Ts, label='Ts')
plt.plot(diffebm.lat, diffebm3.Tatm... | docs/source/courseware/PolarAmplification.ipynb | cjcardinale/climlab | mit |
Pretty much the same result.
Some stuff with Band models | # Put in some ozone
import xarray as xr
ozonepath = "http://thredds.atmos.albany.edu:8080/thredds/dodsC/CLIMLAB/ozone/apeozone_cam3_5_54.nc"
ozone = xr.open_dataset(ozonepath)
# Dimensions of the ozone file
lat = ozone.lat
lon = ozone.lon
lev = ozone.lev
# Taking annual, zonal average of the ozone data
O3_zon = oz... | docs/source/courseware/PolarAmplification.ipynb | cjcardinale/climlab | mit |
Model gets very very hot near equator. Very large equator-to-pole gradient.
Band model with heat transport and evaporation | diffmodel1 = climlab.process_like(model1)
# thermal diffusivity in W/m**2/degC
D = 0.01
# meridional diffusivity in m**2/s
K = D / diffmodel1.Tatm.domain.heat_capacity[0] * const.a**2
d = climlab.dynamics.MeridionalDiffusion(K=K, state={'Tatm': diffmodel1.Tatm}, **diffmodel1.param)
diffmodel1.add_subprocess('diffusion'... | docs/source/courseware/PolarAmplification.ipynb | cjcardinale/climlab | mit |
Exercises
Exercise: The linear model I used in this chapter has the obvious drawback that it is linear, and there is no reason to expect prices to change linearly over time. We can add flexibility to the model by adding a quadratic term, as we did in Section 11.3.
Use a quadratic model to fit the time series of daily... | # Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here | code/chap12ex.ipynb | smorton2/think-stats | gpl-3.0 |
Exercise: Write a definition for a class named SerialCorrelationTest that extends HypothesisTest from Section 9.2. It should take a series and a lag as data, compute the serial correlation of the series with the given lag, and then compute the p-value of the observed correlation.
Use this class to test whether the seri... | # Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here | code/chap12ex.ipynb | smorton2/think-stats | gpl-3.0 |
Scikit-Learn Model Deployment Use Case
In this case, we will build a very large ensemble model (here, Random Foreast with 512 trees) on a digits dataset (not very original !!!) and generate a SQL code for deployment using the web service.
We then execute the SQL code on a local database (postgresql) and compare the S... | from sklearn import datasets
digits = datasets.load_digits()
X = digits.data
n_classes = len(digits.target_names)
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=512, max_depth=7, min_samples_leaf=30, random_state = 1960)
clf.fit(digits.data, digits.target)
#clf.__dict_... | docs/WebService-RandomForest_512_Deploy.ipynb | antoinecarme/sklearn2sql_heroku | bsd-3-clause |
Generate SQL Code from the Model |
def test_ws_sql_gen(pickle_data):
WS_URL="http://localhost:1888/model"
b64_data = base64.b64encode(pickle_data).decode('utf-8')
data={"Name":"model1", "PickleData":b64_data , "SQLDialect":"postgresql"}
r = requests.post(WS_URL, json=data)
#print(r.__dict__)
content = r.json()
# print(conte... | docs/WebService-RandomForest_512_Deploy.ipynb | antoinecarme/sklearn2sql_heroku | bsd-3-clause |
Execute the SQL Code | # save the dataset in a database table
engine = sa.create_engine('postgresql://db:db@localhost/db?port=5432' , echo=False)
conn = engine.connect()
lTable = pd.DataFrame(digits.data);
lTable.columns = ['Feature_' + str(c) for c in range(digits.data.shape[1])]
lTable['KEY'] = range(lTable.shape[0])
lTable.to_sql("INPUT... | docs/WebService-RandomForest_512_Deploy.ipynb | antoinecarme/sklearn2sql_heroku | bsd-3-clause |
Scikit-learn Prediction | skl_outputs = pd.DataFrame()
skl_output_key = pd.DataFrame(list(range(X.shape[0])), columns=['KEY']);
skl_output_score = pd.DataFrame(columns=['Score_' + str(c) for c in range(n_classes)]);
skl_output_proba = pd.DataFrame(clf.predict_proba(X), columns=['Proba_' + str(c) for c in range(n_classes)])
skl_output_log_proba ... | docs/WebService-RandomForest_512_Deploy.ipynb | antoinecarme/sklearn2sql_heroku | bsd-3-clause |
Data
We use the same data as for all our previous experiments. Here we load the training, development and test data for a particular prompt. | import sys
sys.path.append('../')
import ndjson
import glob
from quillnlp.models.bert.preprocessing import preprocess, create_label_vocabulary
train_file = f"../data/interim/{PREFIX}_train_withprompt_diverse200.ndjson"
synth_files = glob.glob(f"../data/interim/{PREFIX}_train_withprompt_*.ndjson")
dev_file = f"../dat... | notebooks/BERT-1.1 Experiments-QuillNLP.ipynb | empirical-org/WikipediaSentences | agpl-3.0 |
Model | import torch
from quillnlp.models.bert.models import get_bert_classifier
device = "cuda" if torch.cuda.is_available() else "cpu"
model = get_bert_classifier(BERT_MODEL, len(label2idx), device=device) | notebooks/BERT-1.1 Experiments-QuillNLP.ipynb | empirical-org/WikipediaSentences | agpl-3.0 |
Training | from quillnlp.models.bert.train import train
output_model_file = train(model, train_dataloader, dev_dataloader, BATCH_SIZE, GRADIENT_ACCUMULATION_STEPS, device) | notebooks/BERT-1.1 Experiments-QuillNLP.ipynb | empirical-org/WikipediaSentences | agpl-3.0 |
Evaluation | from quillnlp.models.bert.train import evaluate
from sklearn.metrics import precision_recall_fscore_support, classification_report
print("Loading model from", output_model_file)
device="cpu"
model = get_bert_classifier(BERT_MODEL, len(label2idx), model_file=output_model_file, device=device)
model.eval()
_, test_corr... | notebooks/BERT-1.1 Experiments-QuillNLP.ipynb | empirical-org/WikipediaSentences | agpl-3.0 |
Loading data
Load the three datasets into RDDs and name them artistData, artistAlias, and userArtistData. View the README, or the files themselves, to see how this data is formated. Some of the files have tab delimeters while some have space delimiters. Make sure that your userArtistData RDD contains only the canonical... | #abs path to the dataset
path = "/home/rajat/courses/bi/01.Apache.Spark.Project-1.RecommenderSystems.FINAL/"
#reading the datasets and also parsing and converting to the data type as required
artistData = sc.textFile(path + "artist_data_small.txt").map(lambda l: l.split("\t")).map(lambda l: (int(l[0]), l[1]))
artistAli... | music-recommender/recommender.ipynb | shahrajat/DataMining | gpl-2.0 |
Data Exploration
In the blank below, write some code that with find the users' total play counts. Find the three users with the highest number of total play counts (sum of all counters) and print the user ID, the total play count, and the mean play count (average number of times a user played an artist). Your output sh... | #group based on the userID to get list of artists for the user
userToPlaycount = userArtistData.map(lambda u: (u[0],u[2])).groupByKey().mapValues(list)
#add a average to each tuple
userToPlaycountAvg = userToPlaycount.map(lambda t: (t[0],sum(t[1]),sum(t[1])//len(t[1])))
#sorted the data based on play count
sorteduserTo... | music-recommender/recommender.ipynb | shahrajat/DataMining | gpl-2.0 |
Splitting Data for Testing
Use the randomSplit function to divide the data (userArtistData) into:
* A training set, trainData, that will be used to train the model. This set should constitute 40% of the data.
* A validation set, validationData, used to perform parameter tuning. This set should constitute 40% of the dat... | #make a dictionary out of the alias data set
artistAliasDict = dict(artistAlias.collect())
#replace in userArtistData each artistID with it's canonical ID
userArtistData = userArtistData.map(lambda a: (a[0], artistAliasDict[a[1]], a[2]) if a[1] in artistAliasDict.keys() else a)
#split data in training, validation and ... | music-recommender/recommender.ipynb | shahrajat/DataMining | gpl-2.0 |
The Recommender Model
For this project, we will train the model with implicit feedback. You can read more information about this from the collaborative filtering page: http://spark.apache.org/docs/latest/mllib-collaborative-filtering.html. The function you will be using has a few tunable parameters that will affect how... | def modelEval(model, dataset):
#set of all the artists in the entire data
allArtists = set(userArtistData.map(lambda a: a[1]).collect())
#set of all the users
users = set(dataset.map(lambda u: u[0]).collect())
#user->[artist1, artist2,...] for current dataset
datasetUserToArtists = dict(dataset.... | music-recommender/recommender.ipynb | shahrajat/DataMining | gpl-2.0 |
Model Construction
Now we can build the best model possibly using the validation set of data and the modelEval function. Although, there are a few parameters we could optimize, for the sake of time, we will just try a few different values for the rank parameter (leave everything else at its default value, except make s... | model = ALS.trainImplicit(trainData, rank=2, seed=345)
print modelEval(model, validationData)
model = ALS.trainImplicit(trainData, rank=10, seed=345)
print modelEval(model, validationData)
model = ALS.trainImplicit(trainData, rank=20, seed=345)
print modelEval(model, validationData) | music-recommender/recommender.ipynb | shahrajat/DataMining | gpl-2.0 |
Trying Some Artist Recommendations
Using the best model above, predict the top 5 artists for user 1059637 using the recommendProducts function. Map the results (integer IDs) into the real artist name using artistAlias. Print the results. The output should look as follows:
Artist 0: Brand New
Artist 1: Taking Back Sunda... | ratings = bestModel.recommendProducts(1059637, 5)
ratingsArtists = map(lambda r : r.product, ratings)
artistDataMap = dict(artistData.collect())
i=0
for artist in ratingsArtists:
print "Artist "+ str(i)+ ":",artistDataMap[artist]
i+=1 | music-recommender/recommender.ipynb | shahrajat/DataMining | gpl-2.0 |
1. User-Specified Input
Python can also ask the user to specify input interactively, as shown below. Execute the cell to see how it works. | faren = input("enter a temperature (in Fahrenheit): ")
print(faren) | Labs/Lab4/Lab4.ipynb | kfollette/ASTR200-Spring2017 | mit |
<div class=hw>
### Exercise 1
-----------------------
Write a function that has no required input, but one optional argument with a default value "C". The function should ask the user what the temperature is and should print that value in Celcius, Farenheit and Kelvin. If the keyword is set to "F" or "K" it should ass... | print("green eggs and\n spam")
# Triple quotes are another way to specify multi-line strings
y = """For score and seven minutes ago,
you folks all learned some basic mathy stuff with Python
and boy were you blown away!"""
print(y) | Labs/Lab4/Lab4.ipynb | kfollette/ASTR200-Spring2017 | mit |
2.2 Concatenating strings | # note the ; allows us to do two calculations on the same line
s = "spam" ; e = "eggs"
print(s + e)
print(s + " and " + e)
# this one won't work
print('I want' + 3 + ' eggs and no ' + s)
# but this will
print('I want ' + str(3) + ' eggs and no ' + s) | Labs/Lab4/Lab4.ipynb | kfollette/ASTR200-Spring2017 | mit |
2.3 Multiple Concatenations | print(s*3 + e)
print("*" * 50) | Labs/Lab4/Lab4.ipynb | kfollette/ASTR200-Spring2017 | mit |
2.4 Comparing Strings | print("spam" == "good"); print("spam" == "spam")
"spam" < "zoo"
"s" < "spam" | Labs/Lab4/Lab4.ipynb | kfollette/ASTR200-Spring2017 | mit |
<div class=hw>
## Exercise 2
------------------
Write a function that does the following:
1) Takes a required input ***string array*** containing the names of the people in your group.
2) Asks the person with the longer name for their order first
3) Asks each person to enter (using user input) how ma... | x = 1
if x > 0:
print("yo")
else:
print("dude")
# the one line version
"yo" if x > 0 else "dude"
# conditionals can lie within function calls
print("yo" if x > 0 else "dude")
z = "no"
np.sin(np.pi if z=="yes" else 0) | Labs/Lab4/Lab4.ipynb | kfollette/ASTR200-Spring2017 | mit |
3.2 While and Iteration | x = 1
y = 0
while y < 10:
print("yo" if x > 0 else "dude")
x *= -1
y += 1 | Labs/Lab4/Lab4.ipynb | kfollette/ASTR200-Spring2017 | mit |
<div class=hw>
### Exercise 3
-------------------
Copy the function above into a code cell and add a print statement that prints the variables x and y so that you can see what they are at each step. Use the output to figure out what the statements x \*= -1 and y += 1 are doing. Type an explanation of what they do into... | #can also do this with a break statement
while True:
print("yo" if x > 0 else "dude")
x *= -1
y += 1
if y >= 10:
break | Labs/Lab4/Lab4.ipynb | kfollette/ASTR200-Spring2017 | mit |
4. Writing and Reading Files with Magic Commands | %%file number_game.py
# The above "magic" command, denoted with the double %% saves the contents
# of the current cell to file. We'll see more of these later
x = 0
max_tries = 10
count = 0
while True:
x_new = int(input("Enter a new number: "))
if x_new > x:
print(" -> it's bigger than the last!")
... | Labs/Lab4/Lab4.ipynb | kfollette/ASTR200-Spring2017 | mit |
<div class=hw>
### Exercise 4
-------------------
Create a program (and write it to a .py file) which repeatedly asks the user for a word. The program should append all the words together. When the user types a "!", "?", or a ".", the program should print the resulting sentence and exit.
For example, a session might l... | 4 % 2
4 % 3
6.28 % 3.14
6.28 % 3.1
25 % 5
25 % 7
from IPython.core.display import HTML
def css_styling():
styles = open("../custom.css", "r").read()
return HTML(styles)
css_styling() | Labs/Lab4/Lab4.ipynb | kfollette/ASTR200-Spring2017 | mit |
Protocol is not the same for XL320 servomotors, set the using_XL320 flag to True if you use them.
Set my_baudrate to the baudrate you are using (1000000 for motors already configured, 57600 for new ones). | using_XL320 = False
my_baudrate = 1000000 | debug/poppy-torso_poppy-humanoid_poppy-ergo__motor_scan.ipynb | poppy-project/community-notebooks | lgpl-3.0 |
If the code below gives you an exception, try to restart all other notebooks that may be running, wait 5 seconds and try again. | for port in ports:
print port
try:
if using_XL320:
dxl_io = pypot.dynamixel.Dxl320IO(port, baudrate=my_baudrate)
else:
dxl_io = pypot.dynamixel.DxlIO(port, baudrate=my_baudrate)
print "scanning"
found = dxl_io.scan(range(60))
print found
... | debug/poppy-torso_poppy-humanoid_poppy-ergo__motor_scan.ipynb | poppy-project/community-notebooks | lgpl-3.0 |
Kill whoever uses the ports (should be used only as last chance try to free the ports). | import os
for port in ports:
os.system('fuser -k '+port); | debug/poppy-torso_poppy-humanoid_poppy-ergo__motor_scan.ipynb | poppy-project/community-notebooks | lgpl-3.0 |
Introduction to scikit-learn
Scikit-learn is a machine learning library in Python.
Scikit-learn is the first of the several machine learning libraries we will explore in this course. It is relatively approachable, supports a wide variety of traditional machine learning models, and is ubiquitous in the world of data sci... | from sklearn.datasets import load_iris
iris_data = load_iris()
iris_data | content/03_regression/01_introduction_to_sklearn/colab.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
That's a lot to take in. Let's examine this loaded data a little more closely. First we'll see what data type this dataset is: | type(iris_data) | content/03_regression/01_introduction_to_sklearn/colab.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
sklearn.utils.Bunch is a type that you'll see quite often when working with datasets built into scikit-learn. It is a dictionary-like container for feature and target data within a dataset.
You won't find much documentation about Bunch objects because they are not really meant for usage beyond containing data native to... | dir(iris_data) | content/03_regression/01_introduction_to_sklearn/colab.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
DESCR is a description of the dataset. | print(iris_data['DESCR']) | content/03_regression/01_introduction_to_sklearn/colab.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
filename is the name of the source file where the data is stored. | print(iris_data['filename']) | content/03_regression/01_introduction_to_sklearn/colab.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.