markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Read the data and get a row count. Data source: U.S. Department of Transportation, TranStats database. Air Carrier Statistics Table T-100 Domestic Market (All Carriers): "This table contains domestic market data reported by both U.S. and foreign air carriers, including carrier, origin, destination, and service class...
file_path = r'data\T100_2015.csv.gz' df = pd.read_csv(file_path, header=0) df.count() df.head(n=10) df = pd.read_csv(file_path, header=0, usecols=["PASSENGERS", "ORIGIN", "DEST"]) df.head(n=10) print('Min: ', df['PASSENGERS'].min()) print('Max: ', df['PASSENGERS'].max()) print('Mean: ', df['PASSENGERS'].mean()) df...
scipy/demos/DevSummit 2016.ipynb
EsriOceans/oceans-workshop-2016
apache-2.0
SymPy SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible.
import sympy from sympy import * from sympy.stats import * from sympy import symbols from sympy.plotting import plot from sympy.interactive import printing printing.init_printing(use_latex=True) print('Sympy version ' + sympy.__version__)
scipy/demos/DevSummit 2016.ipynb
EsriOceans/oceans-workshop-2016
apache-2.0
This example was gleaned from: Rocklin, Matthew, and Andy R. Terrel. "Symbolic Statistics with SymPy." Computing in Science & Engineering 14.3 (2012): 88-93. Problem: Data assimilation -- we want to assimilate new measurements into a set of old measurements. Both sets of measurements have uncertainty. For example, AC...
T = Normal('T', 30, 3)
scipy/demos/DevSummit 2016.ipynb
EsriOceans/oceans-workshop-2016
apache-2.0
What is the probability that the temperature is actually greater than 33 degrees? <img src="eq1.png"> We can use Sympy's integration engine to calculate a precise answer.
P(T > 33) N(P(T > 33))
scipy/demos/DevSummit 2016.ipynb
EsriOceans/oceans-workshop-2016
apache-2.0
Assume we now have a thermometer and can measure the temperature. However, there is still uncertainty involved.
noise = Normal('noise', 0, 1.5) observation = T + noise
scipy/demos/DevSummit 2016.ipynb
EsriOceans/oceans-workshop-2016
apache-2.0
We now have two measurements -- 30 +- 3 degrees and 26 +- 1.5 degrees. How do we combine them? 30 +- 3 was our prior measurement. We want to cacluate a better estimate of the temperature (posterior) given an observation of 26 degrees. <img src="eq2.png">
T_posterior = given(T, Eq(observation, 26))
scipy/demos/DevSummit 2016.ipynb
EsriOceans/oceans-workshop-2016
apache-2.0
А також функції для визначення положення підвісу та вантажу у довільний момент часу: $x_1(t) = x(t)$ $x_2(t) = x_1(t)+lsin(\alpha(t))$ $y_2(t) = -lcos(\alpha(t))$
def x1(): return xr() def x2(): return x1()+l*sin(ar()) def y2(): return -l*cos(ar())
pendulum_model.ipynb
nikita-mayorov/math_modelling
gpl-3.0
Визначаємо початкові умови:
g = 9.8 # Час прискорення вільного падіння. m1 = 3.0 # Маса підвісу. m2 = 2.0 # Маса вантажу. l = 6.0 # Довжина тросу підвісу. a0 = pi/4.0 # Кут початкового відхилення від положення рівноваги. v0 = 2.0 # Початкова швидкість. x0 = 0.0 # Початкова координата по вісі Ox. global_length, delta = 15.0, 0...
pendulum_model.ipynb
nikita-mayorov/math_modelling
gpl-3.0
Будуємо графіки:
figure1 = plt.figure() plot1 = figure1.add_subplot(3, 2, 1) plot2 = figure1.add_subplot(3, 2, 2) plot3 = figure1.add_subplot(3, 1, 2) for ax in figure1.axes: ax.grid(True) plt.subplots_adjust(top=2.0, right=2.0, wspace=0.10, hspace=0.25) plot1.plot(t, xr(), 'g') plot2.plot(t, ar(), 'g') plot3.plot(x1(), [0.01 for ...
pendulum_model.ipynb
nikita-mayorov/math_modelling
gpl-3.0
Апроксимація побудованої моделі методом Ейлера Зведення до системи рівнянь першого порядку \begin{equation} \left{ \begin{matrix} l\ddot{\alpha}+\ddot{x}+g\alpha=0\ (m_1+m_2)\ddot{x}+m_1l\ddot{\alpha}=0\ \end{matrix} \right. \end{equation} Отримана система містить рівняння другого порядку. Отже, для побудови наближенн...
x = arange(x0, global_length, delta) a = arange(x0, global_length, delta) y = arange(x0, global_length, delta) b = arange(x0, global_length, delta) x[0], a[0], y[0], b[0] = x0, a0, v0, sqrt(g/l) for i in range(0, len(t)-1): x[i+1] = x[i] + delta * y[i] a[i+1] = a[i] + delta * b[i] y[i+1] = y[i] + delta * (m...
pendulum_model.ipynb
nikita-mayorov/math_modelling
gpl-3.0
Будуємо графіки:
figure2 = plt.figure() plot4 = figure2.add_subplot(3, 2, 1) plot5 = figure2.add_subplot(3, 2, 2) plot6 = figure2.add_subplot(3, 1, 2) for ax in figure2.axes: ax.grid(True) plt.subplots_adjust(top=2.0, right=2.0, wspace=0.10, hspace=0.25) plot4.plot(t, xr(), 'r') plot4.plot(t, x, 'b') plot5.plot(t, ar(), 'r') plot5...
pendulum_model.ipynb
nikita-mayorov/math_modelling
gpl-3.0
Specifying the model in pymc3 mirrors its statistical specification.
model = pm.Model() with model: sigma = pm.Exponential('sigma', 1./.02, testval=.1) nu = pm.Exponential('nu', 1./10) s = GaussianRandomWalk('s', sigma**-2, shape=n) r = pm.T('r', nu, lam=pm.exp(-2*s), observed=returns)
pymc3/examples/stochastic_volatility.ipynb
jameshensman/pymc3
apache-2.0
2 - Outline of the Assignment You will be implementing the building blocks of a convolutional neural network! Each function you will implement will have detailed instructions that will walk you through the steps needed: Convolution functions, including: Zero Padding Convolve window Convolution forward Convolution bac...
# GRADED FUNCTION: zero_pad def zero_pad(X, pad): """ Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image, as illustrated in Figure 1. Argument: X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images pad -- i...
Convolutional Neural Networks/Convolution+model+-+Step+by+Step+-+v2.ipynb
AhmetHamzaEmra/Deep-Learning-Specialization-Coursera
mit
Expected Output: <table> <tr> <td> **x.shape**: </td> <td> (4, 3, 3, 2) </td> </tr> <tr> <td> **x_pad.shape**: </td> <td> (4, 7, 7, 2) </td> </tr> <tr> <td> **x[1...
# GRADED FUNCTION: conv_single_step def conv_single_step(a_slice_prev, W, b): """ Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation of the previous layer. Arguments: a_slice_prev -- slice of input data of shape (f, f, n_C_prev) W -- Weight ...
Convolutional Neural Networks/Convolution+model+-+Step+by+Step+-+v2.ipynb
AhmetHamzaEmra/Deep-Learning-Specialization-Coursera
mit
Expected Output: <table> <tr> <td> **Z** </td> <td> -6.99908945068 </td> </tr> </table> 3.3 - Convolutional Neural Networks - Forward pass In the forward pass, you will take many filters and convolve them on the input. Each 'convolution' gives you a 2D m...
# GRADED FUNCTION: conv_forward def conv_forward(A_prev, W, b, hparameters): """ Implements the forward propagation for a convolution function Arguments: A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) W -- Weights, numpy array of shap...
Convolutional Neural Networks/Convolution+model+-+Step+by+Step+-+v2.ipynb
AhmetHamzaEmra/Deep-Learning-Specialization-Coursera
mit
Expected Output: <table> <tr> <td> A = </td> <td> [[[[ 1.74481176 0.86540763 1.13376944]]] [[[ 1.13162939 1.51981682 2.18557541]]]] </td> </tr> <tr> <td> A = </td> <td> [[[[ 0.02105773 -0.20328806 -0.40389855]]] [[[-0.22154621 ...
def conv_backward(dZ, cache): """ Implement the backward propagation for a convolution function Arguments: dZ -- gradient of the cost with respect to the output of the conv layer (Z), numpy array of shape (m, n_H, n_W, n_C) cache -- cache of values needed for the conv_backward(), output of conv...
Convolutional Neural Networks/Convolution+model+-+Step+by+Step+-+v2.ipynb
AhmetHamzaEmra/Deep-Learning-Specialization-Coursera
mit
Expected Output: <table> <tr> <td> **x =** </td> <td> [[ 1.62434536 -0.61175641 -0.52817175] <br> [-1.07296862 0.86540763 -2.3015387 ]] </td> </tr> <tr> <td> **mask =** </td> <td> [[ True False False] <br> [False False False]] </td> </tr> </table> Why do we keep track of the position of the max? It's b...
def distribute_value(dz, shape): """ Distributes the input value in the matrix of dimension shape Arguments: dz -- input scalar shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz Returns: a -- Array of size (n_H, n_W) for which we dis...
Convolutional Neural Networks/Convolution+model+-+Step+by+Step+-+v2.ipynb
AhmetHamzaEmra/Deep-Learning-Specialization-Coursera
mit
Expected Output: <table> <tr> <td> distributed_value = </td> <td> [[ 0.5 0.5] <br\> [ 0.5 0.5]] </td> </tr> </table> 5.2.3 Putting it together: Pooling backward You now have everything you need to compute backward propagation on a pooling layer. Exercise: Implement the pool_backward function in both modes ("max"...
def pool_backward(dA, cache, mode = "max"): """ Implements the backward pass of the pooling layer Arguments: dA -- gradient of cost with respect to the output of the pooling layer, same shape as A cache -- cache output from the forward pass of the pooling layer, contains the layer's input and h...
Convolutional Neural Networks/Convolution+model+-+Step+by+Step+-+v2.ipynb
AhmetHamzaEmra/Deep-Learning-Specialization-Coursera
mit
Compute DICS beamfomer on evoked data Compute a Dynamic Imaging of Coherent Sources (DICS) beamformer from single trial activity in a time-frequency window to estimate source time courses based on evoked data. The original reference for DICS is: Gross et al. Dynamic imaging of coherent sources: Studying neural interact...
# Author: Roman Goj <roman.goj@gmail.com> # # License: BSD (3-clause) import mne import matplotlib.pyplot as plt import numpy as np from mne.datasets import sample from mne.time_frequency import compute_epochs_csd from mne.beamformer import dics print(__doc__) data_path = sample.data_path() raw_fname = data_path +...
0.12/_downloads/plot_dics_beamformer.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Read raw data
raw = mne.io.read_raw_fif(raw_fname) raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set picks picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=False, stim=False, exclude='bads') # Read epochs event_id, tmin, tmax = 1, -0.2, 0.5 events = mne.read_events(event_fname) epo...
0.12/_downloads/plot_dics_beamformer.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
As some you were asking about differences between Python2 and Python3, here is an example:
# This is an online comment: Python3 print('hello world') # Python2: print 'hello world'
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
More broadly speaking, some function interfaces (here print function) change. We will encounter other examples as we move along. More information regarding this issue is available at https://wiki.python.org/moin/Python2orPython3. Basic Types We now look at different types of objects that Python offers: floats, interger...
1 * 1.0 a = 3.0 type(a) b = 3 > 5 type(b) a = int(a) type(a)
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
What about integer division?
# Different between Python2 and Python3 3 / 2
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
Let us now turn to containers: lists, strings, etc.
L = ['red', 'blue', 'green', 'black', 'white'] L[3], L[-2], L[3:], L[3:4]
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
Lists are mutable objects, i.e. they can be changed.
L[1] = 'yellow'
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
There is an important distinction between independent copies and references to objects.
G = L L[1] = 'blue' L, G G = L[:] L[1] = 'yellow' L, G
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
How to work with lists, or objects more generally?
L.append('pink') print(L) L.pop() print(L)
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
Now we turn to tuples, which are immutable objects.
T = 'white', 'black', 'yellow' T T[1] = 'brown'
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
As you asked, here is one way to delete objects.
print(T) del T print(T)
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
Now, let us turn to dictionaries, which are tables that map keys to values.
tel = {'Yike': 4546456, 'Philipp': 773456454} tel tel[1] # What is Yike's telephone number? tel['Yike'] # How do we add Adam? tel['Adam'] = 7745464 tel # What keys are defined in our dictionary so far? tel.keys() # Yike has a new telephone number. tel['Yike'] = 77378797
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
Control Flow
a, b = 1, 5 if a == 1: print(1) elif a == 2: print(2) else: if b == 5: print('A lot') # Note the indentation. for key_ in tel.keys(): print(key_, tel[key_])
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
Functions It is important to distinguish between required, optional, and default arguments.
def return_phone_number(book, name = 'Philipp'): ''' This unction returns the telephone nummber for the requested name. ''' # Check inputs. assert (isinstance(name, str)), 'The requested name needs to be a string object.' assert (name in ['Yike', 'Philipp', 'Adam']) return book[name] retur...
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
Next Steps Python Environment Python Science Stacks Quantitative Economics Virtual Machines Data Science Toolbox VM Depot VagrantCloud Dual Boot Mac Windows Miscellaneous Keyboard Shortcuts Markdown Tutorial Formatting
import urllib; from IPython.core.display import HTML HTML(urllib.urlopen('http://bit.ly/1Ki3iXw').read())
lectures/python_basics/lecture.ipynb
softEcon/bootcamp
mit
Mean and variance PDF of a Gaussian using ABC The mean As an illustration of Approximate Bayesian Computation (ABC), we will infer first the mean and then the variance of a Gaussian. First we generate the mock data
data= numpy.random.normal(size=100)
inference/Gaussian-ABC-Inference.ipynb
jobovy/misc-notebooks
bsd-3-clause
First we assume that we know the variance and constrain the PDF for the mean. Let's write a simple function that samples the PDF using ABC. The sample mean is a sufficient statistic for the mean, so we will use that together with the absolute value of the difference between that and that of the simulated data as the di...
def Mean_ABC(n=1000,threshold=0.05): out= [] for ii in range(n): d= threshold+1. while d > threshold: m= numpy.random.uniform()*4-2. sim= numpy.random.normal(size=len(data))+m d= numpy.fabs(numpy.mean(sim)-numpy.mean(data)) out.append(m) return out
inference/Gaussian-ABC-Inference.ipynb
jobovy/misc-notebooks
bsd-3-clause
Now we sample the PDF using ABC:
mean_pdfsamples_abc= Mean_ABC()
inference/Gaussian-ABC-Inference.ipynb
jobovy/misc-notebooks
bsd-3-clause
Let's plot this, as well as the analytical PDF
h= hist(mean_pdfsamples_abc,range=[-1.,1.],bins=51,normed=True) xs= numpy.linspace(-1.,1.,1001) plot(xs,numpy.sqrt(len(data)/2./numpy.pi)*numpy.exp(-(xs-numpy.mean(data))**2./2.*len(data)),lw=2.)
inference/Gaussian-ABC-Inference.ipynb
jobovy/misc-notebooks
bsd-3-clause
What happens when we make the threshold larger?
mean_pdfsamples_abc= Mean_ABC(threshold=1.) h= hist(mean_pdfsamples_abc,range=[-1.,1.],bins=51,normed=True) plot(xs,numpy.sqrt(len(data)/2./numpy.pi)*numpy.exp(-(xs-numpy.mean(data))**2./2.*len(data)),lw=2.)
inference/Gaussian-ABC-Inference.ipynb
jobovy/misc-notebooks
bsd-3-clause
That's not good! What if we make it smaller?
mean_pdfsamples_abc= Mean_ABC(threshold=0.001) h= hist(mean_pdfsamples_abc,range=[-1.,1.],bins=51,normed=True) plot(xs,numpy.sqrt(len(data)/2./numpy.pi)*numpy.exp(-(xs-numpy.mean(data))**2./2.*len(data)),lw=2.)
inference/Gaussian-ABC-Inference.ipynb
jobovy/misc-notebooks
bsd-3-clause
This runs very long, because it's difficult to find simulated data sets that are close enough to the true one. The variance Let's know look at the variance, assuming that we know that the mean is zero. The sample variance is a sufficient statistic in this case and we can again write an ABC function, similar to that abo...
def Var_ABC(n=1000,threshold=0.05): out= [] for ii in range(n): d= threshold+1. while d > threshold: v= numpy.random.uniform()*4 sim= numpy.random.normal(size=len(data))*numpy.sqrt(v) d= numpy.fabs(numpy.var(sim)-numpy.var(data)) out.append(v) retu...
inference/Gaussian-ABC-Inference.ipynb
jobovy/misc-notebooks
bsd-3-clause
We again run this to get the PDF and compare to the analytical one
var_pdfsamples_abc= Var_ABC() h= hist(var_pdfsamples_abc,range=[0.,2.],bins=51,normed=True) xs= numpy.linspace(0.001,2.,1001) ys= xs**(-len(data)/2.)*numpy.exp(-1./xs/2.*len(data)*(numpy.var(data)+numpy.mean(data)**2.)) ys/= numpy.sum(ys)*(xs[1]-xs[0]) plot(xs,ys,lw=2.)
inference/Gaussian-ABC-Inference.ipynb
jobovy/misc-notebooks
bsd-3-clause
What if we make the threshold larger?
var_pdfsamples_abc= Var_ABC(threshold=1.) h= hist(var_pdfsamples_abc,range=[0.,2.],bins=51,normed=True) plot(xs,ys,lw=2.)
inference/Gaussian-ABC-Inference.ipynb
jobovy/misc-notebooks
bsd-3-clause
That's not good! What if we make the threshold smaller?
var_pdfsamples_abc= Var_ABC(threshold=0.005) h= hist(var_pdfsamples_abc,range=[0.,2.],bins=51,normed=True) plot(xs,ys,lw=2.)
inference/Gaussian-ABC-Inference.ipynb
jobovy/misc-notebooks
bsd-3-clause
Set up your Google Cloud Platform project The following steps are required, regardless of your notebook environment. Select or create a project. When you first create an account, you get a $300 free credit towards your compute/storage costs. Make sure that billing is enabled for your project. Enable the AI Platfo...
PROJECT_ID = "UPDATE TO YOUR PROJECT ID" REGION = "US" DATA_SET_ID = "bqml_kmeans" # Ensure you first create a data set in BigQuery !gcloud config set project $PROJECT_ID # If you have not built the Data Set, the following command will build it for you # !bq mk --location=$REGION --dataset $PROJECT_ID:$DATA_SET_ID
notebooks/community/analytics-componetized-patterns/retail/clustering/bqml/bqml_scaled_clustering.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Import libraries and define constants
import matplotlib.pyplot as plt import numpy as np import pandas as pd import pandas_gbq from google.cloud import bigquery pd.set_option( "display.float_format", lambda x: "%.3f" % x ) # used to display float format client = bigquery.Client(project=PROJECT_ID)
notebooks/community/analytics-componetized-patterns/retail/clustering/bqml/bqml_scaled_clustering.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Data exploration and preparation Prior to building your models, you are typically expected to invest a significant amount of time cleaning, exploring, and aggregating your dataset in a meaningful way for modeling. For the purpose of this demo, we aren't showing this step only to prioritize showcasing clustering with k...
# We start with GA360 data, and will eventually build synthetic CRM as an example. # This block is the first step, just working with GA360 ga360_only_view = "GA360_View" shared_dataset_ref = client.dataset(DATA_SET_ID) ga360_view_ref = shared_dataset_ref.table(ga360_only_view) ga360_view = bigquery.Table(ga360_view_re...
notebooks/community/analytics-componetized-patterns/retail/clustering/bqml/bqml_scaled_clustering.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Build a final view for to use as trainding data for clustering You may decide to change the view below based on your specific dataset. This is fine, and is exactly why we're creating a view. All steps subsequent to this will reference this view. If you change the SQL below, you won't need to modify other parts of th...
# Build a final view, which joins GA360 data with CRM data final_data_view = "Final_View" shared_dataset_ref = client.dataset(DATA_SET_ID) final_view_ref = shared_dataset_ref.table(final_data_view) final_view = bigquery.Table(final_view_ref) final_data_query = f""" SELECT g.*, c.* EXCEPT(fullVisitorId) FROM {...
notebooks/community/analytics-componetized-patterns/retail/clustering/bqml/bqml_scaled_clustering.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Create our initial model In this section, we will build our initial k-means model. We won't focus on optimal k or other hyperparemeters just yet. Some additional points: We remove fullVisitorId as an input, even though it is grouped at that level because we don't need fullVisitorID as a feature for clustering. full...
def makeModel(n_Clusters, Model_Name): sql = f""" CREATE OR REPLACE MODEL `{PROJECT_ID}.{DATA_SET_ID}.{Model_Name}` OPTIONS(model_type='kmeans', kmeans_init_method = 'KMEANS++', num_clusters={n_Clusters}) AS SELECT * except(fullVisitorID, Hashed_fullVisitorID) FROM `{final_view.full_table_id.r...
notebooks/community/analytics-componetized-patterns/retail/clustering/bqml/bqml_scaled_clustering.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Work towards creating a better model In this section, we want to determine the proper k value. Determining the right value of k depends completely on the use case. There are straight forward examples that will simply tell you how many clusters are needed. Suppose you are pre-processing hand written digits - this tel...
# Define upper and lower bound for k, then build individual models for each. # After running this loop, look at the UI to see several model objects that exist. low_k = 3 high_k = 15 model_prefix_name = "kmeans_clusters_" lst = list(range(low_k, high_k + 1)) # build list to iterate through k values for k in lst: ...
notebooks/community/analytics-componetized-patterns/retail/clustering/bqml/bqml_scaled_clustering.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Select optimal k
# list all current models models = client.list_models(DATA_SET_ID) # Make an API request. print("Listing current models:") for model in models: full_model_id = f"{model.dataset_id}.{model.model_id}" print(full_model_id) # Remove our sample model from BigQuery, so we only have remaining models from our previou...
notebooks/community/analytics-componetized-patterns/retail/clustering/bqml/bqml_scaled_clustering.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
The code below assumes we've used the naming convention originally created in this notebook, and the k value occurs after the 2nd underscore. If you've changed the model_prefix_name variable, then this code might break.
# This will modify the dataframe above, produce a new field with 'n_clusters', and will sort for graphing df["n_clusters"] = df["model_name"].str.split("_").map(lambda x: x[2]) df["n_clusters"] = df["n_clusters"].apply(pd.to_numeric) df = df.sort_values(by="n_clusters", ascending=True) df df.plot.line(x="n_clusters",...
notebooks/community/analytics-componetized-patterns/retail/clustering/bqml/bqml_scaled_clustering.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Note - when you run this notebook, you will get different results, due to random cluster initialization. If you'd like to consistently return the same cluster for reach run, you may explicitly select your initialization through hyperparameter selection (https://cloud.google.com/bigquery-ml/docs/reference/standard-sql/...
model_to_use = "kmeans_clusters_5" # User can edit this final_model = DATA_SET_ID + "." + model_to_use sql_get_attributes = f""" SELECT centroid_id, feature, categorical_value FROM ML.CENTROIDS(MODEL {final_model}) WHERE feature IN ('OS','gender') """ job_config = bigquery.QueryJobConfig() # Start the que...
notebooks/community/analytics-componetized-patterns/retail/clustering/bqml/bqml_scaled_clustering.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
In addition to the output above, I'll note a few insights we get from our clusters. Cluster 1 - The apparel shopper, which also purchases more often than normal. This (although synthetic data) segment skews female. Cluster 2 - Most likely to shop by brand, and interested in bags. This segment has fewer purchases on a...
sql_score = f""" SELECT * EXCEPT(nearest_centroids_distance) FROM ML.PREDICT(MODEL {final_model}, ( SELECT * FROM {final_view.full_table_id.replace(":", ".")} LIMIT 1)) """ job_config = bigquery.QueryJobConfig() # Start the query query_job = client.query(sql_score, job_config=job_confi...
notebooks/community/analytics-componetized-patterns/retail/clustering/bqml/bqml_scaled_clustering.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Load the census data
X,y = shap.datasets.adult() X["Occupation"] *= 1000 # to show the impact of feature scale on KNN predictions X_display,y_display = shap.datasets.adult(display=True) X_train, X_valid, y_train, y_valid = sklearn.model_selection.train_test_split(X, y, test_size=0.2, random_state=7)
notebooks/tabular_examples/model_agnostic/Census income classification with scikit-learn.ipynb
slundberg/shap
mit
Train a k-nearest neighbors classifier Here we just train directly on the data, without any normalizations.
knn = sklearn.neighbors.KNeighborsClassifier() knn.fit(X_train, y_train)
notebooks/tabular_examples/model_agnostic/Census income classification with scikit-learn.ipynb
slundberg/shap
mit
Explain predictions Normally we would use a logit link function to allow the additive feature inputs to better map to the model's probabilistic output space, but knn's can produce infinite log odds ratios so we don't for this example. It is important to note that Occupation is the dominant feature in the 1000 predictio...
f = lambda x: knn.predict_proba(x)[:,1] med = X_train.median().values.reshape((1,X_train.shape[1])) explainer = shap.Explainer(f, med) shap_values = explainer(X_valid.iloc[0:1000,:]) shap.plots.waterfall(shap_values[0])
notebooks/tabular_examples/model_agnostic/Census income classification with scikit-learn.ipynb
slundberg/shap
mit
A summary beeswarm plot is an even better way to see the relative impact of all features over the entire dataset. Features are sorted by the sum of their SHAP value magnitudes across all samples.
shap.plots.beeswarm(shap_values)
notebooks/tabular_examples/model_agnostic/Census income classification with scikit-learn.ipynb
slundberg/shap
mit
A heatmap plot provides another global view of the model's behavior, this time with a focus on population subgroups.
shap.plots.heatmap(shap_values)
notebooks/tabular_examples/model_agnostic/Census income classification with scikit-learn.ipynb
slundberg/shap
mit
Normalize the data before training the model Here we retrain a KNN model on standardized data.
# normalize data dtypes = list(zip(X.dtypes.index, map(str, X.dtypes))) X_train_norm = X_train.copy() X_valid_norm = X_valid.copy() for k,dtype in dtypes: m = X_train[k].mean() s = X_train[k].std() X_train_norm[k] -= m X_train_norm[k] /= s X_valid_norm[k] -= m X_valid_norm[k] /= s knn_norm...
notebooks/tabular_examples/model_agnostic/Census income classification with scikit-learn.ipynb
slundberg/shap
mit
Explain predictions When we explain predictions from the new KNN model we find that Occupation is no longer the dominate feature, but instead more predictive features, such as marital status, drive most predictions. This is simple example of how explaining why your model is making it's predicitons can uncover problems ...
f = lambda x: knn_norm.predict_proba(x)[:,1] med = X_train_norm.median().values.reshape((1,X_train_norm.shape[1])) explainer = shap.Explainer(f, med) shap_values_norm = explainer(X_valid_norm.iloc[0:1000,:])
notebooks/tabular_examples/model_agnostic/Census income classification with scikit-learn.ipynb
slundberg/shap
mit
With a summary plot with see marital status is the most important on average, but other features (such as captial gain) can have more impact on a particular individual.
shap.summary_plot(shap_values_norm, X_valid.iloc[0:1000,:])
notebooks/tabular_examples/model_agnostic/Census income classification with scikit-learn.ipynb
slundberg/shap
mit
A dependence scatter plot shows how the number of years of education increases the chance of making over 50K annually.
shap.plots.scatter(shap_values_norm[:,"Education-Num"])
notebooks/tabular_examples/model_agnostic/Census income classification with scikit-learn.ipynb
slundberg/shap
mit
Negative Neurons - Feature Visualization This notebook uses Lucid to reproduce the results in Feature Visualization. This notebook doesn't introduce the abstractions behind lucid; you may wish to also read the Lucid tutorial. Note: The easiest way to use this tutorial is as a colab notebook, which allows you to dive i...
!pip install --quiet lucid==0.0.5 import numpy as np import scipy.ndimage as nd import tensorflow as tf import lucid.modelzoo.vision_models as models from lucid.misc.io import show import lucid.optvis.objectives as objectives import lucid.optvis.param as param import lucid.optvis.render as render import lucid.optvis....
notebooks/feature-visualization/negative_neurons.ipynb
tensorflow/lucid
apache-2.0
Negative Channel Visualizations <img src="https://storage.googleapis.com/lucid-static/feature-visualization/4.png" width="800"></img> Unfortunately, constraints on ImageNet mean we can't provide an easy way for you to reproduce the dataset examples. However, we can reproduce the positive / negative optimized visualizat...
param_f = lambda: param.image(128, batch=2) obj = objectives.channel("mixed4a_pre_relu", 492, batch=1) - objectives.channel("mixed4a_pre_relu", 492, batch=0) _ = render.render_vis(model, obj, param_f)
notebooks/feature-visualization/negative_neurons.ipynb
tensorflow/lucid
apache-2.0
Here, each component of the values tensor has one more sample point in the direction it is facing. If the extrapolation was extrapolation.ZERO, it would be one less (see above image). Creating Staggered Grids The StaggeredGrid constructor supports two modes: Direct construction StaggeredGrid(values: Tensor, extrapolat...
domain = dict(x=10, y=10, bounds=Box(x=1, y=1), extrapolation=extrapolation.ZERO) grid = StaggeredGrid((1, -1), **domain) # from constant vector grid = StaggeredGrid(Noise(), **domain) # sample analytic field grid = StaggeredGrid(grid, **domain) # resample existing field grid = StaggeredGrid(lambda x: math.exp(-x),...
docs/Staggered_Grids.ipynb
tum-pbs/PhiFlow
mit
Staggered grids can also be created from other fields using field.at() or @ by passing an existing StaggeredGrid. Some field functions also return StaggeredGrids: spatial_gradient() with type=StaggeredGrid stagger() Values Tensor For non-periodic staggered grids, the values tensor is non-uniform to reflect the differ...
grid.vector['x'] # select component
docs/Staggered_Grids.ipynb
tum-pbs/PhiFlow
mit
Grids do not support slicing along spatial dimensions because the result would be ambiguous with StaggeredGrids. Instead, slice the values directly.
grid.values.x[3:4] # spatial slice grid.values.x[0] # spatial slice
docs/Staggered_Grids.ipynb
tum-pbs/PhiFlow
mit
Slicing along batch dimensions has no special effect, this just slices the values.
grid.batch[0] # batch slice
docs/Staggered_Grids.ipynb
tum-pbs/PhiFlow
mit
H &rarr; ZZ* &rarr; 4$\mu$ - cuts and plot, using Monte Carlo signal data (this is a step of the broader analsys)
# Start the Spark Session # This uses local mode for simplicity # the use of findspark is optional import findspark findspark.init("/home/luca/Spark/spark-3.3.0-bin-hadoop3") from pyspark.sql import SparkSession spark = (SparkSession.builder .appName("H_ZZ_4Lep") .master("local[*]") .config...
Spark_Physics/CMS_Higgs_opendata/H_ZZ_4l_analysis_basic_monte_carlo_signal.ipynb
LucaCanali/Miscellaneous
apache-2.0
Apply cuts More details on the cuts (filters applied to the event data) in the reference CMS paper on the discovery of the Higgs boson
df_events = df_MC_events_signal.selectExpr("""arrays_zip(Muon_charge, Muon_mass, Muon_pt, Muon_phi, Muon_eta, Muon_dxy, Muon_dz, Muon_dxyErr, Muon_dzErr, Muon_pfRelIso04_all) Muon""", "nMuon") df_events.printSchema() # Apply filters to the input ...
Spark_Physics/CMS_Higgs_opendata/H_ZZ_4l_analysis_basic_monte_carlo_signal.ipynb
LucaCanali/Miscellaneous
apache-2.0
Compute the invariant mass This computes the 4-vectors sum for the 4-lepton system using formulas from special relativity. See also http://edu.itp.phys.ethz.ch/hs10/ppp1/2010_11_02.pdf and https://en.wikipedia.org/wiki/Invariant_mass
# This computes the 4-vectors sum for the 4-muon system # convert to cartesian coordinates df_4lep = df_events_4muons.selectExpr( "Muon.Muon_pt[0] * cos(Muon.Muon_phi[0]) P0x", "Muon.Muon_pt[1] * cos(Muon.Muon_phi[1]) P1x", "Muon.Muon_pt[2] * cos(Muon.Muon_phi[2]) P2x", "Muon.Muon_pt[3] * cos(Muon.Muon_phi[3]) P3x", "...
Spark_Physics/CMS_Higgs_opendata/H_ZZ_4l_analysis_basic_monte_carlo_signal.ipynb
LucaCanali/Miscellaneous
apache-2.0
Motor imagery decoding from EEG data using the Common Spatial Pattern (CSP) Decoding of motor imagery applied to EEG data decomposed using CSP. A classifier is then applied to features extracted on CSP-filtered signals. See https://en.wikipedia.org/wiki/Common_spatial_pattern and [1]. The EEGBCI dataset is documented i...
# Authors: Martin Billinger <martin.billinger@tugraz.at> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.model_selection import ShuffleSplit, cross_val_score from mn...
0.21/_downloads/a4d4c1a667c2374c09eed24ac047d840/plot_decoding_csp_eeg.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Suppress wikipedia package warnings.
import warnings warnings.filterwarnings('ignore')
Task 3 - Text Mining/task3.ipynb
ggljzr/mi-ddw
mit
Helper functions to process output of nltk.ne_chunk and to count frequency of named entities in a given text.
def count_entites(entity, text): s = entity if type(entity) is tuple: s = entity[0] return len(re.findall(s, text)) def get_top_n(entities, text, n): a = [ (e, count_entites(e, text)) for e in entities] a.sort(key=lambda x: x[1], reverse=True) return a[0:n] # For a list of en...
Task 3 - Text Mining/task3.ipynb
ggljzr/mi-ddw
mit
Since nltk.ne_chunks tends to put same named entities into more classes (like 'American' : 'ORGANIZATION' and 'American' : 'GPE'), we would want to filter these duplicities.
# returns list of named entities in a form [(entity_text, entity_label), ...] def extract_entities(chunk): data = [] for entity in chunk: d = get_entity(entity) if d is not None and d[0] not in [e[0] for e in data]: data.append(d) return data
Task 3 - Text Mining/task3.ipynb
ggljzr/mi-ddw
mit
Our custom NER functio from example here.
def custom_NER(tagged): entities = [] entity = [] for word in tagged: if word[1][:2] == 'NN' or (entity and word[1][:2] == 'IN'): entity.append(word) else: if entity and entity[-1][1].startswith('IN'): entity.pop() if entity: ...
Task 3 - Text Mining/task3.ipynb
ggljzr/mi-ddw
mit
Loading processed article, approximately 500 sentences. Regex substitution removes reference links (e.g. [12])
text = None with open('text', 'r') as f: text = f.read() text = re.sub(r'\[[0-9]*\]', '', text)
Task 3 - Text Mining/task3.ipynb
ggljzr/mi-ddw
mit
Now we try to recognize entities with both nltk.ne_chunk and our custom_NER function and print 10 most frequent entities. Yielded results seem to be fairly similar. nltk.ne_chunk function also added basic classification tags.
tokens = nltk.word_tokenize(text) tagged = nltk.pos_tag(tokens) ne_chunked = nltk.ne_chunk(tagged, binary=False) ex = extract_entities(ne_chunked) ex_custom = custom_NER(tagged) top_ex = get_top_n(ex, text, 20) top_ex_custom = get_top_n(ex_custom, text, 20) print('ne_chunked:') for e in top_ex: print('{} count: {...
Task 3 - Text Mining/task3.ipynb
ggljzr/mi-ddw
mit
Next we would want to do our own classification, using Wikipedia articles for each named entity. Idea is to find article matching entity string (for example 'America') and then create a noun phrase from its first sentence. When no suitable article or description is found, entity classification will be 'Thing'.
def get_noun_phrase(entity, sentence): t = nltk.pos_tag([word for word in nltk.word_tokenize(sentence)]) phrase = [] stage = 0 for word in t: if word[0] in ('is', 'was', 'were', 'are', 'refers') and stage == 0: stage = 1 continue elif stage == 1: if wo...
Task 3 - Text Mining/task3.ipynb
ggljzr/mi-ddw
mit
Obivously this classification is way more specific than tags used by nltk.ne_chunk. We can also see that both NER methods mistook common words for entities unrelated to the article (for example 'New'). Since custom_NER function relies on uppercase letters to recognize entities, this can be commonly caused by first wor...
for entity in top_ex: print(get_wiki_desc(entity[0][0])) for entity in top_ex_custom: print(get_wiki_desc(entity[0]))
Task 3 - Text Mining/task3.ipynb
ggljzr/mi-ddw
mit
When searching simple wiki, entity 'Americas' gets fairly reasonable description. However there seems to be an issue with handling DisambiguationError in some cases when looking for first page in DisambiguationError.options raises another DisambiguationError (even if pages from .options should be guaranteed hit).
get_wiki_desc('Americas', wiki='simple')
Task 3 - Text Mining/task3.ipynb
ggljzr/mi-ddw
mit
Creating training sets Each class of tissue in our pandas framework has a pre assigned label (Module 1). This labels were: - ClassTissuePost - ClassTissuePre - ClassTissueFlair - ClassTumorPost - ClassTumorPre - ClassTumorFlair - ClassEdemaPost - ClassEdemaPre - ClassEdemaFlair For demontration purposes we will create...
ClassBrainTissuepost=(Data['ClassTissuePost'].values) ClassBrainTissuepost= (np.asarray(ClassBrainTissuepost)) ClassBrainTissuepost=ClassBrainTissuepost[~np.isnan(ClassBrainTissuepost)] ClassBrainTissuepre=(Data[['ClassTissuePre']].values) ClassBrainTissuepre= (np.asarray(ClassBrainTissuepre)) ClassBrainTissuepre=Class...
notebooks/Module 3.ipynb
slowvak/MachineLearningForMedicalImages
mit
X is the feature vector y are the labels Split Training/Validation
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
notebooks/Module 3.ipynb
slowvak/MachineLearningForMedicalImages
mit
Create the classifier For the following example we will consider a SVM classifier. The classifier is provided by the Scikit-Learn library
h = .02 # step size in the mesh # we create an instance of SVM and fit out data. We do not scale our # data since we want to plot the support vectors C = 1.0 # SVM regularization parameter svc = svm.SVC(kernel='linear', C=C).fit(X, y) rbf_svc = svm.SVC(kernel='rbf', gamma=0.1, C=10).fit(X, y) poly_svc = svm.SVC(kerne...
notebooks/Module 3.ipynb
slowvak/MachineLearningForMedicalImages
mit
Run some basic analytics Calculate some basic metrics.
print ('C=100') model=svm.SVC(C=100,kernel='linear') model.fit(X_train, y_train) # make predictions expected = y_test predicted = model.predict(X_test) # summarize the fit of the model print(metrics.classification_report(expected, predicted)) print(metrics.confusion_matrix(expected, predicted)) print (20*'---') print...
notebooks/Module 3.ipynb
slowvak/MachineLearningForMedicalImages
mit
Correct way Fine tune hyperparameters
gamma_val =[0.01, .2,.3,.4,.9] classifier = svm.SVC(kernel='rbf', C=10).fit(X, y) classifier = GridSearchCV(estimator=classifier, cv=5, param_grid=dict(gamma=gamma_val)) classifier.fit(X_train, y_train)
notebooks/Module 3.ipynb
slowvak/MachineLearningForMedicalImages
mit
Debug algorithm with learning curve X_train is randomly split into a training and a test set 3 times (n_iter=3). Each point on the training-score curve is the average of 3 scores where the model was trained and evaluated on the first i training examples. Each point on the cross-validation score curve is the average of ...
title = 'Learning Curves (SVM, gamma=%.6f)' %classifier.best_estimator_.gamma estimator = svm.SVC(kernel='rbf', C=10, gamma=classifier.best_estimator_.gamma) plot_learning_curve(estimator, title, X_train, y_train, cv=4) plt.show() ### Final evaluation on the test set classifier.score(X_test, y_test)
notebooks/Module 3.ipynb
slowvak/MachineLearningForMedicalImages
mit
Heatmap This will take some time...
C_range = np.logspace(-2, 10, 13) gamma_range = np.logspace(-9, 3, 13) param_grid = dict(gamma=gamma_range, C=C_range) cv = StratifiedShuffleSplit(n_splits=5, test_size=0.2, random_state=42) grid_clf = GridSearchCV(SVC(), param_grid=param_grid, cv=cv) grid_clf.fit(X, y) print("The best parameters are %s with a score of...
notebooks/Module 3.ipynb
slowvak/MachineLearningForMedicalImages
mit
<font color='blue'> What you need to remember: Common steps for pre-processing a new dataset are: - Figure out the dimensions and shapes of the problem (m_train, m_test, num_px, ...) - Reshape the datasets such that each example is now a vector of size (num_px * num_px * 3, 1) - "Standardize" the data 3 - General Archi...
# GRADED FUNCTION: sigmoid def sigmoid(z): """ Compute the sigmoid of z Arguments: x -- A scalar or numpy array of any size. Return: s -- sigmoid(z) """ ### START CODE HERE ### (≈ 1 line of code) s = 1.0 / (1 + np.exp(-z)) ### END CODE HERE ### return s print ("sigm...
coursera/deep-learning/1.neural-networks-deep-learning/week2/pa.2.Logistic Regression with a Neural Network mindset.ipynb
huajianmao/learning
mit
Expected Output: <table style="width:20%"> <tr> <td>**sigmoid(0)**</td> <td> 0.5</td> </tr> <tr> <td>**sigmoid(9.2)**</td> <td> 0.999898970806 </td> </tr> </table> 4.2 - Initializing parameters Exercise: Implement parameter initialization in the cell below. You have to initialize w as a vec...
# GRADED FUNCTION: initialize_with_zeros def initialize_with_zeros(dim): """ This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0. Argument: dim -- size of the w vector we want (or number of parameters in this case) Returns: w -- initialized vector of...
coursera/deep-learning/1.neural-networks-deep-learning/week2/pa.2.Logistic Regression with a Neural Network mindset.ipynb
huajianmao/learning
mit
Expected Output: <table style="width:15%"> <tr> <td> ** w ** </td> <td> [[ 0.] [ 0.]] </td> </tr> <tr> <td> ** b ** </td> <td> 0 </td> </tr> </table> For image inputs, w will be of shape (num_px $\times$ num_px $\times$ 3, 1). 4.3 - Forward and Backward propagation...
# GRADED FUNCTION: propagate def propagate(w, b, X, Y): """ Implement the cost function and its gradient for the propagation explained above Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) ...
coursera/deep-learning/1.neural-networks-deep-learning/week2/pa.2.Logistic Regression with a Neural Network mindset.ipynb
huajianmao/learning
mit
Expected Output: <table style="width:40%"> <tr> <td> **w** </td> <td>[[ 0.1124579 ] [ 0.23106775]] </td> </tr> <tr> <td> **b** </td> <td> 1.55930492484 </td> </tr> <tr> <td> **dw** </td> <td> [[ 0.90158428] [ 1.76250842]] </td> </tr> <tr> ...
# GRADED FUNCTION: predict def predict(w, b, X): ''' Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b) Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of example...
coursera/deep-learning/1.neural-networks-deep-learning/week2/pa.2.Logistic Regression with a Neural Network mindset.ipynb
huajianmao/learning
mit
Expected Output: <table style="width:30%"> <tr> <td> **predictions** </td> <td> [[ 1. 1.]] </td> </tr> </table> <font color='blue'> What to remember: You've implemented several functions that: - Initialize (w,b) - Optimize the loss iteratively t...
# GRADED FUNCTION: model def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False): """ Builds the logistic regression model by calling the function you've implemented previously Arguments: X_train -- training set represented by a numpy array of shape (n...
coursera/deep-learning/1.neural-networks-deep-learning/week2/pa.2.Logistic Regression with a Neural Network mindset.ipynb
huajianmao/learning
mit
Expected Output: <table style="width:40%"> <tr> <td> **Train Accuracy** </td> <td> 99.04306220095694 % </td> </tr> <tr> <td>**Test Accuracy** </td> <td> 70.0 % </td> </tr> </table> Comment: Training accuracy is close to 100%. This is a good sanity check: your mode...
# Example of a picture that was wrongly classified. index = 5 plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3))) print(d["Y_prediction_test"][0, index]) print ("y = " + str(test_set_y[0, index]) + ", you predicted that it is a \"" + classes[d["Y_prediction_test"][0, index]].decode("utf-8") + "\" picture.")
coursera/deep-learning/1.neural-networks-deep-learning/week2/pa.2.Logistic Regression with a Neural Network mindset.ipynb
huajianmao/learning
mit
Interpretation: - Different learning rates give different costs and thus different predictions results. - If the learning rate is too large (0.01), the cost may oscillate up and down. It may even diverge (though in this example, using 0.01 still eventually ends up at a good value for the cost). - A lower cost doesn't...
## START CODE HERE ## (PUT YOUR IMAGE NAME) ## END CODE HERE ## # We preprocess the image to fit your algorithm. fname = "images/" + my_image image = np.array(ndimage.imread(fname, flatten=False)) my_image = scipy.misc.imresize(image, size=(num_px, num_px)).reshape((1, num_px * num_px * 3)).T my_predicted_image = pr...
coursera/deep-learning/1.neural-networks-deep-learning/week2/pa.2.Logistic Regression with a Neural Network mindset.ipynb
huajianmao/learning
mit
<p class="normal"> &raquo; <b>Continuous-valued</b> vs. <b>Discrete-valued</b>: <i>based on values assumed by the dependent variable.</i></p> <div class="formula"> $$ \begin{cases} x(t) \in [a, b] & \text{Continuous-valued} \\ x(t) \in \{a_1, a_2, \cdots\} & \text{Discrete-valued} \\ \end{cases} $$ </div>
def continuous_discrete_valued_signals(): t = np.arange(-10, 10.01, 0.01) n_steps = 10. x_c = np.exp(-0.1 * (t ** 2)) x_d = (1/n_steps) * np.round(n_steps * x_c) fig = figure(figsize=(17,5)) plot(t, x_c, label="Continuous-valued") plot(t, x_d, label="Discrete-valued") ylim(-0.1, 1.1) ...
lectures/lecture_1/.ipynb_checkpoints/lecture_1-checkpoint.ipynb
siva82kb/intro_to_signal_processing
mit
<p class="normal">Last two classifications can be combined to have four possible combinations of signals:</p> <ul class="content"> <li><i>Continuous-time continuous-valued signals</i></li> <li><i>Continuous-time discrete-valued signals</i></li> <li><i>Discrete-time continuous-valued signals</i></li> <li><i>Discrete-tim...
def continuous_discrete_combos(): t = np.arange(-10, 10.01, 0.01) n = np.arange(-10, 11, 0.5) n_steps = 5. # continuous-time continuous-valued signal x_t_c = np.exp(-0.1 * (t ** 2)) # continuous-time discrete-valued signal x_t_d = (1/n_steps) * np.round(n_steps * x_t_c) # discrete-time ...
lectures/lecture_1/.ipynb_checkpoints/lecture_1-checkpoint.ipynb
siva82kb/intro_to_signal_processing
mit
<p class="normal">EMG recorded from a linear electrode array.</p> <p class="normal"> &raquo; <b>Deterministic</b> vs. <b>Stochastic</b>: <i>e.g. EMG is an example of a stochastic signal.</i></p>
def deterministic_stochastic(): t = np.arange(0., 10., 0.005) x = np.exp(-0.5 * t) * np.sin(2 * np.pi * 2 * t) y1 = np.random.normal(0, 1., size=len(t)) y2 = np.random.uniform(0, 1., size=len(t)) figure(figsize=(17, 10)) # deterministic signal subplot2grid((3,3), (0,0), rowspan=1, colspan=...
lectures/lecture_1/.ipynb_checkpoints/lecture_1-checkpoint.ipynb
siva82kb/intro_to_signal_processing
mit
<p class="normal"> &raquo; <b>Even</b> vs. <b>Odd</b>: <i>based on symmetry about the $t=0$ axis.</i></p> <div class="formula"> $$ \begin{cases} x(t) = x(-t), & \text{Even signal} \\ x(t) = -x(-t), & \text{Odd signal} \\ \end{cases} $$ </div> <p class="normal"><i>Can there be signals that are neither even nor odd?</i>...
def even_odd_decomposition(): t = np.arange(-5, 5, 0.01) x = (0.5 * np.exp(-(t-2.1)**2) * np.cos(2*np.pi*t) + np.exp(-t**2) * np.sin(2*np.pi*3*t)) figure(figsize=(17,4)) # Original function plot(t, x, label="$x(t)$") # Even component plot(t, 0.5 * (x + x[::-1]) - 2, label="$x_{ev...
lectures/lecture_1/.ipynb_checkpoints/lecture_1-checkpoint.ipynb
siva82kb/intro_to_signal_processing
mit
<p class="normal"> &raquo; <b>Periodic</b> vs. <b>Non-periodic</b>: <i>a signal is periodic, if and only if</i></p> <div class="formula"> $$ x(t) = x(t + T), \,\, \forall t, \,\,\, T \text{ is the fundamental period.}$$ </div> <p class="normal"> &raquo; <b>Energy</b> vs. <b>Power</b>: <i>indicates if a signal is sho...
def memory(): dt = 0.01 N = np.round(0.5/dt) t = np.arange(-1.0, 5.0, dt) x = 1.0 * np.array([t >= 1.0, t < 3.0]).all(0) # memoryless system y1 = 0.5 * x # system with memory. y2 = np.zeros(len(x)) for i in xrange(len(y2)): y2[i] = np.sum(x[max(0, i-N):i]) * dt figure(f...
lectures/lecture_1/.ipynb_checkpoints/lecture_1-checkpoint.ipynb
siva82kb/intro_to_signal_processing
mit