markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Uczenie regresji liniowej: Model: $$h_{\theta}(x) = \sum_{i=0}^n \theta_ix_i$$ Funkcja kosztu (błąd średniokwadratowy): $$J(\theta) = \frac{1}{m} \sum_{i=1}^{m} (h_{\theta}(x^{(i)}) - y^{(i)})^2$$ Po obliczeniu $\nabla J(\theta)$, zwykły SGD Perceptron a binarna regresja logistyczna
%%tikz -l arrows,automata,positioning,shapes,shapes.geometric,fit -f png -s 2000,1400 \tikzstyle{every node}=[font=\large] \tikzstyle{every path}=[line width=1pt] \node[state] (x0) {$1$}; \node[state] (x1) [below=0.5cm of x0] {$x_1$}; \node[state] (x2) [below=0.5cm of x1] {$x_2$}; \node[state, draw=none,fill=none] (do...
Wyklady/10/Sieci neuronowe.ipynb
emjotde/UMZ
cc0-1.0
Uczenie regresji logistycznej binarnej: Model: $$h_{\theta}(x) = \sigma(\sum_{i=0}^n \theta_ix_i) = P(1|x,\theta)$$ Funkcja kosztu (entropia krzyżowa): $$\begin{eqnarray} J(\theta) &=& -\frac{1}{m} \sum_{i=1}^{m} [y^{(i)}\log P(1|x^{(i)},\theta) \ && + (1-y^{(i)})\log(1-P(1|x^{(i)},\theta))]\end{eqnarray}$$ Po obli...
%%tikz -l arrows,automata,positioning,shapes,shapes.geometric,fit -f png -s 1000,600 \tikzstyle{every node}=[font=\large] \tikzstyle{every path}=[line width=1pt] \node[state] (x0) {$1$}; \node[state] (x1) [below=0.5cm of x0] {$x_1$}; \node[state] (x2) [below=0.5cm of x1] {$x_2$}; \node[state, draw=none,fill=none] (dot...
Wyklady/10/Sieci neuronowe.ipynb
emjotde/UMZ
cc0-1.0
Wieloklasowa regresji logistyczna Model (dla $c$ klasyfikatorów binarnych): $$\begin{eqnarray} h_{(\theta^{(1)},\dots,\theta^{(c)})}(x) &=& \mathrm{softmax}(\sum_{i=0}^n \theta_{i}^{(1)}x_i, \ldots, \sum_{i=0}^n \theta_i^{(c)}x_i) \ &=& \left[ P(k|x,\theta^{(1)},\dots,\theta^{(c)}) \right]_{k=1,\dots,c} \end{eqnarr...
%%tikz -l arrows,automata,positioning,shapes,shapes.geometric,fit -f png -s 1000,600 \node[state] (x1) {$x_1$}; \node[state] (x2) [below=0.5cm of x1] {$x_2$}; \node[state, draw=none,fill=none] (dots) [below=0.5cm of x2] {$\cdots$}; \node[state] (xn) [below=0.5cm of dots] {$x_n$}; \node[state,circle] (a1) [below right...
Wyklady/10/Sieci neuronowe.ipynb
emjotde/UMZ
cc0-1.0
Feedforward 1 Mając daną $n$-warstwową sieć neuronową oraz jej parametry $\Theta^{(1)}, \ldots, \Theta^{(L)} $ oraz $\beta^{(1)}, \ldots, \beta^{(L)} $ liczymy: $$a^{(l)} = g^{(l)}\left( a^{(l-1)} \Theta^{(l)} + \beta^{(l)} \right). $$ Parametry $\Theta$ to wagi na połączeniach miedzy neuronami dwóch warstw. Rozmiar...
%%tikz -l arrows,automata,positioning,shapes,shapes.geometric,fit -f png -s 1000,600 \node[state] (x1) {$x_1$}; \node[state] (x2) [below=0.5cm of x1] {$x_2$}; \node[state, draw=none,fill=none] (dots) [below=0.5cm of x2] {$\cdots$}; \node[state] (xn) [below=0.5cm of dots] {$x_n$}; \node[state,circle] (a1) [below right...
Wyklady/10/Sieci neuronowe.ipynb
emjotde/UMZ
cc0-1.0
Connecting a python function to the workbench Now we are ready to connect this model to the workbench. We have to specify the uncertainties, the outcomes, and the policy levers. For the uncertainties and the levers, we can use real valued parameters, integer valued parameters, and categorical parameters. For outcomes, ...
from ema_workbench import RealParameter, ScalarOutcome, Constant, Model from dps_lake_model import lake_model model = Model("lakeproblem", function=lake_model) # specify uncertainties model.uncertainties = [ RealParameter("b", 0.1, 0.45), RealParameter("q", 2.0, 4.5), RealParameter("mean", 0.01, 0.05), ...
docs/source/indepth_tutorial/general-introduction.ipynb
quaquel/EMAworkbench
bsd-3-clause
Performing experiments Now that we have specified the model with the workbench, we are ready to perform experiments on it. We can use evaluators to distribute these experiments either over multiple cores on a single machine, or over a cluster using ipyparallel. Using any parallelization is an advanced topic, in particu...
from ema_workbench import MultiprocessingEvaluator, ema_logging, perform_experiments ema_logging.log_to_stderr(ema_logging.INFO) with MultiprocessingEvaluator(model) as evaluator: results = evaluator.perform_experiments(scenarios=1000, policies=10)
docs/source/indepth_tutorial/general-introduction.ipynb
quaquel/EMAworkbench
bsd-3-clause
Processing the results of the experiments By default, the return of perform_experiments is a tuple of length 2. The first item in the tuple is the experiments. The second item is the outcomes. Experiments and outcomes are aligned by index. The experiments are stored in a Pandas DataFrame, while the outcomes are a dict ...
experiments, outcomes = results print(experiments.shape) print(list(outcomes.keys()))
docs/source/indepth_tutorial/general-introduction.ipynb
quaquel/EMAworkbench
bsd-3-clause
We can easily visualize these results. The workbench comes with various convenience plotting functions built on top of matplotlib and seaborn. We can however also easily use seaborn or matplotlib directly. For example, we can create a pairplot using seaborn where we group our outcomes by policy. For this, we need to cr...
policies = experiments["policy"] for i, policy in enumerate(np.unique(policies)): experiments.loc[policies == policy, "policy"] = str(i) data = pd.DataFrame(outcomes) data["policy"] = policies
docs/source/indepth_tutorial/general-introduction.ipynb
quaquel/EMAworkbench
bsd-3-clause
Next, all that is left is to use seaborn's pairplot function to visualize the data.
sns.pairplot(data, hue="policy", vars=list(outcomes.keys())) plt.show()
docs/source/indepth_tutorial/general-introduction.ipynb
quaquel/EMAworkbench
bsd-3-clause
Create the Code Save your code to a file with the %%file magic:
%%file type_util.py class TypeUtil: @classmethod def is_iterable(cls, obj): """Determines if obj is iterable. Useful when writing functions that can accept multiple types of input (list, tuple, ndarray, iterator). Pairs well with convert_to_list. """ try: ...
jup_notebooks/data-science-ipython-notebooks-master/python-data/unit_tests.ipynb
steinam/teacher
mit
Create the Nose Tests Save your test to a file with the %%file magic:
%%file tests/test_type_util.py from nose.tools import assert_equal from ..type_util import TypeUtil class TestUtil(): def test_is_iterable(self): assert_equal(TypeUtil.is_iterable('foo'), True) assert_equal(TypeUtil.is_iterable(7), False) def test_convert_to_list(self): assert_equal(...
jup_notebooks/data-science-ipython-notebooks-master/python-data/unit_tests.ipynb
steinam/teacher
mit
Run the Nose Tests Run the following command line:
!nosetests tests/test_type_util.py -v
jup_notebooks/data-science-ipython-notebooks-master/python-data/unit_tests.ipynb
steinam/teacher
mit
Generate noisy samples Draw real and imaginary part of each sample from independent normal distributions:
# Time reference: T_S = 1e-6 # seconds f_S = 1 / T_S # sampling frequency f_nyquist = f_S / 2 # nyquist frequency print(""" Sampling rate: {rate} kHz Sample period: {period} µs Nyquist frequency: {nyquist} kHz""".format(rate=f_S/1000, period=T_S*1e6, nyquist=f_nyquist/1000)) N_0 = 1; ...
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
Noise samples in complex plane
plt.axis('square'); plt.scatter(complex_noisy_samples.real, complex_noisy_samples.imag, s=6, alpha=0.3) plt.xlim(-3000, 3000); plt.ylim(-3000, 3000) plt.xlabel('In-phase component'); plt.ylabel('Quadrature component') plt.tight_layout()
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
Can you see the Gaussian bell? Where's the Gaussian?
seaborn.jointplot(complex_noisy_samples.real, complex_noisy_samples.imag, kind="reg", size=6, joint_kws={"scatter_kws": {"s":6, "alpha":0.3}}) plt.xlim(-3000, 3000); plt.ylim(-3000, 3000) plt.xlabel('In-phase component'); plt.ylabel('Quadrature component')
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
Visualize Noise
t = np.arange(num_samples) * T_S # vector of sampling time instances plt.plot(t*1e3, complex_noisy_samples.real, t*1e3, complex_noisy_samples.imag, alpha=0.7) plt.title("Time Domain of I an Q components") plt.xlabel('Time / ms'); plt.ylabel('Amplitude'); plt.legend(('inphase', 'quadrature'));
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
Autocorrelation function
plt.subplot(121) plt.acorr(complex_noisy_samples.real, usevlines=True, maxlags=50) plt.ylabel('$\phi_{\Re\Re}$'); plt.xlabel('lag / Samples'); plt.axis('tight') plt.subplot(122) plt.acorr(complex_noisy_samples.imag, usevlines=True, maxlags=50) plt.ylabel('$\phi_{\Im\Im}$'); plt.xlabel('lag / Samples'); plt.axis('tight...
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
Histogram & PDF of normal distribution
# Plot normalized histogram plt.hist(complex_noisy_samples.real, bins=40, normed=True, alpha=0.5); plt.xlabel('Amplitude'); plt.ylabel('Probability') # Plot normal distribution x = np.linspace(-3000, 3000, 100) _ = plt.plot(x,stats.norm.pdf(x,0,sigma))
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
Amplitudes are normally distributed. Try to play with number of samples and number of bins. You may also want to take a look at histogram of quadrature component. What do you expect? Power spectral density using Welch method
freqs, Pxx = signal.welch(complex_noisy_samples, fs=f_S, nfft=1024, noverlap=0, window="hanning", scaling="density", return_onesided=False) freqs = np.fft.fftshift(freqs); Pxx = np.fft.fftshift(Pxx) # Plot PSD, use logarithmic scale: plt.plot...
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
Not quite a constant, why not? Low-Pass filtered Gaussian noise
cutoff_freq = 1e5 # cutoff frequency of lowpass filter: 100 kHz numtaps = 51 # number of filter taps # FIR filter design: lpass_taps = signal.firwin(numtaps, cutoff_freq, nyq=f_nyquist) # Get filter taps freq_norm, response = signal.freqz(lpass_taps) # filter response in frequency domain freq = freq_norm * f_...
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
Filter noisy samples Actually generate low-pass filtered Gaussian noise.
# Filter noise with lowpass: filtered_x = signal.lfilter(lpass_taps, 1.0, complex_noisy_samples) # Calculate PSD: freqs, Pxx = signal.welch(filtered_x, nfft=1024, fs=f_S, window="hanning", noverlap=0, scaling="density", return_onesided=False) plt.plot(np.fft.fftshift(freqs), 10*np.log...
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
Autocorrelation function
plt.acorr(filtered_x.real, usevlines=False, maxlags=50, marker=None, linestyle='-') plt.acorr(filtered_x.imag, usevlines=False, maxlags=50, marker=None, linestyle='-') plt.xlabel('lag / Samples') plt.legend(('inphase', 'quadrature'));
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
If you compare this with the autocorrelation function of the unfiltered noise, can you explain what happened? Downsampling
# Take every 5th element of filtered signal factor = 5; filt_x_dwnsampled = filtered_x[::factor] plt.acorr(filt_x_dwnsampled.real, usevlines=False, maxlags=50, marker=None, linestyle='-') plt.acorr(filt_x_dwnsampled.imag, usevlines=False, maxlags=50, marker=None, linestyle='-') plt.title('Autocorrelation function of do...
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
What happened? Why did we take every 5th sample? Hint: take a look at the cutoff frequency of the filter and at the nyquist frequency. PSD after downsampling
freqs, Pxx = signal.welch(filt_x_dwnsampled, fs=f_S/factor,nfft=1024, window="hanning", noverlap=0, scaling="density", return_onesided=False) # Plot PSD, use logarithmic scale: plt.plot(np.fft.fftshift(freqs), 10*np.log10(np.abs(np.fft.fftshift(Pxx)))) plt.axis('tight'); plt.ylim(-70, 10) plt.ylab...
nt1/uebung/AWGN_Demo.ipynb
kit-cel/wt
gpl-2.0
Notice, we have to specify the column number where the X and Y (optionally Z) coordinates are stored. In this example, X coordinates are in the first column Y in the second one. Don't forget to specify correct column delimiter. If the data are not in the CRS we are using, create a new Location with matching CRS, import...
!lasinfo tile_0793_016_spm.las
notebooks/grass/bash/import.ipynb
wasat/JupyTEPIDE
apache-2.0
r.in.lidar module can be used to scan the spatial extent of the dataset:
!r.in.lidar input=tile_0793_016_spm.las -s
notebooks/grass/bash/import.ipynb
wasat/JupyTEPIDE
apache-2.0
Binning Before creating the actual raster with elevation, we need to decide the extent and the resolution we will use for the binning. We can use r.in.lidar module for that by setting the resolution directly and using a -e flag to use dataset extent instead of taking it from the computational region. We are interested ...
!r.in.lidar input=tile_0793_016_spm.las output=tile_0793_016_n method=n -e resolution=2
notebooks/grass/bash/import.ipynb
wasat/JupyTEPIDE
apache-2.0
After determining the optimal resolution for binning and the desired area, we can use g.region to set the computational region. r.in.lidar without the additional parameters above will create a raster map from points using binning with resolution and extent taken from the computational region:
!r.in.lidar input=tile_0793_016_spm.las output=tile_0793_016
notebooks/grass/bash/import.ipynb
wasat/JupyTEPIDE
apache-2.0
Interpolation When the result of binning contains a lot of NULL cells or when it is not smooth enough for further analysis, we can import the point cloud as vector points and interpolate a raster. Supposing that we already determined the desired extent and resolution (using r.in.lidar as described above) we can use v.i...
!v.in.lidar input=tile_0793_016_spm.las output=tile_0793_016 class=2 -r -t -b
notebooks/grass/bash/import.ipynb
wasat/JupyTEPIDE
apache-2.0
This import only the points of class 2 (ground) in the current computational region without the attribute table and building the topology. Then we follow with interpolation using, e.g. v.surf.rst module:
!v.surf.rst input=tile_0793_016 elevation=tile_0793_016_elevation slope=tile_0793_016_slope aspect=tile_0793_016_aspect npmin=100 tension=20 smooth=1
notebooks/grass/bash/import.ipynb
wasat/JupyTEPIDE
apache-2.0
Importing data in different CRS In case the CRS of the file doesn't match the CRS used in the GRASS Location, reprojection can be done before importing using las2las tool. The following example command is for reprojecting tiles in NAD83/North Carolina in feet (EPSG:2264) into NAD83/North Carolina in meters (EPSG:3358):
!las2las --a_srs=EPSG:2264 --t_srs=EPSG:3358 -i input_spf.las -o output_spm.las
notebooks/grass/bash/import.ipynb
wasat/JupyTEPIDE
apache-2.0
Importing data with broken projection information Modules r.in.lidar and v.in.lidar check whether the CRS of the imported data matches the Location's CRS. Sometimes the CRS of imported data is not specified correctly or is missing and therefore import fails. If you know that the actual CRS matches the Location's CRS, i...
!r.in.lidar input=tile_0793_016_spm.las -s -o
notebooks/grass/bash/import.ipynb
wasat/JupyTEPIDE
apache-2.0
Transferring GRASS GIS data between two computers If two GRASS GIS users want to exchange data, they can use GRASS GIS native exchange format -- packed map. A vector or raster map can be exported from a GRASS Location in this format using v.pack or r.pack respectively. This format preserves everything for a map in a wa...
# end the GRASS session os.remove(rcfile)
notebooks/grass/bash/import.ipynb
wasat/JupyTEPIDE
apache-2.0
2. Generador congruencial lineal
def lcg(n, m=2**31-1, a=16807, c=0, seed=2**30): x = np.zeros(n+1) x[0]=seed for i in range(1,n+1): x[i] = (a * x[i-1]+c)%m return x[1:]/m
02. Parte 2/13. Clase 13/.ipynb_checkpoints/06Class NB-checkpoint.ipynb
jdsanch1/SimRC
mit
Ejemplo
lcg(10, m=31, a=13, c=0, seed=3)
02. Parte 2/13. Clase 13/.ipynb_checkpoints/06Class NB-checkpoint.ipynb
jdsanch1/SimRC
mit
Generador mínimo estándar
x=lcg(10000) sns.distplot(x, color="b", fit=stats.uniform);
02. Parte 2/13. Clase 13/.ipynb_checkpoints/06Class NB-checkpoint.ipynb
jdsanch1/SimRC
mit
Generado Randu (Usado por IBM)
x=lcg(10000, m=2**31, a=2**16+3, c=0, seed=3) sns.distplot(x, color="b", fit=stats.uniform);
02. Parte 2/13. Clase 13/.ipynb_checkpoints/06Class NB-checkpoint.ipynb
jdsanch1/SimRC
mit
3. Método de Box-Muller
def bm(n): m=2**31-1 a=16807 c=0 seed=2**30 x = np.zeros(n+1) x[0]=seed for i in range(1,n+1): x[i] = (a * x[i-1]+c)%m u=x[1:]/m u1=u[:int((n/2))] u2=u[int(n/2):] nn=np.concatenate((np.sqrt(-2*np.log(1-u1))*np.cos(2*np.pi*u2), np.sqrt(-2*np.log(1-u1))*np.sin(2*np.pi*u...
02. Parte 2/13. Clase 13/.ipynb_checkpoints/06Class NB-checkpoint.ipynb
jdsanch1/SimRC
mit
To shut the window showing the simulation, use env.close().
env.close()
reinforcement/Q-learning-cart.ipynb
azhurb/deep-learning
mit
If you ran the simulation above, we can look at the rewards:
print(rewards[-20:])
reinforcement/Q-learning-cart.ipynb
azhurb/deep-learning
mit
Creating a class Defining your own classes allows you to create a completely customisable data type for your own needs. This will be guided by the problem you are solving, you might need to create a class Cell() for a computational biology task, when you are modelling lots of kinds of cells. Or you might create a class...
# Let me create a class Dog # This is the how you declare a class class Dog(object): # You can then declare Data members of the class Dog() name = '' age = '' breed = '' animal = 'Dog' # Creating object of class Dog is now as easy as creating any of the standard variables my_dog = Dog() my_dog.name...
lesson5.ipynb
trsherborne/learn-python
mit
Initialising a class with a constructor We can initialise our class in a smarter way using a constructor, which means we can initialise the Dog() object on one line as below. The self keyword you see when making a class is the way that we refer to the specific instance of the class we want inside the class itself.
class Dog(object): # You can then declare Data members of the class Dog() animal = 'Dog' # This is similar to all the other functions you have written but the args start with self def __init__(self,name,age,breed): self.name = name self.age = age self.breed = bre...
lesson5.ipynb
trsherborne/learn-python
mit
Creating methods of a class First things first. When we tried to print the Dog() class we didn't get something that was entirely useful. This is because when we want to print our own classes, we need to tell Python how to print it, and we do that using the __str__ method. One note: the __str__ method and the __repr__ ...
class Dog(object): __animal = 'Dog' def __init__(self,name,age,breed): self.name = name self.age = age self.breed = breed def __str__(self): return 'Hi my name is {} and I am a {} year old {}'.format(self.name,self.age,self.breed) my_other_d...
lesson5.ipynb
trsherborne/learn-python
mit
Any method between the __example__ double underscores is a special method called a magic method which we will look at further below. We can also define other methods as function attributes of the class which can take arguments like an isolated function
class Dog(object): __animal = 'Dog' def __init__(self,name,age,breed,favourite_toy): self.name = name self.age = age self.breed = breed self.favourite_toy = favourite_toy def __str__(self): return 'Hi my name is {} and I am a {} year ...
lesson5.ipynb
trsherborne/learn-python
mit
Magic Methods Magic methods (like __str__) are what allows your own classes to behave similarly to the Python built in types. Instinctively it is hard to image how to do dog_a > dog_b, but if we use magic methods then this behaviour is definable. A detailed list of the definitions of the different kind of Magic Meth...
class Dog(object): __animal = 'Dog' def __init__(self,name,age,breed,favourite_toy): self.name = name self.age = age self.breed = breed self.favourite_toy = favourite_toy # THESE ARE ALL MAGIC METHODS def __str__(self): return 'Hi ...
lesson5.ipynb
trsherborne/learn-python
mit
Challenge for today Create a class Human() which has attributes 'name', 'age' and 'height' (in centimetres). Add a constructor to the class to be able to create Human objects in a program. Add magic methods to the class to be able to compare Humans by age Add a method to class Human() to return the age of the Human i...
class Human(object): #Everything goes here!
lesson5.ipynb
trsherborne/learn-python
mit
This is the test block, run this to evaluate your code.
joe = Human('Joe',19,174) lisa = Human('Lisa',23,181) chu = Human('Chu',23,160) # Test the attributes set by the Constructor try: print(joe.name) print(lisa.age) print(chu.height) except AttributeError as e: print('Your attributes are not working correctly :(\n') else: print('All your attributes ar...
lesson5.ipynb
trsherborne/learn-python
mit
Using scalar aggregates in filters
table = con.table('functional_alltypes') table.limit(5)
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
We could always compute some aggregate value from the table and use that in another expression, or we can use a data-derived aggregate in the filter. Take the average of a column for example:
table.double_col.mean()
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
You can use this expression as a substitute for a scalar value in a filter, and the execution engine will combine everything into a single query rather than having to access Impala multiple times:
cond = table.bigint_col > table.double_col.mean() expr = table[cond & table.bool_col].limit(5) expr
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
Conditional aggregates Suppose that we wish to filter using an aggregate computed conditional on some other expressions holding true. Using the TPC-H datasets, suppose that we want to filter customers based on the following criteria: Orders such that their amount exceeds the average amount for their sales region over t...
region = con.table('tpch_region') nation = con.table('tpch_nation') customer = con.table('tpch_customer') orders = con.table('tpch_orders') fields_of_interest = [customer, region.r_name.name('region'), orders.o_totalprice, orders.o_orderdate.cast('time...
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
In this particular case, filtering based on the conditional average o_totalprice by region requires creating a table view (similar to the self-join examples from earlier) that can be treated as a distinct table entity in the expression. This would not be required if we were computing a conditional statistic from some o...
t2 = tpch.view() conditional_avg = t2[(t2.region == tpch.region)].o_totalprice.mean()
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
Once you've done this, you can use the conditional average in a filter expression
amount_filter = tpch.o_totalprice > conditional_avg tpch[amount_filter].limit(10)
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
By looking at the table sizes before and after applying the filter you can see the relative size of the subset taken.
tpch.count() tpch[amount_filter].count()
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
Or even group by year and compare before and after:
tpch.schema() year = tpch.odate.year().name('year') pre_sizes = tpch.group_by(year).size() post_sizes = tpch[amount_filter].group_by(year).size().view() percent = ((post_sizes['count'] / pre_sizes['count'].cast('double')) .name('fraction')) expr = (pre_sizes.join(post_sizes, pre_sizes.year == post_sizes....
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
"Existence" filters Some filtering involves checking for the existence of a particular value in a column of another table, or amount the results of some value expression. This is common in many-to-many relationships, and can be performed in numerous different ways, but it's nice to be able to express it with a single c...
customer = con.table('tpch_customer') orders = con.table('tpch_orders') orders.limit(5)
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
We introduce the any reduction:
has_open_orders = ((orders.o_orderstatus == 'O') & (customer.c_custkey == orders.o_custkey)).any()
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
This is now a valid filter:
customer[has_open_orders].limit(10)
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
For the second example, in which we want to find customers not having any open urgent orders, we write down the condition that they do have some first:
has_open_urgent_orders = ((orders.o_orderstatus == 'O') & (orders.o_orderpriority == '1-URGENT') & (customer.c_custkey == orders.o_custkey)).any()
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
Now, we can negate this condition and use it as a filter:
customer[-has_open_urgent_orders].count()
docs/source/notebooks/tutorial/7-Advanced-Topics-ComplexFiltering.ipynb
deepfield/ibis
apache-2.0
A. http://httpbin.org/get?a=b B. http://httpbin.org/get?c=d C. http://httpbin.org/get?a=b&c=d D. http://httpbin.org/get Vote Now: https://poll.ist256.com FEQT (Future Exam Questions Training) 2 Which line de-serializes the response?
import requests # <= load up a bunch of pre-defined functions from the requests module w = 'http://httpbin.org/ip' # <= string response = requests.get(w) # <= w is a url. HTTP POST/GET/PUT/DELETE Verbs of HTTP response.raise_for_status() # <= response code.if not 2??, throw exception 4 clie...
content/lessons/11-WebAPIs/Slides.ipynb
IST256/learn-python
mit
A. 2 B. 3 C. 4 D. 5 Vote Now: https://poll.ist256.com Agenda Lesson 10 Homework Solution A look at web API's Places to find web API's How to read API documentation Examples of using API's Connect Activity Question: A common two-step verification process uses by API's discussed in the reading is A. OAUTH2 B. Mu...
import requests url = "http://data.fixer.io/api/latest?access_key=159f1a48ad7a3d6f4dbe5d5a" response = requests.get(url) response.json()
content/lessons/11-WebAPIs/Slides.ipynb
IST256/learn-python
mit
Exercise 1.2 Write down a function that takes the list of all names of the files you downloaded in Exercise 1.1 and compile them into one single file. There must be only one header line in the output file. For example, if file_1 has: line 1... line 2... and the other file, file_2, has: line 3... line 4... line 5... We...
def create_master_turnstile_file(filenames, output_file): with open(output_file, 'w') as master_file: master_file.write('C/A,UNIT,SCP,STATION, LINENAME, DIVISION, DATEn,TIMEn,DESCn,ENTRIESn,EXITSn\n') for filename in filenames: # your code here
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
Exercise 1.3 For this exercise, you will write a function that reads the master_file created in the previous exercise and load it into a Pandas Dataframe. This function can be filtered, so that the Dataframe only has lines where column "DESCn" has the value "Regular". For example, if the Pandas Dataframe looks like thi...
import pandas def filter_by_regular(filename): turnstile_data = # your code here # more of your code here return turnstile_data
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
Exercise 1.4 The NYC Subway data has cumulative entry and exit data in each line. Let's assume you have a Dataframe called df, which contains only lines for one particular turnstile (unique SCP, C/A, and UNIT). The following function must change these cumulative entries for counting all entries since the last reading (...
import pandas def get_hourly_entries(df): #your code here return df
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
Exercise 1.5 Do the same thing you did in the previous exercise, but taking into account the exits, column EXITSn. For this, you need to create a column called EXITSn_hourly and insert the difference between the column EXITSn in the current line vs he previous line. If there is any NaN, fill it out/replace by 0.
import pandas def get_hourly_exits(df): #your code here return df
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
Exercise 1.6 Given an entry variable that represents time, in the format:      "00:00:00" (hour: minutes: seconds)      Write a function to extract the hour part from the time in the entry variable And return it as an integer. For example:          1) if hour is 00, your code must return 0          2) if hour...
def time_to_hour(time): hour = # your code here return hour
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
Exercise 2 - Data Analysis Exercise 2.1 To understand the relationship between the Subway activity and the weather, please complete the data from the file already downloaded with the weather data. We provided you with the file containing NYC weather data and made it available with the Support Material. You can access i...
import pandas as pd filename = "turnstile_data_master_with_weather.csv" #your code here
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
Exercise 2.2 Now, create a function that calculates the number of rainy days. For this, return the count of the number of days where the column "rain" is equal to 1. Tip: You might think that interpreting numbers as integers or floats might not      work at first. To handle this issue, it might be useful to convert    ...
def num_rainy_days(df): #your code here return
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
Exercise 2.3 Calculate if the day was cloudy or not (0 or 1) and the maximum temperature for fog (i.e. the maximum temperature      for cloudy days).
def max_temp_aggregate_by_fog(df): #your code here return
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
*Exercise 2.4 Now, calculate the mean for 'meantempi' for the days that are Saturdays or Sundays (weekend):
def avg_weekend_temperature(filename): mean_temp_weekends = return mean_temp_weekends
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
*Exercise 2.5 Calculate the mean of the minimum temperature 'mintempi' for the days when the minimum temperature was greater that 55 degrees:
def avg_min_temperature(filename): avg_min_temp_rainy = return avg_min_temp_rainy
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
*Exercise 2.6 Before you make any analysis, it might be useful to look at the data we want to analyse. More specifically, we will evaluate the entries by hour in our data from the NYC Subway to determine the data distribution. This data is stored in the column ['ENTRIESn_hourly'].      Draw two histogramns in the same ...
import numpy as np import pandas import matplotlib.pyplot as plt def entries_histogram(turnstile_weather): plt.figure() turnstile_weather['...'] # your code here to plot a historgram for hourly entries when it is raining turnstile_weather['...'] # your code here to plot a histogram for hourl...
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
*Exercise 2.7 The data you just plotted is in what kind of distribution? Is there a difference in distribution between rainy and non-rainy days? Answer : Replace this text with your answer! *Exercise 2.8 Build a function that returns: The mean of entries when it's raining The mean of entries when it's not raining
import numpy as np import pandas def means(turnstile_weather): ### YOUR CODE HERE ### return with_rain_mean, without_rain_mean, p # leave this line for the grader
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
Answer to the following questions according to your functions' exits: What is the mean of entries when it's raining? What is the mean of entries when it's not raining? Answer : Replace this text with your answer! Exercise 3 - Map Reduce Exercise 3.1 The entry for this exercise is the same file from the previous sess...
import sys def mapper(): for line in sys.stdin: # your code here mapper() sys.stdin = open('turnstile_data_master_with_weather.csv') sys.stdout = open('mapper_result.txt', 'w')
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
Exercise 3.2 Now, create the reducer. Given the mapper result from the previous exercise, the reducer must print (not return) one line per UNIT, with the total number of ENTRIESn_hourly during May (which is our data duration), separated by a tab. An example of exit line from the reducer may look like this: 'R001 \ t500...
def reducer(): for line in sys.stdin: # your code here reducer()
Analyzing_Subway_Data_NDFDSI.ipynb
sarathid/Learning
gpl-3.0
Load data
datadirs = ['/home/etienne/Dropbox/neoReader/Data', 'C:/etienne/Dropbox/neoReader/Data', '/Users/etienne/Dropbox/neoReader/Data'] fileroot = next( (dir for dir in datadirs if os.path.isdir(dir)), None) animal = 'gor01'; month,day = (6,7); session = '11-26-53' # WARNING! POSITION DATA INCOMPLET...
KLscore.ipynb
kemerelab/NeuroHMM
mit
Basic visualization of hmm state evolutions
myhmm.transmat_.sum(axis=1) # confirm orientation of transition prob matrix A = myhmm.transmat_.copy() fig, ax = plt.subplots(figsize=(3.5, 3)) im = ax.matshow(A, interpolation='none', cmap='RdPu') # Make an axis for the colorbar on the right side cax = fig.add_axes([0.9, 0.1, 0.03, 0.8]) fig.colorbar(im, cax=cax) m =...
KLscore.ipynb
kemerelab/NeuroHMM
mit
Remark: Note that steady-state state information is related to the eigenvectors of $\mathbf{A}$, since $p(S)\mathbf{A} = p(S) \implies p(S)$ is a steady-state state distribution, such that $p(S)$ is an eigenvector of $\mathbf{A}$ with associated eigenvalue $\lambda = 1$.
seq_id = 0 tmpseqbdries = [0]; tmpseqbdries.extend(np.cumsum(ts_b.sequence_lengths).tolist()); obs = ts_b.data[tmpseqbdries[seq_id]:tmpseqbdries[seq_id+1],:] ll, pp = myhmm.score_samples(obs) fig, ax = plt.subplots(figsize=(10, 3)) ax.matshow(np.transpose(pp)) def advance_states_one(pp, A): return np.dot(pp, A) p...
KLscore.ipynb
kemerelab/NeuroHMM
mit
Remark: What if our pmfs contain any zeros? Problem! One way to think about your problem is that you don't really have confidence in the PMF you have calculated from the histogram. You might need a slight prior in your model. Since if you were confident in the PMF, then the KL divergence should be infinity since you g...
from scipy.stats import entropy as KLD KLlist = [] KLlist_shfl = [] for ii in np.arange(1,len(pth)): KLlist.append(KLD(pp[ii,:],ppp[ii,:])) KLlist_shfl.append(KLD(pp_shfl[ii,:],ppp_shfl[ii,:])) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 3)) ax1.plot(np.cumsum(KLlist), label='sequence', lw=1.5) ax1.pl...
KLscore.ipynb
kemerelab/NeuroHMM
mit
First look at shuffle distribution for single sequence
def KL(distr_matU, distr_matV): from scipy.stats import entropy as KLD num_bins = distr_matU.shape[0] KLarray = np.zeros(num_bins) for ii in np.arange(1,num_bins): KLarray[ii-1] = KLD(distr_matU[ii,:],distr_matV[ii,:]) return KLarray.mean() from random import shuffle #######...
KLscore.ipynb
kemerelab/NeuroHMM
mit
Now look at entire data set, with shuffles for each sequence In particular, we consider all the sequences in the test set of running behavior, ts_b, none of which have been seen by the HMM before.
from random import shuffle ###########################################################3 stacked_data = ts_b n_shuffles = 250 # shuffles PER sequence in data set ###########################################################3 num_sequences = len(stacked_data.sequence_lengths) tmpseqbdries = [0]; tmpseqbdries.extend(np.cu...
KLscore.ipynb
kemerelab/NeuroHMM
mit
Suppose you are tracking a rotating part and want to estimate its angle, in degrees, as a function of time, given noisy measurements of its position and velocity. I'll represent possible positions using a vector of 360 values in degrees.
n = 360 xs = np.arange(n)
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
I'll represent distributions using a Numpy array of probabilities. The following function takes a Numpy array and normalizes it so the probabilities add to 1.
def normalize(dist): dist /= sum(dist)
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
The following function creates a discrete approximation of a Gaussian distribution with the given parameters, evaluated at the given positions, xs:
def gaussian(xs, mu, sigma): dist = stats.norm.pdf(xs, loc=180, scale=sigma) dist = np.roll(dist, mu-180) normalize(dist) return dist
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
Suppose that initially we believe that the position of the part is 180 degrees, with uncertainty represented by a Gaussian distribution with $\sigma=4$. Here's what that looks like:
pos = gaussian(xs, mu=180, sigma=4) plt.plot(xs, pos);
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
And suppose that we believe the part is rotating at an angular velocity of 15 degrees per time unit, with uncertainty represented by a Gaussian distribution with $\sigma=3$:
move = gaussian(xs, mu=15, sigma=3) plt.plot(xs, move);
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
The predict step What should we believe about the position of the part after one time unit has elapsed? A simple way to estimate the answer is to draw samples from the distributions of position and velocity, and add them together. The following function draws a sample from a distribution (again, represented by a Numpy ...
def sample_dist(xs, dist, n=1000): series = pd.Series(xs) return series.sample(n=n, weights=dist, replace=True).values
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
As a quick check, the sample from the position distribution has the mean and standard deviation we expect.
pos_sample = sample_dist(xs, pos) pos_sample.mean(), pos_sample.std()
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
And so does the sample from the distribution of velocities:
move_sample = sample_dist(xs, move) move_sample.mean(), move_sample.std()
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
When we add them together, we get a sample from the distribution of positions after one time unit. The mean is the sum of the means, and the standard deviation is the hypoteneuse of a triangle with the other two standard deviations. In this case, it's a 3-4-5 triangle:
sample = pos_sample + move_sample sample.mean(), sample.std()
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
Based on the samples, we can estimate the distribution of the sum. To compute the distribution of the sum exactly, we can iterate through all possible values from both distributions, computing the sum of each pair and the product of their probabilities:
def add_dist(xs, dist1, dist2): res = np.zeros_like(dist1) for x1, p1 in zip(xs, dist1): for x2, p2 in zip(xs, dist2): x = (x1 + x2) % 360 res[x] = res[x] + p1 * p2 return res
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
This algorithm is slow (taking time proportional to $N^2$, where $N$ is the length of xs), but it works:
new_pos = add_dist(xs, pos, move)
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
Here's what the result looks like:
plt.plot(xs, new_pos);
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
And we can check the mean and standard deviation:
def mean_dist(xs, dist): return sum(xs * dist)
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
The mean of the sum is the sum of the means:
mu = mean_dist(xs, new_pos) mu
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
And the standard deviation of the sum is the hypoteneuse of the standard deviations:
def std_dist(xs, dist, mu): return np.sqrt(sum((xs - mu)**2 * dist))
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
Which should be 5:
sigma = std_dist(xs, new_pos, mu) sigma
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
What we just computed is the convolution of the two distributions. Now we get to the fun part. The characteristic function is an alternative way to represent a distribution. It is the Fourier transform of the probability density function, or for discrete distributions, the DFT of the probability mass function. I'll u...
from numpy.fft import fft char_pos = fft(pos) plt.plot(xs, np.abs(char_pos));
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit
The Fourier transform of a Gaussian is also a Gaussian, which we can see more clearly if we rotate the characteristic function before plotting it.
plt.plot(xs, np.roll(np.abs(char_pos), 180));
convolution.ipynb
AllenDowney/ProbablyOverthinkingIt
mit