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 |
|---|---|---|---|---|---|
샘플 갯수가 1000개일 경우에 theta = 0.9, N = 20 | N = 20
theta = 0.9
rv = sp.stats.binom(N, theta)
xx = np.arange(N + 1)
plt.bar(xx, rv.pmf(xx), align = 'center')
plt.ylabel('P(x)')
plt.title('binomial pmf when N=20')
plt.show()
x1000 = rv.rvs(1000) # sample 1000개 생성
sns.countplot(x1000)
plt.title("Binomial Distribution's Simulation")
plt.xlabel('values')
plt.show()
... | C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\font_manager.py:1320: UserWarning: findfont: Font family ['nanumgothic'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))
| MIT | 2018_06_11_Preview_SciPy_Bern.ipynb | jaykim-asset/datascience_review |
<img src="assets/bokeh-transparent.png" style="width:50px" > Bokeh Tutorial 07. Exporting and Embedding So far we have seen how to generate interactive Bokeh output directly inline in Jupyter not... | from bokeh.io import output_notebook, show
output_notebook() | _____no_output_____ | BSD-3-Clause | tutorial/10 - Exporting and Embedding.ipynb | bingyao/bokeh-notebooks |
And also load some data that will be used throughout this chapter | import pandas as pd
from bokeh.plotting import figure
from bokeh.sampledata.stocks import AAPL
df = pd.DataFrame(AAPL)
df['date'] = pd.to_datetime(df['date']) | _____no_output_____ | BSD-3-Clause | tutorial/10 - Exporting and Embedding.ipynb | bingyao/bokeh-notebooks |
Embedding Interactive ContentTo start we will look differnet ways of embedding live interactive Bokeh output in various situations. Displaying in the NotebookThe first way to embed Bokeh output is in the Jupyter Notebooks, as we have already, seen. As a reminder, the cell below will generate a plot inline as output,... | p = figure(plot_width=800, plot_height=250, x_axis_type="datetime")
p.line(df['date'], df['close'], color='navy', alpha=0.5)
show(p) | _____no_output_____ | BSD-3-Clause | tutorial/10 - Exporting and Embedding.ipynb | bingyao/bokeh-notebooks |
Saving to an HTML FileIt is also often useful to generate a standalone HTML script containing Bokeh content. This is accomplished by calling the `output_file(...)` function. It is especially common to do this from standard Python scripts, but here we see that it works in the notebook as well. | from bokeh.io import output_file, show
output_file("plot.html")
show(p) # save(p) will save without opening a new browser tab | _____no_output_____ | BSD-3-Clause | tutorial/10 - Exporting and Embedding.ipynb | bingyao/bokeh-notebooks |
In addition the inline plot above, you should also have seen a new browser tab open with the contents of the newly saved "plot.html" file. It is important to note that `output_file` initiates a *persistent mode of operation*. That is, all subsequent calls to show will generate output to the specified file. We can "rese... | from bokeh.io import reset_output
reset_output() | _____no_output_____ | BSD-3-Clause | tutorial/10 - Exporting and Embedding.ipynb | bingyao/bokeh-notebooks |
Templating in HTML DocumentsAnother use case is to embed Bokeh content in a Jinja HTML template. We will look at a simple explicit case first, and then see how this technique might be used in a web app framework such as Flask. The simplest way to embed standalone (i.e. not Bokeh server) content is to use the `componen... | import jinja2
from bokeh.embed import components
# IMPORTANT NOTE!! The version of BokehJS loaded in the template should match
# the version of Bokeh installed locally.
template = jinja2.Template("""
<!DOCTYPE html>
<html lang="en-US">
<link
href="http://cdn.pydata.org/bokeh/dev/bokeh-0.13.0.min.css"
rel="s... | _____no_output_____ | BSD-3-Clause | tutorial/10 - Exporting and Embedding.ipynb | bingyao/bokeh-notebooks |
Note that it is possible to pass multiple objects to a single call to `components`, in order to template multiple Bokeh objects at once. See the [User's Guide for components](https://bokeh.pydata.org/en/latest/docs/user_guide/embed.htmlcomponents) for more information.Once we have the script and div from `components`, ... | from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_bokeh():
return template.render(script=script, div=div)
# Uncomment to run the Flask Server. Use Kernel -> Interrupt from Notebook menubar to stop
#app.run(port=5050)
# EXERCISE: Create your own template (or modify the one above)
| _____no_output_____ | BSD-3-Clause | tutorial/10 - Exporting and Embedding.ipynb | bingyao/bokeh-notebooks |
Exporting Static ImagesSometimes it is desirable to produce static images of plots or other Bokeh output, without any interactive capabilities. Bokeh supports exports to PNG and SVG formats. PNG ExportBokeh supports exporting a plot or layout to PNG image format with the `export_png` function. This function is alled... | from bokeh.io import export_png
p = figure(plot_width=800, plot_height=250, x_axis_type="datetime")
p.line(df['date'], df['close'], color='navy', alpha=0.5)
export_png(p, filename="plot.png")
from IPython.display import Image
Image('plot.png')
# EXERCISE: Save a layout of plots (e.g. row or column) as SVG and see wha... | _____no_output_____ | BSD-3-Clause | tutorial/10 - Exporting and Embedding.ipynb | bingyao/bokeh-notebooks |
SVG ExportBokeh can also generate SVG output in the browser, instead of rendering to HTML canvas. This is accomplished by setting `output_backend='svg'` on a figure. This can be be used to generate SVGs in `output_file` HTML files, or in content emebdded with `components`. It can also be used with the `export_svgs` fu... | from bokeh.io import export_svgs
p = figure(plot_width=800, plot_height=250, x_axis_type="datetime", output_backend='svg')
p.line(df['date'], df['close'], color='navy', alpha=0.5)
export_svgs(p, filename="plot.svg")
from IPython.display import SVG
SVG('plot.svg')
# EXERCISE: Save a layout of plots (e.g. row or column... | _____no_output_____ | BSD-3-Clause | tutorial/10 - Exporting and Embedding.ipynb | bingyao/bokeh-notebooks |
Gaussian processes with genetic algorithm for the reconstruction of late-time Hubble data This notebook uses Gaussian processes (GP) with the genetic algorithm (GA) to reconstruct the cosmic chronometers and supernovae data sets ([2106.08688](https://arxiv.org/abs/2106.08688)). We shall construct our own GP class and ... | %matplotlib inline
import numpy as np
from numpy.random import uniform as unif
import matplotlib.pyplot as plt
import pygad | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
0. My GP class Here is the GP class (written from scratch) that we shall use in this notebook. | class GP:
'''Class for making GP predictions.
rbf: k(r) = A^2 \exp(-r^2/(2l^2))
rq : k(r) = A^2 (1 + (r^2/(2 \alpha l^2)))^{-\alpha}
m52: k(r) = A^2 \exp(-\sqrt{5}r/l)
(1 + \sqrt{5}r/l + 5r^2/(3l^2))
mix: rbf + chy + m52
Input:
chromosome: list of kernel hyperparame... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
This will be used for both the cosmic chronometers (Section 1) and supernovae applications (Section 2). 1. Cosmic chronometers Importing the cosmic chronometers data set. | cc_data = np.loadtxt('cc_data.txt')
z_cc = cc_data[:, 0]
Hz_cc = cc_data[:, 1]
sigHz_cc = cc_data[:, 2]
fig, ax = plt.subplots()
ax.errorbar(z_cc, Hz_cc, yerr = sigHz_cc,
fmt = 'ro', ecolor = 'k',
markersize = 7, capsize = 3)
ax.set_xlabel('$z$')
ax.set_ylabel('$H(z)$')
plt.show() | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
To use the GA, we setup the log-marginal likelihood as a fitness function. In addition, we consider a Bayesian-information type penalty to fine complex kernels. | n_data = len(z_cc)
def penalty(chromosome):
'''Identifies a penalty term to be factored in the fitness function
so that longer/more complex kernels will be given a due weight.'''
c_rbf = chromosome[0]
l_rbf = chromosome[1]
A_rbf = c_rbf*l_rbf
c_rq = chromosome[3]
l_rq = chromosome[4]
... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
In the next line, we setup an equally uniform population of pure-bred kernels and a diverse set of kernels. It is interesting to see the evolution of the uniform population compared to one which is a lot more diverse. | pop_size = 1000 # population size
init_uni = []
for i in range(0, pop_size):
if i < int(pop_size/3):
init_uni.append([unif(0, 300), unif(0, 10), unif(0, 5),
0, 0, 0, 0, 0, 0, 0])
elif (i > int(pop_size/3)) and (i < int(2*pop_size/3)):
init_uni.append([0, 0, 0,
... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
Given this, we prepare the parameters of the GA. | gene_space = [{'low': 0, 'high': 300}, {'low': 0, 'high': 10}, {'low': 0, 'high': 5}, # rbf lims
{'low': 0, 'high': 300}, {'low': 0, 'high': 10}, # chy lims
{'low': 0, 'high': 2}, {'low': 0, 'high': 5},
{'low': 0, 'high': 300}, {'low': 0, 'high': 10}, {'low': 0, 'high': 5}] # ... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
The ``GA run`` is performed in the next line.*The next two code runs may be skipped if output have already been saved. In this case, proceed to the loading lines. | # setup GA instance, for random initial pop.
ga_inst_uni_cc = pygad.GA(initial_population = init_uni,
num_genes = num_genes,
num_generations = n_gen,
num_parents_mating = num_parents_mating,
fitness_func = fitness_fu... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
Next run creates a GA instance with the same parameters as with the previous run, but a a diversified initial population. | ga_inst_div_cc = pygad.GA(initial_population = init_div,
num_genes = num_genes,
num_generations = n_gen,
num_parents_mating = num_parents_mating,
fitness_func = fitness_function,
parent_sele... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
``Loading lines``We can load the ``pygad`` results should they have been saved already in previous runs. | load_ga_uniform = pygad.load('gp_ga_cc_uniform_init')
load_ga_diverse = pygad.load('gp_ga_cc_diverse_init') | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
We can view the prediction based on this superior individual below. | # champion chromosomes
chr_1 = load_ga_uniform.best_solutions[-1]
chr_2 = load_ga_diverse.best_solutions[-1]
z_min = 0
z_max = 3
n_div = 1000
z_rec = np.linspace(z_min, z_max, n_div)
champs = {}
champs['uniform'] = {'chromosome': chr_1}
champs['diverse'] = {'chromosome': chr_2}
for champ in champs:
chromosome = ... | uniform
H0 = 69.7 +/- 6.3
log-marginal likelihood -123.7946112476086
penalty 16.83647914993237
fitness function -140.63109039754096
chi^2 12.241263910472332
diverse
H0 = 67.3 +/- 5.9
log-marginal likelihood -123.76904376987132
penalty 16.83647914993237
fitness function -140.6055229198037
chi^2 12.30756281659826
| MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
A plot of the generation vs fitness can also be shown. | fit_uni = [get_fit(c) for c in load_ga_uniform.best_solutions]
fit_div = [get_fit(c) for c in load_ga_diverse.best_solutions]
fig, ax = plt.subplots()
ax.plot(fit_uni, 'b-', label = 'uniform')
ax.plot(fit_div, 'r--', label = 'diverse')
ax.set_xlabel('generation')
ax.set_ylabel('best fitness')
ax.set_xlim(1, n_gen)
ax.... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
2. Supernovae Type Ia In this section, we perform the GP reconstruction with the compressed Pantheon data set. | # load pantheon compressed m(z) data
loc_lcparam = 'lcparam_DS17f.txt'
loc_lcparam_sys = 'sys_DS17f.txt'
lcparam = np.loadtxt(loc_lcparam, usecols = (1, 4, 5))
lcparam_sys = np.loadtxt(loc_lcparam_sys, skiprows = 1)
# setup pantheon samples
z_ps = lcparam[:, 0]
logz_ps = np.log(z_ps)
mz_ps = lcparam[:, 1]
sigmz_ps = l... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
The fitness function, now taking in the SNe data set, is prepared below for the GA. | n_data = len(z_ps)
def get_fit(chromosome):
'''Evaluates the fitness of the indivial with chromosome'''
if all(hp > 0 for hp in chromosome) == True:
pnl = penalty(chromosome)
try:
gp = GP(chromosome)
lml = gp.get_logmlike(logz_ps, mz_ps,
... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
Then, we setup the initial uniform and diverse kernel populations. | pop_size = 1000 # population size
init_uni = []
for i in range(0, pop_size):
if i < int(pop_size/3):
init_uni.append([unif(0, 200), unif(0, 100), unif(0, 5),
0, 0, 0, 0, 0, 0, 0])
elif (i > int(pop_size/3)) and (i < int(2*pop_size/3)):
init_uni.append([0, 0, 0,
... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
The GA parameters can now be set for the SNe fitting. | gene_space = [{'low': 0, 'high': 200}, {'low': 0, 'high': 100}, {'low': 0, 'high': 5}, # rbf lims
{'low': 0, 'high': 200}, {'low': 0, 'high': 100}, # chy lims
{'low': 0, 'high': 2}, {'low': 0, 'high': 5},
{'low': 0, 'high': 200}, {'low': 0, 'high': 100}, {'low': 0, 'high': 5}]... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
Here are the ``GA runs``. We start with the uniform population.*Skip the runs and jump ahead to loading lines if results have already been prepared. | ga_inst_uni_sn = pygad.GA(initial_population = init_uni,
num_genes = num_genes,
num_generations = n_gen,
num_parents_mating = num_parents_mating,
fitness_func = fitness_function,
parent_sele... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
Here is the GA run for a diversified initial population. | ga_inst_div_sn = pygad.GA(initial_population = init_div,
num_genes = num_genes,
num_generations = n_gen,
num_parents_mating = num_parents_mating,
fitness_func = fitness_function,
parent_sele... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
``Load GA runs``Saved ``pygad`` output can be accessed. This is done for the SNe runs below. | load_ga_uniform = pygad.load('gp_ga_sn_uniform_init')
load_ga_diverse = pygad.load('gp_ga_sn_diverse_init') | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
The GP reconstructions are shown below. | # champion chromosomes
chr_1 = load_ga_uniform.best_solutions[-1]
chr_2 = load_ga_diverse.best_solutions[-1]
z_min = 1e-5
z_max = 3
n_div = 1000
z_rec = np.logspace(np.log(z_min), np.log(z_max), n_div)
logz_rec = np.log(z_rec)
champs = {}
champs['uniform'] = {'chromosome': chr_1}
champs['diverse'] = {'chromosome': ch... | uniform
log-marginal likelihood 62.18631886438317
penalty 18.44439727056968
fitness function 43.74192159381349
chi^2 35.429040731552476
diverse
log-marginal likelihood 62.55037313828511
penalty 18.44439727056968
fitness function 44.10597586771543
chi^2 34.62680636352342
| MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
Here is the fitness per generation for the GPs above. | fit_uni = [get_fit(c) for c in load_ga_uniform.best_solutions]
fit_div = [get_fit(c) for c in load_ga_diverse.best_solutions]
fig, ax = plt.subplots()
ax.plot(fit_uni, 'b-', label = 'uniform')
ax.plot(fit_div, 'r--', label = 'diverse')
ax.set_xlabel('generation')
ax.set_ylabel('best fitness')
ax.set_xlim(1, n_gen)
ax.... | _____no_output_____ | MIT | supp_ntbks_arxiv.2106.08688/gp_ga_reconstruction.ipynb | reggiebernardo/notebooks |
[](https://www.pythonista.io) Declaraciones y bloques de código. Flujo de ejecución del código.El intérprete de Python es capaz de leer, evaluar y ejecutar una sucesión de instrucciones línea por línea de principio a fin. A esto se le conoce copmo flujo de ejecución de código... | for i in range (1, 11):
print(i)
print('Esta es la línea final.') | _____no_output_____ | MIT | 11_declaraciones_y_bloques_de_codigo.ipynb | OscarLpzL/CursoPython |
Declaraciones anidadas.Es muy común que el código incluya declaraciones dentro de otras declaraciones, por lo que para delimitar el códifgo dentro de una declaración anidada se utiliza la misma regla de indentación dejando 4 espacios adicionales. **Ejemplo:** | '''Esta celda realizará una iteración de números en el rango
entre el ```1``` y ```10``` y mostrará un mensaje dependiendo
si el número es par o non.'''
for i in range (1, 11):
if i % 2 == 0:
print ('El número %d es par.' %i)
else:
print ('El número %d es non.' %i)
print('Esta es la línea fina... | _____no_output_____ | MIT | 11_declaraciones_y_bloques_de_codigo.ipynb | OscarLpzL/CursoPython |
SeriesDtMethodTransformerThis notebook shows the functionality in the `SeriesDtMethodTransformer` class. This transformer applys a `pd.Series.dt` method to a specific column in the input `X`. This generic transformer means that many `pd.Series.dt` methods are available for use within the package without having to dire... | import pandas as pd
import numpy as np
import tubular
from tubular.dates import SeriesDtMethodTransformer
tubular.__version__ | _____no_output_____ | BSD-3-Clause | examples/dates/SeriesDtMethodTransformer.ipynb | munichpavel/tubular |
Load dummy datasetNote, the load_boston script modifies the original Boston dataset to include nulls values and pandas categorical dtypes. | df = tubular.testing.test_data.create_datediff_test_df()
df
df.dtypes | _____no_output_____ | BSD-3-Clause | examples/dates/SeriesDtMethodTransformer.ipynb | munichpavel/tubular |
Simple usage Initialising SeriesDtMethodTransformer The user must specify the following; - `new_column_name` the name of the column to assign the outputs of the `pd.Series.str` method to - `pd_method_name` the name of the `pd.Series.dt` method to be called - `column` the column in the `DataFrame` passed to the `tran... | month_transformer = SeriesDtMethodTransformer(
column = 'a',
pd_method_name = 'month',
new_column_name = 'a_month'
) | _____no_output_____ | BSD-3-Clause | examples/dates/SeriesDtMethodTransformer.ipynb | munichpavel/tubular |
SeriesDtMethodTransformer fitThere is no fit method for the `SeriesDtMethodTransformer` as the methods that it can run do not 'learn' anything from the data. SeriesDtMethodTransformer transformWhen running transform with this configuration a new column `a_month` is added to the input `X` which is the result or runnin... | df_2 = month_transformer.transform(df)
df_2[['a', 'a_month']].head() | _____no_output_____ | BSD-3-Clause | examples/dates/SeriesDtMethodTransformer.ipynb | munichpavel/tubular |
Testing accuracy of RF classifier for lightly loaded, testing and training with all the rotational speeds | from jupyterthemes import get_themes
import jupyterthemes as jt
from jupyterthemes.stylefx import set_nb_theme
set_nb_theme('chesterish')
import pandas as pd
data_10=pd.read_csv(r'D:\Acads\BTP\Lightly Loaded\Train10hz.csv')
data_20=pd.read_csv(r'D:\Acads\BTP\Lightly Loaded\Train20hz.csv')
data_30=pd.read_csv(r'D:\Acad... | _____no_output_____ | MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Assigning X and y for training | dataset_10=data_10.values
X_10= dataset_10[:,0:9]
print(X_10)
y_10=dataset_10[:,9]
print(y_10)
dataset_15=data_15.values
X_15= dataset_15[:,0:9]
print(X_15)
y_15=dataset_15[:,9]
print(y_15)
dataset_20=data_20.values
X_20= dataset_20[:,0:9]
print(X_20)
y_20=dataset_20[:,9]
print(y_20)
dataset_25=data_25.values
X_25= dat... | [[ 1.027550e+00 4.547200e-01 7.451636e+00 ... -2.186170e-01
8.330000e-04 -1.628680e-01]
[ 1.026400e+00 1.122346e+00 -1.123838e+00 ... 9.845900e-02
-9.220000e-04 -1.297100e-02]
[ 4.594950e+00 -3.482196e+00 -5.994413e+00 ... 3.765800e-02
3.358000e-03 -1.788950e-01]
...
[ 1.244615e+01 4.545544e+00 -8.181... | MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Training Random Forest Classifier | from sklearn.ensemble import RandomForestClassifier
rf_10 = RandomForestClassifier(n_estimators = 1000, random_state = 42)
rf_10.fit(X_10, y_10);
from sklearn.ensemble import RandomForestClassifier
rf_15 = RandomForestClassifier(n_estimators = 1000, random_state = 42)
rf_15.fit(X_15, y_15);
from sklearn.ensemble import... | _____no_output_____ | MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Importing Testing data | test_10=pd.read_csv(r'D:\Acads\BTP\Lightly Loaded\Test10hz.csv')
test_20=pd.read_csv(r'D:\Acads\BTP\Lightly Loaded\Test20hz.csv')
test_30=pd.read_csv(r'D:\Acads\BTP\Lightly Loaded\Test30Hz.csv')
test_15=pd.read_csv(r'D:\Acads\BTP\Lightly Loaded\Test15hz.csv')
test_25=pd.read_csv(r'D:\Acads\BTP\Lightly Loaded\Test25hz.c... | _____no_output_____ | MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Assigning X and y for testing | dataset_test_10 = test_10.values
X_test_10 = dataset_test_10[:,0:9]
print(X_test_10)
y_test_10= dataset_test_10[:,9]
print(y_test_10)
dataset_test_15 = test_15.values
X_test_15 = dataset_test_15[:,0:9]
print(X_test_15)
y_test_15= dataset_test_15[:,9]
print(y_test_15)
dataset_test_20 = test_20.values
X_test_20 = datas... | [[ 5.9940000e-01 2.2963700e-01 -2.8239780e+00 ... -2.4300000e-02
-3.6200000e-04 2.4489600e-01]
[ 7.3290000e-01 -9.8103230e+00 -7.1901720e+00 ... 2.5711800e-01
-6.0500000e-04 -7.1654000e-02]
[ 2.1705000e-01 -3.7397320e+00 4.0531970e+00 ... 1.9575700e-01
-1.3330000e-03 -8.8163000e-02]
...
[ 2.5000000e-01 ... | MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Predictions with 10Hz Trained Model | import numpy as np
predictions_10 = rf_10.predict(X_test_10)
errors_10 = abs(predictions_10 - y_test_10)
print('Mean Absolute Error 10Hz with 10Hz:', round(np.mean(errors_10), 3), 'degrees.')
accuracy = 100 - np.mean(errors_10)
print('Accuracy:', round(accuracy, 3), '%.')
predictions_15 = rf_10.predict(X_test_15)
erro... | Mean Absolute Error 40Hz with 10Hz: 1.541 degrees.
Accuracy: 98.459 %.
| MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Predictions with 15Hz model | predictions_10 = rf_15.predict(X_test_10)
errors_10 = abs(predictions_10 - y_test_10)
print('Mean Absolute Error 10Hz with 15Hz:', round(np.mean(errors_10), 3), 'degrees.')
accuracy = 100 - np.mean(errors_10)
print('Accuracy:', round(accuracy, 3), '%.')
predictions_15 = rf_15.predict(X_test_15)
errors_15 = abs(predict... | Mean Absolute Error 40Hz with 15Hz: 1.296 degrees.
Accuracy: 98.704 %.
| MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Predictions with 20Hz model | predictions_10 = rf_20.predict(X_test_10)
errors_10 = abs(predictions_10 - y_test_10)
print('Mean Absolute Error 10Hz with 20Hz:', round(np.mean(errors_10), 3), 'degrees.')
accuracy = 100 - np.mean(errors_10)
print('Accuracy:', round(accuracy, 3), '%.')
predictions_15 = rf_20.predict(X_test_15)
errors_15 = abs(predict... | Mean Absolute Error 40Hz with 20Hz: 1.19 degrees.
Accuracy: 98.81 %.
| MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Predictions with 25Hz model | predictions_10 = rf_25.predict(X_test_10)
errors_10 = abs(predictions_10 - y_test_10)
print('Mean Absolute Error 10Hz with 25Hz:', round(np.mean(errors_10), 3), 'degrees.')
accuracy = 100 - np.mean(errors_10)
print('Accuracy:', round(accuracy, 3), '%.')
predictions_15 = rf_25.predict(X_test_15)
errors_15 = abs(predict... | Mean Absolute Error 40Hz with 25Hz: 0.995 degrees.
Accuracy: 99.005 %.
| MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Predictions with 30Hz model | predictions_10 = rf_30.predict(X_test_10)
errors_10 = abs(predictions_10 - y_test_10)
print('Mean Absolute Error 10Hz with 30Hz:', round(np.mean(errors_10), 3), 'degrees.')
accuracy = 100 - np.mean(errors_10)
print('Accuracy:', round(accuracy, 3), '%.')
predictions_15 = rf_30.predict(X_test_15)
errors_15 = abs(predict... | Mean Absolute Error 40Hz with 30Hz: 0.775 degrees.
Accuracy: 99.225 %.
| MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Testing with 35Hz model | predictions_10 = rf_35.predict(X_test_10)
errors_10 = abs(predictions_10 - y_test_10)
print('Mean Absolute Error 10Hz with 35Hz:', round(np.mean(errors_10), 3), 'degrees.')
accuracy = 100 - np.mean(errors_10)
print('Accuracy:', round(accuracy, 3), '%.')
predictions_15 = rf_35.predict(X_test_15)
errors_15 = abs(predict... | Mean Absolute Error 40Hz with 35Hz: 0.933 degrees.
Accuracy: 99.067 %.
| MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Training with 40Hz model | predictions_10 = rf_35.predict(X_test_10)
errors_10 = abs(predictions_10 - y_test_10)
print('Mean Absolute Error 10Hz with 35Hz:', round(np.mean(errors_10), 3), 'degrees.')
accuracy = 100 - np.mean(errors_10)
print('Accuracy:', round(accuracy, 3), '%.')
predictions_15 = rf_35.predict(X_test_15)
errors_15 = abs(predict... | Mean Absolute Error 40Hz with 35Hz: 0.933 degrees.
Accuracy: 99.067 %.
| MIT | LL_Phase_1.ipynb | Aficionado45/IM-Fault-Detection |
Made With MLApplied ML · MLOps · ProductionJoin 20K+ developers in learning how to responsibly deliver value with ML. 🔥 Among the top ML repositories on GitHub Neural NetworksIn this lesson, we will explore multilayer perceptrons (MLPs) which are a basic type o... | import numpy as np
import random
SEED = 1234
# Set seed for reproducibility
np.random.seed(SEED)
random.seed(SEED) | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Load data I created some non-linearly separable spiral data so let's go ahead and download it for our classification task. | import matplotlib.pyplot as plt
import pandas as pd
# Load data
url = "https://raw.githubusercontent.com/GokuMohandas/MadeWithML/main/datasets/spiral.csv"
df = pd.read_csv(url, header=0) # load
df = df.sample(frac=1).reset_index(drop=True) # shuffle
df.head()
# Data shapes
X = df[['X1', 'X2']].values
y = df['color'].va... | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Split data We'll shuffle our dataset (since it's ordered by class) and then create our data splits (stratified on class). | import collections
from sklearn.model_selection import train_test_split
TRAIN_SIZE = 0.7
VAL_SIZE = 0.15
TEST_SIZE = 0.15
def train_val_test_split(X, y, train_size):
"""Split dataset into data splits."""
X_train, X_, y_train, y_ = train_test_split(X, y, train_size=TRAIN_SIZE, stratify=y)
X_val, X_test, y_va... | X_train: (1050, 2), y_train: (1050,)
X_val: (225, 2), y_val: (225,)
X_test: (225, 2), y_test: (225,)
Sample point: [-0.63919105 -0.69724176] → c1
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Label encoding In the previous lesson we wrote our own label encoder class to see the inner functions but this time we'll use scikit-learn [`LabelEncoder`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html) class which does the same operations as ours. | from sklearn.preprocessing import LabelEncoder
# Output vectorizer
label_encoder = LabelEncoder()
# Fit on train data
label_encoder = label_encoder.fit(y_train)
classes = list(label_encoder.classes_)
print (f"classes: {classes}")
# Convert labels to tokens
print (f"y_train[0]: {y_train[0]}")
y_train = label_encoder.tra... | counts: [350 350 350]
weights: {0: 0.002857142857142857, 1: 0.002857142857142857, 2: 0.002857142857142857}
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Standardize data We need to standardize our data (zero mean and unit variance) so a specific feature's magnitude doesn't affect how the model learns its weights. We're only going to standardize the inputs X because our outputs y are class values. | from sklearn.preprocessing import StandardScaler
# Standardize the data (mean=0, std=1) using training data
X_scaler = StandardScaler().fit(X_train)
# Apply scaler on training and test data (don't standardize outputs for classification)
X_train = X_scaler.transform(X_train)
X_val = X_scaler.transform(X_val)
X_test = X_... | X_test[0]: mean: 0.1, std: 0.9
X_test[1]: mean: 0.0, std: 1.0
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Linear model Before we get to our neural network, we're going to motivate non-linear activation functions by implementing a generalized linear model (logistic regression). We'll see why linear models (with linear activations) won't suffice for our dataset. | import torch
# Set seed for reproducibility
torch.manual_seed(SEED) | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Model | from torch import nn
import torch.nn.functional as F
INPUT_DIM = X_train.shape[1] # X is 2-dimensional
HIDDEN_DIM = 100
NUM_CLASSES = len(classes) # 3 classes
class LinearModel(nn.Module):
def __init__(self, input_dim, hidden_dim, num_classes):
super(LinearModel, self).__init__()
self.fc1 = nn.Linea... | <bound method Module.named_parameters of LinearModel(
(fc1): Linear(in_features=2, out_features=100, bias=True)
(fc2): Linear(in_features=100, out_features=3, bias=True)
)>
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Training | from torch.optim import Adam
LEARNING_RATE = 1e-2
NUM_EPOCHS = 10
BATCH_SIZE = 32
# Define Loss
class_weights_tensor = torch.Tensor(list(class_weights.values()))
loss_fn = nn.CrossEntropyLoss(weight=class_weights_tensor)
# Accuracy
def accuracy_fn(y_pred, y_true):
n_correct = torch.eq(y_pred, y_true).sum().item()
... | Epoch: 0 | loss: 1.13, accuracy: 49.9
Epoch: 1 | loss: 0.91, accuracy: 50.3
Epoch: 2 | loss: 0.79, accuracy: 55.3
Epoch: 3 | loss: 0.74, accuracy: 54.6
Epoch: 4 | loss: 0.74, accuracy: 53.7
Epoch: 5 | loss: 0.75, accuracy: 53.6
Epoch: 6 | loss: 0.76, accuracy: 53.7
Epoch: 7 | loss: 0.77, accuracy: 53.8
Epoch: 8 | loss:... | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Evaluation | import json
import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_fscore_support
def get_performance(y_true, y_pred, classes):
"""Per-class performance metrics."""
# Performance
performance = {"overall": {}, "class": {}}
# Overall performance
metrics = precision_recall_fscore... | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Activation functions Using the generalized linear method (logistic regression) yielded poor results because of the non-linearity present in our data yet our activation functions were linear. We need to use an activation function that can allow our model to learn and map the non-linearity in our data. There are many di... | # Fig size
plt.figure(figsize=(12,3))
# Data
x = torch.arange(-5., 5., 0.1)
# Sigmoid activation (constrain a value between 0 and 1.)
plt.subplot(1, 3, 1)
plt.title("Sigmoid activation")
y = torch.sigmoid(x)
plt.plot(x.numpy(), y.numpy())
# Tanh activation (constrain a value between -1 and 1.)
plt.subplot(1, 3, 2)
y... | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
The ReLU activation function ($max(0,z)$) is by far the most widely used activation function for neural networks. But as you can see, each activation function has its own constraints so there are circumstances where you'll want to use different ones. For example, if we need to constrain our outputs between 0 and 1, the... | # Initialize first layer's weights
W1 = 0.01 * np.random.randn(INPUT_DIM, HIDDEN_DIM)
b1 = np.zeros((1, HIDDEN_DIM))
print (f"W1: {W1.shape}")
print (f"b1: {b1.shape}") | W1: (2, 100)
b1: (1, 100)
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Model 2. Feed inputs $X$ into the model to do the forward pass and receive the probabilities. First we pass the inputs into the first layer. * $z_1 = XW_1$ | # z1 = [NX2] · [2X100] + [1X100] = [NX100]
z1 = np.dot(X_train, W1) + b1
print (f"z1: {z1.shape}") | z1: (1050, 100)
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Next we apply the non-linear activation function, ReLU ($max(0,z)$) in this case. * $a_1 = f(z_1)$ | # Apply activation function
a1 = np.maximum(0, z1) # ReLU
print (f"a_1: {a1.shape}") | a_1: (1050, 100)
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
We pass the activations to the second layer to get our logits. * $z_2 = a_1W_2$ | # Initialize second layer's weights
W2 = 0.01 * np.random.randn(HIDDEN_DIM, NUM_CLASSES)
b2 = np.zeros((1, NUM_CLASSES))
print (f"W2: {W2.shape}")
print (f"b2: {b2.shape}")
# z2 = logits = [NX100] · [100X3] + [1X3] = [NX3]
logits = np.dot(a1, W2) + b2
print (f"logits: {logits.shape}")
print (f"sample: {logits[0]}") | logits: (1050, 3)
sample: [-0.00010001 0.00418463 -0.00067274]
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
We'll apply the softmax function to normalize the logits and btain class probabilities. * $\hat{y} = softmax(z_2)$ | # Normalization via softmax to obtain class probabilities
exp_logits = np.exp(logits)
y_hat = exp_logits / np.sum(exp_logits, axis=1, keepdims=True)
print (f"y_hat: {y_hat.shape}")
print (f"sample: {y_hat[0]}") | y_hat: (1050, 3)
sample: [0.33292037 0.33434987 0.33272975]
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Loss 3. Compare the predictions $\hat{y}$ (ex. [0.3, 0.3, 0.4]) with the actual target values $y$ (ex. class 2 would look like [0, 0, 1]) with the objective (cost) function to determine loss $J$. A common objective function for classification tasks is cross-entropy loss. * $J(\theta) = - \sum_i ln(\hat{y_i}) = - \s... | # Loss
correct_class_logprobs = -np.log(y_hat[range(len(y_hat)), y_train])
loss = np.sum(correct_class_logprobs) / len(y_train) | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Gradients 4. Calculate the gradient of loss $J(\theta)$ w.r.t to the model weights. The gradient of the loss w.r.t to $W_2$ is the same as the gradients from logistic regression since $\hat{y} = softmax(z_2)$. * $\frac{\partial{J}}{\partial{W_{2j}}} = \frac{\partial{J}}{\partial{\hat{y}}}\frac{\partial{\hat{y}}}{\par... | # dJ/dW2
dscores = y_hat
dscores[range(len(y_hat)), y_train] -= 1
dscores /= len(y_train)
dW2 = np.dot(a1.T, dscores)
db2 = np.sum(dscores, axis=0, keepdims=True)
# dJ/dW1
dhidden = np.dot(dscores, W2.T)
dhidden[a1 <= 0] = 0 # ReLu backprop
dW1 = np.dot(X_train.T, dhidden)
db1 = np.sum(dhidden, axis=0, keepdims=True) | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Update weights 5. Update the weights $W$ using a small learning rate $\alpha$. The updates will penalize the probability for the incorrect classes ($j$) and encourage a higher probability for the correct class ($y$). * $W_i = W_i - \alpha\frac{\partial{J}}{\partial{W_i}}$ | # Update weights
W1 += -LEARNING_RATE * dW1
b1 += -LEARNING_RATE * db1
W2 += -LEARNING_RATE * dW2
b2 += -LEARNING_RATE * db2 | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Training 6. Repeat steps 2 - 4 until model performs well. | # Convert tensors to NumPy arrays
X_train = X_train.numpy()
y_train = y_train.numpy()
X_val = X_val.numpy()
y_val = y_val.numpy()
X_test = X_test.numpy()
y_test = y_test.numpy()
# Initialize random weights
W1 = 0.01 * np.random.randn(INPUT_DIM, HIDDEN_DIM)
b1 = np.zeros((1, HIDDEN_DIM))
W2 = 0.01 * np.random.randn(HIDD... | Epoch: 0, loss: 1.099, accuracy: 0.349
Epoch: 100, loss: 0.545, accuracy: 0.687
Epoch: 200, loss: 0.247, accuracy: 0.903
Epoch: 300, loss: 0.142, accuracy: 0.949
Epoch: 400, loss: 0.099, accuracy: 0.974
Epoch: 500, loss: 0.076, accuracy: 0.986
Epoch: 600, loss: 0.062, accuracy: 0.990
Epoch: 700, loss: 0.052, accuracy: ... | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Evaluation | class MLPFromScratch():
def predict(self, x):
z1 = np.dot(x, W1) + b1
a1 = np.maximum(0, z1)
logits = np.dot(a1, W2) + b2
exp_logits = np.exp(logits)
y_hat = exp_logits / np.sum(exp_logits, axis=1, keepdims=True)
return y_hat
# Evaluation
model = MLPFromScratch()
y_pr... | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
PyTorch Model We'll be using two linear layers along with PyTorch [Functional](https://pytorch.org/docs/stable/nn.functional.html) API's [ReLU](https://pytorch.org/docs/stable/nn.functional.htmltorch.nn.functional.relu) operation. | class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, num_classes):
super(MLP, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, num_classes)
def forward(self, x_in, apply_softmax=False):
z = F.relu(self.fc1(x_in)) # ... | <bound method Module.named_parameters of MLP(
(fc1): Linear(in_features=2, out_features=100, bias=True)
(fc2): Linear(in_features=100, out_features=3, bias=True)
)>
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Training | # Define Loss
class_weights_tensor = torch.Tensor(list(class_weights.values()))
loss_fn = nn.CrossEntropyLoss(weight=class_weights_tensor)
# Accuracy
def accuracy_fn(y_pred, y_true):
n_correct = torch.eq(y_pred, y_true).sum().item()
accuracy = (n_correct / len(y_pred)) * 100
return accuracy
# Optimizer
opti... | Epoch: 0 | loss: 1.11, accuracy: 24.3
Epoch: 10 | loss: 0.67, accuracy: 55.4
Epoch: 20 | loss: 0.51, accuracy: 70.6
Epoch: 30 | loss: 0.39, accuracy: 88.5
Epoch: 40 | loss: 0.29, accuracy: 90.3
Epoch: 50 | loss: 0.22, accuracy: 93.4
Epoch: 60 | loss: 0.18, accuracy: 94.7
Epoch: 70 | loss: 0.15, accuracy: 95.9
Epoch: 80... | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Evaluation | # Predictions
y_prob = model(X_test, apply_softmax=True)
y_pred = y_prob.max(dim=1)[1]
# Performance report
performance = get_performance(y_true=y_test, y_pred=y_pred, classes=classes)
print (json.dumps(performance, indent=2))
# Visualize the decision boundary
plt.figure(figsize=(12,5))
plt.subplot(1, 2, 1)
plt.title("... | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Inference | # Inputs for inference
X_infer = pd.DataFrame([{'X1': 0.1, 'X2': 0.1}])
X_infer.head()
# Standardize
X_infer = X_scaler.transform(X_infer)
print (X_infer)
# Predict
y_infer = model(torch.Tensor(X_infer), apply_softmax=True)
prob, _class = y_infer.max(dim=1)
label = label_encoder.inverse_transform(_class.detach().numpy(... | The probability that you have c1 is 92%
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Initializing weights So far we have been initializing weights with small random values and this isn't optimal for convergence during training. The objective is to have weights that are able to produce outputs that follow a similar distribution across all neurons. We can do this by enforcing weights to have unit varian... | from torch.nn import init
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, num_classes):
super(MLP, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, num_classes)
def init_weights(self):
init.xavier_normal(self.fc1.weigh... | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Dropout A great technique to have our models generalize (perform well on test data) is to increase the size of your data but this isn't always an option. Fortuntely, there are methods like regularization and dropout that can help create a more robust model. Dropout is a technique (used only during training) that allow... | DROPOUT_P = 0.1 # % of the neurons that are dropped each pass
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, dropout_p, num_classes):
super(MLP, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.dropout = nn.Dropout(dropout_p) # dropout
self.fc2 = nn.... | <bound method Module.named_parameters of MLP(
(fc1): Linear(in_features=2, out_features=100, bias=True)
(dropout): Dropout(p=0.1, inplace=False)
(fc2): Linear(in_features=100, out_features=3, bias=True)
)>
| MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
Overfitting Though neural networks are great at capturing non-linear relationships they are highly susceptible to overfitting to the training data and failing to generalize on test data. Just take a look at the example below where we generate completely random data and are able to fit a model with [$2*N*C + D$](https:... | NUM_EPOCHS = 500
NUM_SAMPLES_PER_CLASS = 50
LEARNING_RATE = 1e-1
HIDDEN_DIM = 2 * NUM_SAMPLES_PER_CLASS * NUM_CLASSES + INPUT_DIM # 2*N*C + D
# Generate random data
X = np.random.rand(NUM_SAMPLES_PER_CLASS * NUM_CLASSES, INPUT_DIM)
y = np.array([[i]*NUM_SAMPLES_PER_CLASS for i in range(NUM_CLASSES)]).reshape(-1)
print ... | _____no_output_____ | MIT | notebooks/08_Neural_Networks.ipynb | Zanah-Tech/MadeWithML |
AWS. S3 Buckets> 'Working with AWS S3 buckets'- toc:true- branch: master- badges: false- comments: false- author: Alexandros Giavaras- categories: [aws, s3-buckets, cloud-computing, data-storage, data-engineering, data-storage, boto3] Overview In this notebook, we are going to have a brief view on AWS S3 storage. Con... | import logging
import boto3
from botocore.exceptions import ClientError | _____no_output_____ | Apache-2.0 | _notebooks/2021-11-11-aws-s3-buckets.ipynb | pockerman/qubit_opus |
Create S3 Bucket | # credentials to be used
AWS_ACCESS_KEY_ID = 'Use your own credentials'
AWS_SECRET_ACCESS_KEY = 'Use your own credentials'
# create a client for the resource we will use
s3_client = boto3.client('s3', region_name='us-west-2',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret... | _____no_output_____ | Apache-2.0 | _notebooks/2021-11-11-aws-s3-buckets.ipynb | pockerman/qubit_opus |
The response of the function all above is shown below: ```{'ResponseMetadata': {'RequestId': '355VX5QNYSQBTSCM', 'HostId': '7jXN853VP175Fw/il1Zvx8UXkfRsdQRXH3VrAFOcCYZl4y2ZTF6zNPp6tXvwnpBGlmAKTCP9RFA=', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': '7jXN853VP175Fw/il1Zvx8UXkfRsdQRXH3VrAFOcCYZl4y2ZTF6zNPp6tXvw... | result = 3_client.get_bucket_policy(Bucket='bucket-name') | _____no_output_____ | Apache-2.0 | _notebooks/2021-11-11-aws-s3-buckets.ipynb | pockerman/qubit_opus |
The call above fails because by default there are no policies set. A bucket's policy can be set by calling the ```put_bucket_policy``` method. Moreover, a policy is defined in the same JSON format as an IAM policy. The **Sid (statement ID)** is an optional identifier that you provide for the policy statement. You can... | response = s3_client.get_bucket_cors(Bucket=bucket_name)
print(response['CORSRules'])
cors_configuration = {
'CORSRules':[{'AllowHeaders':['Authorization'],
'AllowedMethods':['GET', 'PUT'],
'AllowedOrigins':['*'],
'ExposeHeaders':['GET', 'PUT'],
'MaxA... | _____no_output_____ | Apache-2.0 | _notebooks/2021-11-11-aws-s3-buckets.ipynb | pockerman/qubit_opus |
Demo Axes GridGrid of 2x2 images with single or own colorbar. | import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
plt.rcParams["mpl_toolkits.legacy_colorbar"] = False
def get_demo_image():
import numpy as np
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(... | _____no_output_____ | MIT | matplotlib/gallery_jupyter/axes_grid1/demo_axes_grid.ipynb | kingreatwill/penter |
Importo librerie | import pandas as pd
import numpy as np
import concurrent.futures
import time
from requests.exceptions import ReadTimeout
!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials | _____no_output_____ | MIT | dataset_integration_3.ipynb | isacco-v/hit-song-prediction |
Autenticazione Spotify API | !pip uninstall spotipy
!pip install spotipy
# autenticazione Spotify API con spotipy
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
auth_manager = SpotifyClientCredentials(client_id='caf57b996b464996bff50ab59186f265', client_secret='0bfcdbff8015426cae855b56b692f69b')
sp = spotipy.Spotify(auth_manage... | _____no_output_____ | MIT | dataset_integration_3.ipynb | isacco-v/hit-song-prediction |
Importo dataset | # autenticazione google drive
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# importo quarta parte del dataset --> 7087 datapoints
drive.CreateFile({'id':'1YAAvPUaPeBIddkuVzWgw7fhPPcT2uJTY'}).GetContentFile('billboard_dataset_un... | _____no_output_____ | MIT | dataset_integration_3.ipynb | isacco-v/hit-song-prediction |
Definizione funzioni | def print_exec_time(start):
print("Esecuzione completata in %.4f secondi" % (time.perf_counter()-start))
# funzione che effettua ricerca con Spotify API considerando i casi in cui nel campo 'artist' siano presenti più artisti (featuring)
def search_fix(artist, title):
artist_separators = ['%%%', ' Featuring', ' fe... | _____no_output_____ | MIT | dataset_integration_3.ipynb | isacco-v/hit-song-prediction |
Integrazione dataset Recupero gli id del Billboard dataset | time_0 = time.perf_counter()
with concurrent.futures.ProcessPoolExecutor() as executor:
results = executor.map(get_id, df_billboard.values.tolist())
output = []
for result in results:
output.append(result)
print_exec_time(time_0)
# creo backup del billboard dataset
df_billboard_bak = df_billboard.copy()
... | Mounted at /content/drive
| MIT | dataset_integration_3.ipynb | isacco-v/hit-song-prediction |
Recupero audio features del Billboard dataset | # reimporto dataset billboard (con ids) + dataset principale
"""
drive.CreateFile({'id':'1fZzuYu-HXKP9HUeio-FL9P4eNygOQ0qq'}).GetContentFile('billboard+ids_0.csv')
df_billboard = pd.read_csv("billboard+ids_0.csv").drop('Unnamed: 0',axis=1)
drive.CreateFile({'id':'1eOqgPk_izGXKIT5y6KfqPkmKWqBonVc0'}).GetContentFile('d... | fetching features for id: 3PyQV3cDjV5tEJGpYYH2K1
fetching features for id: 7qHGRefOGiaPqrG4IEckcv
fetching features for id: 1PSfY3lSwBD888PZW0s5JH
fetching features for id: 1er2tyXb4iw23SfZxb1FW1
fetching features for id: 6C9MYPkHrESo8n3KnapaR9
fetching features for id: 2kLrFBgVs9BsyNQ6EDc5LH
fetching features for id: ... | MIT | dataset_integration_3.ipynb | isacco-v/hit-song-prediction |
Inserisco audio features nel dataset Billboard | num_datapoints = np.array(output).shape[0]
output = np.array(output).reshape((num_datapoints,14))
# creo backup df_billboard
df_billboard_bak = df_billboard.copy()
# filtro dataset billboard tenendo solo id nell'array 'ids_new', quindi quelli che non sono presenti nel dataset principale
df_billboard = df_billboard[df... | _____no_output_____ | MIT | dataset_integration_3.ipynb | isacco-v/hit-song-prediction |
Esporto | # esporto in google drive
from google.colab import drive
# mounts the google drive to Colab Notebook
drive.mount('/content/drive',force_remount=True)
df_billboard.to_csv('/content/drive/My Drive/Colab Notebooks/datasets/billboard+features_3.csv') | Mounted at /content/drive
| MIT | dataset_integration_3.ipynb | isacco-v/hit-song-prediction |
Notebook use to check the result of the classifier, how well can you detect the nucleus .You can click `shift` + `enter` to run one cell, you can also click run in top menu.To run all the cells, you can click `kernel` and `Restart and run all` in the top menu. | # Some more magic so that the notebook will reload external python modules;
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
%reload_ext autoreload
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = 8,8
plt.rcParams['im... | _____no_output_____ | MIT | notebook/Sliding_Window_Chloe.ipynb | Chloe-Girard/Foci_counting |
The following path should direct to the folder "utils", on Window env it should have slash " / " and not backslash " \ " . | # Create a temporary python PATH to the module that we are using for the analysis
import sys
sys.path.insert(0, "/Users/Espenel/Desktop/Mini-Grant-Image-analysis/2018/Chloe/ChromosomeDetectionChloe/utils")
from chromosome_dsb import * | _____no_output_____ | MIT | notebook/Sliding_Window_Chloe.ipynb | Chloe-Girard/Foci_counting |
Loading a typical image using bioformats | javabridge.start_vm(class_path=bioformats.JARS) | _____no_output_____ | MIT | notebook/Sliding_Window_Chloe.ipynb | Chloe-Girard/Foci_counting |
In the path variable you should enter the path to your image of interest: | path = '/Users/Espenel/Desktop/Mini-Grant-Image-analysis/2018/Chloe/data_chloe/cku-exo1_002/2017-04-12_RAD51-HTP3_cku80-exo1_002_visit_13_D3D_ALX.dv' | _____no_output_____ | MIT | notebook/Sliding_Window_Chloe.ipynb | Chloe-Girard/Foci_counting |
in the following cell in "channel" enter the the channel (starting from 0) where you will find the nucleus | img = load_data.load_bioformats(path, channel = 3, no_meta_direct = True)
img.shape
#view(visualization.convert_view(img)) | _____no_output_____ | MIT | notebook/Sliding_Window_Chloe.ipynb | Chloe-Girard/Foci_counting |
Sliding Window First need to load the classifier (clf) and scaler. | clf = joblib.load("/Users/Espenel/Desktop/Mini-Grant-Image-analysis/2018/Chloe/clf_scaler/clf")
scaler = joblib.load("/Users/Espenel/Desktop/Mini-Grant-Image-analysis/2018/Chloe/clf_scaler/scaler")
import time
tp1 = time.time()
result = search.rolling_window(img, clf, scaler)
tp2 = time.time()
print("It took {}sec to f... | _____no_output_____ | MIT | notebook/Sliding_Window_Chloe.ipynb | Chloe-Girard/Foci_counting |
Optionally you can create a Heat map with the probability at every pixel that there is a nucleus | #heat_map = visualization.heatmap(result)
#view(visualization.convert_view(heat_map)) | _____no_output_____ | MIT | notebook/Sliding_Window_Chloe.ipynb | Chloe-Girard/Foci_counting |
Max projection and check how the result looks like | proj = np.amax(img, axis=0) | _____no_output_____ | MIT | notebook/Sliding_Window_Chloe.ipynb | Chloe-Girard/Foci_counting |
When boxes are overlapping, only keep the highest probability one.Here you can adjust `probaThresh` and `overlaThresh`, if you find better parameters, you can change them in the function `batch.batch` in the `chromosome_dsb` folder. | box = search.non_max_suppression(result, probaThresh=0.8, overlapThresh=0.3)
import matplotlib.patches as patches
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.imshow(proj, vmax = 100000)
for rec in box:
rect = patches.Rectangle((rec[0],rec[1]),70,70,linewidth=3,edgecolor='y',facecolor='none')
# Add the pa... | _____no_output_____ | MIT | notebook/Sliding_Window_Chloe.ipynb | Chloe-Girard/Foci_counting |
Save the result | #path = "/Users/Espenel/Desktop/Mini-Grant-Image-analysis/2018/Chloe/13/"
#load_data.save_file(path, "bbox_3D", box, model=False)
#load_data.save_file(path, "bbox_3D", binary, model=False) | _____no_output_____ | MIT | notebook/Sliding_Window_Chloe.ipynb | Chloe-Girard/Foci_counting |
Generator States Let's look at a simple generator function: | def gen(s):
for c in s:
yield c | _____no_output_____ | Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
We create an generator object by calling the generator function: | g = gen('abc') | _____no_output_____ | Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.