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 |
|---|---|---|---|---|---|
Microsoft ML Twitter Sentiment Analysis Tutorial1. [Overview](Overview)2. [Fitting Models That Identify Sentiment](TwitterSentiment)3. [What's Next?](Next) 1. OVERVIEWMicrosoft Machine Learning, or Microsoft ML for short, is an R package within Microsoft R Services that includes powerful machine learning algorithms a... | #-----------------------------------------------------------------------
# 1. Load packages.
#-----------------------------------------------------------------------
if (!suppressPackageStartupMessages(require("MicrosoftML",
quietly = TRUE,
... | _____no_output_____ | MIT | microsoft-ml/Microsoft ML Tutorial/Microsoft ML Tutorial Notebooks/Microsoft ML Twitter Sentiment Analysis Tutorial.ipynb | Microsoft/microsoft-r |
2.2. IMPORT DATAThe second step consists of importing the data we will use to fit a model. There is only one table of data: the HappyOrSad table. This section imports that table into an Xdf. These Xdfs are an efficient way of working with large amounts of data. They are files in which the rows are grouped in blocks wh... | #-----------------------------------------------------------------------
# 2. Import data.
#-----------------------------------------------------------------------
# The directory containing data files.
dataDir <- file.path("Data")
# Verify that the data file exists.
if (!file.exists(file.path(dataDir, "HappyOrSad.cs... | _____no_output_____ | MIT | microsoft-ml/Microsoft ML Tutorial/Microsoft ML Tutorial Notebooks/Microsoft ML Twitter Sentiment Analysis Tutorial.ipynb | Microsoft/microsoft-r |
The HappyOrSad table has one row per tweet, and three columns: id_nfpu, features, and label. Because the id_nfpu column uniquely identifies each tweet, it is ignored. The two remaining columns are text, and they are respectively renamed Text and sentiment. As part of the importing process, we create Label, a logical v... | # The data source has three columns. Keep the tweet text and sentiment.
datasetSource <-
RxTextData(file.path(dataDir, "HappyOrSad.csv"),
varsToKeep = c("features", "label"),
colInfo = list(features = list(type = "character",
newName = "Tex... | Rows Read: 10362, Total Rows Processed: 10362, Total Chunk Time: 0.152 seconds
| MIT | microsoft-ml/Microsoft ML Tutorial/Microsoft ML Tutorial Notebooks/Microsoft ML Twitter Sentiment Analysis Tutorial.ipynb | Microsoft/microsoft-r |
We can see from the output that the activity table has 252,204 rows, and its first few rows are | head(dataset) | _____no_output_____ | MIT | microsoft-ml/Microsoft ML Tutorial/Microsoft ML Tutorial Notebooks/Microsoft ML Twitter Sentiment Analysis Tutorial.ipynb | Microsoft/microsoft-r |
2.3. SPLIT THE DATASET INTO TRAIN AND TESTTo create train and test sets, the data are randomly split by tweet into two datasets. The training data tweets will be used by the learners to fit models, while the test data tweets will be used as a fair measure the performance of the fit models. Because the split is random... | #-----------------------------------------------------------------------
# 3. Split the dataset into train and test data.
#-----------------------------------------------------------------------
# Set the random seed for reproducibility of randomness.
set.seed(2345, "L'Ecuyer-CMRG")
# Randomly split the data 80-20 betw... | Rows Read: 10362, Total Rows Processed: 10362Rows Read: 8279, Total Rows Processed: 8279, Total Chunk Time: 0.020 seconds
Rows Read: 2083, Total Rows Processed: 2083, Total Chunk Time: 0.006 seconds
, Total Chunk Time: 0.219 seconds
| MIT | microsoft-ml/Microsoft ML Tutorial/Microsoft ML Tutorial Notebooks/Microsoft ML Twitter Sentiment Analysis Tutorial.ipynb | Microsoft/microsoft-r |
We can explore the distribution of "Label" in the train and test sets. | rxSummary(~ Label, dataTrain)$sDataFrame
rxSummary(~ Label, dataTest)$sDataFrame | Rows Read: 8279, Total Rows Processed: 8279, Total Chunk Time: Less than .001 seconds
Computation time: 0.002 seconds.
| MIT | microsoft-ml/Microsoft ML Tutorial/Microsoft ML Tutorial Notebooks/Microsoft ML Twitter Sentiment Analysis Tutorial.ipynb | Microsoft/microsoft-r |
We read from the output that train has 8,279 rows while test has 2,083 rows. Because Label is a boolean, its mean shows the proportion of happy tweets in the data. We see that train has more than 50% happy tweets and that test has almost 49% happy tweets, which is a reasonable split. 2.4. DEFINE THE MODELThe model is ... | #-----------------------------------------------------------------------
# 4. Define the model to be fit.
#-----------------------------------------------------------------------
# The model is a formula that says that sentiments are to be identified
# using Features, a stand-in for variables created on-the-fly from te... | _____no_output_____ | MIT | microsoft-ml/Microsoft ML Tutorial/Microsoft ML Tutorial Notebooks/Microsoft ML Twitter Sentiment Analysis Tutorial.ipynb | Microsoft/microsoft-r |
The left-hand side of the formula is the label, while the right-hand side lists the source of the rxPredictors. 2.5. FIT THE MODELThe model will be fit by learners that can rxPredict class data: rxLogisticRegression, rxFastLinear, rxFastTrees, rxFastForest, and rxNeuralNet. In the next section, each fit will be used t... | #-----------------------------------------------------------------------
# 5. Fit the model using different learners.
#-----------------------------------------------------------------------
# Fit the model with logistic regression. This finds the variable
# weights that are most useful for rxPredicting sentiment. The
... | Beginning read for block: 1
Rows Read: 8279, Read Time: 0.007, Transform Time: 0
Beginning read for block: 2
No rows remaining. Finished reading data set.
Beginning read for block: 1
Rows Read: 8279, Read Time: 0.005, Transform Time: 0
Beginning read for block: 2
No rows remaining. Finished reading data set.
Computin... | MIT | microsoft-ml/Microsoft ML Tutorial/Microsoft ML Tutorial Notebooks/Microsoft ML Twitter Sentiment Analysis Tutorial.ipynb | Microsoft/microsoft-r |
2.6. SCORE THE TEST DATAEach fit will be used to score the test data. In order to plot together each fit's performance for convenient side-by-side comparison, we append each rxPrediction column to the test dataset. This will also conveniently include the Label column with the rxPredictions, so that the rxPrediction p... | #-----------------------------------------------------------------------
# 6. Score the held-aside test data with the fit models.
#-----------------------------------------------------------------------
# The scores are each test record's probability of being a sentiment.
# This combines each fit model's rxPredictions ... | Beginning read for block: 1
Rows Read: 2083, Read Time: 0.002, Transform Time: 0
Beginning read for block: 2
No rows remaining. Finished reading data set.
Elapsed time: 00:00:00.3493465
Finished writing 2083 rows.
Writing completed.
Beginning read for block: 1
Rows Read: 2083, Read Time: 0.002, Transform Time: 0
Begin... | MIT | microsoft-ml/Microsoft ML Tutorial/Microsoft ML Tutorial Notebooks/Microsoft ML Twitter Sentiment Analysis Tutorial.ipynb | Microsoft/microsoft-r |
We see in the output of the command that the number of rows in the results is the same as the number of rows in the test data. 2.7. COMPARE THE FIT MODEL PERFORMANCEFor each fit model, its rxPredictions and the Label are used to compute an ROC curve for that fit. The curves will then be plotted side-by-side in a graph... | #-----------------------------------------------------------------------
# 7. Compare the performance of fit models.
#-----------------------------------------------------------------------
# Compute the fit models's ROC curves.
fitRoc <-
rxRoc("Label",
paste("Probability",
c("rxLogisticR... | _____no_output_____ | MIT | microsoft-ml/Microsoft ML Tutorial/Microsoft ML Tutorial Notebooks/Microsoft ML Twitter Sentiment Analysis Tutorial.ipynb | Microsoft/microsoft-r |
The fit models are then used to compute the fit model AUCs, and these are used to select the best model. | # Create a named list of the fit models.
fitList <-
list(rxLogisticRegression = rxLogisticRegressionFit,
rxFastLinear = rxFastLinearFit,
rxFastTrees = rxFastTreesFit,
rxFastForest = rxFastForestFit,
rxNeuralNet = rxNeuralNetFit)
# Compute the fit models's AUCs.
fitAuc <- rxAuc(f... | Fit model AUCs:
rxFastForest rxFastLinear rxFastTrees
0.80 0.87 0.88
rxLogisticRegression rxNeuralNet
0.85 0.82
Best fit model with rxFastTrees, AUC = 0.88.
| MIT | microsoft-ml/Microsoft ML Tutorial/Microsoft ML Tutorial Notebooks/Microsoft ML Twitter Sentiment Analysis Tutorial.ipynb | Microsoft/microsoft-r |
Direction recontruction (DL2) **Recommended datasample(s):**Datasets of fully-analyzed showers used to obtain Instrument Response Functions, which in the default pipeline workflow are called ``gamma3``, ``proton2`` and ``electron``.**Data level(s):** DL2 (shower geometry + estimated energy + estimated particle classif... | import os
from pathlib import Path
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from matplotlib.pyplot import rc
import matplotlib.style as style
from cycler import cycler
import numpy as np
import pandas as pd
import astropy.units as u
from astropy.coordinates import SkyC... | _____no_output_____ | CECILL-B | protopipe/benchmarks/notebooks/DL2/benchmarks_DL2_direction-reconstruction.ipynb | Iburelli/protopipe |
Load data | # Parametrized cell
analyses_directory = None
output_directory = Path.cwd() # default output directory for plots
analysis_name = None
analysis_name_2 = None
gammas_infile_name = "DL2_tail_gamma_merged.h5"
protons_infile_name = "DL2_tail_proton_merged.h5"
electrons_infile_name = "DL2_tail_electron_merged.h5"
efficiency_... | _____no_output_____ | CECILL-B | protopipe/benchmarks/notebooks/DL2/benchmarks_DL2_direction-reconstruction.ipynb | Iburelli/protopipe |
Benchmarks Here we use events with the following cuts:- valid reconstructed events- at least 2 reconstructed images, regardless of the camera (on top of any other hardware trigger)- gammaness > 0.75 (mostly a conservative choice) | min_true_energy = 0.006
max_true_energy = 660 | _____no_output_____ | CECILL-B | protopipe/benchmarks/notebooks/DL2/benchmarks_DL2_direction-reconstruction.ipynb | Iburelli/protopipe |
Energy-dependent offset distribution[back to top](Table-of-contents) | n_bins = 4
true_energy_bin_edges = np.logspace(np.log10(min_true_energy),
np.log10(max_true_energy), n_bins + 1)
plt.figure(figsize=get_fig_size(ratio=4./3., scale=scale))
plt.xlabel("Offset [deg]")
plt.ylabel("Number of events")
for i in range(len(true_energy_bin_edges)-1):
... | _____no_output_____ | CECILL-B | protopipe/benchmarks/notebooks/DL2/benchmarks_DL2_direction-reconstruction.ipynb | Iburelli/protopipe |
Angular resolution as a function of telescope multiplicity[back to top](Table-of-contents) Here we compare how the multiplicity influences the performance of reconstructed events with a 90% gamma efficiency within a 68% containment radius. | r_containment = 68
min_true_energy = 0.003
max_true_energy = 330
n_true_energy_bins = 21
true_energy_bin_edges = np.logspace(np.log10(min_true_energy),
np.log10(max_true_energy),
n_true_energy_bins)
true_energy_bin_centers = 0.5 * (true_energy_bin... | _____no_output_____ | CECILL-B | protopipe/benchmarks/notebooks/DL2/benchmarks_DL2_direction-reconstruction.ipynb | Iburelli/protopipe |
Angular resolution for different containment radii and fixed signal efficiency[back to top](Table-of-contents) Apply fixed signal efficiency cut (requires well defined ML separator and ML train-ing)Calculate angular resolution for 68%, 80%, and 95% containment radius. | scale=0.75
plt.figure(figsize=(16*scale,9*scale))
true_energy_bins = create_bins_per_decade(10**-1.9 * u.TeV, 10**2.31 * u.TeV, 5).value
gamma_efficiency = 0.9
reconstructed_gammas = gammas.query("is_valid == True")
gammaness = reconstructed_gammas["gammaness"]
gammaness_cut = np.quantile(gammaness, gamma_efficiency)... | _____no_output_____ | CECILL-B | protopipe/benchmarks/notebooks/DL2/benchmarks_DL2_direction-reconstruction.ipynb | Iburelli/protopipe |
H_max as a function of energy for gammas and protons Fixed gamma efficiency at 90% | reconstructed_gammas = gammas.query("is_valid == True")
reconstructed_protons = protons.query("is_valid == True")
plt.figure(figsize=(12,6))
mask_gammaness = f"gammaness > 0.9"
plt.subplot(1, 2, 1)
hist_opt = {"bins":[100,100],
"range": [[0.003, 300],[1,8]],
"norm": LogNorm(vmin=1,vmax=1.e6)... | _____no_output_____ | CECILL-B | protopipe/benchmarks/notebooks/DL2/benchmarks_DL2_direction-reconstruction.ipynb | Iburelli/protopipe |
PSF asymmetry[back to top](Table-of-contents) | reco_alt = selected_gammas.reco_alt
reco_az = selected_gammas.reco_az
# right now all reco_az for a 180° deg simualtion turn out to be all around -180°
#if ~np.count_nonzero(np.sign(reco_az) + 1):
reco_az = np.abs(reco_az)
# this is needed for projecting the angle onto the sky
reco_az_corr = reco_az * np.cos(np.deg2r... | _____no_output_____ | CECILL-B | protopipe/benchmarks/notebooks/DL2/benchmarks_DL2_direction-reconstruction.ipynb | Iburelli/protopipe |
2D representation with **orange** events being those with **offset 20 TeV** | angcut = (selected_gammas['offset'] < 1) & (selected_gammas['true_energy'] > 20)
plt.figure(figsize=(5,5))
ax = plt.gca()
FOV_size = 2.5 # deg
ax.scatter(daz_corr, dalt, alpha=0.1, s=1, label='no angular cut')
ax.scatter(daz_corr[angcut], dalt[angcut], alpha=0.05, s=1, label='offset < 1 deg & E_true > 20 TeV')
ax.se... | _____no_output_____ | CECILL-B | protopipe/benchmarks/notebooks/DL2/benchmarks_DL2_direction-reconstruction.ipynb | Iburelli/protopipe |
True energy distributions[back to top](Table-of-contents) | #min_true_energy = 0.003
#max_true_energy = 330
true_energy_bins_edges = np.logspace(np.log10(min_true_energy), np.log10(max_true_energy), 6 + 1)
if len(np.unique(gammas["true_az"]))==1:
true_az = np.unique(gammas["true_az"]) * u.deg
true_alt = np.unique(gammas["true_alt"]) * u.deg
else:
print("WARNING: di... | _____no_output_____ | CECILL-B | protopipe/benchmarks/notebooks/DL2/benchmarks_DL2_direction-reconstruction.ipynb | Iburelli/protopipe |
Same, but with a fixed gamma efficiency cut of 90% | plt.figure(figsize=(15,15))
plt.subplots_adjust(wspace=0.3, hspace=0.3)
center = SkyCoord(az=true_az, alt=true_alt, frame="altaz")
nominal_frame = NominalFrame(origin=center)
for i in range(len(true_energy_bins_edges)-1):
plt.subplot(3,2,i+1)
ax = plt.gca()
ax.set_aspect("equal")
reconstruc... | _____no_output_____ | CECILL-B | protopipe/benchmarks/notebooks/DL2/benchmarks_DL2_direction-reconstruction.ipynb | Iburelli/protopipe |
Xarray-I: Data Structure * [**Sign up to the JupyterHub**](https://www.phenocube.org/) to run this notebook interactively from your browser* **Compatibility:** Notebook currently compatible with the Open Data Cube environments of the University of Wuerzburg* **Prerequisites**: There is no prerequisite learning requir... | import datacube
import pandas as pd
from odc.ui import DcViewer
from odc.ui import with_ui_cbk
import xarray as xr
import matplotlib.pyplot as plt
# Set config for displaying tables nicely
# !! USEFUL !! otherwise parts of longer infos won't be displayed in tables
pd.set_option("display.max_colwidth", 200)
pd.set_opt... | _____no_output_____ | MIT | 3_Data_Cube_Basics/notebooks/02_xarrayI_data_structure.ipynb | eo2cube/datacube_eagles |
**What is inside a `xarray.dataset`?**The figure below is a diagramm depicting the structure of the **`xarray.dataset`** we've just loaded. Combined with the diagramm, we hope you may better interpret the texts below explaining the data strucutre of a **`xarray.dataset`**. | _____no_output_____ | MIT | 3_Data_Cube_Basics/notebooks/02_xarrayI_data_structure.ipynb | eo2cube/datacube_eagles |
* **To select data of all spectral bands of year 2020** | ds.sel(time='2020-12')
#print(ds.sel(time='2019')) | _____no_output_____ | MIT | 3_Data_Cube_Basics/notebooks/02_xarrayI_data_structure.ipynb | eo2cube/datacube_eagles |
***Tip: More about indexing and sebsetting Dataset or DataArray is presented in the [Notebook_05](https://github.com/eo2cube/eo2cube_notebooks/blob/main/get_started/intro_to_eo2cube/05_xarrayII.ipynb).*** **Reshape Dataset*** **Convert the Dataset (subset to 2019) to a *4-dimension* DataArray** | da = ds.sel(time='2020-12').to_array().rename({"variable":"band"})
da | _____no_output_____ | MIT | 3_Data_Cube_Basics/notebooks/02_xarrayI_data_structure.ipynb | eo2cube/datacube_eagles |
* **Convert the *4-dimension* DataArray back to a Dataset by setting the "time" as DataVariable (reshaped)** | ds_reshp = da.to_dataset(dim="time")
print(ds_reshp) | _____no_output_____ | MIT | 3_Data_Cube_Basics/notebooks/02_xarrayI_data_structure.ipynb | eo2cube/datacube_eagles |
Seaborn Übung - AufgabeZeit unsere neu gelernten Seaborn Fähigkeiten anzuwenden! Versucht die gezeigten Diagramme selbst nachzustellen. Dabei ist die Farbgebung nicht entscheidend, es geht um die Inhalte. Die DatenWir werde dazu ein berühmten Datensatz zur Titanic benutzen. Später im Machine Learning Teil des Kurses k... | import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
titanic = sns.load_dataset('titanic')
titanic.head() | _____no_output_____ | BSD-3-Clause | 3-Visualization/2-Seaborn/7-Seaborn Uebung - Aufgabe.ipynb | Klaynie/Jupyter-Test |
ÜbungVersucht die gezeigten Diagramme selbst nachzustellen. Dabei ist die Farbgebung nicht entscheidend, es geht um die Inhalte.Achtet außerdem darauf, die Zelle direkt über dem Diagramm nicht zu verwenden. So könnt ihr verhindern, dass das Diagramm verloren geht. Wir haben eine extra Zelle zum Coden eingebaut. | # Hier eigenen Code schreiben
# Nächste Zelle nicht nutzen
# Hier eigenen Code schreiben
# Nächste Zelle nicht nutzen
# Hier eigenen Code schreiben
# Nächste Zelle nicht nutzen
# Hier eigenen Code schreiben
# Nächste Zelle nicht nutzen
sns.swarmplot(x='class', y='age', data=titanic, palette='Set2')
# Hier eigenen Code ... | _____no_output_____ | BSD-3-Clause | 3-Visualization/2-Seaborn/7-Seaborn Uebung - Aufgabe.ipynb | Klaynie/Jupyter-Test |
Fundamentos de Numpy> Hasta ahora sólo hemos hablado acerca de tipos (clases) de variables y funciones que vienen por defecto en Python.> Sin embargo, una de las mejores cosas de Python (especialmente si eres o te preparas para ser un científico de datos) es la gran cantidad de librerías de alto nivel que se encuentra... | # Crear dos vectores
x = [4, 5, 8, -2, 3]
y = [3, 1, -7, -9, 5]
# Suma de vectores
x + y
# ¿con ciclos quizá?
sum_ = [x[i] + y[i] for i in range(len(x))]
sum_
# Producto por escalar
3 * x
# ¿con ciclos quizá?
prod_ = [3 * x[i] for i in range(len(x))]
prod_ | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
Solución: NumPyNumPy es la librería fundamental para computación científica con Python. Contiene, entre otros:- una clase de objetos tipo arreglo N-dimensional muy poderso;- funciones matemáticas sofisticadas;- herramientas matemáticas útiles de álgebra lineal, transformada de Fourier y números aleatorios. Aparte de s... | # Importar numpy
import numpy as np
np.sin(np.pi / 2) | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
Lo que acabamos de hacer es un procedimiento genérico para importar librerías:- se comienza con la palabra clave `import`;- a continuación el nombre de la librería, en este caso `numpy`;- opcionalmente se puede incluir una cláusula `as` y una abreviación del nombre de la librería. Para el caso de NumPy, la comunidad co... | # Ayuda sobre arreglo N-dimensional
help(np.array)
a = [5, 6]
a
import copy
b = copy.copy(a)
b
a[1] = 8
b
# Crear dos vectores
x = np.array([4, 5, 8, -2, 3])
y = np.array([3, 1, -7, -9, 5])
x, y
# Tipo
type(x)
# Suma de vectores
x + y
# Producto interno
7 * x
x.dtype
np.array([5], dtype="float64")**np.array([28], dtype... | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
Diferencias fundamentales entre Listas de Python y Arreglos de NumPyMientras que las listas y los arreglos tienen algunas similaridades (ambos son colecciones ordenadas de valores), existen ciertas diferencias abismales entre este tipo de estructuras de datos:- A diferencia de las listas, todos los elementos en un arr... | np.array([6, 'hola', help]) | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
1. ¿Qué podemos hacer en NumPy?Ya vimos como crear arreglos básicos en NumPy, con el comando `np.array()` | x | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
¿Cuál es el tipo de estos arreglos? | type(x)
len(x)
x.shape
x.size
x.ndim | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
También podemos crear arreglos multidimensionales: | # Matriz 4x5
A = np.array([[1, 2, 0, 5, -2],
[9, -7, 5, 3, 0],
[2, 1, 1, 1, -3],
[4, 8, -3, 2, 1]])
len([[1, 2, 0, 5, -2],
[9, -7, 5, 3, 0],
[2, 1, 1, 1, -3],
[4, 8, -3, 2, 1]])
# Tipo
type(A)
# Atributos
A.shape
A.size
A.ndim
len(A) | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
1.1 Funciones de NumPy Seguiremos nuestra introducción a NumPy mediante la resolución del siguiente problema: Problema 1> Dados cinco (5) contenedores cilíndricos con diferentes radios y alturas que pueden variar entre 5 y 25 cm, encontrar:> 1. El volumen del agua que puede almacenar cada contenedor;> 2. El volumen t... | # Definir numero de contenedores, medida minima y medida maxima
n_contenedores = 5
medida_min = 5
medida_max = 25 | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
A continuación, generaremos un arreglo de números enteros aleatorios entre 5 y 25 cm que representarán los radios y las alturas de los cilindros: | # Ayuda de np.random.randint()
help(np.random.randint)
help(np.random.seed)
import numpy as np
# Números aleatorios que representan radios y alturas.
# Inicializar la semilla
np.random.seed(1001)
medidas = np.random.randint(medida_min, medida_max, size=(10,))
# Ver valores
medidas
help(medidas.reshape)
# array.reshape
... | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
De los números generados, separemos los que corresponden a los radios, y los que corresponden a las alturas: | # Radios
radios = medidas[0, :]
radios
medidas[:, 3:5]
medidas[:, ::2]
# Alturas
alturas = medidas[1, :]
alturas | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
1. Con lo anterior, calculemos cada uno los volúmenes: | radios
radios**2
alturas
# Volúmenes de los contenedores
volumenes = (np.pi * radios**2) * alturas
volumenes | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
¡Excelente!Con esta línea de código tan sencilla, pudimos obtener de un solo jalón todos los volúmenes de nuestros contenedores.Esta es la potencia que nos ofrece NumPy. Podemos operar los arreglos de forma rápida, sencilla, y muy eficiente. 2. Ahora, el volumen total | # Volumen total
volumenes.sum() | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
3. ¿Cuál contenedor puede almacenar más volumen? ¿Cuánto? | volumenes
# Contenedor que puede almacenar más volumen
volumenes.argmax()
# Volumen máximo
volumenes.max()
# También se puede, pero no es recomendable. Ver comparación de tiempos
max(volumenes)
random_vector = np.random.randint(0, 1000, size=(1000,))
%timeit random_vector.max()
%timeit np.max(random_vector)
%timeit max... | 181 µs ± 4.44 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
| MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
4. ¿Cuál contenedor puede almacenar menos volumen? ¿Cuánto? | # Contenedor que puede almacenar menos volumen
volumenes.argmin()
# Volumen mínimo
volumenes.min() | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
5. Media, mediana y desviación estándar de los volúmenes | # Media, mediana y desviación estándar
volumenes.mean(), volumenes.std()
np.median(volumenes)
# Atributos shape y dtype
volumenes.shape
volumenes.dtype
A
A.shape
A.size | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
1.2 Trabajando con matrices Problema 2> 25 cartas numeradas de la 1 a la 25 se distribuyen aleatoriamente y en partes iguales a 5 personas. Encuentre la suma de cartas para cada persona tal que: > - para la primera persona, la suma es el valor de la primera carta menos la suma del resto de las cartas;> - para la segu... | # Ayuda en la función np.arange()
help(np.arange)
# Números del 1 al 25
cartas = np.arange(1, 26)
cartas | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
Luego, tal y como en un juego de cartas, deberíamos barajarlos, antes de repartirlos: | # Ayuda en la función np.random.shuffle()
help(np.random.shuffle)
# Barajar
np.random.shuffle(cartas)
# Ver valores
cartas | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
Bien. Ahora, deberíamos distribuir las cartas. Podemos imaginarnos la distribución como una matriz 5x5: | # Repartir cartas
cartas = cartas.reshape((5, 5))
# Ver valores
cartas | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
Entonces, tenemos 5 cartas para cada una de las 5 personas, visualizadas como una matriz 5x5.Lo único que nos falta es encontrar la suma para cada uno, es decir, sumar el elemento de la diagonal principal y restar las demás entradas de la fila (o columna).¿Cómo hacemos esto? | # Ayuda en la función np.eye()
help(np.eye)
# Matriz con la diagonal principal
I5 = np.eye(5)
I5
I5 * cartas
# Ayuda en la función np.ones()
help(np.ones)
# Matriz con los elementos fuera de la diagonal negativos
complement = np.ones((5, 5)) - I5
complement
complement * cartas
# Matriz completa
matriz_para_suma = I5 * ... | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
¿Quién es el ganador? | suma.argmax() | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
2. Algo de álgebra lineal con NumPyBueno, ya hemos utilizado NumPy para resolver algunos problemas de juguete. A través de estos problemas, hemos introducido el tipo de objetos que podemos manipular con NumPy, además de varias funcionalidades que podemos utilizar.Pues bien, este tipo de objetos nos sirven perfectament... | A = np.array([[1, 0, 1],
[-1, 2, 4],
[2, 1, 1]])
A | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
Podemos obtener varios cálculos útiles alrededor de la matriz A: | # Rango de la matriz A
np.linalg.matrix_rank(A)
# Determinante de la matriz A
np.linalg.det(A)
# Inversa de la matriz A
np.linalg.inv(A)
A.dot(np.linalg.inv(A))
np.linalg.inv(A).dot(A)
np.dot(A, np.linalg.inv(A))
np.dot(np.linalg.inv(A), A)
# Potencia de la matriz A
# A.dot(A).dot(A).dot(A).dot(A)
np.linalg.matrix_powe... | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
Por otra parte, si tenemos dos vectores: | x, y | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
podemos calcular su producto interno (producto punto) | x.dot(y)
(x * y).sum()
x[:3], y[:3]
np.cross(x[:3], y[:3]) | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
De la misma manera, podemos calcular la multiplicación de la matriz A por un vector | A
z = np.array([1, 0, 1])
A.dot(z) | _____no_output_____ | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
$$A x = z$$ | np.linalg.inv(A).dot(z)
np.linalg.solve(A, z)
help(np.linalg.cross)
help(np.linalg.svd)
a = np.arange(25).reshape(5,5)
a
np.einsum('ii', a)
help(a) | Help on ndarray object:
class ndarray(builtins.object)
| ndarray(shape, dtype=float, buffer=None, offset=0,
| strides=None, order=None)
|
| An array object represents a multidimensional, homogeneous array
| of fixed-size items. An associated data-type object describes the
| format of each element... | MIT | Semana3/Clase4_NumpyFundamentos.ipynb | mr1023/prope_programacion_2021 |
Reducing the problem sizeI reduced the number of qubits for my simulation considering the following:- I froze the core electrons that do not contribute significantly to chemistry and considered only the valence electrons. Qiskit already has this functionality implemented. So inspected the different transformers in `q... | from qiskit_nature.drivers import PySCFDriver
from qiskit_nature.transformers import FreezeCoreTransformer, ActiveSpaceTransformer
from qiskit.visualization import array_to_latex
molecule = 'Li 0.0 0.0 0.0; H 0.0 0.0 1.5474'
freezeCoreTransfomer = FreezeCoreTransformer(True, [3,4])
driver = PySCFDriver(atom=molecule)
q... | Total number of electrons is 2
Total number of molecular orbitals is 3
Total number of spin orbitals is 6
qubits you need to simulate this molecule with Jordan-Wigner mapping is 6
The value of the nuclear repulsion energy is 1.0259348796432726
| Apache-2.0 | solutions by participants/ex5/ex5-AnurananDas-3cnot-2.339767mHa-32params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
2. Electronic structure problemCreated an `ElectronicStructureProblem` that can produce the list of fermionic operators before mapping them to qubits (Pauli strings), included the 'freezecore' parameter. | from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
problem = ElectronicStructureProblem(driver, [freezeCoreTransfomer])
# Generate the second-quantized operators
second_q_ops = problem.second_q_ops()
# Hamiltonian
main_op = second_q_ops[0]
print(problem.__dict__) | {'driver': <qiskit_nature.drivers.pyscfd.pyscfdriver.PySCFDriver object at 0x7fe3a68f8e50>, 'transformers': [<qiskit_nature.transformers.freeze_core_transformer.FreezeCoreTransformer object at 0x7fe3a2965850>], '_molecule_data': <qiskit_nature.drivers.qmolecule.QMolecule object at 0x7fe398925250>, '_molecule_data_trans... | Apache-2.0 | solutions by participants/ex5/ex5-AnurananDas-3cnot-2.339767mHa-32params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
3. QubitConverterMapping defined as `ParityMapper` with ``two_qubit_reduction=True`` | from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper
from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter
# Setup the mapper and qubit converter
mapper_type = 'ParityMapper'
if mapper_type == 'ParityMapper':
mapper = ParityMa... | Z2 symmetries:
Symmetries:
Single-Qubit Pauli X:
Cliffords:
Qubit index:
[]
Tapering values:
- Possible values: []
| Apache-2.0 | solutions by participants/ex5/ex5-AnurananDas-3cnot-2.339767mHa-32params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
4. Initial stateAs we described in the Theory section, a good initial state in chemistry is the HF state (i.e. $|\Psi_{HF} \rangle = |0101 \rangle$). I initialize it as follows: | from qiskit_nature.circuit.library import HartreeFock
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals
init_state = HartreeFock(num_spin_orbitals, num_particles, conver... | ┌───┐
q_0: ┤ X ├
├───┤
q_1: ┤ X ├
└───┘
q_2: ─────
q_3: ─────
| Apache-2.0 | solutions by participants/ex5/ex5-AnurananDas-3cnot-2.339767mHa-32params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
5. AnsatzThe ansatz used was `TwoLocal`, with rotation layers as `['ry', 'rx', 'ry', 'rx']`, entanglement gate was only `cx`, `linear` type of entanglement, `repetitions` set to `1`. Idea was to get maximum entanglement with minimum circuit depth, all the while satisfying the costs. | from qiskit.circuit.library import TwoLocal
from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD
# Choose the ansatz
ansatz_type = "TwoLocal"
# Parameters for q-UCC antatze
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
num_spin_orbitals... | _____no_output_____ | Apache-2.0 | solutions by participants/ex5/ex5-AnurananDas-3cnot-2.339767mHa-32params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
7. OptimizerThe optimizer guides the evolution of the parameters of the ansatz so it is very important to investigate the energy convergence as it would define the number of measurements that have to be performed on the QPU. Here it was set to `COBYLA` with sufficient amount of maximum iterations possible before conve... | from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP
optimizer_type = 'COBYLA'
# You may want to tune the parameters
# of each optimizer, here the defaults are used
if optimizer_type == 'COBYLA':
optimizer = COBYLA(maxiter=30000)
elif optimizer_type == 'L_BFGS_B':
optimizer = L_BFGS_B(maxfu... | _____no_output_____ | Apache-2.0 | solutions by participants/ex5/ex5-AnurananDas-3cnot-2.339767mHa-32params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
8. Exact eigensolver | from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver
import numpy as np
def exact_diagonalizer(problem, converter):
solver = NumPyMinimumEigensolverFactory()
calc ... | Exact electronic energy after freezing core, for the valence electrons is -1.0887060157347412
| Apache-2.0 | solutions by participants/ex5/ex5-AnurananDas-3cnot-2.339767mHa-32params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
9. VQE and initial parameters for the ansatzNow we can import the VQE class and run the algorithm. | from qiskit.algorithms import VQE
from IPython.display import display, clear_output
# Print and save the data in lists
def callback(eval_count, parameters, mean, std):
# Overwrites the same line when printing
display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std))
clear_output(wait=T... | { 'aux_operator_eigenvalues': None,
'cost_function_evals': 9660,
'eigenstate': array([ 1.42330541e-04+1.43431962e-03j, -4.23490958e-04-4.89065970e-03j,
2.23678404e-03+2.63113429e-02j, -8.30964184e-02-9.87905676e-01j,
-3.50684854e-03-5.38647331e-02j, -1.74375790e-05-3.17583535e-04j,
4.88... | Apache-2.0 | solutions by participants/ex5/ex5-AnurananDas-3cnot-2.339767mHa-32params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
9. Scoring function The following was the simple scoring function:$$ score = N_{CNOT}$$where $N_{CNOT}$ is the number of CNOTs. We had to reach the chemical accuracy which is $\delta E_{chem} = 0.004$ Ha $= 4$ mHa.The lower the score the better! | # Store results in a dictionary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
# Unroller transpile your circuit into CNOTs and U gates
pass_ = Unroller(['u', 'cx'])
pm = PassManager(pass_)
ansatz_tp = pm.run(ansatz)
cnots = ansatz_tp.count_ops()['cx']
score = cnots
accuracy_t... | _____no_output_____ | Apache-2.0 | solutions by participants/ex5/ex5-AnurananDas-3cnot-2.339767mHa-32params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
Starbucks Capstone Challenge IntroductionThis data set contains simulated data that mimics customer behavior on the Starbucks rewards mobile app. Once every few days, Starbucks sends out an offer to users of the mobile app. An offer can be merely an advertisement for a drink or an actual offer such as a discount or BO... | import warnings
warnings.filterwarnings('ignore') # make the output cleaner
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('seaborn-white')
plt.rcParams['figure.figsize'] = (10,6)
plt.rcParams['font.size'] = 13
plt.rcParams['font.sans-serif'] = 'Open Sans'
plt.rcParams['font.fam... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
Portfolio | # read in the json files
portfolio = pd.read_json('data/portfolio.json', orient='records', lines=True)
portfolio | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
three types of promotion:- **BOGO (Buy One Get One free)**: customer received this offer, customer can get two similar drinks and pay for one, essentially 50% except customer now have two drinks, works better for customer who has a friend or a colleague to join that drink- **Discount**: after certain dollars purchased ... | # load data in show first 5 lines
profile = pd.read_json('data/profile.json', orient='records', lines=True)
profile.head()
# shape: rows by columns
profile.shape
profile.info(verbose=True)
# genders
profile.gender.value_counts()
profile.gender.value_counts().plot(kind='bar');
# age distribution, we saw some discrepancy... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
- clear more young male members than female members in the dataset. It makes sense since Starbuck sells coffee as the main drink, | # let group genders and age
gender = profile.groupby(['age', 'gender']).count()['id'].unstack()
gender
gender['M/F'] = gender['M']/gender['F']
plt.title('Ratio of Male/Female of Starbucks customers over age')
plt.ylabel('Male/Female')
plt.xlabel('age')
plt.grid()
plt.plot(gender.index, gender['M/F']); | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
- more male customers under 40, and female customers are increased propotionally with age- over 80 years old, more female than male using Starbucks products (or as Starbucks customer) | # explore member join
profile['became_member_on'] = pd.to_datetime(profile.became_member_on, format='%Y%m%d')
latest_ts = profile.became_member_on.max()
profile.became_member_on.apply(lambda x: (latest_ts - x).total_seconds()/
(3600*24*365)).plot(kind='hist', bins=20);
profile['membershi... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
encoded profile | # for columns with a few categorical values, we can get encode them direcly such as gender, became_member_on
# other need to be cut into a larger bin and then encoded by pd.get_dummies
# will we find a similar customer based on characteristics from profile
profile.columns
# membership age
profile['membership_age'] = pr... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
Transcript | # transaction record
transcript = pd.read_json('data/transcript.json', orient='records', lines=True)
transcript.head()
transcript.info()
# long table
transcript.shape
# average traffic per user
transcript.shape[0]/transcript.person.nunique()
# transaction by timestamp (hours)
transcript.time.plot(kind='hist');
# trans... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
- over the all transaction, about 44% promotion received gets completed- 75% of promotions received gets viewed- 58% of promotions viewed gets completed- two informational promotions don't have "completed" record user-offer-matrix | transcript.head()
# get content of value columns, unpack
transcript['amount'] = transcript['value'].apply(lambda x: list(x.values())[0]
if 'amount' in list(x.keys())[0] else np.NaN)
transcript['offer'] = transcript['value'].apply(lambda x: list(x.values())[0]
... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
- We need to rate how a promotion is sucess or not, for discout or BOGO, a **success case** this should be: `offer received >> offer viewed >> offer completed`- A **failed** promotion is: `offer received >> no view on offer >> offer completed`basically, an offer made, customer did not know about an offer but sti... | def rate_offer_discount_bogo(offer_id, df=None):
'''
rate a offer based on average number of viewed to number of completed
and total offer received.
score = number of completed / number of received (promotion)
For example:
- if a customer received two offers, viewed two and completed two,... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
Apply FunkSVD | # we get about 2/3 matrix is null values
sum(df.isnull().sum())/(df.shape[0]*df.shape[1])
# is any user with no promotional available?
# user will get at least 4 offers, and maximum 9 offers
df.isnull().sum(axis=1).sort_values(ascending=False).value_counts().sort_values()
# adopted from Udacity's exercise
def FunkSVD(u... | Optimizaiton Statistics
Iterations | Mean Squared Error
1 0.042280
2 0.028292
3 0.027818
4 0.027364
5 0.026920
6 0.026486
7 0.026063
8 0.025649
9 0.025245
10 0.024850
| MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
- small error, but is this a good approximation? | # reconstruct user-item matrix based on decomposed matrices
pred_mat = np.dot(user_mat, offer_mat)
# check average value of each columns
df.mean(axis=1)
# a quick check on the mean value is not promissing, we are looking value between -1 to 1
pred_mat.mean(axis=1) | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
- this approximation using FunkSVD seems NOT working well with our dataset How FunkSVD with a denser matrix? | # select matrix have 5 or less cells as null values
df2 = df[df.isnull().sum(axis=1) <= 5]
df_ = df2.to_numpy()
user_mat, offer_mat = FunkSVD(df_, latent_features=20, learning_rate=0.005, iters=10)
pred_mat = np.dot(user_mat, offer_mat)
# still. something is not working right
pred_mat.mean(axis=1)
pred_mat.max(axis=1)
... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
Surprise SVD | # let try out another FunkSVD
# https://surprise.readthedocs.io/en/stable/getting_started.html
from surprise import SVD
from surprise import Reader
from surprise import Dataset
from surprise.model_selection import cross_validate
from surprise.model_selection import KFold
from surprise import accuracy
reader = Reader(ra... | RMSE: nan
RMSE: nan
RMSE: nan
| MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
- it appeared that SVD algorithm is not converged. It is consistent with the RMSE error of 0.5 as above for value between 0 and zero Deeper dive into `Transcript` Rate transaction by completion | # let see transaction records again
transcript.head()
# and make a wide table by counting records
transcript.groupby(['offer', 'event']).count()['person'].unstack()
df_offer = transcript.groupby(['offer', 'event']).count()['person'].unstack()
df_offer.index.set_names(names='id', inplace=True)
# and calculate some ratio... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
summary:- more marketing channels resulted a higher view rate- all promotion has email as one of the channel- view rate is not linear over each channel, - without social marketing, the view rate is about 0.54 (or 54% customers saw their promotion) - without social plus mobile, the view rate drops to 0.35 - wi... | # let see all the rates with each promotion id
categories = ['view/receive','comp/receive', 'comp/view']
portfolio_extra[categories].plot(kind='bar', subplots=True); | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
**Successful rate of completion**- we will define a term to quantify a successful transaction by: s_rate = 1 - (completed/ received)*(completed/ viewed)for each transaction or overall users in this dataset. - in a perfect case, an offer was received, viewed, then completed, `s_rate = 0`- if a customer received a... | # for a simpler approach, I will use the ratio of (completed/received)*(completed/viewed)
# as one rating for how succesful the promotion is. This is only applicable for discount for BOGO
categories = ['view/receive','comp/receive', 'comp/view']
portfolio_extra['s_rate'] = 1 - portfolio_extra['comp/receive']*portfolio_... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
Grouping transaction by users | def analyze_df(df, offer_id, info_offer=False):
'''summary a transaction if it was viewed, other offer, and amount spent.
INPUT:
df: a dataframe containing transaction records
offer_id: an promotion id about an offer
OUPUT:
a dictionary containing summary
'''
# ... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
If you want to test the grouping transaction with with person, this is a screenshot. Otherwise, change `LOAD_JSON` from `True` to `False` at the beginning of the file | # LOAD_JSON = False
if not LOAD_JSON:
import progressbar
df_info = user_transaction(transcript=transcript, portfolio=portfolio)
df_info
else:
df_info = pd.read_json('data/offer_summary.json')
# make a short label from portfolio dataframe
labels = portfolio[['id', 'offer_type']].apply(
lambda row: ... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
remarks: - one transaction marked completion of informational offer is not sufficient to distinguish. All received offers were completed based on this assumption, which is minimal. - when a BOGO and discount offer was viewed, the total transaction during the offer was valid make a huge different to the offer not ... | # load group transaction from json file
df_info = pd.read_json('data/offer_summary.json')
encoded_profile = encoding_profile(df=profile)
def evaluate_similar_users(user_id, profile_df=None,
info_df=None, sort_amount=False, n_top=100):
'''evaluate similar users responded to promotions
... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
Test recommendation | import random
random.seed(2021)
max_idx = len(profile)
user_idx = random.randint(0, max_idx)
user_id = profile.iloc[user_idx].id
user_id
# '3713b8ef49c541beaa07ed83ed0136d5'
# group preference
group = evaluate_similar_users(user_id, profile_df=encoded_profile,
info_df=df_info, sort_amoun... | _____no_output_____ | MIT | Starbucks_Capstone_notebook.ipynb | binh-bk/Starbucks-Promotion-Recommender |
Amazon web services (AWS)- [Loading data into S3 buckets](Loading-data-into-S3-buckets) - via Console, CLI, Boto3- [Setting up an EC2 reserved instance](Setting-up-a-reserved-instance) - via Console, CLI, Boto3- [Spin up containers via Docker Machine](Spin-up-containers-via-Docker-Machine)- [Instance types](Inst... | import boto3
# initialize the S3 service
s3 = boto3.client('s3')
# create a test bucket (tip: use a different name!)
s3.create_bucket(Bucket='jo8a7fn8sfn8', CreateBucketConfiguration={'LocationConstraint': 'eu-central-1'})
# Call S3 to list current buckets
response = s3.list_buckets()
# Get a list of all bucket nam... | _____no_output_____ | CC0-1.0 | day3/aws.ipynb | NBISweden/workshop-advanced-python |
Now I want to test using the buchet without local file storage. Setting up a reserved instanceAmazon names their most popular instances Elastic Compute Cloud (EC2).- https://aws.amazon.com/ec2/- https://docs.aws.amazon.com/efs/latest/ug/gs-step-one-create-ec2-resources.html- https://docs.aws.amazon.com/AWSEC2/latest/U... |
import boto3
import botocore
import paramiko
ec2 = boto3.resource('ec2')
instance = ec2.Instance('id')
ec2.create_instances(ImageId='<ami-image-id>', MinCount=1, MaxCount=5)
key = paramiko.RSAKey.from_private_key_file(path/to/mykey.pem)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoA... | _____no_output_____ | CC0-1.0 | day3/aws.ipynb | NBISweden/workshop-advanced-python |
import pandas as pd
!ls ./drive/MyDrive/Test01
!ls ./smtphP
df = pd.read_csv('./drive/MyDrive/Test01/smtph_total.csv')
df.head(5)
posts = df['Description']
posts
!python -m pip install konlpy
!python -m pip install eunjeon
from konlpy.tag import Mecab
tagger = Mecab()
| _____no_output_____ | Apache-2.0 | NLTK_korean.ipynb | creamcheesesteak/test_deeplearning | |
Creating two graphs including the trends of TFR and FLPR. One graph includes 3 countries with the highest current HDI and the other graph includes 3 with the lowest current HDI. **Importing Libraries and Uploading Files** | import matplotlib.pyplot as plt
import pandas as pd
import pylab
%matplotlib inline
pylab.rcParams['figure.figsize'] = (10., 8.)
from google.colab import files
uploaded = files.upload()
#upload Africa_FULL_MERGE.csv file
data = 'Africa_FULL_MERGE.csv'
africa = pd.read_csv(data)
africa
africa['HDI'] = pd.to_nume... | _____no_output_____ | MIT | Python Analysis/Visualisations/Code/Visualisation_TFR_and_FLPR_of_Highest_and_Lowest_HDI_countries.ipynb | ChangHuaHua/QM2-Group-12 |
**3 Highest and Lowest HDI** | africa_2018 = africa[africa['Year'] == 2018]
africa_2018 = africa_2018.reset_index(drop=True)
africa_2018
africa_string = africa_2018['HDI'].astype(float)
africa_string.nlargest(3)
# corresponding countries to index numbers 43, 35, and 3 are:
# 43 Seychelles 0.801
# 35 Mauritius 0.796
# 3 Algeria 0.759
af... | _____no_output_____ | MIT | Python Analysis/Visualisations/Code/Visualisation_TFR_and_FLPR_of_Highest_and_Lowest_HDI_countries.ipynb | ChangHuaHua/QM2-Group-12 |
**Segregating Dataframe** | africa_seychelles = africa[africa['Country'] == 'Seychelles']
africa_mauritius = africa[africa['Country'] == 'Mauritius']
africa_algeria = africa[africa['Country'] == 'Algeria']
africa_niger = africa[africa['Country'] == 'Niger']
africa_CAR = africa[africa['Country'] == 'Central African Republic']
africa_chad = af... | _____no_output_____ | MIT | Python Analysis/Visualisations/Code/Visualisation_TFR_and_FLPR_of_Highest_and_Lowest_HDI_countries.ipynb | ChangHuaHua/QM2-Group-12 |
**Getting Values for Analysis** | africa_algeria[africa_algeria['Year']==1960]
africa_algeria[africa_algeria['Year']==1990]
africa_algeria[africa_algeria['Year']==2001]
africa_algeria[africa_algeria['Year']==2002]
africa_algeria[africa_algeria['Year']==2003]
africa_algeria[africa_algeria['Year']==2017]
africa_algeria[africa_algeria['Year']==2018]
afric... | _____no_output_____ | MIT | Python Analysis/Visualisations/Code/Visualisation_TFR_and_FLPR_of_Highest_and_Lowest_HDI_countries.ipynb | ChangHuaHua/QM2-Group-12 |
**Creating Visualisations**
The darker the colour, the higher the HDI
Red = highest HDI countries
Blue = lowest HDI countries 3 Highest HDI Countries | ax = africa_high.loc[africa_high['Country']=='Seychelles'].plot(x='Year', y= 'TFR', kind='scatter', c = 'maroon', label = 'Seychelles')
africa_high.loc[africa_high['Country']=='Mauritius'].plot(x='Year', y= 'TFR', kind='scatter', c = 'red', ax=ax, label = 'Mauritius')
africa_high.loc[africa_high['Country']=='Algeria'... | _____no_output_____ | MIT | Python Analysis/Visualisations/Code/Visualisation_TFR_and_FLPR_of_Highest_and_Lowest_HDI_countries.ipynb | ChangHuaHua/QM2-Group-12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.