markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
<img src="static/conda-names.png" style="margin: 0 auto;" />
(From http://conda.pydata.org/docs/building/pkg-name-conv.html) | !conda install pytest-benchmark --use-local --yes | talks_materials/20160409_1130_Embrace_conda_packages/Embrace conda packages.ipynb | PyDataMadrid2016/Conference-Info | mit |
Build, test, upload, repeat
Custom packages can be uploaded to Anaconda Cloud https://anaconda.org/
This process can be automated through Anaconda Build http://docs.anaconda.org/build.html
Later on we can use our custom channels to install non-official packages
<img src="static/anaconda-cloud.png" style="margin: 0 au... | !conda install anaconda-client --quiet --yes
!anaconda upload ~/.miniconda3/conda-bld/linux-64/pytest-benchmark-3.0.0-py35_0.tar.bz2 | talks_materials/20160409_1130_Embrace_conda_packages/Embrace conda packages.ipynb | PyDataMadrid2016/Conference-Info | mit |
And now, let's install it! | !conda remove pytest-benchmark --yes > /dev/null
!conda install pytest-benchmark --channel juanlu001 --yes | talks_materials/20160409_1130_Embrace_conda_packages/Embrace conda packages.ipynb | PyDataMadrid2016/Conference-Info | mit |
Some more tricks
Running the tests
You can run your tests with Python, Perl or shell scripts (run_test.[py,pl,sh,bat])
Convert pure Python packages to other platforms
Using conda convert for pure Python packages, we can quickly provide packages for other platforms | !conda convert ~/.miniconda3/conda-bld/linux-64/pytest-benchmark-3.0.0-py35_0.tar.bz2 --platform all | grep Converting | talks_materials/20160409_1130_Embrace_conda_packages/Embrace conda packages.ipynb | PyDataMadrid2016/Conference-Info | mit |
Read CSV with Labels | with open(LABELS_FILE, newline='') as f:
reader = csv.DictReader(f)
# each public id is unique and set operation will be usefull later
spectra_idents = set(map(lambda x: x['id'], reader))
len(spectra_idents) | notebooks/01-data-download.ipynb | podondra/bt-spectraldl | gpl-3.0 |
Simple Spectral Access protocol
This is not much revlevant now since only datalink is used
to download normalized spectra.
SSAP, SSA defines a uniform intreface to remotely discover
and access one dimenisonal spectra. Spectral data access
mmay involve active transformation of data. SSA also
defines complete metadata to... | def request_url(url):
'''Make HTTP request and return response data.'''
try:
with urllib.request.urlopen(url) as response:
data = response.read()
except Exception as e:
print(e)
return None
return data | notebooks/01-data-download.ipynb | podondra/bt-spectraldl | gpl-3.0 |
Datalink
Datalink is a service for working with spectra.
For information about the one which is used here see http://voarchive.asu.cas.cz/ccd700/q/sdl/info. | datalink_service = 'http://voarchive.asu.cas.cz/ccd700/q/sdl/dlget'
def make_datalink_url(
pub_id, fluxcalib=None, wave_min=None, wave_max=None,
file_format='application/fits', url=datalink_service
):
url_parameters = {'ID': pub_id}
if fluxcalib:
url_parameters['FLUXCALIB'] = fluxcalib
if w... | notebooks/01-data-download.ipynb | podondra/bt-spectraldl | gpl-3.0 |
Show fluxcalib Parameters
To show how to work with datalink
and what it offers.
From this is obvious that the 'normalized' setting is the desired. | def plot_fluxcalib(fluxcalib, ax):
# create the datalink service URL
datalink_url = make_datalink_url('ivo://asu.cas.cz/stel/ccd700/sh270028', fluxcalib=fluxcalib)
# download the data
fits_data = request_url(datalink_url)
# open the data as file
hdulist = fits.open(io.BytesIO(fits_data))
# p... | notebooks/01-data-download.ipynb | podondra/bt-spectraldl | gpl-3.0 |
FITS Download | def download_spectrum(pub_id, n, directory, fluxcalib, minimum=None, maximum=None):
# get the name from public id
name = pub_id.split('/')[-1]
# directory HAS TO end with '/'
path = directory + name + '.fits'
url = make_datalink_url(pub_id, fluxcalib, minimum, maximum)
print('{:5} downloadi... | notebooks/01-data-download.ipynb | podondra/bt-spectraldl | gpl-3.0 |
We can use the gpio and timer components in concert to flash an LED connected to G1. The timer header provides PWM and program delay functionality, although only one can be used simultaneously. | %%microblaze base.PMODA
#include <timer.h>
#include <gpio.h>
#include <pmod_grove.h>
void flash_led() {
gpio led = gpio_open(PMOD_G1_A);
gpio_set_direction(led, GPIO_OUT);
int state = 0;
while (1) {
gpio_write(led, state);
state = !state;
delay_ms(500);
}
}
flash_led() | boards/Pynq-Z1/base/notebooks/microblaze/microblaze_c_libraries.ipynb | cathalmccabe/PYNQ | bsd-3-clause |
pyprintf
The pyprint library exposes a single pyprintf function which acts similarly to a regular printf function but forwards arguments to Python for formatting and display result in far lower code overhead than a regular printf as well as not requiring access to standard in and out. | %%microblaze base.PMODA
#include <pyprintf.h>
int test_print(float value) {
pyprintf("Printing %f from the Microblaze!\n", value);
return 0;
}
test_print(1.5) | boards/Pynq-Z1/base/notebooks/microblaze/microblaze_c_libraries.ipynb | cathalmccabe/PYNQ | bsd-3-clause |
Equal Placement Ballots
The equal placement ballot assumes that any position on the ballot is equal to any other. And given that this how the voting was designed, it makes the most sense to look at this first. There are some differences, but given that /u/kaptain_carbon was tallying by hand, and I manually copy-pasted ... | vote_table(tallied.most_common(10)) | top-ten-experiment/analyzing_top_ten_lists.ipynb | justanr/notebooks | mit |
And here's the top ten from my computed tally: | vote_table(equal_placement_ballots.most_common(10)) | top-ten-experiment/analyzing_top_ten_lists.ipynb | justanr/notebooks | mit |
Weighted Tally Ballot
But that's boring. What if we pretended for a second that everyone submitted a ballot where the albums were actually ranked one through five. What would the top ten look like then? There's a few ways to figure this one out. Initially, my thought was to provide a number 1 to 5 based on position to ... | weighted_ballot = Counter()
for ballot in ballots:
for item, weight in zip(ballot, range(5, 0, -1)):
weighted_ballot[item] += weight | top-ten-experiment/analyzing_top_ten_lists.ipynb | justanr/notebooks | mit |
This handles the situation where a ballot may not be full (five votes), which make up a surpsingly non trival amount of the ballots: | sum(1 for _ in filter(lambda x: len(x) < 5, ballots)) / len(ballots) | top-ten-experiment/analyzing_top_ten_lists.ipynb | justanr/notebooks | mit |
Anyways, what does a top ten for weighted votes end up looking like? | vote_table(weighted_ballot.most_common(10)) | top-ten-experiment/analyzing_top_ten_lists.ipynb | justanr/notebooks | mit |
Hm, it's not actually all the different. Some bands move around a little bit, Deathhammer moves into the top ten using this method. But overall, the general spread is pretty much the same.
It's also interesting to look at the difference in position from the weighted tally vs the way it's done in the thread. There's maj... | regular_tally_spots = {name.lower(): pos for pos, (name, _) in enumerate(tallied.most_common(), 1)}
base_table = """
<table>
<tr><td>Album</td><td>Regular Spot</td><td>Weighted Spot</td></tr>
{}
</table>
"""
base_row = "<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>"
rows = [base_row.format(name, regular_tally... | top-ten-experiment/analyzing_top_ten_lists.ipynb | justanr/notebooks | mit |
What album appeared at number one most often?
Another question I've been pondering is, "How do you figure out what thing appears at number one most often?" Again, this is assuming everyone submitted a ballot with the intention of it being read as ranked. Turns out, doing this isn't that hard either: | number_one = Counter([b[0] for b in ballots])
vote_table(number_one.most_common(10)) | top-ten-experiment/analyzing_top_ten_lists.ipynb | justanr/notebooks | mit |
This paints a slightly different picture of the top ten. While the names are largely the same, Scar Sighted was thought of as the top album most often, despite being at two or three through the other methods. And Misþyrming is at four (okay, "2", again fast and loose with numbering) despite being the solid top choice f... | #regular tallying
vote_table(equal_placement_ballots.most_common())
#weighted ballot
vote_table(weighted_ballot.most_common())
#number one count
vote_table(number_one.most_common()) | top-ten-experiment/analyzing_top_ten_lists.ipynb | justanr/notebooks | mit |
Instrumental Variables Estimation
This section is taken from Chapter 10 of Methods Matter by Richard Murnane and John Willett. The descriptions are taken from Wikipedia, for copyright reasons.
In statistics, econometrics, epidemiology and related disciplines, the method of instrumental variables (IV) is used to estimat... | # THINGS TO IMPORT
# This is a baseline set of libraries I import by default if I'm rushed for time.
import codecs # load UTF-8 Content
import json # load JSON files
import pandas as pd # Pandas handles dataframes
import numpy as np # Numpy handles... | instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
Acquire Dee Dataset from Methods Matter | import urllib2
import os.path
if(os.path.isfile("dee.dta")!=True):
response = urllib2.urlopen("http://www.ats.ucla.edu/stat/stata/examples/methods_matter/chapter10/dee.dta")
if(response.getcode()==200):
f = open("dee.dta","w")
f.write(response.read())
f.close()
dee_df = pd.read_stata("de... | instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
Summary Statistics | dee_df[['register','college', 'distance']].describe() | instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
Cross-Tabulation | print pd.crosstab(dee_df.register, dee_df.college)
chi2 = scipy.stats.chi2_contingency(pd.crosstab(dee_df.register, dee_df.college))
print "chi2: %(c)d" % {"c":chi2[0]}
print "p: %(p)0.03f" % {"p":chi2[1]}
print "df: %(df)0.03f" % {"df":chi2[2]}
print "expected:"
print chi2[3] | instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
Correlation Matrix | sns.corrplot(dee_df[['register','college','distance']]) | instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
Linear Regression of REGISTER on COLLEGE | result = smf.ols(formula = "register ~ college", data = dee_df).fit()
print result.summary()
| instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
Two-Stage Least Squares Regression of REGISTER ~ COLLEGE where IV=DISTANCE
using statsmodels.formula.api.ols
In two-stage least squares regression, we regress COLLEGE on DISTANCE and use the predictions from that model as the predictors for REGISTER. | print "=============================================================================="
print " FIRST STAGE"
print "=============================================================================="
result = smf.ols(formula = "college ~ distance", data = dee_df).fit()
print result.summary()... | instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
^^^^^^ Not sure what's going on with the R2 statistic here (it's 0.001 here, versus 0.022 in the example), although everything else matches what we see from the Stata output in the published example
Adding Covariates that do not satisfy the requirements of instrumental variables
In the case of the covariate of race/et... | sns.corrplot(dee_df[['register','college','distance', 'black','hispanic','otherrace']]) | instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
Two-Stage Least Squares Regression of REGISTER ~ COLLEGE + BLACK + HISPANIC + OTHERRACE where IV=DISTANCE | print "=============================================================================="
print " FIRST STAGE"
print "=============================================================================="
result = smf.ols(formula = "college ~ distance + black + hispanic + otherrace", data = dee_d... | instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
Interactions Between the Endogenous Question Predictor and Exogenous Covariates in the Second Stage Model
In this case, we explore whether interactions between college and race/ethnicity are significant predictors of voter registration. Here, it's important to meet the "rank condition": that "for every endogenous predi... | print "=============================================================================="
print " FIRST STAGE"
print "=============================================================================="
# generate the stage one main effect instrument
result = smf.ols(formula = "college ~ distan... | instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
^^^ in this particular case, we find no significant interactions and fall back on our previous model, which simply included race/ethnicity as a covariate
Binomial Regression: Logistic Model
In this example, we use a logistic model with a two-stage least-squares regression. NOTE: This is not attempted in the textbook ex... | print "=============================================================================="
print " FIRST STAGE"
print "=============================================================================="
result = smf.glm(formula = "college ~ distance + black + hispanic + otherrace",
... | instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
Binomial Regression: Probit Model
In this example, we use a probit model with a two-stage least-squares regression. NOTE: This is not attempted in the textbook example, so I cannot be completely certain about this, unlike the above results. | import patsy
print "=============================================================================="
print " FIRST STAGE"
print "=============================================================================="
a,b = patsy.dmatrices("college ~ distance + black + hispanic + otherrace",
... | instrumental_variables_estimation/Instrumental-Variables Estimation.ipynb | natematias/research_in_python | mit |
Some useful methods to train | from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
"""
Function
--------
def cv_optimize(clf, parameters, Xtrain, ytrain, n_folds=5)
Performs cross validation of n_folds using a list of values for a chosen parameter (say regularization parameter, C) and returns
the param... | Chart_Samples.ipynb | xpmanoj/content | mit |
Getting the data
Get json data | import simplejson as json
with open('./data/us_state_map.geojson','r') as fp:
statedata = json.load(fp)
with open('./data/us_county_map.geojson','r') as fp:
data = json.load(fp) | Chart_Samples.ipynb | xpmanoj/content | mit |
Get json data from url | #your code here
def get_senate_vote(vote):
url = 'https://www.govtrack.us/data/congress/113/votes/2013/s'+str(vote)+'/data.json'
vote_data = requests.get(url)
return json.loads(vote_data.text) | Chart_Samples.ipynb | xpmanoj/content | mit |
Get data from a url using beautiful soup | #Your code here
def get_all_votes():
url = 'http://www.govtrack.us/data/congress/113/votes/2013'
response = requests.get(url)
soup = bs(response.content, "lxml")
s_votes = [a['href'][1:-1] for a in soup.find_all('a')
if a['href'].startswith('s')]
return [get_senate_vote(vote) for vote... | Chart_Samples.ipynb | xpmanoj/content | mit |
Useful functions and tricks | fulldf=pd.read_csv("bigdf.csv") | Chart_Samples.ipynb | xpmanoj/content | mit |
Recompute dataframe
The following function is used to re-compute review counts and averages whenever you subset a reviews data frame. We'll use it soon to construct a smaller, more computationally tractable data frame. | def recompute_frame(ldf):
"""
takes a dataframe ldf, makes a copy of it, and returns the copy
with all averages and review counts recomputed
this is used when a frame is subsetted.
"""
ldfu=ldf.groupby('user_id')
ldfb=ldf.groupby('business_id')
user_avg=ldfu.stars.mean()
user_review_... | Chart_Samples.ipynb | xpmanoj/content | mit |
Compute Common Support
The common support is an important concept, as for each pair of restaurants, its the number of people who reviewed both. It will be used to modify similarity between restaurants. If the common support is low, the similarity is less believable. | restaurants=smalldf.business_id.unique() #get all the unique restaurant ids
supports=[]
for i,rest1 in enumerate(restaurants): # first restaurant (rest1) in the pair
for j,rest2 in enumerate(restaurants): # second restaurant(rest2) in the pair
if i < j: #skip pairing same restaurants and forming duplicat... | Chart_Samples.ipynb | xpmanoj/content | mit |
Return X (column value) from a df given Y (another column value) | # test business id
testbizid="eIxSLxzIlfExI6vgAbn2JA"
# Return business name from a df given id
def biznamefromid(df, theid):
return df['biz_name'][df['business_id']==theid].values[0]
print testbizid, biznamefromid(smalldf,testbizid) | Chart_Samples.ipynb | xpmanoj/content | mit |
Plotting the data
Histograms
Simulating Elections | predictwise = pd.read_csv('data/predictwise.csv').set_index('States')
predictwise.head(10)
#Your code here
def simulate_election(model, n_sim):
simulations = np.random.uniform(size= (51,n_sim))
obama_votes = (simulations < model.Obama.values.reshape(-1,1))* model.Votes.values.reshape(-1,1)
results = obama... | Chart_Samples.ipynb | xpmanoj/content | mit |
Movie Reviews | # import data
critics = pd.read_csv('critics.csv') # Rotten Tomatoes Top Critics Reviews Data for about 3000 movies
# clean data
critics = critics[~critics.quote.isnull()]
critics = critics[critics.fresh.notnull()]
critics = critics[critics.quote.str.len() > 0]
critics = critics.reset_index(drop = True)
critics.head() | Chart_Samples.ipynb | xpmanoj/content | mit |
What does the distribution of number of reviews per reviewer look like? | plt.hist(critics.groupby('critic').rtid.count(),log = True, bins=range(20), edgecolor='white')
plt.xlabel("Number of reviews per critic")
plt.ylabel("N")
histogram_style()
| Chart_Samples.ipynb | xpmanoj/content | mit |
Of the critics with > 100 reviews, plot the distribution of average "freshness" rating per critic | df = critics.copy()
df['fresh'] = df.fresh == 'fresh'
grp = df.groupby('critic')
counts = grp.rtid.count()
means = grp.fresh.mean()
means[counts > 100].hist(bins=10, edgecolor='w', lw=1)
plt.xlabel("Average rating per critic")
plt.ylabel("N")
plt.yticks([0, 2, 4, 6, 8, 10])
histogram_style() | Chart_Samples.ipynb | xpmanoj/content | mit |
Using the original movies dataframe, plot the rotten tomatoes Top Critics Rating as a function of year. Overplot the average for each year, ignoring the score=0 examples (some of these are missing data). | # Get the data
from io import StringIO
movie_txt = requests.get('https://raw.github.com/cs109/cs109_data/master/movies.dat').text
movie_file = StringIO(movie_txt) # treat a string like a file
movies = pd.read_csv(movie_file, delimiter='\t')
movies = movies.dropna()
movies = movies.reset_index(drop = True)
# process ... | Chart_Samples.ipynb | xpmanoj/content | mit |
This graph shows a trend towards a lower average score, as well as a greater abundance of low scores, with time. This is probably at least partially a selection effect -- Rotten Tomatoes probably doesn't archive reviews for all movies, especially ones that came out before the website existed. Thus, reviews of old movie... | df=pd.read_csv("01_heights_weights_genders.csv")
df.head()
from sklearn.linear_model import LogisticRegression
clf_l, Xtrain_l, ytrain_l, Xtest_l, ytest_l = do_classify(LogisticRegression(), {"C": [0.01, 0.1, 1, 10, 100]}, df, ['Weight', 'Height'], 'Gender','Male')
plt.figure(figsize =(12,8))
plt.xlabel("Weight")
pl... | Chart_Samples.ipynb | xpmanoj/content | mit |
Let us plot the probabilities obtained from predict_proba, overlayed on the samples with their true labels: | plt.figure(figsize =(12,8))
plt.grid(True)
ax=plt.gca()
points_plot_prob(ax, Xtrain_l, Xtest_l, ytrain_l, ytest_l, clf_l, psize=20, alpha=0.1); | Chart_Samples.ipynb | xpmanoj/content | mit |
Linear Discriminant Analysis | from sklearn.lda import LDA
clflda = LDA(solver="svd", store_covariance=True)
clflda.fit(Xtrain_l, ytrain_l)
#from REF
from scipy import linalg
def plot_ellipse(splot, mean, cov, color):
v, w = linalg.eigh(cov)
u = w[0] / linalg.norm(w[0])
angle = np.arctan(u[1] / u[0])
angle = 180 * angle / np.pi # ... | Chart_Samples.ipynb | xpmanoj/content | mit |
Calibration Plot | dfd=pd.read_csv("https://dl.dropboxusercontent.com/u/75194/pima.csv")
dfd.head()
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
features=['npreg', 'bmi','diaped', 'age', 'glconc','insulin']
X=dfd[features].values
y=dfd.diabetes.values
from sklearn.naive_bayes import ... | Chart_Samples.ipynb | xpmanoj/content | mit |
Coin tosses: Binomial-Beta | plt.figure(figsize=(11, 9))
import scipy.stats as stats
beta = stats.beta
n_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]
data = stats.bernoulli.rvs(0.5, size=n_trials[-1])
x = np.linspace(0, 1, 100)
# For the already prepared, I'm using Binomial's conj. prior.
for k, N in enumerate(n_trials):
sx = plt.subplot(len... | Chart_Samples.ipynb | xpmanoj/content | mit |
Gaussian with known $\sigma$ | Y = [16.4, 17.0, 17.2, 17.4, 18.2, 18.2, 18.2, 19.9, 20.8]
# Prior mean
mu_prior = 19.5
# prior std
tau = 10
N = 15000
#Data Quantities
sig = np.std(Y) # assume that is the value of KNOWN sigma (in the likelihood)
mu_data = np.mean(Y)
n = len(Y)
kappa = sig**2 / tau**2
sig_post =np.sqrt(1./( 1./tau**2 + n/sig**2));
#... | Chart_Samples.ipynb | xpmanoj/content | mit |
The function defined in the following cell uses a copula approach to simulate correlated random values that marginally follow a negative binomial distribution. The input parameter u is an array of values in (0, 1). The elements of u must be marginally uniformly distributed on (0, 1). Correlation in u will induce cor... | def negbinom(u, mu, scale):
p = (scale - 1) / scale
r = mu * (1 - p) / p
x = np.random.gamma(r, p / (1 - p), len(u))
return poisson.ppf(u, mu=x) | v0.13.0/examples/notebooks/generated/gee_score_test_simulation.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Below are some parameters that govern the data used in the simulation. | # Sample size
n = 1000
# Number of covariates (including intercept) in the alternative hypothesis model
p = 5
# Cluster size
m = 10
# Intraclass correlation (controls strength of clustering)
r = 0.5
# Group indicators
grp = np.kron(np.arange(n/m), np.ones(m)) | v0.13.0/examples/notebooks/generated/gee_score_test_simulation.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
The simulation uses a fixed design matrix. | # Build a design matrix for the alternative (more complex) model
x = np.random.normal(size=(n, p))
x[:, 0] = 1 | v0.13.0/examples/notebooks/generated/gee_score_test_simulation.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
The null design matrix is nested in the alternative design matrix. It has rank two less than the alternative design matrix. | x0 = x[:, 0:3] | v0.13.0/examples/notebooks/generated/gee_score_test_simulation.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
The GEE score test is robust to dependence and overdispersion. Here we set the overdispersion parameter. The variance of the negative binomial distribution for each observation is equal to scale times its mean value. | # Scale parameter for negative binomial distribution
scale = 10 | v0.13.0/examples/notebooks/generated/gee_score_test_simulation.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
In the next cell, we set up the mean structures for the null and alternative models | # The coefficients used to define the linear predictors
coeff = [[4, 0.4, -0.2], [4, 0.4, -0.2, 0, -0.04]]
# The linear predictors
lp = [np.dot(x0, coeff[0]), np.dot(x, coeff[1])]
# The mean values
mu = [np.exp(lp[0]), np.exp(lp[1])] | v0.13.0/examples/notebooks/generated/gee_score_test_simulation.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Below is a function that carries out the simulation. | # hyp = 0 is the null hypothesis, hyp = 1 is the alternative hypothesis.
# cov_struct is a statsmodels covariance structure
def dosim(hyp, cov_struct=None, mcrep=500):
# Storage for the simulation results
scales = [[], []]
# P-values from the score test
pv = []
# Monte Carlo loop
... | v0.13.0/examples/notebooks/generated/gee_score_test_simulation.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Run the simulation using the independence working covariance structure. We expect the mean to be around 0 under the null hypothesis, and much lower under the alternative hypothesis. Similarly, we expect that under the null hypothesis, around 10% of the p-values are less than 0.1, and a much greater fraction of the p-... | rslt, scales = [], []
for hyp in 0, 1:
s, t = dosim(hyp, sm.cov_struct.Independence())
rslt.append(s)
scales.append(t)
rslt = pd.DataFrame(rslt, index=["H0", "H1"], columns=["Mean", "Prop(p<0.1)"])
print(rslt) | v0.13.0/examples/notebooks/generated/gee_score_test_simulation.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Next we check to make sure that the scale parameter estimates are reasonable. We are assessing the robustness of the GEE score test to dependence and overdispersion, so here we are confirming that the overdispersion is present as expected. | _ = plt.boxplot([scales[0][0], scales[0][1], scales[1][0], scales[1][1]])
plt.ylabel("Estimated scale") | v0.13.0/examples/notebooks/generated/gee_score_test_simulation.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Next we conduct the same analysis using an exchangeable working correlation model. Note that this will be slower than the example above using independent working correlation, so we use fewer Monte Carlo repetitions. | rslt, scales = [], []
for hyp in 0, 1:
s, t = dosim(hyp, sm.cov_struct.Exchangeable(), mcrep=100)
rslt.append(s)
scales.append(t)
rslt = pd.DataFrame(rslt, index=["H0", "H1"], columns=["Mean", "Prop(p<0.1)"])
print(rslt) | v0.13.0/examples/notebooks/generated/gee_score_test_simulation.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Choose some parameters to use throughout | n = 1000
seed = 1234
sigma = 0.5
model =df.model.Schechter()
p_true = model.p0 | docs/example_notebooks/basic_example.ipynb | steven-murray/pydftools | mit |
Generate mock data with observing errors: | data, selection, model, other = df.mockdata(n = n, seed = seed, sigma = sigma, model=model, verbose=True) | docs/example_notebooks/basic_example.ipynb | steven-murray/pydftools | mit |
Create a fitting object (the fit is not performed until the fit object is accessed): | survey = df.DFFit(data=data, selection=selection, model=model) | docs/example_notebooks/basic_example.ipynb | steven-murray/pydftools | mit |
Perform the fit and get the best set of parameters: | start = time.time()
print(survey.fit.p_best)
print("Time for fitting: ", time.time() - start, " seconds") | docs/example_notebooks/basic_example.ipynb | steven-murray/pydftools | mit |
Plot the covariances: | fig = df.plotting.plotcov([survey], p_true=p_true, figsize=1.3) | docs/example_notebooks/basic_example.ipynb | steven-murray/pydftools | mit |
Plot the mass function itself: | fig, ax = df.mfplot(survey, xlim=(1e7,2e12), ylim=(1e-4,2), p_true = p_true, bin_xmin=7.5, bin_xmax=12) | docs/example_notebooks/basic_example.ipynb | steven-murray/pydftools | mit |
Write out fitted parameters with (Gaussian) uncertainties: | display(Markdown(survey.fit_summary(format_for_notebook=True))) | docs/example_notebooks/basic_example.ipynb | steven-murray/pydftools | mit |
Configurations | # stock parameter
StockPrice = 20.83
StrikePrice = 21.50
Volatility = 0.021
InterestRate = 0.20
Maturity = 5. / 12.
# monte-carlo parameter
NumPath = 3000000
NumStep = 100
# plotting
MAX_PATH_IN_PLOT = 50 | notebooks/montecarlo_numbapro.ipynb | david-hoffman/scripts | apache-2.0 |
Driver
The driver measures the performance of the given pricer and plots the simulation paths. | def driver(pricer, do_plot=False):
paths = np.zeros((NumPath, NumStep + 1), order='F')
paths[:, 0] = StockPrice
DT = Maturity / NumStep
ts = timer()
pricer(paths, DT, InterestRate, Volatility)
te = timer()
elapsed = te - ts
ST = paths[:, -1]
PaidOff = np.maximum(paths[:, -1] - Stri... | notebooks/montecarlo_numbapro.ipynb | david-hoffman/scripts | apache-2.0 |
Result | numpy_time = driver(mc_numpy, do_plot=True) | notebooks/montecarlo_numbapro.ipynb | david-hoffman/scripts | apache-2.0 |
Basic Vectorize
The vectorize decorator compiles a scalar function into a Numpy ufunc-like object for operation on arrays.
The decorator must be provided with a list of possible signatures.
The step_cpuvec takes 5 double arrays and return a double array. | from numbapro import vectorize
@vectorize(['f8(f8, f8, f8, f8, f8)'])
def step_cpuvec(last, dt, c0, c1, noise):
return last * math.exp(c0 * dt + c1 * noise)
def mc_cpuvec(paths, dt, interest, volatility):
c0 = interest - 0.5 * volatility ** 2
c1 = volatility * np.sqrt(dt)
for j in range(1, paths.shap... | notebooks/montecarlo_numbapro.ipynb | david-hoffman/scripts | apache-2.0 |
Parallel Vectorize
By setting the target to parallel, the vectorize decorator produces a multithread implementation. | @vectorize(['f8(f8, f8, f8, f8, f8)'], target='parallel')
def step_parallel(last, dt, c0, c1, noise):
return last * math.exp(c0 * dt + c1 * noise)
def mc_parallel(paths, dt, interest, volatility):
c0 = interest - 0.5 * volatility ** 2
c1 = volatility * np.sqrt(dt)
for j in range(1, paths.shape[1]):
... | notebooks/montecarlo_numbapro.ipynb | david-hoffman/scripts | apache-2.0 |
CUDA Vectorize
To take advantage of the CUDA GPU, user can simply set the target to gpu.
There are no different other than the target keyword argument. | @vectorize(['f8(f8, f8, f8, f8, f8)'], target='gpu')
def step_gpuvec(last, dt, c0, c1, noise):
return last * math.exp(c0 * dt + c1 * noise)
def mc_gpuvec(paths, dt, interest, volatility):
c0 = interest - 0.5 * volatility ** 2
c1 = volatility * np.sqrt(dt)
for j in range(1, paths.shape[1]):
pri... | notebooks/montecarlo_numbapro.ipynb | david-hoffman/scripts | apache-2.0 |
In the above simple CUDA vectorize example, the speedup is not significant due to the memory transfer overhead. Since the kernel has relatively low compute intensity, explicit management of memory transfer would give a significant speedup.
CUDA JIT
This implementation uses the CUDA JIT feature with explicit memory tra... | from numbapro import cuda, jit
from numbapro.cudalib import curand
@jit('void(double[:], double[:], double, double, double, double[:])', target='gpu')
def step_cuda(last, paths, dt, c0, c1, normdist):
i = cuda.grid(1)
if i >= paths.shape[0]:
return
noise = normdist[i]
paths[i] = last[i] * math.... | notebooks/montecarlo_numbapro.ipynb | david-hoffman/scripts | apache-2.0 |
Performance Comparision | def perf_plot(rawdata, xlabels):
data = [numpy_time / x for x in rawdata]
idx = np.arange(len(data))
fig = pyplot.figure()
width = 0.5
ax = fig.add_subplot(111)
ax.bar(idx, data, width)
ax.set_ylabel('normalized speedup')
ax.set_xticks(idx + width / 2)
ax.set_xticklabels(xlabels)
... | notebooks/montecarlo_numbapro.ipynb | david-hoffman/scripts | apache-2.0 |
Dense blocks
A conv block uses BN-activation-conv in order. | def conv_block(input_channels, num_channels):
return nn.Sequential(
nn.BatchNorm2d(input_channels), nn.ReLU(), nn.Conv2d(input_channels, num_channels, kernel_size=3, padding=1)
) | notebooks/book1/14/densenet_torch.ipynb | probml/pyprobml | mit |
A DenseBlock is a sequence of conv-blocks, each consuming as input all previous outputs. | class DenseBlock(nn.Module):
def __init__(self, num_convs, input_channels, num_channels):
super(DenseBlock, self).__init__()
layer = []
for i in range(num_convs):
layer.append(conv_block(num_channels * i + input_channels, num_channels))
self.net = nn.Sequential(*layer)
... | notebooks/book1/14/densenet_torch.ipynb | probml/pyprobml | mit |
Example: we start with 3 channels, make a DenseBlock with 2 conv-blocks each with 10 channels, to get an output with 23 channels. | blk = DenseBlock(2, 3, 10)
X = torch.randn(4, 3, 8, 8)
Y = blk(X)
Y.shape | notebooks/book1/14/densenet_torch.ipynb | probml/pyprobml | mit |
Transition layers
To prevent the number of channels exploding, we can add a transition layer, that uses 1x1 convolution. We can also reduce the spatial resolution using stride 2 average pooling. | def transition_block(input_channels, num_channels):
return nn.Sequential(
nn.BatchNorm2d(input_channels),
nn.ReLU(),
nn.Conv2d(input_channels, num_channels, kernel_size=1),
nn.AvgPool2d(kernel_size=2, stride=2),
) | notebooks/book1/14/densenet_torch.ipynb | probml/pyprobml | mit |
Below we show an example where we map the 23 channels back down to 10, and halve the spatial dimensions. | blk = transition_block(23, 10)
blk(Y).shape | notebooks/book1/14/densenet_torch.ipynb | probml/pyprobml | mit |
Full model
The first part of the model is similar to resnet. | b1 = nn.Sequential(
nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
) | notebooks/book1/14/densenet_torch.ipynb | probml/pyprobml | mit |
The "backbone" is 4 dense-blocks, each of which has 4 conv-blocks with 32 channels. Since the number of channels increases for each conv-block, the parameter 32 is called the "growth rate". We insert a transition block between each dense-block to keep things from getting too large. | # `num_channels`: the current number of channels
num_channels = 64 # output of first part of model
growth_rate = 32
num_convs_in_dense_blocks = [4, 4, 4, 4]
blks = []
for i, num_convs in enumerate(num_convs_in_dense_blocks):
blks.append(DenseBlock(num_convs, num_channels, growth_rate))
# This is the number of ... | notebooks/book1/14/densenet_torch.ipynb | probml/pyprobml | mit |
Finally we add average pooling and an FC layer. We assume 10 classes, for MNIST. | net = nn.Sequential(
b1,
*blks,
nn.BatchNorm2d(num_channels),
nn.ReLU(),
nn.AdaptiveMaxPool2d((1, 1)),
nn.Flatten(),
nn.Linear(num_channels, 10)
)
net
X = torch.rand(size=(1, 1, 224, 224))
for layer in net:
X = layer(X)
print(layer.__class__.__name__, "output shape:\t", X.shape)
X... | notebooks/book1/14/densenet_torch.ipynb | probml/pyprobml | mit |
Training
We fit the model to Fashion-MNIST. We rescale images from 28x28 to 96x96, so that the input to the final average pooling layer has size 3x3. We notice that the training speed is much less than for ResNet. | def load_data_fashion_mnist(batch_size, resize=None):
"""Download the Fashion-MNIST dataset and then load it into memory."""
trans = [transforms.ToTensor()]
if resize:
trans.insert(0, transforms.Resize(resize))
trans = transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST... | notebooks/book1/14/densenet_torch.ipynb | probml/pyprobml | mit |
Train function | def train(net, train_iter, test_iter, num_epochs, lr, device):
"""Train a model with a GPU (defined in Chapter 6)."""
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
nn.init.xavier_uniform_(m.weight)
net.apply(init_weights)
print("training on", device)
net... | notebooks/book1/14/densenet_torch.ipynb | probml/pyprobml | mit |
Learning curve | lr, num_epochs, batch_size = 0.1, 10, 256
train_iter, test_iter = load_data_fashion_mnist(batch_size, resize=96)
train(net, train_iter, test_iter, num_epochs, lr, try_gpu()) | notebooks/book1/14/densenet_torch.ipynb | probml/pyprobml | mit |
Loading the General Inquirer.
This takes some doing, because the General Inquirer doesn't start out as a set of wordlists. I have to translate it into that form.
I start by loading an English dictionary. | # start by loading the dictionary
dictionary = set()
with open('../../lexicons/MainDictionary.txt', encoding = 'utf-8') as f:
reader = csv.reader(f, delimiter = '\t')
for row in reader:
word = row[0]
count = int(row[2])
if count < 10000:
continue
# that ignores ... | chapter3/notebooks/chapter3table3.ipynb | tedunderwood/horizon | mit |
The next stage is to translate the Inquirer. It begins as a table where word senses are row labels, and the Inquirer categories are columns (except for two columns at the beginning and two at the end). This is, by the way, the "basic spreadsheet" described at this site:
http://www.wjh.harvard.edu/~inquirer/spreadsheet_... | inquirer = dict()
suffixes = dict()
suffixes['verb'] = ['s', 'es', 'ed', 'd', 'ing']
suffixes['noun'] = ['s', 'es']
allinquirerwords = set()
with open('../../lexicons/inquirerbasic.csv', encoding = 'utf-8') as f:
reader = csv.DictReader(f)
fields = reader.fieldnames[2:-2]
for field in fields:
inq... | chapter3/notebooks/chapter3table3.ipynb | tedunderwood/horizon | mit |
Load model predictions about volumes
The next step is to create some vectors that store predictions about volumes. In this case, these are predictions about the probability that a volume is fiction, rather than biography. | # the folder where wordcounts will live
# we're only going to load predictions
# that correspond to files located there
sourcedir = '../sourcefiles/'
docs = []
logistic = []
with open('../modeloutput/fullfiction.results.csv', encoding = 'utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
genr... | chapter3/notebooks/chapter3table3.ipynb | tedunderwood/horizon | mit |
And get the wordcounts themselves
This cell of the notebook is very short (one line), but it takes a lot of time to execute. There's a lot of file i/o that happens inside the function get_wordfreqs, in the FileCabinet module, which is invoked here. We come away with a dictionary of wordcounts, keyed in the first instan... | wordcounts = filecab.get_wordfreqs(sourcedir, '.tsv', docs) | chapter3/notebooks/chapter3table3.ipynb | tedunderwood/horizon | mit |
Now calculate the representation of each Inquirer category in each doc
We normalize by the total wordcount for a volume.
This cell also takes a long time to run. I've added a counter so you have some confidence that it's still running. | # Initialize empty category vectors
categories = dict()
for field in fields:
categories[field] = np.zeros(numdocs)
# Now fill them
for i, doc in enumerate(docs):
ctcat = Counter()
allcats = 0
for word, count in wordcounts[doc].items():
if word in dictionary:
allcats += count
... | chapter3/notebooks/chapter3table3.ipynb | tedunderwood/horizon | mit |
Calculate correlations
Now that we have all the information, calculating correlations is easy. We iterate through Inquirer categories, in each case calculating the correlation between a vector of model predictions for docs, and a vector of category-frequencies for docs. | logresults = []
for inq_category in fields:
l = pearsonr(logistic, categories[inq_category])[0]
logresults.append((l, inq_category))
logresults.sort()
| chapter3/notebooks/chapter3table3.ipynb | tedunderwood/horizon | mit |
Load expanded names of Inquirer categories
The terms used in the inquirer spreadsheet are not very transparent. DAV for instance is "descriptive action verbs." BodyPt is "body parts." To make these more transparent, I have provided expanded names for many categories that turned out to be relevant in the book, trying to... | short2long = dict()
with open('../../lexicons/long_inquirer_names.csv', encoding = 'utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
short2long[row['short_name']] = row['long_name']
| chapter3/notebooks/chapter3table3.ipynb | tedunderwood/horizon | mit |
Print results
I print the top 12 correlations and the bottom 12, skipping categories that are drawn from the "Laswell value dictionary." The Laswell categories are very finely discriminated (things like "enlightenment gain" or "power loss"), and I have little faith that they're meaningful. I especially doubt that they ... | print('Printing the correlations of General Inquirer categories')
print('with the predicted probabilities of being fiction in allsubset2.csv:')
print()
print('First, top positive correlations: ')
print()
for prob, n in reversed(logresults[-15 : ]):
if n in short2long:
n = short2long[n]
if 'Laswell' in n... | chapter3/notebooks/chapter3table3.ipynb | tedunderwood/horizon | mit |
Counting word frequency
To start off we'll need to count how often each word appears in the data. We'll use this count to create a vocabulary we'll use to encode the review data. This resulting count is known as a bag of words. We'll use it to select our vocabulary and build the word vectors. You should have seen how t... | from collections import Counter
total_counts = Counter(word for review in reviews.values for word in review[0].split(' '))
print("Total words in data set: ", len(total_counts)) | lessons/intro-to-tflearn/TFLearn_Sentiment_Analysis.ipynb | Hyperparticle/deep-learning-foundation | mit |
The last word in our vocabulary shows up in 30 reviews out of 25000. I think it's fair to say this is a tiny proportion of reviews. We are probably fine with this number of words.
Note: When you run, you may see a different word from the one shown above, but it will also have the value 30. That's because there are many... | word2idx = {word: idx for idx,word in enumerate(vocab)} | lessons/intro-to-tflearn/TFLearn_Sentiment_Analysis.ipynb | Hyperparticle/deep-learning-foundation | mit |
Train, Validation, Test 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. Here we're using the fu... | Y = (labels=='positive').astype(np.int_)
records = len(labels)
shuffle = np.arange(records)
np.random.shuffle(shuffle)
test_fraction = 0.9
train_split, test_split = shuffle[:int(records*test_fraction)], shuffle[int(records*test_fraction):]
trainX, trainY = word_vectors[train_split,:], to_categorical(Y.values[train_sp... | lessons/intro-to-tflearn/TFLearn_Sentiment_Analysis.ipynb | Hyperparticle/deep-learning-foundation | mit |
Steps to use the TF Experiment APIs
Define dataset metadata
Define data input function to read the data from .tfrecord files + feature processing
Create TF feature columns based on metadata + extended feature columns
Define an a model function with the required feature columns, EstimatorSpecs, & parameters
Run an Expe... | MODEL_NAME = 'class-model-02'
TRAIN_DATA_FILES_PATTERN = 'data/train-*.csv'
VALID_DATA_FILES_PATTERN = 'data/valid-*.csv'
TEST_DATA_FILES_PATTERN = 'data/test-*.csv'
RESUME_TRAINING = False
PROCESS_FEATURES = True
EXTEND_FEATURE_COLUMNS = True
MULTI_THREADING = True | 02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb | GoogleCloudPlatform/tf-estimator-tutorials | apache-2.0 |
1. Define Dataset Metadata
tf.example feature names and defaults
Numeric and categorical feature names
Target feature name
Target feature labels
Unused features | HEADER = ['key','x','y','alpha','beta','target']
HEADER_DEFAULTS = [[0], [0.0], [0.0], ['NA'], ['NA'], ['NA']]
NUMERIC_FEATURE_NAMES = ['x', 'y']
CATEGORICAL_FEATURE_NAMES_WITH_VOCABULARY = {'alpha':['ax01', 'ax02'], 'beta':['bx01', 'bx02']}
CATEGORICAL_FEATURE_NAMES = list(CATEGORICAL_FEATURE_NAMES_WITH_VOCABULARY... | 02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb | GoogleCloudPlatform/tf-estimator-tutorials | apache-2.0 |
2. Define Data Input Function
Input csv files name pattern
Use TF Dataset APIs to read and process the data
Parse CSV lines to feature tensors
Apply feature processing
Return (features, target) tensors
a. Parsing and preprocessing logic | def parse_csv_row(csv_row):
columns = tf.decode_csv(csv_row, record_defaults=HEADER_DEFAULTS)
features = dict(zip(HEADER, columns))
for column in UNUSED_FEATURE_NAMES:
features.pop(column)
target = features.pop(TARGET_NAME)
return features, target
def process_features(featur... | 02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb | GoogleCloudPlatform/tf-estimator-tutorials | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.