markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
If you would have wanted to split on the linebreaks only (possible followed by e.g. spaces), you could have used the following pattern: | s = """This is a text on three lines
with multiple instances of
double spaces."""
whitespace = re.compile(r"\s*\n\s*")
print(whitespace.split(s)) | Chapter 6 - Regular Expressions.ipynb | mikekestemont/ghent1516 | mit |
If we want to correct the double spaces, we could now do: | ds = re.compile(r" +")
for line in whitespace.split(s):
print ds.sub(" ", line) | Chapter 6 - Regular Expressions.ipynb | mikekestemont/ghent1516 | mit |
One final feature we should mention is the [^...] syntax: this will match any character that is NOT between the brackets. Remember the vowel_pattern above? Using the caret symbol we can quickly 'invert' this pattern, so that it will match all consonants: | s = "these are vowels and consonants"
consonants = re.compile(r"[^aeuoi]")
print(consonants.sub("X", s)) | Chapter 6 - Regular Expressions.ipynb | mikekestemont/ghent1516 | mit |
Regular expressions are really useful, but they can get tricky as well as difficult to read, because of the many different options that exist. There is a whole range of special symbols which you can use to match nearly everything in a text, from word boundaries (\b) to digits (\d) etc. Don't learn these by heart but lo... | from IPython.core.display import HTML
def css_styling():
styles = open("styles/custom.css", "r").read()
return HTML(styles)
css_styling() | Chapter 6 - Regular Expressions.ipynb | mikekestemont/ghent1516 | mit |
Time to build the network
Below you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.
The network has two layers, a hid... | class NeuralNetwork(object):
@staticmethod
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
# Set number of nodes in input, hidden and output layers.
self.input_nodes = input_nodes
self.hidden_n... | py3/project-1/dlnd-your-first-neural-network.ipynb | jjonte/udacity-deeplearning-nd | unlicense |
Training the network
Here you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training se... | import sys
### Set the hyperparameters here ###
epochs = 1000
learning_rate = 0.1
hidden_nodes = 10
output_nodes = 1
N_i = train_features.shape[1]
network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)
losses = {'train':[], 'validation':[]}
for e in range(epochs):
# Go through a random batch of ... | py3/project-1/dlnd-your-first-neural-network.ipynb | jjonte/udacity-deeplearning-nd | unlicense |
Thinking about your results
Answer these questions about your results. How well does the model predict the data? Where does it fail? Why does it fail where it does?
Note: You can edit the text in this cell by double clicking on it. When you want to render the text, press control + enter
Your answer below
It does pret... | import unittest
inputs = [0.5, -0.2, 0.1]
targets = [0.4]
test_w_i_h = np.array([[0.1, 0.4, -0.3],
[-0.2, 0.5, 0.2]])
test_w_h_o = np.array([[0.3, -0.1]])
class TestMethods(unittest.TestCase):
##########
# Unit tests for data loading
##########
def test_data_path(self... | py3/project-1/dlnd-your-first-neural-network.ipynb | jjonte/udacity-deeplearning-nd | unlicense |
Aufgabe 2 Informationsextraktion per Syntaxanalyse
Gegenstand dieser Aufgabe ist eine anwendungsnahe Möglichkeit, Ergebnisse einer Syntaxanalyse weiterzuverarbeiten. Aus den syntaktischen Abhängigkeiten eines Textes soll (unter Zuhilfenahme einiger Normalisierungsschritte) eine semantische Repräsenta... | from nltk.parse.stanford import StanfordDependencyParser
PATH_TO_CORE = "/pfad/zu/stanford-corenlp-full-2017-06-09"
jar = PATH_TO_CORE + '/' + "stanford-corenlp-3.8.0.jar"
model = PATH_TO_CORE + '/' + "stanford-corenlp-3.8.0-models.jar"
dep_parser = StanfordDependencyParser(
jar, model,
model_path="edu/stanfo... | 11-notebook-after-class.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
Hausaufgaben
Aufgabe 3 Parent Annotation
Parent Annotation kann die Performanz einer CFG wesentlich verbessern. Schreiben Sie eine Funktion, die einen gegebenen Syntaxbaum dieser Optimierung unterzieht. Auf diese Art und Weise transformierte Bäume können dann wiederum zur Grammatikinduktion verwendet... | def parent_annotation(tree, parentHistory=0, parentChar="^"):
pass
test_tree = nltk.Tree(
"S",
[
nltk.Tree("NP", [
nltk.Tree("DET", []),
nltk.Tree("N", [])
]),
nltk.Tree("VP", [
nltk.Tree("V", []),
nltk.Tree("NP", [
nlt... | 11-notebook-after-class.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
Aufgabe 4 Mehr Semantik für IE
Zusätzlich zu den in Aufgabe 2 behandelten Konstruktionen sollen jetzt auch negierte und komplexe Sätze mit Konjunktionen sinnvoll verarbeitet werden.
Eingabe:
I see an elephant.
You didn't see the elephant.
Peter saw the elephant and drank wine.
Gewünschte Ausgabe:
se... | def generate_predicates_for_sentence(sentence):
pass
def generate_predicates_for_text(text):
pass
text = """
I see an elephant.
You didn't see the elephant.
Peter saw the elephant and drank wine.
""" | 11-notebook-after-class.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
2.Drucke alle die Zahlen von 0 bis 4 aus: | for x in range(5):
print(x)
for x in range(3, 6):
print(x)
| 06_Python_Rückblick/01+Rückblick+02+For-Loop-Übungen+-Copy1.ipynb | dostrebel/working_place_ds_17 | mit |
4.Baue einen For-Loop, indem Du alle geraden Zahlen ausdruckst, die tiefer sind als 237. | numbers = [
951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,
615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941,
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, ... | 06_Python_Rückblick/01+Rückblick+02+For-Loop-Übungen+-Copy1.ipynb | dostrebel/working_place_ds_17 | mit |
6.Addiere nur die Zahlen, die gerade sind | evennumber = []
for elem in numbers:
if elem % 2 == 0:
evennumber.append(elem)
sum(evennumber) | 06_Python_Rückblick/01+Rückblick+02+For-Loop-Übungen+-Copy1.ipynb | dostrebel/working_place_ds_17 | mit |
7.Drucke mit einem For Loop 5 Mal hintereinander Hello World aus | Satz = ['Hello World', 'Hello World','Hello World','Hello World','Hello World']
for elem in Satz:
print(elem)
#Lösung | 06_Python_Rückblick/01+Rückblick+02+For-Loop-Übungen+-Copy1.ipynb | dostrebel/working_place_ds_17 | mit |
8.Entwickle ein Programm, das alle Nummern zwischen 2000 und 3200 findet, die durch 7, aber nicht durch 5 teilbar sind. Das Ergebnis sollte auf einer Zeile ausgedruckt werden. Tipp: Schaue Dir hier die Vergleichsoperanden von Python an. | l=[]
for i in range(2000, 3201):
if (i % 7==0) and (i % 5!=0):
l.append(str(i))
print(','.join(l)) | 06_Python_Rückblick/01+Rückblick+02+For-Loop-Übungen+-Copy1.ipynb | dostrebel/working_place_ds_17 | mit |
9.Schreibe einen For Loop, der die Nummern in der folgenden Liste von int in str verwandelt. | lst = range(45,99)
newlst = []
for i in lst:
i = str(i)
newlst.append(i)
print(newlst)
| 06_Python_Rückblick/01+Rückblick+02+For-Loop-Übungen+-Copy1.ipynb | dostrebel/working_place_ds_17 | mit |
10.Schreibe nun ein Programm, das alle Ziffern 4 mit dem Buchstaben A ersetzte, alle Ziffern 5 mit dem Buchtaben B. | newnewlist = []
for elem in newlst:
if '4' in elem:
elem = elem.replace('4', 'A')
if '5' in elem:
elem = elem.replace('5', 'B')
newnewlist.append(elem)
newnewlist | 06_Python_Rückblick/01+Rückblick+02+For-Loop-Übungen+-Copy1.ipynb | dostrebel/working_place_ds_17 | mit |
Note: The R code and the results in this notebook has been converted to markdown so that R is not required to build the documents. The R results in the notebook were computed using R 3.5.1 and lme4 1.1.
ipython
%load_ext rpy2.ipython
ipython
%R library(lme4)
array(['lme4', 'Matrix', 'tools', 'stats', 'graphics', 'grDev... | data = sm.datasets.get_rdataset('dietox', 'geepack').data
md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"])
mdf = md.fit(method=["lbfgs"])
print(mdf.summary()) | examples/notebooks/mixed_lm_example.ipynb | jseabold/statsmodels | bsd-3-clause |
Here is the same model fit in R using LMER:
ipython
%%R
data(dietox, package='geepack')
ipython
%R print(summary(lmer('Weight ~ Time + (1|Pig)', data=dietox)))
```
Linear mixed model fit by REML ['lmerMod']
Formula: Weight ~ Time + (1 | Pig)
Data: dietox
REML criterion at convergence: 4809.6
Scaled residuals:
M... | md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"], re_formula="~Time")
mdf = md.fit(method=["lbfgs"])
print(mdf.summary()) | examples/notebooks/mixed_lm_example.ipynb | jseabold/statsmodels | bsd-3-clause |
Here is the same model fit using LMER in R:
ipython
%R print(summary(lmer("Weight ~ Time + (1 + Time | Pig)", data=dietox)))
```
Linear mixed model fit by REML ['lmerMod']
Formula: Weight ~ Time + (1 + Time | Pig)
Data: dietox
REML criterion at convergence: 4434.1
Scaled residuals:
Min 1Q Median 3Q ... | .294 / (19.493 * .416)**.5
md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"],
re_formula="~Time")
free = sm.regression.mixed_linear_model.MixedLMParams.from_components(np.ones(2),
np.eye(2))
mdf = md.fit(free=free, method... | examples/notebooks/mixed_lm_example.ipynb | jseabold/statsmodels | bsd-3-clause |
The likelihood drops by 0.3 when we fix the correlation parameter to 0. Comparing 2 x 0.3 = 0.6 to the chi^2 1 df reference distribution suggests that the data are very consistent with a model in which this parameter is equal to 0.
Here is the same model fit using LMER in R (note that here R is reporting the REML crit... | data = sm.datasets.get_rdataset("Sitka", "MASS").data
endog = data["size"]
data["Intercept"] = 1
exog = data[["Intercept", "Time"]] | examples/notebooks/mixed_lm_example.ipynb | jseabold/statsmodels | bsd-3-clause |
Here is the statsmodels LME fit for a basic model with a random intercept. We are passing the endog and exog data directly to the LME init function as arrays. Also note that endog_re is specified explicitly in argument 4 as a random intercept (although this would also be the default if it were not specified). | md = sm.MixedLM(endog, exog, groups=data["tree"], exog_re=exog["Intercept"])
mdf = md.fit()
print(mdf.summary()) | examples/notebooks/mixed_lm_example.ipynb | jseabold/statsmodels | bsd-3-clause |
Here is the same model fit in R using LMER:
ipython
%R
data(Sitka, package="MASS")
print(summary(lmer("size ~ Time + (1 | tree)", data=Sitka)))
```
Linear mixed model fit by REML ['lmerMod']
Formula: size ~ Time + (1 | tree)
Data: Sitka
REML criterion at convergence: 164.8
Scaled residuals:
Min 1Q Median ... | exog_re = exog.copy()
md = sm.MixedLM(endog, exog, data["tree"], exog_re)
mdf = md.fit()
print(mdf.summary()) | examples/notebooks/mixed_lm_example.ipynb | jseabold/statsmodels | bsd-3-clause |
We can further explore the random effects structure by constructing plots of the profile likelihoods. We start with the random intercept, generating a plot of the profile likelihood from 0.1 units below to 0.1 units above the MLE. Since each optimization inside the profile likelihood generates a warning (due to the ran... | import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
likev = mdf.profile_re(0, 're', dist_low=0.1, dist_high=0.1) | examples/notebooks/mixed_lm_example.ipynb | jseabold/statsmodels | bsd-3-clause |
Here is a plot of the profile likelihood function. We multiply the log-likelihood difference by 2 to obtain the usual $\chi^2$ reference distribution with 1 degree of freedom. | import matplotlib.pyplot as plt
plt.figure(figsize=(10,8))
plt.plot(likev[:,0], 2*likev[:,1])
plt.xlabel("Variance of random slope", size=17)
plt.ylabel("-2 times profile log likelihood", size=17) | examples/notebooks/mixed_lm_example.ipynb | jseabold/statsmodels | bsd-3-clause |
Here is a plot of the profile likelihood function. The profile likelihood plot shows that the MLE of the random slope variance parameter is a very small positive number, and that there is low uncertainty in this estimate. | re = mdf.cov_re.iloc[1, 1]
with warnings.catch_warnings():
# Parameter is often on the boundary
warnings.simplefilter("ignore", ConvergenceWarning)
likev = mdf.profile_re(1, 're', dist_low=.5*re, dist_high=0.8*re)
plt.figure(figsize=(10, 8))
plt.plot(likev[:,0], 2*likev[:,1])
plt.xlabel("Variance of random... | examples/notebooks/mixed_lm_example.ipynb | jseabold/statsmodels | bsd-3-clause |
2. use nested DataStructs
nesting DataStructs allows for much more complex parsing patterns. | from dstruct import DataStruct
from datetime import datetime
class Transaction(DataStruct):
amount = DataField()
@datafield(path=None)
def time(self, data):
s = data['utc-unix']
tz = data['time-zone']
if 'UTC' not in tz:
raise ValueError("Unknow time-zone standard:... | examples/advanced.ipynb | rmorshea/dstruct | mit |
The Parsed Account Summary | print(DetailedAccountSummary('data_files/bank_data.json')) | examples/advanced.ipynb | rmorshea/dstruct | mit |
<br> | # Import wine quality data from a local CSV file
wine = h2o.import_file("winequality-white.csv")
wine.head(5)
# Define features (or predictors)
features = list(wine.columns) # we want to use all the information
features.remove('quality') # we need to exclude the target 'quality' (otherwise there is nothing to predi... | py_03c_regression_ensembles.ipynb | woobe/odsc_h2o_machine_learning | apache-2.0 |
<br>
Step 1: Build GBM Models using Random Grid Search and Extract the Best Model | # define the range of hyper-parameters for GBM grid search
# 27 combinations in total
hyper_params = {'sample_rate': [0.7, 0.8, 0.9],
'col_sample_rate': [0.7, 0.8, 0.9],
'max_depth': [3, 5, 7]}
# Set up GBM grid search
# Add a seed for reproducibility
gbm_rand_grid = H2OGridSearch(
... | py_03c_regression_ensembles.ipynb | woobe/odsc_h2o_machine_learning | apache-2.0 |
<br>
Step 2: Build DRF Models using Random Grid Search and Extract the Best Model | # define the range of hyper-parameters for DRF grid search
# 27 combinations in total
hyper_params = {'sample_rate': [0.5, 0.6, 0.7],
'col_sample_rate_per_tree': [0.7, 0.8, 0.9],
'max_depth': [3, 5, 7]}
# Set up DRF grid search
# Add a seed for reproducibility
drf_rand_grid = H2OGridSea... | py_03c_regression_ensembles.ipynb | woobe/odsc_h2o_machine_learning | apache-2.0 |
<br>
Step 3: Build DNN Models using Random Grid Search and Extract the Best Model | # define the range of hyper-parameters for DNN grid search
# 81 combinations in total
hyper_params = {'activation': ['tanh', 'rectifier', 'maxout'],
'hidden': [[50], [50,50], [50,50,50]],
'l1': [0, 1e-3, 1e-5],
'l2': [0, 1e-3, 1e-5]}
# Set up DNN grid search
# Add a seed... | py_03c_regression_ensembles.ipynb | woobe/odsc_h2o_machine_learning | apache-2.0 |
<br>
Model Stacking | # Define a list of models to be stacked
# i.e. best model from each grid
all_ids = [best_gbm_model_id, best_drf_model_id, best_dnn_model_id]
# Set up Stacked Ensemble
ensemble = H2OStackedEnsembleEstimator(model_id = "my_ensemble",
base_models = all_ids)
# use .train to start mo... | py_03c_regression_ensembles.ipynb | woobe/odsc_h2o_machine_learning | apache-2.0 |
<br>
Comparison of Model Performance on Test Data | print('Best GBM model from Grid (MSE) : ', best_gbm_from_rand_grid.model_performance(wine_test).mse())
print('Best DRF model from Grid (MSE) : ', best_drf_from_rand_grid.model_performance(wine_test).mse())
print('Best DNN model from Grid (MSE) : ', best_dnn_from_rand_grid.model_performance(wine_test).mse())
print('Stac... | py_03c_regression_ensembles.ipynb | woobe/odsc_h2o_machine_learning | apache-2.0 |
Purpose
The purpose of this notebook is to work out the data structure for saving the computed results for a single session. Here we are using the xarray package to structure the data, because:
It is built to handle large multi-dimensional data (orginally for earth sciences data).
It allows you to call dimensions by n... | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import xarray as xr
from src.data_processing import (get_LFP_dataframe, make_tetrode_dataframe,
make_tetrode_pair_info, reshape_to_segments)
from src.parameters import (ANIMALS, SAMPLING_FREQUE... | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
Go through the steps to get the ripple triggered connectivity | epoch_key = ('HPa', 6, 2)
ripple_times = detect_epoch_ripples(
epoch_key, ANIMALS, sampling_frequency=SAMPLING_FREQUENCY)
tetrode_info = make_tetrode_dataframe(ANIMALS)[epoch_key]
tetrode_info = tetrode_info[
~tetrode_info.descrip.str.endswith('Ref').fillna(False)]
tetrode_pair_info = make_tetrode_pair_info(t... | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
Make an xarray dataset for coherence and pairwise spectral granger | n_lfps = len(lfps)
ds = xr.Dataset(
{'coherence_magnitude': (['time', 'frequency', 'tetrode1', 'tetrode2'], c.coherence_magnitude()),
'pairwise_spectral_granger_prediction': (['time', 'frequency', 'tetrode1', 'tetrode2'], c.pairwise_spectral_granger_prediction())},
coords={'time': c.time + np.diff(c.time)[... | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
Show that it is easy to select two individual tetrodes and plot a subset of their frequency for coherence. | ds.sel(
tetrode1='HPa621',
tetrode2='HPa624',
frequency=slice(0, 30)).coherence_magnitude.plot(x='time', y='frequency'); | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
Show the same thing for spectral granger. | ds.sel(
tetrode1='HPa621',
tetrode2='HPa6220',
frequency=slice(0, 30)
).pairwise_spectral_granger_prediction.plot(x='time', y='frequency'); | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
Now show that we can plot all tetrodes pairs in a dataset | ds['pairwise_spectral_granger_prediction'].sel(
frequency=slice(0, 30)).plot(x='time', y='frequency', col='tetrode1', row='tetrode2', robust=True);
ds['coherence_magnitude'].sel(
frequency=slice(0, 30)).plot(x='time', y='frequency', col='tetrode1', row='tetrode2'); | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
It is also easy to select a subset of tetrode pairs (in this case all CA1-PFC tetrode pairs). | (ds.sel(
tetrode1=ds.tetrode1[ds.brain_area1=='CA1'],
tetrode2=ds.tetrode2[ds.brain_area2=='PFC'],
frequency=slice(0, 30))
.coherence_magnitude
.plot(x='time', y='frequency', col='tetrode1', row='tetrode2')); | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
xarray also makes it easy to compare the difference of a connectivity measure from its baseline (in this case, the baseline is the first time bin) | ((ds - ds.isel(time=0)).sel(
tetrode1=ds.tetrode1[ds.brain_area1=='CA1'],
tetrode2=ds.tetrode2[ds.brain_area2=='PFC'],
frequency=slice(0, 30))
.coherence_magnitude
.plot(x='time', y='frequency', col='tetrode1', row='tetrode2')); | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
It is also easy to average over the tetrode pairs | (ds.sel(
tetrode1=ds.tetrode1[ds.brain_area1=='CA1'],
tetrode2=ds.tetrode2[ds.brain_area2=='PFC'],
frequency=slice(0, 30))
.coherence_magnitude.mean(['tetrode1', 'tetrode2'])
.plot(x='time', y='frequency')); | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
And also average over the difference | ((ds - ds.isel(time=0)).sel(
tetrode1=ds.tetrode1[ds.brain_area1=='CA1'],
tetrode2=ds.tetrode2[ds.brain_area2=='PFC'],
frequency=slice(0, 30))
.coherence_magnitude.mean(['tetrode1', 'tetrode2'])
.plot(x='time', y='frequency')); | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
Test saving as netcdf file | import os
path = '{0}_{1:02d}_{2:02d}.nc'.format(*epoch_key)
group = '{0}/'.format(multitaper_parameter_name)
write_mode = 'a' if os.path.isfile(path) else 'w'
ds.to_netcdf(path=path, group=group, mode=write_mode) | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
Show that we can open the saved dataset and recover the data | with xr.open_dataset(path, group=group) as da:
da.load()
print(da) | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
Make data structure for group delay | n_bands = len(FREQUENCY_BANDS)
delay, slope, r_value = (np.zeros((c.time.size, n_bands, m.n_signals, m.n_signals)),) * 3
for band_ind, frequency_band in enumerate(FREQUENCY_BANDS):
(delay[:, band_ind, ...],
slope[:, band_ind, ...],
r_value[:, band_ind, ...]) = c.group_delay(
FREQUENCY_BANDS[frequ... | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
Make data structure for canonical coherence | canonical_coherence, area_labels = c.canonical_coherence(tetrode_info.area.tolist())
dimension_names = ['time', 'frequency', 'brain_area1', 'brain_area2']
data_vars = {'canonical_coherence': (dimension_names, canonical_coherence)}
coordinates = {
'time': c.time + np.diff(c.time)[0] / 2,
'frequency': c.frequenci... | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
Now after adding this code into the code base, test if we can compute, save, and load | from src.analysis import ripple_triggered_connectivity
for parameters_name, parameters in MULTITAPER_PARAMETERS.items():
ripple_triggered_connectivity(
lfps, epoch_key, tetrode_info, ripple_times, parameters,
FREQUENCY_BANDS,
multitaper_parameter_name=parameters_name,
group_name='al... | notebooks/2017_06_14_Test_Spectral_Single_Session.ipynb | edeno/Jadhav-2016-Data-Analysis | gpl-3.0 |
Identificando a rotação entre 2 imagens
Calcular a Transformada de Fourier das 2 imagens que se quer comparar;
Converter as imagens obtidas para coordenadas polares
Calcular a correlação de fase usando a função phasecorr
Encontrar o ponto de máximo do mapa de correlação resultante | f = mpimg.imread('../data/cameraman.tif')
# Inserindo uma borda de zeros para permitir a rotação da imagem
t = np.zeros(np.array(f.shape)+100,dtype=np.uint8)
t[50:f.shape[0]+50,50:f.shape[1]+50] = f
f = t
t1 = np.array([
[1,0,-f.shape[0]/2.],
[0,1,-f.shape[1]/2.],
[0,0,1]]);... | 2S2018/13 Correlacao de fase.ipynb | robertoalotufo/ia898 | mit |
<table class="bq-notebook-buttons" align="left">
<td>
<a target="_blank" href="#"><img src="./images/bigquery_32px.png" />View on BigQuery Docs</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/GoogleCloudPlatform/bigquery-notebooks/blob/main/notebooks/official/notebook_temp... | import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
! pip3 install {... | notebooks/official/notebook_template.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Before you begin
Select a GPU runtime
Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select "Runtime --> Change runtime type > GPU"
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.
Select or create a Google Cloud pr... | PROJECT_ID = ""
# Get your Google Cloud project ID from gcloud
if not os.getenv("IS_TESTING"):
shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT_ID = shell_output[0]
print("Project ID: ", PROJECT_ID) | notebooks/official/notebook_template.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
{TODO: Adjust wording in the first paragraph to fit your use case - explain how your tutorial uses the Cloud Storage bucket. The example below shows how Vertex AI uses the bucket for training.}
When you submit a tra... | BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"}
REGION = "[your-region]" # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]":
BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP | notebooks/official/notebook_template.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Import libraries and define constants
{TODO: Put all your imports and installs up into a setup section.} | import os
import sys
import numpy as np
import tensorflow as tf | notebooks/official/notebook_template.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
General style examples
Notebook heading
Include the collapsed license at the top (this uses Colab's "Form" mode to hide the cells).
Only include a single H1 title.
Include the button-bar immediately under the H1.
Check that the Colab and GitHub links at the top are correct.
Notebook sections
Use H2 (##) and H3 (###)... | # Build the model
model = tf.keras.Sequential(
[
tf.keras.layers.Dense(10, activation="relu", input_shape=(None, 5)),
tf.keras.layers.Dense(3),
]
)
# Run the model on a single batch of data, and inspect the output.
result = model(tf.constant(np.random.randn(10, 5), dtype=tf.float32)).numpy()
p... | notebooks/official/notebook_template.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Keep examples quick. Use small datasets, or small slices of datasets. You don't need to train to convergence, train until it's obvious it's making progress.
For a large example, don't try to fit all the code in the notebook. Add python files to tensorflow examples, and in the notebook run:
! pip3 install git+https:/... | # Delete endpoint resource
! gcloud ai endpoints delete $ENDPOINT_NAME --quiet --region $REGION_NAME
# Delete model resource
! gcloud ai models delete $MODEL_NAME --quiet
# Delete Cloud Storage objects that were created
! gsutil -m rm -r $JOB_DIR | notebooks/official/notebook_template.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Although this works, it is visually unappealing. We can improve on this using styles and themes. | import tkinter as tk
from tkinter import ttk
class Application(ttk.Frame):
def __init__(self, master=None):
super().__init__(master, padding="3 3 12 12")
self.grid(column=0, row=0, )
self.createWidgets()
self.master.title('Test')
def createWidgets(self):
self.hi_there ... | Wk04/Wk04-GUI.ipynb | briennakh/BIOF509 | mit |
As our applications get more complicated we must give greater thought to the layout. The following example comes from the TkDocs site. | from tkinter import *
from tkinter import ttk
def calculate(*args):
try:
value = float(feet.get())
meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
except ValueError:
pass
root = Tk()
root.title("Feet to Meters")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(... | Wk04/Wk04-GUI.ipynb | briennakh/BIOF509 | mit |
Matplotlib
For simple programs, displaying data and taking basic input, often a command line application will be much faster to implement than a GUI. The times when I have moved away from the command line it has been to interact with image data and plots. Here, matplotlib often works very well. Either it can be embedde... | """
Do a mouseclick somewhere, move the mouse to some destination, release
the button. This class gives click- and release-events and also draws
a line or a box from the click-point to the actual mouseposition
(within the same axes) until the button is released. Within the
method 'self.ignore()' it is checked wether ... | Wk04/Wk04-GUI.ipynb | briennakh/BIOF509 | mit |
Load and prepare the data
Import data from static tumbling csv file | static_tumbling = pd.read_csv('static-tumbling.csv') | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Separate the data into features and targets | elements, score = static_tumbling['elements'], static_tumbling['score'] | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Generate global vocabulary | #Main vocabulary, based on the data set elements
main_vocab = set()
for line in elements:
for element in line.split(" "):
main_vocab.add(element)
main_vocab = list(main_vocab)
#Expanded vocabulary based on 49 permutations of the posible transitions
vocab = list(main_vocab)
for roll in product(ma... | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Create dictionary to map each element to an index | word2idx = {word: i for i, word in enumerate(vocab)}
word2idx | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Text to vector fucntion
It will convert the elements to a vector of words | def text_to_vector(text):
word_vector = np.zeros(len(vocab), dtype=np.int_)
text_vector = text.split(' ')
#basic vocab matching
for element in text_vector:
idx = word2idx.get(element, None)
if idx is None:
continue
else:
word_vector[idx] += 1
... | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Convert all static tumbling passes to vectors | word_vectors = np.zeros((len(elements), len(vocab)), dtype=np.int_)
for ii, text in enumerate(elements):
word_vectors[ii] = text_to_vector(text)
word_vectors | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Train, validation, Tests sets
Now that we have the word_vectors, we're ready to split our data into train, validation, and test sets. Remember that we train on the train data, use the validation data to set the hyperparameters, and at the very end measure the network performance on the test data. | Y = (score).astype(np.float_)
records = len(score)
shuffle = np.arange(records)
np.random.shuffle(shuffle)
test_fraction = 0.9
#Y values are one dimentional array of shape (1, N) in order to get the dot product we need it in the form
# (N, 1) so that's why i'm using `Y.values[train_split,None]`
train_split, test_spli... | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Building the network | # Network building
def build_model():
# This resets all parameters and variables, leave this here
tf.reset_default_graph()
#Input
net = tflearn.input_data([None, 56])
#Hidden
net = tflearn.fully_connected(net, 350, activation='sigmoid')
net = tflearn.fully_connected(net, 150, activation='sig... | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Initializing the model | model = build_model() | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Training the network | # Training
model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=128, n_epoch=2000) | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
I know total loss is still to high, but not that bad for the first round of hyper parameters, still room for total loss improvement
Saving de model | # Load model
# model.load('Checkpoints/model-with-transitions-with-3-layers.tfl')
# Manually save model
model.save("Checkpoints/model-with-transitions-with-3-layers.tfl") | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Testing | # Helper function that uses our model to get the score for the static tumbling pass
def test_score(sentence):
score = model.predict([text_to_vector(sentence.lower())])
print('Gym pass: {}'.format(sentence))
print('Score: {}'.format(score))
print()
return score
# Helper function that uses our model ... | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Now we check the accuracy of the mode, this test checks which static tumbling line is more difficult, the second one is not even in the data we trianed the neural network.
First we compare to static tumblin pass that has the same elements but different transition cost or effort,
acording to flick mortal and mortal fli... | element1 = "flick mortal"
element2 = "mortal flick"
test_compare(element1,element2) | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Now test the model with data that wasn't in the data set
in this complex example the second element is a lot harder to execute | test_element1 = "flick flick flick flick flick mortal giro giro giro2"
test_element2 = "mortal flick giro flick giro mortal giro2 giro2 giro2"
test_compare(test_element1,test_element2) | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Test data validation
Now the test values we separeted from the begining are going to be compared with the actual values to check model accuracy | fig, ax = plt.subplots(figsize=(15,6))
predictions = model.predict(testX)
ax.plot(predictions,label='Prediction')
ax.plot(testY, label='Data')
ax.set_xlim(right=len(predictions))
ax.legend() | Static_tumbling_nn.ipynb | steelcolosus/static.tumbling.neural.network | mit |
Hyperparameterers | # data
num_epochs = 10 # train for 400 epochs for good results
image_size = 64
# resolution of Kernel Inception Distance measurement, see related section
kid_image_size = 75
padding = 0.25
dataset_name = "caltech_birds2011"
# adaptive discriminator augmentation
max_translation = 0.125
max_rotation = 0.125
max_zoom = ... | examples/generative/ipynb/gan_ada.ipynb | keras-team/keras-io | apache-2.0 |
Data pipeline
In this example, we will use the
Caltech Birds (2011) dataset for
generating images of birds, which is a diverse natural dataset containing less then 6000
images for training. When working with such low amounts of data, one has to take extra
care to retain as high data quality as possible. In this example... |
def round_to_int(float_value):
return tf.cast(tf.math.round(float_value), dtype=tf.int32)
def preprocess_image(data):
# unnormalize bounding box coordinates
height = tf.cast(tf.shape(data["image"])[0], dtype=tf.float32)
width = tf.cast(tf.shape(data["image"])[1], dtype=tf.float32)
bounding_box = ... | examples/generative/ipynb/gan_ada.ipynb | keras-team/keras-io | apache-2.0 |
After preprocessing the training images look like the following:
Kernel inception distance
Kernel Inception Distance (KID) was proposed as a
replacement for the popular
Frechet Inception Distance (FID)
metric for measuring image generation quality.
Both metrics measure the difference in the generated and training dist... |
class KID(keras.metrics.Metric):
def __init__(self, name="kid", **kwargs):
super().__init__(name=name, **kwargs)
# KID is estimated per batch and is averaged across batches
self.kid_tracker = keras.metrics.Mean()
# a pretrained InceptionV3 is used without its classification layer
... | examples/generative/ipynb/gan_ada.ipynb | keras-team/keras-io | apache-2.0 |
Adaptive discriminator augmentation
The authors of StyleGAN2-ADA propose to change the
augmentation probability adaptively during training. Though it is explained differently
in the paper, they use integral control on the augmentation
probability to keep the discriminator's accuracy on real images close to a target val... | # "hard sigmoid", useful for binary accuracy calculation from logits
def step(values):
# negative values -> 0.0, positive values -> 1.0
return 0.5 * (1.0 + tf.sign(values))
# augments images with a probability that is dynamically updated during training
class AdaptiveAugmenter(keras.Model):
def __init__(s... | examples/generative/ipynb/gan_ada.ipynb | keras-team/keras-io | apache-2.0 |
Network architecture
Here we specify the architecture of the two networks:
generator: maps a random vector to an image, which should be as realistic as possible
discriminator: maps an image to a scalar score, which should be high for real and low
for generated images
GANs tend to be sensitive to the network architect... | # DCGAN generator
def get_generator():
noise_input = keras.Input(shape=(noise_size,))
x = layers.Dense(4 * 4 * width, use_bias=False)(noise_input)
x = layers.BatchNormalization(scale=False)(x)
x = layers.ReLU()(x)
x = layers.Reshape(target_shape=(4, 4, width))(x)
for _ in range(depth - 1):
... | examples/generative/ipynb/gan_ada.ipynb | keras-team/keras-io | apache-2.0 |
GAN model |
class GAN_ADA(keras.Model):
def __init__(self):
super().__init__()
self.augmenter = AdaptiveAugmenter()
self.generator = get_generator()
self.ema_generator = keras.models.clone_model(self.generator)
self.discriminator = get_discriminator()
self.generator.summary()
... | examples/generative/ipynb/gan_ada.ipynb | keras-team/keras-io | apache-2.0 |
Training
One can should see from the metrics during training, that if the real accuracy
(discriminator's accuracy on real images) is below the target accuracy, the augmentation
probability is increased, and vice versa. In my experience, during a healthy GAN
training, the discriminator accuracy should stay in the 80-95%... | # create and compile the model
model = GAN_ADA()
model.compile(
generator_optimizer=keras.optimizers.Adam(learning_rate, beta_1),
discriminator_optimizer=keras.optimizers.Adam(learning_rate, beta_1),
)
# save the best model based on the validation KID metric
checkpoint_path = "gan_model"
checkpoint_callback = ... | examples/generative/ipynb/gan_ada.ipynb | keras-team/keras-io | apache-2.0 |
Inference | # load the best model and generate images
model.load_weights(checkpoint_path)
model.plot_images() | examples/generative/ipynb/gan_ada.ipynb | keras-team/keras-io | apache-2.0 |
Wood products DF with and without logging slash utilization
Using studies from Sathre and O'Connor in the US. | HWu = pd.read_sql('''SELECT *
FROM so4
WHERE harvestslash = "X"
AND processingresidues = "X"
AND "post-usewoodproduct" = "X"
AND stumps is null''', sqdb['cx'],index_col = 'index')
HWo = pd.read_sql('... | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Timber Products Output
The TPO estimates logging redisues produced from commercial timber harvesting operations. The follwoing is in million cubic feet (MCF) | tpoData = ut.gData('1GDdquzrCoq2cxVN2fbCpP4gwi2yrMnONNrWbfhZKZu4', 872275354, hrow=1)
tpoData.to_sql('tpo', sqdb['cx'], if_exists = 'replace')
print tabulate(tpoData, headers = ['Ownership','Roundwood Products','Logging Residues', 'Year'],tablefmt="pipe") | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Board of Equalization Data
The board of equalization | pd.read_csv('boe_hh.csv').to_sql('boe',sqdb['cx'], if_exists = 'replace')
pd.read_sql('select * from boe', sqdb['cx']) | wood_fates.ipynb | peteWT/fcat_biomass | mit |
McIver and Morgan annual in cubic
Figure 2 from morgan and mciver presents total roundwood harvest from 1947 through 2012 in MMBF. To convert MMBF to MCF we use a sawlog conversion of 5.44. This is an approximation as the actual sawlog conversion varies with the log size on average over time has changed. | mm_histHarvest = ut.gData('13UQtRfNBSJ81PXxbYSnB2LrjHePNcvhJhrsxRBjHpoY', 2081880100).fillna(value=0)
mm_histHarvest.to_sql('mm_hist', sqdb['cx'], if_exists = 'replace')
mm_histHarvest | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Bioenergy consumption
To apply the apropriate DF for harvested wood we need to know what fraction of the logging residues were utilized as bioenergy feedstock. McIver and Morgan (Table 6) reports bioenergy consumption from 2000 forward. For years previous, we use the average bioenergy consumption from 2000 -- 2012. | bioEnergy = ut.gData('138FWlGeW57MKdcz2UkWxtWV4o50SZO8sduB1R6JOFp8', 529610043)
bioEnergy.set_index('producttype').transpose().to_sql('mciver_bio', sqdb['cx'], if_exists = 'replace')
bio_pct = pd.read_sql('select "index" as year,"Bioenergy"/100 as biopct from mciver_bio where "Bioenergy" is not null', sqdb['cx'])
bio_d... | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Logging residuals
The BOE data does not specifically estimate logging residuals, it simply reports harvested roundwood. To accurately ascribe fate to roundwood harvested, an estimation of logging residuals must be made
Calculating emissions reductions
The following functions calculate the displaced emissions resulting ... | def WPu (rw_harvest, lr, year, mill_efficiency = constants['me']['value'], wdens = constants['wDens']['value'], df = constants['DFu']['value']):
'''
Calculates the emissions reduction resulting from harvested wood with with utilization of loggin residuals for bioenergy
'''
# establish the aproporiate bi... | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Emissions reduction from harvested wood with LR utilized
Emissions reductions resulting from harvested roundwood with logging residue utilized in bioenergy | erWPu = []
for row in tpoData.index:
rw,lr,yr = tpoData.iloc[row][['roundwoodproducts','loggingresidues', 'year']].tolist()
erWPu.append(WPu(rw,lr,yr))
tpoData['erWPu'] = erWPu
erWPo = []
for row in tpoData.index:
rw,lr,yr = tpoData.iloc[row][['roundwoodproducts','loggingresidues', 'year']].tolist()
er... | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Emissions reduction from harvested wood without LR utilization
Emissions reductions resulting from harvested roundwood without logging residue utilized in bioenergy. Though wood with LR utilization rate has a higher displacement factor, the majority of loggin residues wer not utilized. | tpoData['erTotal'] = tpoData.erWPo+tpoData.erWPu
tpoData.to_sql('tpo_emreduc', sqdb['cx'], if_exists='replace')
tpoData['bioe_pct'] = tpoData.year.apply(bioPct)
tpoData['bioe_t'] = tpoData.bioe_pct * tpoData.loggingresidues * 1e6* constants['wDens']['value']/2204.62 | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Using M&M Historical data | erWPo = []
for row in mm_histHarvest.index:
r = mm_histHarvest.iloc[row]
yr = r['year'] ## year
rw = (r.state+r.private+r.tribal+r.blm+r.nat_forest)/5.44
qry = 'select avg(loggingresidues/roundwoodproducts) lr from tpo where year = {}'.format(yr)
if yr in tpoData.year.tolist():
lr = pd.read... | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Total emissions reduction from harvested wood products
Sum of emissions reductions from harvested wood with and without LR utilization | mm_histHarvest['erTotal'] = mm_histHarvest.erWPo+mm_histHarvest.erWPu
mm_histHarvest.to_sql('mm_emreduc', sqdb['cx'], if_exists='replace')
mm_histHarvest['bioe_pct'] = mm_histHarvest.year.apply(bioPct)
mm_histHarvest['bioe_t'] = mm_histHarvest.bioe_pct * mm_histHarvest.loggingresidues * 1e6* constants['wDens']['value']... | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Total emissions reductions from roundwood harvesting in CA, 2012 | pd.read_sql('select sum("erTotal") from tpo_emreduc where year = "2012"', sqdb['cx']) | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Emissions from un-utilized logging residuals
From logging residuals not used in bioenergy, emmisions are produced from combustion of the residual material or from decomposition of the material over time. To calculate the ratio of burned to decompsed logging residues I begin with the CARB estimate of PM2.5 produced from... | tName = 'cpe_allyears'
sqdb['crs'].executescript('drop table if exists {0};'.format(tName))
for y in [2000, 2005, 2010, 2012, 2015]:
url = 'http://www.arb.ca.gov/app/emsinv/2013/emsbyeic.csv?F_YR={0}&F_DIV=0&F_SEASON=A&SP=2013&SPN=2013_Almanac&F_AREA=CA'
df = pd.read_csv(url.format(y))
df.to_sql(tName, sqdb... | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Estimate biomass, CO2, CH4 and BC from PM2.5
To estimate total biomass from PM2.5 I assume 90% consumption of biomass in piles and use the relationship of pile tonnage to PM emissions calculated using the Piled Fuels Biomass and Emissions Calculator provided by the Washington State Department of Natural resources. This... | pfbec = pd.read_csv('fera_pile_cemissions.csv', header=1)
ward = ut.gData('13UQtRfNBSJ81PXxbYSnB2LrjHePNcvhJhrsxRBjHpoY', 475419971)
def sp2bio(pm, species = 'PM2.5 (tons)'):
return pm * (pfbec[species]/pfbec['Pile Biomass (tons)'])
def bioPm(pm):
return pm * (pfbec['Pile Biomass (tons)']/pfbec['PM2.5 (tons)']... | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Estimating GHG emissions from decomposition of unitilized logging slash
To provide a full picture of the emissions from residual material produced from commercial timber harvesting in California, decomposition of unutilized logging residuals left on-site that are not burned must be accounted for. To establish the fract... | annLrAvg = pd.read_sql('''with ann as (select sum(loggingresidues) lr
from tpo
group by year)
select avg(lr) foo
... | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Biomass residuals from non-commercial management activities
Data from TPO does not account for forest management activities that do not result in commercial products (timber sales, biomass sales). To estimate the amount of residual material produced from non commercial management activities we use data from the US Fore... | pd.read_excel('lf/FACTS_Tabular_092115.xlsx', sheetname = 'CategoryCrosswalk').to_sql('facts_cat', sqdb['cx'], if_exists = 'replace')
pd.read_csv('pd/facts_notimber.csv').to_sql('facts_notimber', sqdb['cx'], if_exists='replace') | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Querying FACTS
The USFS reports Hazardous Fuels Treatment (HFT) activities as well as Timber Sales (TS) derived from the FACTS database. We use these two datasets to estimate the number of acres treated that did not produce commercial material (sawlogs or biomass) and where burning was not used. The first step is to el... | usfs_acres = pd.read_sql('''select
sum(nbr_units1) acres,
method,
strftime('%Y',date_compl) year,
cat."ACTIVITY" activity,
cat."TENTATIVE_CATEGORY" r5_cat
... | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Converting acres to cubic feet
FACTS reports in acres. To estimate the production of biomass from acres treated we use a range of 10-35 BDT/acre. We assume that actual biomass residuals per acre are normally distributed with a mean of 22.5 and a standard deviation of (35-10)/4 = 6.25 | def sumBDT(ac, maxbdt = 35, minbdt = 10):
av = (maxbdt + minbdt)/2
stdev = (float(maxbdt) - float(minbdt))/4
d_frac = (ac-np.floor(ac))*np.random.normal(av, stdev, 1).clip(min=0)[0]
t_bdt = np.sum(np.random.normal(av,stdev,np.floor(ac)).clip(min=0))
return d_frac+t_bdt
usfs_acres['bdt'] = usfs_acr... | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Weighted average wood density
Average wood density weighted by harvested species percent. Derived from McIver and Morgan, Table 4 | wood_dens = ut.gData('138FWlGeW57MKdcz2UkWxtWV4o50SZO8sduB1R6JOFp8', 1297253755)
wavg_dens =sum(wood_dens.pct/100 * wood_dens.density_lbscuft) | wood_fates.ipynb | peteWT/fcat_biomass | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.