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
Don't forget the validation set!And note that you can use the check_accuracy function to evaluate on either the test set or the validation set, by passing either **loader_test** or **loader_val** as the second argument to check_accuracy. You should not touch the test set until you have finished your architecture and h...
import time import hyperopt.pyll from hyperopt import fmin, tpe, hp, STATUS_OK, Trials from hyperopt.pyll import scope @scope.define_pure def L1_shift(a): return [a + 5] @scope.define_pure def L2_shift(a): return [a + 5] @scope.define_pure def L2_L3_shift(a, b): return [a + 5, b + 5] @scope.define_pure ...
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
Base ModelAfter 20 rounds of hyperparameters optimization we were able to get a 60% validation accuracy. parameters_zero = {'L1': [6], 'S': [3], 'W1': [651], 'loss': 0.6},
# Train your model here, and make sure the output of this cell is the accuracy of your best model on the # train, val, and test sets. Here's some code to get you started. The output of this cell should be the training # and validation accuracy on your best model (measured by validation accuracy). def model_zero(L1, W...
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
[conv-relu-pool]xN -> [affine]xM -> [softmax or SVM]66.5% validation accuracy with: {'L1': [16], 'L2': [8], 'W1': [464], 'W2': [], 'loss': 0.665}
def model_one(conv_relu_pool_depths, affine_depths, C = 10): from functools import reduce from collections import OrderedDict Conv2d_K = 3 Conv2d_S = 1 MaxPool2d_K = 2 MaxPool2d_S = 2 # 15, 4500; 6, 720 conv_relu_pool_sizes = [ lambda N: out_dim(N, Conv2d_K, 0, Conv2d_S), ...
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
[batchnorm-relu-conv]xN -> [affine]xM -> [softmax or SVM]64.9% validation accuracy with: {'L1': [20], 'L2': [21], 'L2_1': [], 'L3_1': [], 'W1': [487], 'W2': [], 'loss': 0.649}
def model_three(batchnorm_conv_relu_depths, affine_depths, C = 10): from functools import reduce from collections import OrderedDict Conv2d_K = 3 Conv2d_S = 1 batchnorm_conv_relu_sizes = [ lambda N: out_dim(N, Conv2d_K, 0, Conv2d_S) ] * len(batchnorm_conv_relu_depths) n_to_Flat...
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
Describe what you did In the cell below you should write an explanation of what you did, any additional features that you implemented, and any visualizations or graphs that you make in the process of training and evaluating your network. DNN with architectures 0, 1 and 3 were implemented and trained on data. Hyperpara...
best_model = None check_accuracy(best_model, loader_test)
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
Introduction to Python
#Python Indention if 5>2: print("five is greater than two!") x = 1 # This is a single variable with single value x,y = 1,2 # these are two variables with two different values x,y,z= 1,2,3 print(x) print(y) print(z) x,y="four",2 x y x
_____no_output_____
Apache-2.0
Demo1.ipynb
RoyMillamis/Roy-Millamis-BSCpE-1-2
Casting
b = int(4) b c= float(4) c
_____no_output_____
Apache-2.0
Demo1.ipynb
RoyMillamis/Roy-Millamis-BSCpE-1-2
Type Function
x=5 y= "John" # This is a type of string h= "ana" H='Ana' print(type(x)) print(type(y)) print(h) print(H)
<class 'int'> <class 'str'> ana Ana
Apache-2.0
Demo1.ipynb
RoyMillamis/Roy-Millamis-BSCpE-1-2
One Value to Multiple Variables
x = y = z = 'four' print(x) print(y) print(z) x = "enjoying" print("Python Programming is" " " + x) x = 11 y = 12 z = 13 print(x+y+z) x+=3 #This is the same as x = +3 print(x) y+=5 print(y) x<y and x!=x # pag isang lang yung true false na x>y or not y==z # kahit isa lang yung true, true paden not(print(x>y)) #Identity ...
False True
Apache-2.0
Demo1.ipynb
RoyMillamis/Roy-Millamis-BSCpE-1-2
Programación lineal> La programación lineal es el campo de la optimización matemática dedicado a maximizar o minimizar (optimizar) funciones lineales, denominada función objetivo, de tal forma que las variables de dicha función estén sujetas a una serie de restricciones expresadas mediante un sistema de ecuaciones o i...
import matplotlib.pyplot as plt %matplotlib inline import numpy as np def res1(x1): return (2400-50*x1)/24 def res2(x1): return (2100-30*x1)/33 x1 = np.linspace(40, 50) r1 = res1(x1) r2 = res2(x1) plt.figure(figsize = (8,6)) plt.plot(x1, res1(x1), 'b--', label = 'res1') plt.plot(x1, res2(x1), 'r--', label = 're...
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
**Actividad.** Mónica hace aretes y cadenitas de joyería. Es tan buena, que todo lo que hace lo vende.Le toma 30 minutos hacer un par de aretes y una hora hacer una cadenita, y como Mónica también es estudihambre, solo dispone de 10 horas a la semana para hacer las joyas. Por otra parte, el material que compra solo le ...
# Importar el módulo optimize de la librería scipy import scipy.optimize as opt
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
El módulo `optimize` que acabamos de importar contiene varias funciones para optimización y búsqueda de raices ($f(x)=0$). Entre ellas se encuentra la función `linprog`
# Función linprog del módulo optimize help(opt.linprog)
Help on function linprog in module scipy.optimize._linprog: linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None, method='simplex', callback=None, options=None) Minimize a linear objective function subject to linear equality and inequality constraints. Linear Programming is intended to s...
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
la cual resuelve problemas como los que aprendimos a plantear. 5.2 Solución del ejemplo básico con linprogYa hicimos la solución gráfica. Contrastemos con la solución que nos da `linprog`...
# Importar numpy para crear las matrices import numpy as np # Crear las matrices para resolver el problema c = np.array([-1, -1]) A = np.array([[50, 24], [30, 33], [-1, 0], [0, -1]]) b = np.array([2400, 2100, -45, -5]) b # Resolver utilizando linprog resultado = opt.linprog(c, ...
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
**Conclusión**- Para maximizar el inventario conjunto de cantidad de productos X1 y X2, se deben producir 45 unidades de X1 y 6.25 unidades de X2.- Con esa producción, el inventario conjunto al finalizar la semana es de 1.25 unidades. **Otra forma:** poner las cotas de las variables a parte
# Escribir matrices y cotas c = np.array([-1, -1]) A = np.array([[50, 24], [30, 33]]) b = np.array([2400, 2100]) x1_bound = (45, None) x2_bound = (5, None) # Resolver resultado2 = opt.linprog(c, A_ub=A, b_ub=b, bounds=(x1_bound,x2_bound)) # Mostrar el resultado resultado2
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
**Actividad.** Resolver el ejemplo de Mónica y sus tiliches con `linprog`
# Resolver acá c = np.array([-15, -20]) A = np.array([[1, 2], [1, 1]]) b = np.array([20, 15]) resultado_monica = opt.linprog(c, A_ub=A, b_ub=b) resultado_monica
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
6. Problema de transporte 1- **Referencia**: https://es.wikipedia.org/wiki/Programaci%C3%B3n_linealEste es un caso curioso, con solo 6 variables (un caso real de problema de transporte puede tener fácilmente más de 1.000 variables) en el cual se aprecia la utilidad de este procedimiento de cálculo.Existen tres minas d...
# Matrices y cotas c = np.array([2, 11, 12, 24, 13, 18]) A = np.array([[1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1], [-1, 0, -1, 0, -1, 0], [0, -1, 0, -1, 0, -1]]) b = np.array([40, 40, 20, -40, -60]) # Resolver resultado_transporte = opt.linprog(c, ...
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
**Conclusión**- La estrategia de menor costo es llevar 40 toneladas de la mina "a" a la central "e", 40 toneladas de la mina "b" a la central "d" y 20 toneladas de la mina "c" a la central "e". El costo total de esta estrategia de transporte es 1280 monedas. 7. Optimización de inversión en bonos**Referencia:**
from IPython.display import YouTubeVideo YouTubeVideo('gukxBus8lOs')
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
El objetivo de este problema es determinar la mejor estrategia de inversión, dados diferentes tipos de bono, la máxima cantidad que puede ser invertida en cada bono, el porcentaje de retorno y los años de madurez. También hay una cantidad fija de dinero disponible ($\$750,000$). Por lo menos la mitad de este dinero deb...
# Matrices y cotas # Resolver # Mostrar resultado
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
Recordar que en el problema minimizamos $-\sum^{6}_{i=1} A_iR_i$. El rendimiento obtenido es entonces: **Conclusión**- 8. Tarea 1. Diseño de la Dieta ÓptimaSe quiere producir comida para gatos de la manera más barata, no obstante se debe también asegurar que se cumplan los datos requeridos de analisis nutricional. P...
import pandas as pd info = pd.DataFrame({'Bar1': [2, 3], 'Bar2': [4, 1], 'Bar3': [5, 3], 'Bar4': [2, 2], 'Bar5': [1, 3]}, index = ['CerveceriaA', 'CerveceriaB']) info
_____no_output_____
MIT
Modulo1/.ipynb_checkpoints/Clase5_ProgramacionLineal-checkpoint.ipynb
danielabenavides/SimMat2018-2
NYSE & BlurrIn this guide we will train a machine learning model that predicts closing price of a stock based on historical data. We will transform time-series stock data into features to train this model. PrerequisitesIt's recommended to have a basic understanding of how Blurr works. Following [tutorials 1](http://p...
import sys print("installing blurr and other required dependencies...") !{sys.executable} -m pip install blurr --quiet !{sys.executable} -m pip install -r requirements.txt --quiet print("done.")
installing blurr and other required dependencies... done.
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
The DatasetThis walkthrough is based on [New York Stock Exchange Data](https://www.kaggle.com/dgawlik/nyse/data) made available for [Kaggle challenges](https://www.kaggle.com/dgawlik/nyse).Let's start by downloading and having a peek at the available data:
!wget http://demo.productml.com/data/nyse-input-data.json.zip !unzip -o nyse-input-data.json.zip -d . import pandas as pd stocks = pd.read_json("./nyse-input-data.json", lines=True) stocks.head()
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
This dataset contains data for each market day.Our **goal is to predict closing price** of a stock for any given day based on historical data. In order to do that, we need to transform our original data source into **features** that can be used for training.We'll calculate **moving averages** and other aggregate data f...
!cat 'nyse-streaming-bts.yml'
Type: Blurr:Transform:Streaming Version: '2018-03-01' Description: New York Store Exchange Transformations Name: nyse Import: - { Module: dateutil.parser, Identifiers: [ parse ]} Identity: source.symbol Time: parse(source.datetime) Stores: - Type: Blurr:Store:Memory Name: memory Aggregates:...
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
**Streaming BTS**We're predicting values for tech companies only (Apple, Facebook, Microsoft, Google):```yamlWhen: source.symbol in ['AAPL', 'MSFT', 'GOOG', 'FB']```Each record in the original dataset represents a single stock transaction. By setting `Split: str(time.date()) != stats.date` we'll create a new aggregate ...
!cat 'nyse-window-bts.yml'
Type: Blurr:Transform:Window Version: '2018-03-01' Name: moving_averages SourceBTS: nyse Anchor: Condition: nyse.stats.volatility < 0.04 Aggregates: - Type: Blurr:Aggregate:Window Name: close WindowType: count WindowValue: 1 Source: nyse.stats Fields: - Name: value ...
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
**Window BTS**We'll use a very rough criteria to remove outliers: our model will only work when closing price changes less than a 4%:```yamlAnchor: Condition: nyse.stats.volatility < 0.04```We're using [moving averages](https://www.investopedia.com/terms/m/movingaverage.asp) to generate features based on historical da...
from blurr_util import print_head, validate, transform validate('nyse-streaming-bts.yml') validate('nyse-window-bts.yml')
Running syntax validation on nyse-streaming-bts.yml Document is valid Running syntax validation on nyse-window-bts.yml Document is valid
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Let's run our Streaming BTS for informational purposes only, so we can preview the result of the transformation:
transform(log_files=["./nyse-input-data.json"], stream_bts='./nyse-streaming-bts.yml', output_file="./nyse-streaming-bts-out.log") print_head("./nyse-streaming-bts-out.log") transform(log_files=["./nyse-input-data.json"], stream_bts='./nyse-streaming-bts.yml', window_bts='./nyse-...
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Let's now preview the data that will be used to **train our model**
window_out = pd.read_csv("./nyse-processed-data.csv") window_out.head()
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Modelling**Blurr** is about Data Preparation and Feature Engineering. Modeling is included here for illustration purpose, and the reader can use any modeling library or tool for such purpose.Let's start by importing the output of our Window BTS as the source dataset. We're dropping unnecessary `_identity` columns:
import numpy as np import matplotlib.pyplot as plt import pandas as pd def import_dataset(): data = pd.read_csv("./nyse-processed-data.csv") data["close"] = data["close.value"] # Moving close to the last column data.drop(['close.value'], 1, inplace=True) data.drop(['close._identity'], 1, inplace=True)...
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Each column represents a Feature, except the rightmost column which represents the Output we're trying to predic
feature_count = len(dataset.columns) - 1 print("#features=" + str(feature_count))
#features=13
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
We're splitting our dataset into Input Variables (`X`) and the Output Variable (`Y`) using pandas' [`iloc` function](http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.iloc.html):
X = dataset.iloc[:, 0:feature_count].values print(X.shape) Y = dataset.iloc[:, feature_count].values print(Y.shape)
(5978,)
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
We need to split between train and test datasets for training and evaluation of the model:
from sklearn.model_selection import train_test_split X_train_raw, X_test_raw, Y_train_raw, Y_test_raw = train_test_split(X, Y, test_size = 0.2)
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Finally, we need to scale our data before training:
from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() X_train = scaler.fit_transform(X_train_raw) X_test = scaler.transform(X_test_raw) Y_train = scaler.fit_transform(Y_train_raw.reshape(-1, 1)) Y_test = scaler.transform(Y_test_raw.reshape(-1, 1))
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
It's now time to build and train our model:
# Importing the Keras libraries and packages import keras from keras.models import Sequential from keras.layers import Dense #Initializing Neural Network model = Sequential() model.add(Dense(units = 36, kernel_initializer = 'uniform', activation = 'relu', input_dim = feature_count)) model.add(Dense(units = 36, kernel...
Train on 4303 samples, validate on 479 samples Epoch 1/70 4303/4303 [==============================] - 0s 46us/step - loss: 0.1025 - acc: 0.0000e+00 - val_loss: 0.0775 - val_acc: 0.0021 Epoch 2/70 4303/4303 [==============================] - 0s 4us/step - loss: 0.0942 - acc: 0.0000e+00 - val_loss: 0.0686 - val_acc: 0.0...
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
We can measure the quality of our model using [MSE](https://en.wikipedia.org/wiki/Mean_squared_error) and [RMSE](https://en.wikipedia.org/wiki/Root-mean-square_deviation):
import math score = model.evaluate(X_test, Y_test, verbose=0) print('Model Score: %.5f MSE (%.2f RMSE)' % (score[0], math.sqrt(score[0])))
Model Score: 0.00004 MSE (0.01 RMSE)
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Finally, let's plot prediction vs actual data.Prior to normalisation, we undo scaling and perform a sort for graph quality:
import matplotlib.pyplot as plt2 prediction_sorted = scaler.inverse_transform(model.predict(X_test)) prediction_sorted.sort(axis=0) Y_test_sorted = scaler.inverse_transform(Y_test.copy().reshape(-1, 1)) Y_test_sorted.sort(axis=0) plt2.plot(prediction_sorted, color='red', label='Prediction') plt2.plot(Y_test_sorted, ...
_____no_output_____
Apache-2.0
docs/examples/nyse/nyse.ipynb
ddrightnow/blurr
Xarray-spatial User Guide: Surface tools-----With the Surface tools, you can quantify and visualize a terrain landform represented by a digital elevation model.Starting with a raster elevation surface, represented as an Xarray DataArray, these tools can help you identify some specific patterns that may not be readily ...
import numpy as np import pandas as pd import xarray as xr import datashader as ds from datashader.transfer_functions import shade from datashader.transfer_functions import stack from datashader.transfer_functions import dynspread from datashader.transfer_functions import set_background from datashader.colors import ...
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Generate Terrain DataThe rest of the geo-related functions focus on raster data, i.e. data that's been aggregated into the row-column grid of cells in a raster image. Datashader's Canvas object provides a convenient frame to set up a new raster, so we'll use that with our `generate_terrain` function to generate some f...
from xrspatial import generate_terrain W = 800 H = 600 terrain = xr.DataArray(np.zeros((H, W))) terrain = generate_terrain(terrain) shade(terrain, cmap=['black', 'white'], how='linear')
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
The grayscale values in the image above show elevation, scaled linearly in black-to-white color intensity (with the large black areas indicating low elevation). This shows the data, but it would look more like a landscape if we map the lowest values to colors representing water, and the highest to colors representing m...
shade(terrain, cmap=Elevation, how='linear')
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Hillshade[Hillshade](https://en.wikipedia.org/wiki/Terrain_cartography) is a technique used to visualize terrain as shaded relief by illuminating it with a hypothetical light source. The illumination value for each cell is determined by its orientation to the light source, which can be calculated from slope and aspect...
from xrspatial import hillshade illuminated = hillshade(terrain) hillshade_gray_white = shade(illuminated, cmap=['gray', 'white'], alpha=255, how='linear') hillshade_gray_white
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Applying hillshade reveals a lot of detail in the 3D shape of the terrain.To add even more detail, we can add the Elevation colormapped terrain from earlier and combine it with the hillshade terrain using datashader's stack function.
terrain_elevation = shade(terrain, cmap=Elevation, alpha=128, how='linear') stack(hillshade_gray_white, terrain_elevation)
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Slope[Slope](https://en.wikipedia.org/wiki/Slope) is the inclination of a surface. In geography, *slope* is the amount of change in elevation for an area in a terrain relative to its surroundings.Xarray-spatial's slope function returns the slope at each cell in degrees.Because Xarray-spatial is integrated with Xarray ...
from xrspatial import slope risky = slope(terrain) risky.data = np.where(np.logical_and(risky.data > 25, risky.data < 50), 1, np.nan) stack(shade(terrain, cmap=['black', 'white'], how='linear'), shade(illuminated, cmap=['black', 'white'], how='linear', alpha=128), shade(risky, cmap='red', ...
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Curvature[Curvature](https://desktop.arcgis.com/en/arcmap/10.3/tools/spatial-analyst-toolbox/curvature.htm) is the second derivative of a surface's elevation, or the *slope-of-the-slope*; in other words, how fast the slope is increasing or decreasing as we move along a surface.- A positive curvature means the surface ...
from xrspatial import curvature terrain_z_one = xr.DataArray(np.zeros((H, W))) terrain_z_one = generate_terrain(terrain_z_one, zfactor=1) curv = curvature(terrain_z_one) curv_hi, curv_low = curv.copy(), curv.copy() curv_hi.data = np.where(np.logical_and(curv_hi.data > 1, curv_hi.data < 4), 1, np.nan) curv_low.data = n...
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Aspect[Aspect](https://en.wikipedia.org/wiki/Aspect_(geography)) is the orientation of a slope, measured clockwise in degrees from 0 to 360, where 0 is north-facing, 90 is east-facing, 180 is south-facing, and 270 is west-facing.The Xarray-spatial aspect function returns the aspect in degrees for each cell in an eleva...
from xrspatial import aspect north_faces = aspect(terrain) north_faces.data = np.where(np.logical_or(north_faces.data > 350 , north_faces.data < 10), 1, np.nan) stack(shade(terrain, cmap=['black', 'white'], how='linear'), shade(illuminated, cmap=['black', 'white'], ...
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
ViewshedThe `xrspatial.viewshed` function operates on a given aggregate to calculate the viewshed (the visible cells in the raster) for a given viewpoint, or *observer location*. The visibility model is as follows: Two cells are visible to each other if the line of sight that connects their centers is not blocked at ...
from xrspatial import viewshed OBSERVER_X = -12.5 OBSERVER_Y = 10 canvas = ds.Canvas(plot_width=W, plot_height=H, x_range=(-20, 20), y_range=(-20, 20)) normal_df = pd.DataFrame({ 'x': np.random.normal(.5, 1, 10000000), 'y': np.random.normal(.5, 1, 10000000) }) normal_agg = canvas.points(norm...
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Calculate viewshed using the observer locationNow we can apply viewshed to the normal_agg, with the observer_agg for the viewpoint. We can then visualize it and stack it with the hillshade and observer rasters.
# Will take some time to run... %time view = viewshed(normal_agg, x=OBSERVER_X, y=OBSERVER_Y) view_shaded = shade(view, cmap=['white', 'red'], alpha=128, how='linear') stack(normal_illuminated_shaded, observer_shaded, view_shaded)
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
As you can see, the image highlights in red all points visible from the observer location marked with the orange dot. As one might expect, the areas behind the normal distribution *mountain* are blocked from the viewer. Viewshed on TerrainNow we can try using viewshed on our more complicated terrain.- We'll set up our...
from xrspatial import viewshed x_range=(-20e6, 20e6) y_range=(-20e6, 20e6) terrain = xr.DataArray(np.zeros((H, W))) terrain = generate_terrain(terrain, x_range=x_range, y_range=y_range) terrain_shaded = shade(terrain, cmap=Elevation, alpha=128, how='linear') illuminated = hillshade(terrain) OBSERVER_X = 0.0 OBSERVER...
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Now we can apply viewshed.- Notice the use of the `observer_elev` argument, which is the height of the observer above the terrain.
%time view = viewshed(terrain, x=OBSERVER_X, y=OBSERVER_Y, observer_elev=100) view_shaded = shade(view, cmap='fuchsia', how='linear') stack(shade(illuminated, cmap=['black', 'white'], alpha=128, how='linear'), terrain_shaded, view_shaded, observer_shaded)
_____no_output_____
MIT
examples/user_guide/1_Surface.ipynb
kwinkunks/xarray-spatial
Logistic Regression with Python In this notebook, you will learn Logistic Regression, and then, you'll create a model for a telecommunication company, to predict when its customers will leave for a competitor, so that they can take some action to retain the customers. Table of contents About the dataset ...
import pandas as pd import pylab as pl import numpy as np import scipy.optimize as opt from sklearn import preprocessing %matplotlib inline import matplotlib.pyplot as plt
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
About the datasetWe will use a telecommunications dataset for predicting customer churn. This is a historical customer dataset where each row represents one customer. The data is relatively easy to understand, and you may uncover insights you can use immediately. Typically it is less expensive to keep customers than ac...
#Click here and press Shift+Enter !wget -O ChurnData.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/ChurnData.csv
--2019-04-09 12:01:22-- https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/ChurnData.csv Resolving s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)... 67.228.254.193 Connecting to s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo...
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
__Did you know?__ When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC) Load Data From CSV ...
churn_df = pd.read_csv("ChurnData.csv") churn_df.head()
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Data pre-processing and selection Lets select some features for the modeling. Also we change the target data type to be integer, as it is a requirement by the skitlearn algorithm:
churn_df = churn_df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip', 'callcard', 'wireless','churn']] churn_df['churn'] = churn_df['churn'].astype('int') churn_df.head()
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
PracticeHow many rows and columns are in this dataset in total? What are the name of columns?
# write your code here churn_df.shape
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Lets define X, and y for our dataset:
X = np.asarray(churn_df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip']]) X[0:5] y = np.asarray(churn_df['churn']) y [0:5]
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Also, we normalize the dataset:
from sklearn import preprocessing X = preprocessing.StandardScaler().fit(X).transform(X) X[0:5]
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Train/Test dataset Okay, we split our dataset into train and test set:
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4) print ('Train set:', X_train.shape, y_train.shape) print ('Test set:', X_test.shape, y_test.shape)
Train set: (160, 7) (160,) Test set: (40, 7) (40,)
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Modeling (Logistic Regression with Scikit-learn) Lets build our model using __LogisticRegression__ from Scikit-learn package. This function implements logistic regression and can use different numerical optimizers to find parameters, including ‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’ solvers. You can find exten...
from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix LR = LogisticRegression(C=0.01, solver='liblinear').fit(X_train,y_train) LR
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Now we can predict using our test set:
yhat = LR.predict(X_test) yhat
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
__predict_proba__ returns estimates for all classes, ordered by the label of classes. So, the first column is the probability of class 1, P(Y=1|X), and second column is probability of class 0, P(Y=0|X):
yhat_prob = LR.predict_proba(X_test) yhat_prob
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Evaluation jaccard indexLets try jaccard index for accuracy evaluation. we can define jaccard as the size of the intersection divided by the size of the union of two label sets. If the entire set of predicted labels for a sample strictly match with the true set of labels, then the subset accuracy is 1.0; otherwise it ...
from sklearn.metrics import jaccard_similarity_score jaccard_similarity_score(y_test, yhat)
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
confusion matrixAnother way of looking at accuracy of classifier is to look at __confusion matrix__.
from sklearn.metrics import classification_report, confusion_matrix import itertools def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusio...
Confusion matrix, without normalization [[ 6 9] [ 1 24]]
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Look at first row. The first row is for customers whose actual churn value in test set is 1.As you can calculate, out of 40 customers, the churn value of 15 of them is 1. And out of these 15, the classifier correctly predicted 6 of them as 1, and 9 of them as 0. It means, for 6 customers, the actual churn value were 1 ...
print (classification_report(y_test, yhat))
precision recall f1-score support 0 0.73 0.96 0.83 25 1 0.86 0.40 0.55 15 micro avg 0.75 0.75 0.75 40 macro avg 0.79 0.68 0.69 40 weighted avg 0.78 0.75 0.72 ...
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
Based on the count of each section, we can calculate precision and recall of each label:- __Precision__ is a measure of the accuracy provided that a class label has been predicted. It is defined by: precision = TP / (TP + FP)- __Recall__ is true positive rate. It is defined as: Recall =  TP / (TP + FN) So, we can ca...
from sklearn.metrics import log_loss log_loss(y_test, yhat_prob)
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
PracticeTry to build Logistic Regression model again for the same dataset, but this time, use different __solver__ and __regularization__ values? What is new __logLoss__ value?
# write your code here
_____no_output_____
MIT
Machine Learning with Python/Machine Learning with Python - Week 3 - Lab 3 - Classification - Logistic Regression.ipynb
ipiyushsonar/coursera-labs
T81-558: Applications of Deep Neural Networks**Module 13: Advanced/Other Topics*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class webs...
try: from google.colab import drive COLAB = True print("Note: using Google CoLab") %tensorflow_version 2.x except: print("Note: not using Google CoLab") COLAB = False # Nicely formatted time string def hms_string(sec_elapsed): h = int(sec_elapsed / (60 * 60)) m = int((sec_elapsed % (60 ...
Note: using Google CoLab
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
Part 13.2: Interrupting and Continuing TrainingWe would train our Keras models in one pass in an ideal world, utilizing as much GPU and CPU power as we need. The world in which we train our models is anything but ideal. In this part, we will see that we can stop and continue and even adjust training at later times. We...
import os import re import sys import time import numpy as np from typing import Any, List, Tuple, Union from tensorflow.keras.datasets import mnist from tensorflow.keras import backend as K import tensorflow as tf import tensorflow.keras import tensorflow as tf from tensorflow.keras.callbacks import EarlyStopping, \ ...
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
We define the basic training parameters and where we wish to write the output.
outdir = "./data/" run_desc = "test-train" batch_size = 128 num_classes = 10 run_dir = generate_output_dir(outdir, run_desc) print(f"Results saved to: {run_dir}")
Results saved to: ./data/00000-test-train
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
Keras provides a prebuilt checkpoint class named **ModelCheckpoint** that contains most of our desired functionality. This built-in class can save the model's state repeatedly as training progresses. Stopping neural network training is not always a controlled event. Sometimes this stoppage can be abrupt, such as a powe...
class MyModelCheckpoint(ModelCheckpoint): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def on_epoch_end(self, epoch, logs=None): super().on_epoch_end(epoch,logs)\ # Also save the optimizer state filepath = self._get_file_path(epoch=epoch, logs=logs, batch=None) ...
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
The optimizer applies a step decay schedule during training to decrease the learning rate as training progresses. It is essential to preserve the current epoch that we are on to perform correctly after a training resume.
def step_decay_schedule(initial_lr=1e-3, decay_factor=0.75, step_size=10): def schedule(epoch): return initial_lr * (decay_factor ** np.floor(epoch/step_size)) return LearningRateScheduler(schedule)
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
We build the model just as we have in previous sessions. However, the training function requires a few extra considerations. We specify the maximum number of epochs; however, we also allow the user to select the starting epoch number for training continuation.
def build_model(input_shape, num_classes): model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout...
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
We now begin training, using the **Logger** class to write the output to a log file in the output directory.
with Logger(os.path.join(run_dir, 'log.txt')): input_shape, x_train, y_train, x_test, y_test = obtain_data() model = build_model(input_shape, num_classes) train_model(model, max_epochs=3)
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11493376/11490434 [==============================] - 0s 0us/step 11501568/11490434 [==============================] - 0s 0us/step Shape of x_train: (60000, 28, 28) Shape of y_train: (60000,) Shape of x_test: (10000, 28, 28) Sha...
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
You should notice that the above output displays the name of the hdf5 and pickle (pkl) files produced at each checkpoint. These files serve the following functions:* Pickle files contain the state of the optimizer.* HDF5 files contain the saved model.For this training run, which went for 3 epochs, these two files were ...
!ls ./data !ls ./data/00000-test-train
log.txt model-01-0.20.pkl model-02-0.11.pkl model-03-0.08.pkl model-01-0.20.hdf5 model-02-0.11.hdf5 model-03-0.08.hdf5
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
Keras stores the model itself in an HDF5, which includes the optimizer. Because of this feature, it is not generally necessary to restore the internal state of the optimizer (such as ADAM). However, we include the code to do so. We can obtain the internal state of an optimizer by calling **get_config**, which will retu...
MODEL_PATH = './data/00000-test-train/model-03-0.08.hdf5' OPT_PATH = './data/00000-test-train/model-03-0.08.pkl'
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
The following code loads the HDF5 and PKL files and then recompiles the model based on the PKL file. Depending on the optimizer in use, you might have to recompile the model.
import tensorflow as tf from tensorflow.keras.models import load_model import pickle def load_model_data(model_path, opt_path): model = load_model(model_path) with open(opt_path, 'rb') as fp: d = pickle.load(fp) epoch = d['epoch'] opt = d['opt'] return epoch, model, opt epoch, model, o...
_____no_output_____
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
Finally, we train the model for additional epochs. You can see from the output that the new training starts at a higher accuracy than the first training run. Further, the accuracy increases with additional training. Also, you will notice that the epoch number begins at four and not one.
outdir = "./data/" run_desc = "cont-train" num_classes = 10 run_dir = generate_output_dir(outdir, run_desc) print(f"Results saved to: {run_dir}") with Logger(os.path.join(run_dir, 'log.txt')): input_shape, x_train, y_train, x_test, y_test = obtain_data() train_model(model, initial_epoch=epoch, max_epochs=6)
Results saved to: ./data/00001-cont-train Shape of x_train: (60000, 28, 28) Shape of y_train: (60000,) Shape of x_test: (10000, 28, 28) Shape of y_test: (10000,) x_train shape: (60000, 28, 28, 1) Training samples: 60000 Test samples: 10000 Epoch 4/6 Epoch 4: saving model to ./data/00001-cont-train/model-04-0.07.hdf5 ...
Apache-2.0
t81_558_class_13_02_checkpoint.ipynb
rserran/t81_558_deep_learning
> Developed by [Yeison Nolberto Cardona Álvarez](https://github.com/yeisonCardona) > [Andrés Marino Álvarez Meza, PhD.](https://github.com/amalvarezme) > César Germán Castellanos Dominguez, PhD. > _Digital Signal Processing and Control Group_ | _Grupo de Control y Procesamiento Digital de Señales ([GCPDS](https://g...
# Acquisition with blocking call from openbci_stream.acquisition import Cyton openbci = Cyton('serial', endpoint='/dev/ttyUSB0', capture_stream=True) # blocking call openbci.stream(15) # collect data for 15 seconds # openbci.eeg_time_series # openbci.aux_time_series # openbci.timestamp_time_series # Acquisition w...
_____no_output_____
BSD-2-Clause
docs/source/notebooks/readme.ipynb
UN-GCPDS/openbci-stream
Notion - Update pages from database **Tags:** notion productivity Input Import library
from naas_drivers import notion
_____no_output_____
BSD-3-Clause
Notion/Notion_Update_pages_from_database.ipynb
vivard/awesome-notebooks
Setup NotionHow to get your Notion integration token ?
# Enter Token API notion_token = "*****" # Enter Database URL database_url = "https://www.notion.so/********"
_____no_output_____
BSD-3-Clause
Notion/Notion_Update_pages_from_database.ipynb
vivard/awesome-notebooks
Model Get pages from Notion DB
database_id = database_url.split("/")[-1].split("?v=")[0] pages = notion.connect(notion_token).database.query(database_id, query={}) print("📊 Pages in Notion DB:", len(pages))
_____no_output_____
BSD-3-Clause
Notion/Notion_Update_pages_from_database.ipynb
vivard/awesome-notebooks
Output Update pages
for page in pages: print(page) # page.title("Name","Page updated") # page.rich_text("Text","Ceci est toto") # page.number("Number", 42) # page.select("Select","Value3") # page.multi_select("Muti Select",["Value1","Value2","Value3"]) # page.date("Date","2021-10-03T17:01:26") #Follow ISO 8601...
_____no_output_____
BSD-3-Clause
Notion/Notion_Update_pages_from_database.ipynb
vivard/awesome-notebooks
Copyright 2019 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
tf.function で性能アップ View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook TensorFlow 2.0 では Eager Execution が既定で有効になっています。ユーザーインターフェイスは直感的で柔軟です(演算を一度だけ行う場合にはずっと簡単に、かつ迅速に実行されます)。しかしながら、それは性能と展開の面での犠牲の上に成り立っています。最高性能を得ながら、モデルをどこへでも展開できるようにするには、`tf.function` を使ってプログ...
from __future__ import absolute_import, division, print_function, unicode_literals try: %tensorflow_version 2.x except Exception: pass import tensorflow as tf import contextlib # 遭遇するかもしれないいくつかのエラーをデモするためのヘルパー関数 @contextlib.contextmanager def assert_raises(error_class): try: yield except error_class as e:...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
あなたが定義した `tf.function` は TensorFlow Core の演算に似たものです。例えばそれを即時に実行することも、計算グラフで使うこともできますし、勾配を計算することも可能です。
# function は演算のように振る舞う @tf.function def add(a, b): return a + b add(tf.ones([2, 2]), tf.ones([2, 2])) # [[2., 2.], [2., 2.]] # function は勾配を計算できる @tf.function def add(a, b): return a + b v = tf.Variable(1.0) with tf.GradientTape() as tape: result = add(v, 1.0) tape.gradient(result, v) # function 内で function...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
トレーシングとポリモーフィズムPython の動的型付けは、関数をさまざまな型の引数で呼び出すことができ、Python がそれぞれのシナリオで異なる動作をするということを意味します。他方で、TensorFlow の計算グラフでは、dtype と shape の次元が静的であることが必要です。`tf.function` は、正しい計算グラフを生成するために必要なときには関数を再トレースして、このギャップをつなぐ役割を果たします。異なる型の引数を使って関数を呼び出し、何が起きるか見てみましょう。
# Function はポリモーフィック @tf.function def double(a): print("Tracing with", a) return a + a print(double(tf.constant(1))) print() print(double(tf.constant(1.1))) print() print(double(tf.constant("a"))) print()
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
トレースの動作を制御するためには、下記のようなテクニックを使います。- 新しい `tf.function` を作成する。別々の `tf.function` オブジェクトがトレースを共有することはない。- 特定のトレースを得るには `get_concrete_function` メソッドを使用する。- 計算グラフの呼び出し時に1回だけトレースを行うには、 `input_signature` を指定して `tf.function` を呼び出す。
print("Obtaining concrete trace") double_strings = double.get_concrete_function(tf.TensorSpec(shape=None, dtype=tf.string)) print("Executing traced function") print(double_strings(tf.constant("a"))) print(double_strings(a=tf.constant("b"))) print("Using a concrete trace with incompatible types will throw an error") wit...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
いつ再トレースするのか?ポリモーフィックな `tf.function` はトレーシングによって生成された具象関数のキャッシュを保持しています。キャッシュのキーは、実際にはその関数の引数及びキーワード引数から生成されたキーのタプルです。`tf.Tensor` 引数から生成されるキーは、テンソルの shape と型です。Python の組み込み型引数から生成されるキーはその値です。それ以外の Python の型では、キーはオブジェクトの `id()` に基づいており、メソッドはクラスのインスタンスひとつずつ独立にトレースされます。将来、TensorFlowには、Python オブジェクトについて安全にテンソルに変換できるような、より洗...
def train_one_step(): pass @tf.function def train(num_steps): print("Tracing with num_steps = {}".format(num_steps)) for _ in tf.range(num_steps): train_one_step() train(num_steps=10) train(num_steps=20)
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
ここでの簡単な回避方法は、生成されたグラフの shape が変わらないのであれば、引数をテンソルにキャストすることです。
train(num_steps=tf.constant(10)) train(num_steps=tf.constant(20))
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
`tf.function` の中の副作用一般的には、(印字やオブジェクト変更のような)Python の副作用は、トレーシングの最中にだけ発生します。それでは、どうしたら `tf.function` で安定的に副作用を起こすことができるでしょうか?一般的な原則は、トレースをデバッグする際にだけ Python の副作用を使用するというものです。あるいは、`tf.Variable.assign`、`tf.print`、そして `tf.summary` のような TensorFlow の演算を使うことで、コードがトレースされるときにも、TensorFlowランタイムによって都度呼び出される際にも、確実に実行されるようにできます。一般には、...
@tf.function def f(x): print("Traced with", x) tf.print("Executed with", x) f(1) f(1) f(2)
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
`tf.function` が呼び出されるたびに Python のコードを実行したいのであれば、`tf.py_function` がぴったりです。`tf.py_function` の欠点は、ポータブルでないこと、それほど性能が高くないこと、(マルチGPU、TPUの)分散環境ではうまく動作しないことなどです。また、`tf.py_function` は計算グラフに組み込まれるため、入出力すべてをテンソルにキャストします。
external_list = [] def side_effect(x): print('Python side effect') external_list.append(x) @tf.function def f(x): tf.py_function(side_effect, inp=[x], Tout=[]) f(1) f(1) f(1) assert len(external_list) == 3 # .numpy() call required because py_function casts 1 to tf.constant(1) assert external_list[0].numpy() ==...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
Python の状態に注意ジェネレーターやイテレーターなど Python の機能の多くは、状態を追跡するために Python のランタイムに依存しています。これらの仕組みは、一般的には Eager モードでも期待通りに動作しますが、トレーシングの振る舞いにより、`tf.function` の中では予期しないことが起きることがあります。1例として、イテレーターの状態が進むのは Python の副作用であり、トレーシングの中だけで発生します。
external_var = tf.Variable(0) @tf.function def buggy_consume_next(iterator): external_var.assign_add(next(iterator)) tf.print("Value of external_var:", external_var) iterator = iter([0, 1, 2, 3]) buggy_consume_next(iterator) # 次のコードは、イテレーターの次の値を使うのではなく、最初の値を再利用する buggy_consume_next(iterator) buggy_consume_next(ite...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
イテレーターが tf.function の中で生成されすべて使われる場合には、正しく動作するはずです。しかし、イテレーター全体がトレースされることとなり、巨大な計算グラフの生成をまねく可能性があります。これは、望みどおりの動作かもしれません。しかし、もし Python のリストとして表されたメモリー上の巨大なデータセットを使って訓練を行うとすると、これは非常に大きな計算グラフを生成することになり、`tf.function` がスピードアップにはつながらないと考えられます。Python データを繰り返し使用する場合、もっとも安全な方法は tf.data.Dataset でラップして、`for x in y` というイディオムを使用する...
def measure_graph_size(f, *args): g = f.get_concrete_function(*args).graph print("{}({}) contains {} nodes in its graph".format( f.__name__, ', '.join(map(str, args)), len(g.as_graph_def().node))) @tf.function def train(dataset): loss = tf.constant(0) for x, y in dataset: loss += tf.abs(y - x) # ダミー計...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
Python/Numpy のデータを Dataset でラップする際には、`tf.data.Dataset.from_generator` と `tf.data.Dataset.from_tensors` の違いに留意しましょう。前者はデータを Python のまま保持し `tf.py_function` を通じて取得するため、性能に影響する場合があります。これに対して後者はデータのコピーを計算グラフの中の、ひとつの大きな `tf.constant()` に結びつけるため、メモリー消費に影響する可能性があります。 TFRecordDataset/CsvDataset/などを通じてデータをファイルから読み込むことが、データを使用する最...
# 自動的な依存関係の制御 a = tf.Variable(1.0) b = tf.Variable(2.0) @tf.function def f(x, y): a.assign(y * b) b.assign_add(x * a) return a + b f(1.0, 2.0) # 10.0
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
変数`tf.function` の中では、意図したコードの実行順序を活用するという同じアイデアを使って、変数の作成と活用を簡単に行うことができます。しかし、ひとつだけ非常に重要な欠点があります。それは、変数を使った場合、先行実行モードとグラフモードでは動作が変わるコードを書いてしまう可能性があるということです。特に、呼び出しの都度新しい変数を作成する場合にこれが発生します。トレーシングの意味では、`tf.function` は呼び出しのたびに同じ変数を再利用しますが、Eager モードでは呼び出しごとに新しい変数を生成します。この間違いを防止するため、`tf.function` は危険な変数の生成動作を見つけるとエラーを発生させま...
@tf.function def f(x): v = tf.Variable(1.0) v.assign_add(x) return v with assert_raises(ValueError): f(1.0) # しかし、曖昧さの無いコードは大丈夫 v = tf.Variable(1.0) @tf.function def f(x): return v.assign_add(x) print(f(1.0)) # 2.0 print(f(2.0)) # 4.0 # 初めて関数が実行されるときだけ変数が生成されることを保証できれば # tf.function 内で変数を作成できる class C:...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
AutoGraph の使用[autograph](https://www.tensorflow.org/guide/function) ライブラリは `tf.function` に完全に統合されており、計算グラフの中で動的に実行される条件文や繰り返しを書くことができます。`tf.cond` や `tf.while_loop` は `tf.function` でも使えますが、制御フローを含むコードは、命令形式で書いたほうが書きやすいし理解しやすいです。
# 単純な繰り返し @tf.function def f(x): while tf.reduce_sum(x) > 1: tf.print(x) x = tf.tanh(x) return x f(tf.random.uniform([5])) # 興味があれば AutoGraph が生成するコードを調べることができる # ただし、アセンブリ言語を読むような感じがする def f(x): while tf.reduce_sum(x) > 1: tf.print(x) x = tf.tanh(x) return x print(tf.autograph.to_code(f))
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
AutoGraph: 条件分岐AutoGraph は `if` 文を等価である `tf.cond` の呼び出しに変換します。この置換は条件がテンソルである場合に行われます。そうでない場合には、条件分岐はトレーシングの中で実行されます。
def test_tf_cond(f, *args): g = f.get_concrete_function(*args).graph if any(node.name == 'cond' for node in g.as_graph_def().node): print("{}({}) uses tf.cond.".format( f.__name__, ', '.join(map(str, args)))) else: print("{}({}) executes normally.".format( f.__name__, ', '.join(map(str, ar...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
`tf.cond` には、色々と注意すべき細かな点があります。- `tf.cond` は条件分岐の両方をトレーシングし、条件に従って実行時に適切な分岐を選択することで機能します。分岐の両方をトレースすることで、Python プログラムを予期せず実行する可能性があります。- `tf.cond` では、分岐の一方が後ほど使用されるテンソルを作成する場合、もう一方の分岐もそのテンソルを作成することが必要です。
@tf.function def f(): x = tf.constant(0) if tf.constant(True): x = x + 1 print("Tracing `then` branch") else: x = x - 1 print("Tracing `else` branch") return x f() @tf.function def f(): if tf.constant(True): x = tf.ones([3, 3]) return x # 分岐のどちらの枝でも `x` を定義する必要があるためエラーが発生 with assert_r...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
AutoGraph と繰り返しAutoGraph には繰り返しの変換にいくつかの単純なルールがあります。- `for`: 反復可能オブジェクトがテンソルである場合に変換する- `while`: while 条件がテンソルに依存している場合に変換する繰り返しが変換される場合、`tf.while_loop` によって動的に展開されます。あるいは、 `for x in tf.data.Dataset` という特別なケースの場合には、 `tf.data.Dataset.reduce` に変換されます。繰り返しが変換されない場合、それは静的に展開されます。
def test_dynamically_unrolled(f, *args): g = f.get_concrete_function(*args).graph if any(node.name == 'while' for node in g.as_graph_def().node): print("{}({}) uses tf.while_loop.".format( f.__name__, ', '.join(map(str, args)))) elif any(node.name == 'ReduceDataset' for node in g.as_graph_def().node):...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
繰り返しに、テンソルに依存する `break` や、途中での `return` がある場合、一番外側の条件あるいは反復可能オブジェクトはテンソルである必要があります。 比較してみましょう。
@tf.function def while_py_true_py_break(x): while True: # py true if x == 0: # py break break x -= 1 return x test_dynamically_unrolled(while_py_true_py_break, 5) @tf.function def buggy_while_py_true_tf_break(x): while True: # py true if tf.equal(x, 0): # tf break break x -= 1 re...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
動的に展開される繰り返しの結果を集計するため、`tf.TensorArray` を使いたくなるかもしれません。
batch_size = 2 seq_len = 3 feature_size = 4 def rnn_step(inp, state): return inp + state @tf.function def dynamic_rnn(rnn_step, input_data, initial_state): # [batch, time, features] -> [time, batch, features] input_data = tf.transpose(input_data, [1, 0, 2]) max_seq_len = input_data.shape[0] states = tf.Ten...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
`tf.cond` と同様に、`tf.while_loop` にも、色々と注意すべき細かな点があります。- 繰り返しの実行回数が 0 である可能性があるため、while_loop の後で使用されるテンソルは、繰り返しの前に初期化されなければならない- すべての繰り返しの変数は、各繰り返しを通じてその形状と dtype が変わらないことが必要
@tf.function def buggy_loop_var_uninitialized(): for i in tf.range(3): x = i return x with assert_raises(ValueError): buggy_loop_var_uninitialized() @tf.function def f(): x = tf.constant(0) for i in tf.range(3): x = i return x f() @tf.function def buggy_loop_type_changes(): x = tf.constant(0, dt...
_____no_output_____
Apache-2.0
site/ja/tutorials/customization/performance.ipynb
nic-fp/docs
Xenon1T We can now implement the projected limits for Xenon1T based off 83 days of exposure using the same recoil energy spectrum as for CRESST-III but with the appropriate changes made for the Xenon nuclei (it is more simple here since there are only Xenon nuclei). We assume that there is only one isotope for our cal...
rho_0 = 0.3*1.e3 # MeV/cm3 # Define energy range in MeV def eta_F(): """Returns an interpolated integral over the velocity distribution, taken to be Maxwellian""" v, gave = np.loadtxt("DD_files/gave.dat", unpack=True, dtype=float) f = interp1d(v, gave, bounds_error=False, fill_value=0.0) # s km^-1 ret...
_____no_output_____
MIT
Examples/swordfish_DD.ipynb
bradkav/swordfish
Setup
array_geometry = uniform_linear_array(n_mics=10, spacing=0.5) microphone_array = MicrophoneArray(array_geometry) us = 0 vs = compute_steering_vector_ULA(us, microphone_array) SNRs = np.arange(0, 31, 10) n_SNRs = len(SNRs) sigma_n = 1
_____no_output_____
MIT
playground_baseline_dictionary_various_training_snapshots_various_noise_interferences_random.ipynb
dung-n-tran/speech-enhancement-beamforming