markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
5.1 Sample data Loads a data sample and draws n_samples from the field. For sampling the field, random samples from a gamma distribution with a fairly high scale are drawn, to ensure there are some outliers in the samle. The values are then re-scaled to the shape of the random field and the values are extracted from it...
N = 80 pan = skg.data.pancake_field().get('sample') coords, vals = skg.data.pancake(N=80, seed=1312).get('sample') fig = make_subplots(1,2,shared_xaxes=True, shared_yaxes=True) fig.add_trace( go.Scatter(x=coords[:,0], y=coords[:,1], mode='markers', marker=dict(color=vals,cmin=0, cmax=255), name='samples'), row=...
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
Uncomment this cell to work on the pancake:
coords, vals = skg.data.meuse().get('sample') vals = vals.flatten() fig = go.Figure(go.Scatter(x=coords[:,0], y=coords[:,1], mode='markers', marker=dict(color=vals), name='samples')) fig.update_layout(width=450, height=450, template='plotly_white') iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.2 Lag class binning - fixed N Apply different lag class binning methods and visualize their histograms. In this section, the distance matrix between all point pair combinations (NxN) is binned using each method. The plots visualize the histrogram of the distance matrix of the variogram, not the variogram lag classes ...
N = 15 # use a nugget V = skg.Variogram(coords, vals, n_lags=N, use_nugget=True)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.2.1 default 'even' lag classes The default binning method will find N equidistant bins. This is the default behavior and used in almost all geostatistical publications. It should not be used without a maxlag (like done in the plot below).
# apply binning bins, _ = skg.binning.even_width_lags(V.distance, N, None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'even'}~~binning$") ) iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.2.2 'uniform' lag classes The histogram of the uniform method will adjust the lag class widths to have the same sample size for each lag class. This can be used, when there must not be any empty lag classes on small data samples, or comparable sample sizes are desireable for the semi-variance estimator.
# apply binning bins, _ = skg.binning.uniform_count_lags(V.distance, N, None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'uniform'}~~binning$") ) iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.2.3 'kmeans' lag classes The distance matrix is clustered by a K-Means algorithm. The centroids, are taken as a good guess for lag class centers. Each lag class is then formed by taking half the distance to each sorted neighboring centroid as a bound. This will most likely result in non-equidistant lag classes. One ...
# apply binning bins, _ = skg.binning.kmeans(V.distance, N, None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'K-Means'}~~binning$") ) iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.2.4 'ward' lag classes The other clustering algorithm is a hierarchical clustering algorithm. This algorithm groups values together based on their similarity, which is expressed by Ward's criterion. Agglomerative algorithms work iteratively and deterministic, as at first iteration each value forms a cluster on its o...
# apply binning bins, _ = skg.binning.ward(V.distance, N, None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'ward'}~~binning$") ) iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.3 Lag class binning - adjustable N 5.3.1 'sturges' lag classes Sturge's rule is well known and pretty straightforward. It's the default method for histograms in R. The number of equidistant lag classes is defined like: $$ n =log_2 (x + 1) $$ Sturge's rule works good for small, normal distributed datasets.
# apply binning bins, n = skg.binning.auto_derived_lags(V.distance, 'sturges', None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'sturges'}~~binning~~%d~classes$" % n) ) iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.3.2 'scott' lag classes Scott's rule is another quite popular approach to estimate histograms. The rule is defined like: $$ h = \sigma \frac{24 * \sqrt{\pi}}{x}^{\frac{1}{3}} $$ Other than Sturge's rule, it will estimate the lag class width from the sample size standard deviation. Thus, it is also quite sensitive to ...
# apply binning bins, n = skg.binning.auto_derived_lags(V.distance, 'scott', None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'scott'}~~binning~~%d~classes$" % n) ) iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.3.3 'sqrt' lag classes The only advantage of this method is its speed. The number of lag classes is simply defined like: $$ n = \sqrt{x} $$ Thus, it's usually not really a good choice, unless you have a lot of samples.
# apply binning bins, n = skg.binning.auto_derived_lags(V.distance, 'sqrt', None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'sqrt'}~~binning~~%d~classes$" % n) ) iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.3.4 'fd' lag classes The Freedman-Diaconis estimator can be used to derive the number of lag classes again from an optimal lag class width like: $$ h = 2\frac{IQR}{x^{1/3}} $$ As it is based on the interquartile range (IQR), it is very robust to outlier. That makes it a suitable method to estimate lag classes on non...
# apply binning bins, n = skg.binning.auto_derived_lags(V.distance, 'fd', None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'fd'}~~binning~~%d~classes$" % n) ) iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.3.5 'doane' lag classes Doane's rule is an extension to Sturge's rule that takes the skewness of the distance matrix into account. It was found to be a very reasonable choice on most datasets where the other estimators didn't yield good results. It is defined like: $$ \begin{split} n = 1 + \log_{2}(s) + \...
# apply binning bins, n = skg.binning.auto_derived_lags(V.distance, 'doane', None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'doane'}~~binning~~%d~classes$" % n) ) iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.4 Variograms The following section will give an overview on the influence of the chosen binning method on the resulting variogram. All parameters will be the same for all variograms, so any change is due to the lag class binning. The variogram will use a maximum lag of 200 to get rid of the very thin last bins at lar...
# use a exponential model V.set_model('spherical') # set the maxlag V.maxlag = 'median'
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.4.1 'even' lag classes
# set the new binning method V.bin_func = 'even' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.4.2 'uniform' lag classes
# set the new binning method V.bin_func = 'uniform' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.4.3 'kmeans' lag classes
# set the new binning method V.bin_func = 'kmeans' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.4.4 'ward' lag classes
# set the new binning method V.bin_func = 'ward' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.4.5 'sturges' lag classes
# set the new binning method V.bin_func = 'sturges' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" adjusted {V.n_lags} lag classes - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.4.6 'scott' lag classes
# set the new binning method V.bin_func = 'scott' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" adjusted {V.n_lags} lag classes - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.4.7 'fd' lag classes
# set the new binning method V.bin_func = 'fd' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" adjusted {V.n_lags} lag classes - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.4.8 'sqrt' lag classes
# set the new binning method V.bin_func = 'sqrt' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" adjusted {V.n_lags} lag classes - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
5.4.9 'doane' lag classes
# set the new binning method V.bin_func = 'doane' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" adjusted {V.n_lags} lag classes - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig)
tutorials/05_binning.ipynb
mmaelicke/scikit-gstat
mit
Tasa de cambio del estado emotivo de Laura $\frac{dL(t)}{dt}=-\alpha_{1}L(t)+R_{L}(P(t))+\beta_{1}A_{P}$ Tasa de cambio del estado emotivo de Petrarca $\frac{dP(t)}{dt}=-\alpha_{2}L(t)+R_{p}(L(t))+\beta_{2}\frac{A_{L}}{1+\delta Z(t)}$ Tasa de cambio de la inspiración del Poeta $\frac{dZ(t)}{dt}=-\alpha_{3}Z(t)+\beta_{3...
def dL(t): return -3.6 * L[t] + 1.2 * (P[t]*(1-P[t]**2) - 1) def dP(t): return -1.2 * L[t] + 6 * L[t] + 12 / (1 + Z[t]) def dZ(t): return -0.12 * Z[t] + 12 * P[t] years = 20 dt = 0.01 steps = int(years / dt) L = np.zeros(steps) P = np.zeros(steps) Z = np.zeros(steps) for t in range(steps-1): L[...
dinamica_amor.ipynb
rgarcia-herrera/sistemas-dinamicos
gpl-3.0
Espacio fase
from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(11,11)) ax = fig.gca(projection='3d') # Make the grid l, p, z = np.meshgrid(np.linspace(-1, 2, 11), np.linspace(-1, 1, 11), np.linspace(0, 18, 11)) # Make the direction data for the arrows u = -3.6 * l + 1.2 ...
dinamica_amor.ipynb
rgarcia-herrera/sistemas-dinamicos
gpl-3.0
Problem 2) Unsupervised Machine Learning Unsupervised machine learning, sometimes referred to as clustering or data mining, aims to group or classify sources in the multidimensional feature space. The "unsupervised" comes from the fact that there are no target labels provided to the algorithm, so the machine is asked t...
from sklearn.cluster import KMeans Kcluster = KMeans( # complete # complete plt.figure() plt.scatter( # complete plt.xlabel('sepal length') plt.ylabel('sepal width') Kcluster = KMeans( # complete # complete plt.figure() plt.scatter( # complete plt.xlabel('sepal length') plt.ylabel('sepal width')
Sessions/Session01/Day4/IntroToMachineLearning.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
With 3 clusters the algorithm does a good job of separating the three classes. However, without the a priori knowledge that there are 3 different types of iris, the 2 cluster solution would appear to be superior. Problem 2b How do the results change if the 3 cluster model is called with n_init = 1 and init = 'random' ...
rs = 14 Kcluster1 = KMeans(# complete plt.figure() plt.scatter(# complete plt.xlabel('sepal length') plt.ylabel('sepal width')
Sessions/Session01/Day4/IntroToMachineLearning.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
A random aside that is not particularly relevant here $k$-means evaluates the Euclidean distance between individual sources and cluster centers, thus, the magnitude of the individual features has a strong effect on the final clustering outcome. Problem 2c Calculate the mean, standard deviation, min, and max of each fe...
print("feature\t\t\tmean\tstd\tmin\tmax") for featnum, feat in enumerate(iris.feature_names): print("{:s}\t{:.2f}\t{:.2f}\t{:.2f}\t{:.2f}".format( # complete
Sessions/Session01/Day4/IntroToMachineLearning.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Petal length has the largest range and standard deviation, thus, it will have the most "weight" when determining the $k$ clusters. The truth is that the iris data set is fairly small and straightfoward. Nevertheless, we will now examine the clustering results after re-scaling the features. [Some algorithms, cough Supp...
from sklearn.preprocessing import StandardScaler scaler = StandardScaler().fit( # complete Kcluster = KMeans( # complete plt.figure() plt.scatter( # complete plt.xlabel('sepal length') plt.ylabel('sepal width')
Sessions/Session01/Day4/IntroToMachineLearning.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
These results are almost identical to those obtained without scaling. This is due to the simplicity of the iris data set. How do I test the accuracy of my clusters? Essentially - you don't. There are some methods that are available, but they essentially compare clusters to labeled samples, and if the samples are label...
from sklearn.cluster import DBSCAN dbs = DBSCAN( # complete dbs.fit( # complete dbs_outliers = # complete plt.figure() plt.scatter( # complete plt.scatter( # complete plt.xlabel('sepal length') plt.ylabel('sepal width')
Sessions/Session01/Day4/IntroToMachineLearning.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
I have used my own domain knowledge to specificly choose features that may be useful when clustering galaxies. If you know a bit about SDSS and can think of other features that may be useful feel free to add them to the query. One nice feature of astropy tables is that they can readily be turned into pandas DataFrames...
# complete
Sessions/Session01/Day4/IntroToMachineLearning.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Note - the above solution seems to separate out elliptical galaxies from blue star forming galaxies, however, the results are highly, highly dependent upon the tuning parameters. Problem 3) Supervised Machine Learning Supervised machine learning, on the other hand, aims to predict a target class or produce a regressio...
from sklearn.neighbors import KNeighborsClassifier KNNclf = KNeighborsClassifier( # complete preds = # complete plt.figure() plt.scatter( # complete KNNclf = KNeighborsClassifier(# complete preds = # complete plt.figure() plt.scatter( # complete
Sessions/Session01/Day4/IntroToMachineLearning.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
These results are almost identical to the training classifications. However, we have cheated! In this case we are evaluating the accuracy of the model (98% in this case) using the same data that defines the model. Thus, what we have really evaluated here is the training error. The relevant parameter, however, is the ge...
from sklearn.cross_validation import cross_val_predict CVpreds = cross_val_predict( # complete plt.figure() plt.scatter( # complete print("The accuracy of the kNN = 5 model is ~{:.4}".format( # complete CVpreds50 = cross_val_predict( # complete print("The accuracy of the kNN = 50 model is ~{:.4}".for...
Sessions/Session01/Day4/IntroToMachineLearning.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
While it is useful to understand the overall accuracy of the model, it is even more useful to understand the nature of the misclassifications that occur. Problem 3c Calculate the accuracy for each class in the iris set, as determined via CV for the $k$NN = 50 model.
# complete
Sessions/Session01/Day4/IntroToMachineLearning.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
We just found that the classifier does a much better job classifying setosa and versicolor than it does for virginica. The main reason for this is some viginica flowers lie far outside the main virginica locus, and within predominantly versicolor "neighborhoods". In addition to knowing the accuracy for the individual c...
from sklearn.metrics import confusion_matrix cm = confusion_matrix( # complete print(cm)
Sessions/Session01/Day4/IntroToMachineLearning.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
The normalization makes it easier to compare the classes, since each class has a different number of sources. Now we can procede with a visual representation of the confusion matrix. This is best done using imshow() within pyplot. You will also need to plot a colorbar, and labeling the axes will also be helpful. Probl...
plt.imshow( # complete
Sessions/Session01/Day4/IntroToMachineLearning.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
First: load the test image and run Gaussian filter on it
%%time X1 = plt.imread('input.png') X1 = rgb2gray(X1) s = 16. # sigma for testing filtering X2 = np.copy(X1).astype(np.float64) # Gaussian filter runs with zero-border X2 = ndimage.filters.gaussian_filter(X1, sigma=s, mode='constant')
python/alg5.ipynb
andmax/gpufilter
mit
Second: setup basic parameters from the input image
%%time b = 32 # squared block size (b,b) w = [ weights1(s), weights2(s) ] # weights of the recursive filter width, height = X1.shape[1], X1.shape[0] m_size, n_size = get_mn(X1, b) blocks = break_blocks(X1, b, m_size, n_size) # Pre-computation of matrices and pre-allocation of carries alg5m1 = build_alg5_matrices(b, 1, ...
python/alg5.ipynb
andmax/gpufilter
mit
Third: run alg5 with filter order 1 then 2
%%time # Running alg5 with filter order r = 1 alg5_stage1(m_size, n_size, 1, w[0], alg5m1, alg5c1, blocks) alg5_stage23(m_size, n_size, alg5m1, alg5c1) alg5_stage45(m_size, n_size, alg5m1, alg5c1) alg5_stage6(m_size, n_size, w[0], alg5c1, blocks) # Running alg5 with filter order r = 2 alg5_stage1(m_size, n_size, 2, w[1...
python/alg5.ipynb
andmax/gpufilter
mit
Data generation Let's first load some data!
# open a pandas dataframe for use below from histogrammar import resources df = pd.read_csv(resources.data("test.csv.gz"), parse_dates=["date"]) df.head()
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Let's fill a histogram! Histogrammar treats histograms as objects. You will see this has various advantages. Let's fill a simple histogram with a numpy array.
# this creates a histogram with 100 even-sized bins in the (closed) range [-5, 5] hist1 = hg.Bin(num=100, low=-5, high=5) # filling it with one data point: hist1.fill(0.5) hist1.entries # filling the histogram with an array: hist1.fill.numpy(np.random.normal(size=10000)) hist1.entries # let's plot it hist1.plot.ma...
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Histogrammar also supports open-ended histograms, which are sparsely represented. Open-ended histograms are used when you have a distribution of known scale (bin width) but unknown domain (lowest and highest bin index). Bins in a sparse histogram only get created and filled if the corresponding data points are encounte...
hist2 = hg.SparselyBin(binWidth=10, origin=0) hist2.fill.numpy(df['age'].values) hist2.plot.matplotlib(); # Alternatively, you can call this to make the same histogram: # hist2 = hg.SparselyHistogram(binWidth=10)
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Filling from a dataframe Let's make the same 1d (sparse) histogram directly from a (pandas) dataframe.
hist3 = hg.SparselyBin(binWidth=10, origin=0, quantity='age') hist3.fill.numpy(df) hist3.plot.matplotlib();
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
When importing histogrammar, pandas (and spark) dataframes get extra functions to create histograms that all start with "hg_". For example: hg_Bin or hg_SparselyBin. Note that the column "age" is picked by setting quantity="age", and also that the filling step is done automatically.
# Alternatively, do: hist3 = df.hg_SparselyBin(binWidth=10, origin=0, quantity='age') # ... where hist3 automatically picks up column age from the dataframe, # ... and does not need to be filled by calling fill.numpy() explicitly.
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Handy histogram methods For any 1-dimensional histogram extract the bin entries, edges and centers as follows:
# full range of bin entries, and those in a specified range: (hist3.bin_entries(), hist3.bin_entries(low=30, high=80)) # full range of bin edges, and those in a specified range: (hist3.bin_edges(), hist3.bin_edges(low=31, high=71)) # full range of bin centers, and those in a specified range: (hist3.bin_centers(), his...
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Irregular bin histogram variants There are two other open-ended histogram variants in addition to the SparselyBin we have seen before. Whereas SparselyBin is used when bins have equal width, the others offer similar alternatives to a single fixed bin width. There are two ways: - CentrallyBin histograms, defined by spec...
hist4 = hg.CentrallyBin(centers=[15, 25, 35, 45, 55, 65, 75, 85, 95], quantity='age') hist4.fill.numpy(df) hist4.plot.matplotlib(); hist4.bin_edges()
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Note the slightly different plotting style for CentrallyBin histograms (e.g. x-axis labels are central values instead of edges). Multi-dimensional histograms Let's make a multi-dimensional histogram. In Histogrammar, a multi-dimensional histogram is composed as two recursive histograms. We will use histograms with irr...
edges1 = [-100, -75, -50, -25, 0, 25, 50, 75, 100] edges2 = [-200, -150, -100, -50, 0, 50, 100, 150, 200] hist1 = hg.IrregularlyBin(edges=edges1, quantity='latitude') hist2 = hg.IrregularlyBin(edges=edges2, quantity='longitude', value=hist1) # for 3 dimensions or higher simply add the 2-dim histogram to the value arg...
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Accessing bin entries For most 2+ dimensional histograms, one can get the bin entries and centers as follows:
from histogrammar.plot.hist_numpy import get_2dgrid x_labels, y_labels, grid = get_2dgrid(hist2) y_labels, grid
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Accessing a sub-histogram Depending on the histogram type of the first axis, hg.Bin or other, one can access the sub-histograms directly from: hist.values or hist.bins
# Acces sub-histograms from IrregularlyBin from hist.bins # The first item of the tuple is the lower bin-edge of the bin. hist2.bins[1] h = hist2.bins[1][1] h.plot.matplotlib() h.bin_entries()
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Histogram types recap So far we have covered the histogram types: - Bin histograms: with a fixed range and even-sized bins, - SparselyBin histograms: open-ended and with a fixed bin-width, - CentrallyBin histograms: open-ended and using bin centers. - IrregularlyBin histograms: open-ended and using (irregular) bin edg...
histy = hg.Categorize('eyeColor') histx = hg.Categorize('favoriteFruit', value=histy) histx.fill.numpy(df) histx.plot.matplotlib(); # show the datatype(s) of the histogram histx.datatype
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Categorize histograms also accept booleans:
histy = hg.Categorize('isActive') histy.fill.numpy(df) histy.plot.matplotlib(); histy.bin_entries() histy.bin_labels() # histy.bin_centers() will work as well for Categorize histograms
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Other histogram functionality There are several more histogram types: - Minimize, Maximize: keep track of the min or max value of a numeric distribution, - Average, Deviate: keep track of the mean or mean and standard deviation of a numeric distribution, - Sum: keep track of the sum of a numeric distribution, - Stack: ...
hmin = df.hg_Minimize('latitude') hmax = df.hg_Maximize('longitude') (hmin.min, hmax.max) havg = df.hg_Average('latitude') hdev = df.hg_Deviate('longitude') (havg.mean, hdev.mean, hdev.variance) hsum = df.hg_Sum('age') hsum.sum # let's illustrate the Stack histogram with longitude distribution # first we plot the re...
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Stack histograms are useful to make efficiency curves. With all these histograms you can make multi-dimensional histograms. For example, you can evaluate the mean and standard deviation of one feature as a function of bins of another feature. (A "profile" plot, similar to a box plot.)
hav = hg.Deviate('age') hlo = hg.SparselyBin(25, 'longitude', value=hav) hlo.fill.numpy(df) hlo.bins hlo.plot.matplotlib();
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Convenience functions There are several convenience functions to make such composed histograms. These are: - Profile: Convenience function for creating binwise averages. - SparselyProfile: Convenience function for creating sparsely binned binwise averages. - ProfileErr: Convenience function for creating binwise average...
# For example, call this convenience function to make the same histogram as above: hlo = df.hg_SparselyProfileErr(25, 'longitude', 'age') hlo.plot.matplotlib();
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Overview of histograms Here you can find the list of all available histograms and aggregators and how to use each one: https://histogrammar.github.io/histogrammar-docs/specification/1.0/ The most useful aggregators are the following. Tinker with them to get familiar; building up an analysis is easier when you know "th...
hists = df.hg_make_histograms() hists.keys() h = hists['transaction'] h.plot.matplotlib(); h = hists['date'] h.plot.matplotlib(); # you can also select which and make multi-dimensional histograms hists = df.hg_make_histograms(features = ['longitude:age']) hist = hists['longitude:age'] hist.plot.matplotlib();
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
Storage Histograms can be easily stored and retrieved in/from the json format.
# storage hist.toJsonFile('long_age.json') # retrieval factory = hg.Factory() hist2 = factory.fromJsonFile('long_age.json') hist2.plot.matplotlib(); # we can store the histograms if we want to import json from histogrammar.util import dumper # store with open('histograms.json', 'w') as outfile: json.dump(hists, ...
histogrammar/notebooks/histogrammar_tutorial_basic.ipynb
histogrammar/histogrammar-python
apache-2.0
For the arrival rate, let's set $N = 10,000$ users, and our time interval $T = 2.0$ hours. From that, we can calculate an arrival rate of $\lambda = N / T = 5,000$ per hour or $\lambda = 1.388$ users / second. Now for the times. Starting at $T_0$ we have no arrivals, but as time passes the probability of an event incre...
count = int(1E6) x = np.arange(count) y = -np.log(1.0 - np.random.random_sample(len(x))) / lmbda np.average(y) y[:10]
src/articles/poisson/index.ipynb
bradhowes/keystrokecountdown
mit
So with a rate of $\lambda = 1.388$ new events would arrive on average $I = 0.72$ seconds apart (or $1 / \lambda$). We can plot the distribution of these random times, where we should see an exponential distribution.
plt.hist(y, 10) plt.show()
src/articles/poisson/index.ipynb
bradhowes/keystrokecountdown
mit
Random Generation Python contains the random.expovariate method which should give us similar intervals. Let's see by averaging a large sum of them.
from random import expovariate sum([expovariate(lmbda) for i in range(count)])/count
src/articles/poisson/index.ipynb
bradhowes/keystrokecountdown
mit
For completeness, we can also use NumPy's random.poisson method if we pass in $1 / \lambda$
y = np.random.exponential(1.0/lmbda, count) np.cumsum(y)[:10] np.average(y)
src/articles/poisson/index.ipynb
bradhowes/keystrokecountdown
mit
Again, this is in agreement with our expected average interval. Note the numbers (and histogram plots) won't match exactly as we are dealing with random time intervals.
x = range(count) y = [expovariate(lmbda) for i in x] plt.hist(y, 10) plt.show()
src/articles/poisson/index.ipynb
bradhowes/keystrokecountdown
mit
Event Times For a timeline of events, we can simply generate a sequence of independent intervals, and then generate a runnng sum of them for absolute timestamps.
intervals = [expovariate(lmbda) for i in range(1000)] timestamps = [0.0] timestamp = 0.0 for t in intervals: timestamp += t timestamps.append(timestamp) timestamps[:10] deltas = [y - x for x, y in zip(timestamps, timestamps[1:])] deltas[:10] sum(deltas) / len(deltas) deltas = [y - x for x, y in zip(timestamp...
src/articles/poisson/index.ipynb
bradhowes/keystrokecountdown
mit
Here we can readily see how the time between events is distributed, with most of the deltas below 1.0 with some fairly large outliers. This is to be expected as $T_n$ will always be greater than $T_{n-1}$ but perhaps not by much. Finally, let's generate $T = 2.0$ hours worth of timestamps and see if we have close to ou...
limit = T * 60 * 60 counts = [] for iter in range(100): count = 0 timestamp = 0.0 while timestamp < limit: timestamp += expovariate(lmbda) count += 1 counts.append(count) sum(counts) / len(counts)
src/articles/poisson/index.ipynb
bradhowes/keystrokecountdown
mit
PyTorch Tutorial Transfer Learning을 이용해 Network를 학습하는 방법에 작성된 글입니다 충분한 크기의 데이터 세트를 갖긴 힘들기 때문에 잘 학습된 네트워크를 Pretrain한 후 사용하는 경우가 많음 convnet finetuning : 무작위 초기화 대신 imagenet 1000 데이터셋에서 학습한 네트워크를 사용해 네트워크 초기화하고 훈련은 동일하게 진행 고정된 Feature 추출 : 최종 Fully Connected Layer를 제외한 모든 네트워크의 가중치를 고정. 마지막 레이어는 새 레이어로 대체되고 이 레이어만 학...
data_transforms = { 'train': transforms.Compose([ transforms.RandomSizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Scale(256), ...
pytorch/Transfer-Learning.ipynb
zzsza/TIL
mit
시각화
def imshow(inp, title=None): """Imshow for Tensor.""" inp = inp.numpy().transpose((1, 2, 0)) # 데이터를 numpy 객체로 바꾼 후 Transpose mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) plt.imshow(inp) if title is not None: ...
pytorch/Transfer-Learning.ipynb
zzsza/TIL
mit
learning rate를 스케쥴링 가장 좋은 Model을 저장
def train_model(model, criterion, optimizer, scheduler, num_epochs=25): since = time.time() best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs-1)) print('-'*10) for phas...
pytorch/Transfer-Learning.ipynb
zzsza/TIL
mit
FineTuning
model_ft = models.resnet18(pretrained=True) model_ft type(model_ft) dir(model_ft) num_ftrs = model_ft.fc.in_features num_ftrs model_ft.fc = nn.Linear(num_ftrs, 2) if use_gpu: model_ft = model_ft.cuda() model_ft.parameters() [i for i in model_ft.parameters()] criterion = nn.CrossEntropyLoss() optimizer_ft ...
pytorch/Transfer-Learning.ipynb
zzsza/TIL
mit
ConvNet as fixed feature extractor 마지막 레이러를 제외한 모든 네트워크를 freeze해야 합니다 backward()할 경우 계산이 되는 것을 방지하기 위해 requires_grad == False를 해서 파라미터를 freeze해야합니다! Autograd 문서 참고하기
model_conv = torchvision.models.resnet18(pretrained=True) for param in model_conv.parameters(): param.requires_grad = False # Parameters of newly constructed modules have requires_grad=True by default num_ftrs = model_conv.fc.in_features model_conv.fc = nn.Linear(num_ftrs, 2) if use_gpu: model_conv = model_co...
pytorch/Transfer-Learning.ipynb
zzsza/TIL
mit
Load all the data
# First we load the file file_location = '../results_database/text_wall_street_big.hdf5' f = h5py.File(file_location, 'r') # Now we need to get the letters and align them text_directory = '../data/wall_street_letters.npy' letters_sequence = np.load(text_directory) Nletters = len(letters_sequence) symbols = set(letter...
presentations/2016-01-28(Wall-Street-Nexa-Maximal-Lag-Analysis).ipynb
h-mayorquin/time_series_basic
bsd-3-clause
Latency analysis
# Set the parameters for the simulation maximal_lags = np.arange(8, 21, 3) # Run the delay analysis N = 50000 delays = np.arange(0, 25, 1) accuracy_matrix = np.zeros((maximal_lags.size, delays.size)) for maximal_lag_index, maximal_lag in enumerate(maximal_lags): # Extract the appropriate database run_name = '/...
presentations/2016-01-28(Wall-Street-Nexa-Maximal-Lag-Analysis).ipynb
h-mayorquin/time_series_basic
bsd-3-clause
Plot it
fig = plt.figure(figsize=(16, 12)) ax = fig.add_subplot(111) for maximal_lag_index in range(maximal_lags.size): ax.plot(delays, accuracy_matrix[maximal_lag_index, :], 'o-', lw=2, markersize=10, label=str(maximal_lags[maximal_lag_index])) ax.set_xlabel('Delays') ax.set_ylabel('Accuracy') ax.set_ylim([0,...
presentations/2016-01-28(Wall-Street-Nexa-Maximal-Lag-Analysis).ipynb
h-mayorquin/time_series_basic
bsd-3-clause
Here we define a string of text by enclosing it with quotations marks and assigning it to a variable or container called text. The fact that Python still sees this piece of text as a continguous string of characters becomes evident when we ask Python to print out the length of text, using the len() function:
print(len(text))
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
One could say that characters are the 'atoms' or smallest meaningful units in computational text processing. Just as computer images use pixels as their fundamental building blocks, all digital text processing applications start from raw characters and it are these characters that are physically stored on your machines...
# your code goes here
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Many people find it more intuitive to consider texts as a strings of words, rather than plain characters, because words correspond to more concrete entities. In Python, we can easily turn our original 'string' into a list of words:
words = text.split() print(words)
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Using the split() method, we split our original sentence into a word list along instances of whitespace characters. Note that, in technical terms, the variable type of text is different from that of the newly created variable words:
print(type(text)) print(type(words))
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Likewise, they evidently differ in length:
print(len(text)) print(len(words))
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
By using 'indexing' (with square brackets), we can now access individual words in our word list. Check out the following print statements:
print(words[3]) print(words[5])
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
DIY Try out the indexes [0] and [-1] for the example with words. Which words are being printed when you use these indices? Do this makes sense? What is peculiar about the way Python 'counts'? Note that words is a so-called list variable in technical terms, but that the individual elements of words are still plain stri...
print(type(words[3]))
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Tokenization In the previous paragraph, we have adopted an extremely crude definition of a 'word', namely as a string of characters that doesn't contain any whitespace. There are of course many problems that arise if we use such a naive definition. Can you think of some? In computer science, and computational linguisti...
import nltk
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
We can now use apply nltk's functionality, for instance, its (default) tokenizer for English:
tokens = nltk.word_tokenize(text) print(tokens)
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Note how the function word_tokenize() neatly splits off punctuation! Many improvements nevertheless remain. To collapse the difference between uppercase and lowercase variables, for instance, we could first lowercase the original input string:
lower_str = text.lower() lower_tokens = nltk.word_tokenize(lower_str) print(lower_tokens)
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Many applications will not be very interested in punctuation marks, so can we can try to remove these as well. The isalpha() method allows you to determine whether a string only contains alphabetic characters:
print(lower_tokens[1].isalpha()) print(lower_tokens[-1].isalpha())
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Functions like isalpha() return something that is called a 'boolean' value, a kind of variable that can only take two values, i.e. True or False. Such values are useful because you can use them to test whether some condition is true or not. For example, if isalpha() evaluates to False for a word, we can have Python ign...
clean_tokens = [w for w in lower_tokens if not w.isalpha()] print(clean_tokens)
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Counting words Once we have come up with a good way to split texts into individual tokens, it is time to start thinking about how we can represent texts via these tokens. One popular approach to this problem is called the bag-of-words model (BOW): this is a very old (and slightly naive) strategy for text representation...
text = """It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife. However little known the feelings or views of such a man may be on his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is consider...
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
We obtain a list of 148 tokens. Counting how often each individual token occurs in this 'document' is trivial, using the Counter object which we can import from Python's collection module:
from collections import Counter bow = Counter(clean_tokens) print(bow)
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Let us have a look at the three most frequent items in the text:
print(bow.most_common(3))
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Obviously, the most common items in such a frequency list are typically small, grammatical words that are very frequent throughout all the texts in a language. Let us add a small visualisation of this information. We can use a barplot to show the top-frequency items in a more pleasing manner. In the following block, we...
%matplotlib inline
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
And then execute the following blocks -- and try to understand the intuition behind them:
# first, we extract the counts: nb_words = 8 wrds, cnts = zip(*bow.most_common(nb_words)) print(wrds) print(cnts) # now the plotting part: import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() bar_width = 0.5 idxs = np.arange(nb_words) #print(idxs) ax.bar(idxs, cnts, bar_width, color='blue', alig...
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
DIY Can you try to increase the number of words plotted? And change the color used for the bars to blue? And the width of the bars plotted? The Bag of Words Model We are almost there: we now know how to split documents into tokens and how we we count (and even visualize!) the frequencies of these items. Now it is only...
# we import some modules which we need import glob import os # we create three emptylist authors, titles, texts = [], [], [] # we loop over the filenames under the directory: for filename in sorted(glob.glob('data/victorian_small/*.txt')): # we open a file and read the contents from it: with open(filenam...
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
This code makes use of a so called for-loop: after retrieving the list of relevant file names, we load the content of each file and add it to a list called texts, using the append() function. Additionally, we also create lists in which we store the authors and titles of the novels:
print(authors) print(titles)
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Note that these three lists can be neatly zipped together, so that the third item in authors corresponds to the third item in titles (remember: Python starts counting at zero!):
print('Title:', titles[2], '- by:', authors[2])
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
To have a peak at the content of this novel, we can now 'stack' indices as follows. Using the first square brackets ([2]) we select the third novel in the list, i.e. Sense and Sensibility by Jane Austen. Then, using a second index ([:300]), we print the first 300 characters in that novel.
print(texts[2][:300])
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
After loading these documents, we can now represent them using a bag of words model. To this end, we will use a library called scikit-learn, or sklearn in shorthand, which is increasingly popular in text analysis nowadays. As you will see below, we import its CountVectorizer object below, and we apply it to our corpus,...
from sklearn.feature_extraction.text import CountVectorizer vec = CountVectorizer(max_features=10) BOW = vec.fit_transform(texts).toarray() print(BOW.shape)
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
The code block above creates a matrix which has a 9x10 shape: this means that the resulting matrix has 9 rows and 10 columns. Can you figure out where these numbers come from? To find out which words are included, we can inspect the newly created vec object as follows:
print(vec.get_feature_names())
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
As you can see, the max_features argument which we used above restricts the model to the n words which are most frequent throughout our texts. These are typically smallish function words. Funnily, sklearn uses its own tokenizer, and this default tokenizer ignores certain words that are surprisingly enough absent in the...
from sklearn.feature_extraction.text import CountVectorizer vec = CountVectorizer(max_features=10, tokenizer=nltk.word_tokenize) BOW = vec.fit_transform(texts).toarray() print(vec.get_feature_names())
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Finally, let us visually inspect the BOW model which we have converted. To this end, we make use of pandas, a Python-package that is nowadays often used to work with all sorts of data tables in Python. In the code block below, we create a new table or 'DataFrame' and add the correct row and column names:
import pandas as pd # conventional shorthand! df = pd.DataFrame(BOW, columns=vec.get_feature_names(), index=titles) print(df)
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
After creating this DataFrame, it becomes very easy to retrieve specific information from our corpus. What is the frequency, for instance, of the word 'the' in each text?
print(df['the'])
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Or the frequency of 'and' in 'Emma'?
print(df['of']['Emma'])
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Text analysis Distance metrics Now that we have converted our small dummy corpus to a bag-of-words matrix, we can finally start actually analyzing it! One very common technique to visualize texts is to render a cluster diagram or dendrogram. Such a tree-like visualization (an example will follow shortly) can be used to...
totals = BOW.sum(axis=1, keepdims=True) print(totals)
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
Now, we can efficiently 'scale' or normalize the matrix using these sums:
BOW = BOW / totals print(BOW.shape)
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit
If we inspect our new frequency table, we can see that the values are now neatly in the 0-1 range:
print(BOW)
Digital Text Analysis.ipynb
mikekestemont/leyden-workshop
mit