markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
The numpy.random module adds to the standard built-in Python random functions for generating efficiently whole arrays of sample values with many kinds of probability distributions. Example: build a 4x4 array of samples from the standard normal distribution,
samples = np.random.normal(size=(4,4)) samples
notebooks/Random Numbers in NumPy Campus.ipynb
rcrehuet/Python_for_Scientists_2017
gpl-3.0
Advantages? Built-in Random Python only samples one value at a time and it is significantly less efficient. The following block builds an array with 10$^7$ normally distributed values:
import random N = 10000000 %timeit samples = [random.normalvariate(0,1) for i in range(N)]
notebooks/Random Numbers in NumPy Campus.ipynb
rcrehuet/Python_for_Scientists_2017
gpl-3.0
Write the equivalent code using the np.random.normal() function and time it! Keep in mind that the NumPy function is vectorized! See the Numpy documentation site for detailed info on the numpy.random module Random Walks Using standard Python builtin functions, try to write a piece of code corresponding to a 1D Random w...
import matplotlib.pyplot as plt %matplotlib inline #plt.plot(INSERT THE NAME OF THE VARIABLE CONTAINING THE PATH)
notebooks/Random Numbers in NumPy Campus.ipynb
rcrehuet/Python_for_Scientists_2017
gpl-3.0
Now think of a possible alternative code using NumPy. Keep in mind that: NumPy offers arrays to store the path numpy.random offers a vectorized version of random generating functions Again, here is my solution. Let's have a look at it:
#plt.plot(INSERT THE NAME OF THE VARIABLE CONTAINING THE PATH)
notebooks/Random Numbers in NumPy Campus.ipynb
rcrehuet/Python_for_Scientists_2017
gpl-3.0
To test your feature derivartive run the following:
(example_features, example_output) = get_numpy_data(sales, ['sqft_living'], 'price') my_weights = np.array([0., 0.]) # this makes all the predictions 0 test_predictions = predict_output(example_features, my_weights) # just like SFrames 2 numpy arrays can be elementwise subtracted with '-': errors = test_predictions ...
machine_learning/2_regression/assignment/week2/week-2-multiple-regression-assignment-2-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Gradient Descent Now we will write a function that performs a gradient descent. The basic premise is simple. Given a starting point we update the current weights by moving in the negative gradient direction. Recall that the gradient is the direction of increase and therefore the negative gradient is the direction of de...
from math import sqrt # recall that the magnitude/length of a vector [g[0], g[1], g[2]] is sqrt(g[0]^2 + g[1]^2 + g[2]^2)
machine_learning/2_regression/assignment/week2/week-2-multiple-regression-assignment-2-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Discussion https://www.coursera.org/learn/ml-regression/module/MFwVC/discussions/nNP11JhqEeWy0Q7ABZMsnQ
def regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance): converged = False weights = np.array(initial_weights) # make sure it's a numpy array while not converged: # compute the predictions based on feature_matrix and weights using your predict_output() functio...
machine_learning/2_regression/assignment/week2/week-2-multiple-regression-assignment-2-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Next run your gradient descent with the above parameters.
test_weight = regression_gradient_descent(simple_feature_matrix, output, initial_weights, step_size, tolerance) print test_weight
machine_learning/2_regression/assignment/week2/week-2-multiple-regression-assignment-2-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Now compute your predictions using test_simple_feature_matrix and your weights from above.
test_predictions = predict_output(test_simple_feature_matrix, test_weight) print test_predictions
machine_learning/2_regression/assignment/week2/week-2-multiple-regression-assignment-2-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Now that you have the predictions on test data, compute the RSS on the test data set. Save this value for comparison later. Recall that RSS is the sum of the squared errors (difference between prediction and output).
test_residuals = test_output - test_predictions test_RSS = (test_residuals * test_residuals).sum() print test_RSS
machine_learning/2_regression/assignment/week2/week-2-multiple-regression-assignment-2-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Use the above parameters to estimate the model weights. Record these values for your quiz.
weight_2 = regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance) print weight_2
machine_learning/2_regression/assignment/week2/week-2-multiple-regression-assignment-2-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Use your newly estimated weights and the predict_output function to compute the predictions on the TEST data. Don't forget to create a numpy array for these features from the test set first!
(test_feature_matrix, test_output) = get_numpy_data(test_data, model_features, my_output) test_predictions_2 = predict_output(test_feature_matrix, weight_2) print test_predictions_2
machine_learning/2_regression/assignment/week2/week-2-multiple-regression-assignment-2-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Quiz Question: What is the predicted price for the 1st house in the TEST data set for model 2 (round to nearest dollar)?
print test_predictions_2[0]
machine_learning/2_regression/assignment/week2/week-2-multiple-regression-assignment-2-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
What is the actual price for the 1st house in the test data set?
print test_data['price'][0]
machine_learning/2_regression/assignment/week2/week-2-multiple-regression-assignment-2-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Quiz Question: Which estimate was closer to the true price for the 1st house on the Test data set, model 1 or model 2? Now use your predictions and the output to compute the RSS for model 2 on TEST data.
test_residuals_2 = test_output - test_predictions_2 test_RSS_2 = (test_residuals_2**2).sum() print test_RSS_2
machine_learning/2_regression/assignment/week2/week-2-multiple-regression-assignment-2-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Useful data and Methods for our Dataset manipulation
#Column names for our data header = ["color","diameter","label"] """Find the unique values for a column in dataset""" def unique_values(rows,col): return set([row[col] for row in rows]) """count the no of examples for each label in a dataset""" def class_counts(rows): counts = {} # a dictionary of labe...
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Let's write a class for a question which can be asked to partition the data Each object of a question class holds a column_no and a col_value Eg. column_no = 0 denotes color and so col_value can be Green, Yellow or Red We can write a method which would compare the feature value of example with the feature value of Q...
class Question: def __init__(self,col, val): self.col = col self.val = val def match(self,example): # Compare the feature value in an example to the # feature value in this question. value = example[self.col] if is_numeric(value): return value...
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Question format -
#create a new question with col = 1 and val = 3 q = Question(1,3) #print q q
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Define a function which partitions the dataset on given question in True and False rows/examples
"""For each row in the dataset, check if it satisfies the question. If so, add it to 'true rows', otherwise, add it to 'false rows'. """ def partition(rows, question): true_rows, false_rows = [], [] for row in rows: if question.match(row): true_rows.append(row) else: ...
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Now calculate a Gini Impurity for a node with given input rows of training dataset
"""Calculate the Gini Impurity for a list of rows.""" def gini(rows): counts = class_counts(rows) impurity = 1 for lbl in counts: prob_of_lbl = counts[lbl] / float(len(rows)) impurity -= prob_of_lbl**2 return impurity
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Calculate the Information gain for a question given uncertainity at present node and incertainities at left and right child nodes
def info_gain(left, right, current_uncertainty): #we need to calculate weighted avg of impurities at both child nodes p = float(len(left)) / (len(left) + len(right)) return current_uncertainty - p * gini(left) - (1 - p) * gini(right)
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Which question to ask ??
"""Find the best question to ask by iterating over every feature / value and calculating the information gain.""" def find_best_split(rows): best_gain = 0 # keep track of the best information gain best_question = None # keep train of the feature / value that produced it current_uncertainty = gini(rows...
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Define nodes in tree 1. Decision Node - Node with Question to ask
""" A Decision Node asks a question. This holds a reference to the question, and to the two child nodes. """ class Decision_Node: def __init__(self,question,true_branch,false_branch): self.question = question self.true_branch = true_branch self.false_branch = false_branch
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
2. Leaf node - Gives prediction
""" A Leaf node classifies data. This holds a dictionary of class (e.g., "Apple") -> number of time it appears in the rows from the training data that reach this leaf. """ class Leaf: def __init__(self, rows): self.predictions = class_counts(rows)
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Build a Tree
def build_tree(rows): # Try partitioing the dataset on each of the unique attribute, # calculate the information gain, # and return the question that produces the highest gain. gain, question = find_best_split(rows) # Base case: no further info gain # Since we can ask no further questions, ...
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Print the Tree
def print_tree(node, spacing=""): # Base case: we've reached a leaf if isinstance(node, Leaf): print (spacing + "Predict", node.predictions) return # Print the question at this node print (spacing + str(node.question)) # Call this function recursively on the true branch print ...
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
All Work Done !!! Now It's time to Build a Model from given Training data
my_tree = build_tree(training_data) print_tree(my_tree)
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Test the model with test data Write a function to classify the test data
def classify(row, node): # Base case: we've reached a leaf if isinstance(node, Leaf): return node.predictions # Decide whether to follow the true-branch or the false-branch. # Compare the feature / value stored in the node, # to the example we're considering. if node.question.match(row...
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Print Prediction at Leaf Node
"""A nicer way to print the predictions at a leaf.""" def print_leaf(counts): total = sum(counts.values()) * 1.0 probs = {} for lbl in counts.keys(): probs[lbl] = str(int(counts[lbl] / total * 100)) + "%" return probs
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Check for example
print_leaf(classify(training_data[0],my_tree))
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Test Data
testing_data = [ ['Green', 3, 'Apple'], ['Yellow', 4, 'Apple'], ['Red', 2, 'Grape'], ['Red', 1, 'Grape'], ['Yellow', 3, 'Lemon'], ]
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
Evaluate
for row in testing_data: print ("Actual: %s. Predicted: %s" % (row[-1], print_leaf(classify(row, my_tree))))
DecisionTree_Math_Fruits.ipynb
imamol555/Machine-Learning
mit
CNTK Time series prediction with LSTM This demo demonstrates how to use CNTK to predict future values in a time series using a Recurrent Neural Network (RNN). It is based on a LSTM tutorial that comes with the CNTK distribution. RNNs are particularly well suited to learn sequence data. For details on RNNs, see this exc...
# Standard packages import math from matplotlib import pyplot as plt import numpy as np import os import pandas as pd import time # Helpers for reading stock prices import pandas_datareader.data as pdr import datetime as dt # Images from IPython.display import Image # CNTK packages import cntk as C import cntk.axis ...
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
Select the notebook runtime environment devices / settings Set the device. If you have both CPU and GPU on your machine, you can optionally switch the devices.
# If you have a GPU, uncomment the GPU line below #C.device.set_default_device(C.device.gpu(0)) C.device.set_default_device(C.device.cpu())
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
Download and Prepare Data Here we define helper methods to prepare the data. download_data() Queries Yahoo Finance for daily close price of a given stock ticker symbol. Returns an array of floats.
def download_data(symbol='MSFT', start=dt.datetime(2017, 1, 1), end=dt.datetime(2017, 3, 1)): """ Download daily close and volume for specified stock symbol from Yahoo Finance Returns pandas DataFrame """ data = pdr.DataReader(symbol, 'yahoo', start, end) data.rename(inplace = True, columns={'Cl...
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
As an alternative, we have code to read two CSV files downloaded from DataMarket. The files are 1. Mean daily temperature, Fisher River near Dallas, Jan 01, 1988 to Dec 31, 1991 2. Monthly milk production: pounds per cow. Jan 62 – Dec 75
def read_data(which = "milk"): """ Read csv """ if(which == 'temp'): data = pd.read_csv('data/mean-daily-temperature-fisher-ri.csv') name = 'Mean Daily Temperature - Fisher River' data.rename(inplace = True, columns={'temp':'data'}) rv = data['data']/100 else: ...
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
generate_RNN_data() The RNN will be trained on sequences of length $N$ of single values (scalars), meaning that each training sample is a $N\times1$ matrix. CNTK requires us to shape our input data as an array with each element being an observation. So, for inputs, $X$, we need to create a tensor or 3-D array with dime...
def generate_RNN_data(x, time_steps=10): """ Generate sequences to feed to rnn x: DataFrame, daily close time_steps: int, number of days in sequences used to train the RNN """ rnn_x = [] for i in range(len(x) - (time_steps+1)): # Each training sample is a sequence of length time...
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
split_data() This function will split the data into training, validation and test sets and return a list with those elements, each containing a ndarray as described above.
def split_data(data, val_size=0.1, test_size=0.1): """ splits np.array into training, validation and test """ pos_test = int(len(data) * (1 - test_size)) pos_val = int(len(data[:pos_test]) * (1 - val_size)) train, val, test = data[:pos_val], data[pos_val:pos_test], data[pos_test:] return {...
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
Execute Download data, generate the RNN training and evaluation data and visualize
symbol = 'MSFT' start = dt.datetime(2010, 1, 1) end = dt.datetime(2017, 3, 1) window = 30 #raw_data = download_data1(symbol=symbol, start=start, end=end) #rd100 = raw_data['Close']/10.0 raw_data = read_data('milk') X, Y = generate_RNN_data(raw_data, window) f, a = plt.subplots(3, 1, figsize=(12, 8)) for j, ds in enum...
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
Quick check on the dimensions of the data + make sure we don't have any NaNs
print([(a, X[a].shape) for a in X.keys()]) print([(a, Y[a].shape) for a in Y.keys()]) print([(a, np.isnan(X[a]).any()) for a in X.keys()]) print([(a, np.isnan(Y[a]).any()) for a in Y.keys()])
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
We define the next_batch() iterator that produces batches we can feed to the training function. Note that because CNTK supports variable sequence length, we must feed the batches as list of sequences. This is a convenience function to generate small batches of data often referred to as minibatch.
def next_batch(x, y, ds, size=10): """get the next batch to process""" for i in range(0, len(x[ds])-size, size): yield np.array(x[ds][i:i+size]), np.array(y[ds][i:i+size])
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
Network modeling We setup our network with $N$ LSTM cells, each receiving the single value of our sequence as input at every time step. The $N$ outputs from the LSTM layer are the input into a dense layer that produces a single output. So, we have 1 input, $N$ hidden LSTM nodes and again a single output node. To train...
def create_model(I, H, O): """Create the model for time series prediction""" with C.layers.default_options(initial_state = 0.1): x = C.layers.Input(I) m = C.layers.Recurrence(C.layers.LSTM(H))(x) m = C.ops.sequence.last(m) m = C.layers.Dropout(0.2)(m) m = cntk.layers.Dens...
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
CNTK inputs, outputs and parameters are organized as tensors, or n-dimensional arrays. CNTK refers to these different dimensions as axes. Every CNTK tensor has some static axes and some dynamic axes. The static axes have the same length throughout the life of the network whereas the dynamic axes can vary in length from...
def create_trainer(model, output, learning_rate = 0.001, batch_size = 20): # the learning rate lr_schedule = C.learning_rate_schedule(learning_rate, C.UnitType.minibatch) # loss function loss = C.ops.squared_error(model, output) # use squared error for training error = C.ops.squared_error(mode...
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
Setup everything else we need for training the model: define user specified training parameters, define inputs, outputs, model and the optimizer.
# create the model with 1 input (x), 10 LSTM units, and 1 output unit (y) (z, x, y) = create_model(1, 10, 1) # Construct the trainer BATCH_SIZE = 2 trainer = create_trainer(z, y, learning_rate=0.0002, batch_size=BATCH_SIZE)
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
Training the network We are ready to train. 100 epochs should yield acceptable results.
# Training parameters EPOCHS = 500 # train loss_summary = [] start = time.time() for epoch in range(0, EPOCHS): for x1, y1 in next_batch(X, Y, "train", BATCH_SIZE): trainer.train_minibatch({x: x1, y: y1}) if epoch % (EPOCHS / 20) == 0: training_loss = cntk.utils.get_train_loss(trainer) ...
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
Let's look at how the loss function decreases over time to see if the model is converging
plt.plot(loss_summary[:,0], loss_summary[:,1], label='training loss');
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
Normally we would validate the training on the data that we set aside for validation but since the input data is small we can run validattion on all parts of the dataset.
# validate def get_mse(X,Y,labeltxt): result = 0.0 for x1, y1 in next_batch(X, Y, labeltxt, BATCH_SIZE): eval_error = trainer.test_minibatch({x:x1, y:y1}) result += eval_error return result/len(X[labeltxt]) # Print the train and validation errors for labeltxt in ["train", "val", 'test']: ...
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
We check that the errors are roughly the same for train, validation and test sets. We also plot the expected output (Y) and the prediction our model made to shows how well the simple LSTM approach worked.
# predict f, a = plt.subplots(3, 1, figsize = (12, 8)) for j, ds in enumerate(["train", "val", "test"]): results = [] for x1, y1 in next_batch(X, Y, ds, BATCH_SIZE): pred = z.eval({x: x1}) results.extend(pred[:, 0]) a[j].plot(Y[ds], label = ds + ' raw') a[j].plot(results, label = ds + ' ...
LSTM_Timeseries_predict.ipynb
jspoelstra/cntk-rnn
mit
User Defined Module
# save the following code as example.py def add(a,b): return a+b # now you can import example.py # import example # example.add(5,4)
Modules+and+Packages.ipynb
vravishankar/Jupyter-Books
mit
Import with renaming We can import a module by renaming it as follows:
import math as m print(m.pi)
Modules+and+Packages.ipynb
vravishankar/Jupyter-Books
mit
from...import statement We can import specific names from am module without importing the full module.
from math import pi print(pi) # please note the dot operator is not required
Modules+and+Packages.ipynb
vravishankar/Jupyter-Books
mit
To import all definitions from the module just specify '*' as below. Please note that this not a good practice as it can lead to duplicate definitions for an identifier.
from math import * print(pi)
Modules+and+Packages.ipynb
vravishankar/Jupyter-Books
mit
Module Search Path While importing a module python looks for a definition at various places and in the following order. First it looks for a built-in module Looks at the current directory PYTHONPATH ( environment variable with a list of directory ) Installation dependent default directory
import sys sys.path
Modules+and+Packages.ipynb
vravishankar/Jupyter-Books
mit
Reloading a Module Python loads modules only once even though you try to import it multiple times. But if the module is changed for some reasons and you want to reload the module you can use the .reload() function inside the 'imp' module.
# my_module.py # print('This code got executed') # import imp # import my_module # This code got executed # import my_module # import my_module # imp.reload(my_module)
Modules+and+Packages.ipynb
vravishankar/Jupyter-Books
mit
Module Functions
print(dir(os)) import math print(math.__doc__) math.__name__
Modules+and+Packages.ipynb
vravishankar/Jupyter-Books
mit
Packages A package is just a way of collecting related modules together within a single tree-like hierarchy. Like we organise the files in directories, Python has packages for directories and modules for files. Similar, as a directory can contain sub-directories and files, a python package can have sub-package and modu...
# examples import math from math import pi print(pi)
Modules+and+Packages.ipynb
vravishankar/Jupyter-Books
mit
Finally, we can do post-estimation prediction and forecasting. Notice that the end period can be specified as a date.
# Perform prediction and forecasting predict = res.get_prediction() forecast = res.get_forecast('2014') fig, ax = plt.subplots(figsize=(10,4)) # Plot the results df['lff'].plot(ax=ax, style='k.', label='Observations') predict.predicted_mean.plot(ax=ax, label='One-step-ahead Prediction') predict_ci = predict.conf_int(...
examples/notebooks/statespace_local_linear_trend.ipynb
edhuckle/statsmodels
bsd-3-clause
Signals Then the input signal can be plotted as following (the x-axis is wrong of course, we will tackle this later on). At first glance, it might be obvious (not for me though) that the input is a superposition of two sine waves.
import matplotlib.pyplot as plt def quickplt(sequence): """Plot the signal as-is.""" plt.plot(sequence) plt.show() quickplt(input_1kHz_15kHz)
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
To confirm this suspection, we apply FFT on the signals and plot the results:
from math import pi import numpy as np from numpy.fft import fft def plt_polar(sequence): """Plot the complex signal in polar coordinate, from 0 to pi*2.""" fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2) domain = np.linspace(0, pi*2, len(sequence)) ax1.plot(domain, np.abs(sequence)) ax1.set_tit...
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
Since the low frequencies are lurking around k*pi*2 and the high frequencies are around k*pi*2 + pi, we can make a good guess that the higher peak is of 1 kHz and the lower one is of 15 kHz. The sample rate would be at exactlyk*pi*2 + pi and can be calculated as
sample_rate = (len(inpft)/2) / np.argmax(inpft) * 1000 print(sample_rate)
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
We can then replot the signal with the correct scaling
def plt_time(sequence): """Plot the signal in time domain.""" length = len(sequence) plt.plot(np.linspace(0, length/sample_rate, length), sequence) plt.show() plt_time(input_1kHz_15kHz)
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
The plot of these in cartesian coordinates doesn't give me any further understanding, however:
def plt_rect(sequence): """Plot the complex signal in rectangular coordinate, from 0 to pi*2.""" fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2) domain = np.linspace(0, pi*2, len(sequence)) ax1.plot(domain, np.real(sequence)) ax1.set_title('real') ax2.plot(domain, np.imag(sequence)) ax2.se...
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
Systems Low-pass Filter In this section, we also try to do the same thing for the impulse response, which seems to be a sinc function.
quickplt(impulse_response) lfft = fft(impulse_response) plt_polar(lfft) plt_rect(lfft)
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
As shown in the graphs, the system is a low-pass filter. Applying the system to the input we get what is undeniably the sinusoidal signal of frequency of 1 kHz:
output = np.convolve(input_1kHz_15kHz, impulse_response) plt_time(output)
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
Alternative to convolution in time domain, we can multiply the FTs:
from numpy.fft import ifft from scipy import interpolate f = interpolate.interp1d(np.linspace(0, pi*2, len(lfft)), lfft, kind='zero') plt_time(np.real(ifft(inpft*f(np.linspace(0, pi*2, len(inpft))))))
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
It is noticeable that the wave is now distorted in shape. Funny enough, using other interpolation methods, the result is much worse (using the convoluted one as the reference), for example the linear one:
f = interpolate.interp1d(np.linspace(0, pi*2, len(lfft)), lfft, kind='linear') plt_time(np.real(ifft(inpft*f(np.linspace(0, pi*2, len(inpft))))))
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
Notice that the low-pass filter filtered out the 15 kHz wave:
plt_polar(fft(output)) plt_rect(fft(output))
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
High-pass filter To turn the given low-pass filter to a high-pass one, we subtract it from the impulse signal (which is equivalent to subtracting it from 1 in the frequency domain thanks to linearity):
high_pass = ((lambda m: [0]*m + [1] + [0]*m)(np.argmax(impulse_response)) - np.array(impulse_response)) quickplt(high_pass) plt_polar(fft(high_pass)) plt_rect(fft(high_pass))
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
We then apply it to the input and get the high frequency signal of 15 kHz:
outputhf = np.convolve(input_1kHz_15kHz, high_pass) plt_time(outputhf) plt_polar(fft(outputhf)) plt_rect(fft(outputhf))
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
Other methods to create a HF filter have been tried, however the result is nowhere as good: Shifting the low-pass filter by pi in frequency domain:
high_pass_bad = ifft(np.roll(lfft, len(impulse_response)>>1)) outputhf_bad = np.convolve(input_1kHz_15kHz, high_pass_bad) plt_rect(outputhf_bad) plt_polar(fft(outputhf_bad))
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
Multiply the low-pass in time domain with (-1)^n (which effectively also shift it by pi):
high_pass_worse = np.fromiter(((-1)**n for n in range(len(impulse_response))), dtype=float) * impulse_response outputhf_worse = np.convolve(input_1kHz_15kHz, high_pass_worse) plt_time(outputhf_worse) plt_polar(fft(outputhf_worse))
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
While both of these produce a high frequency signal for most of the interval, at the start and end the volume is significantly higher and there are many different frequencies instead of just 15 kHz. This seems disagrees with the theory at first, but the theory is only supposed to apply to infinite length impulse respo...
ecg = [ 0, 0.0010593, 0.0021186, 0.003178, 0.0042373, 0.0052966, 0.0063559, 0.0074153, 0.0084746, 0.045198, 0.081921, 0.11864, 0.15537, 0.19209, 0.22881, 0.26554, 0.30226, 0.33898, 0.30226, 0.26554, 0.22881, 0.19209, 0.15537, 0.11864, 0.081921, 0.045198, 0.0084746, 0.0077684, 0.0070621, 0.0063559, 0...
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
The plots of the ECG gives us the initial intuition that it's a rather low frequency signal (in fact we have the heartrate of somewhere between 50 to 500 Hz) with multiple face each priod. This is confirmed by the low-passed response, which looks surprisingly similar to the original in time domain
ecglf = np.convolve(ecg, impulse_response) quickplt(ecglf) plt_polar(fft(ecglf)) plt_rect(fft(ecglf))
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
Just for fun, we add some high frequency noise to the signal (because heartbeats are repetitive and boring!):
real, imag = np.random.random((2, len(ecg)-len(high_pass)+1)) whitenoise = ifft(real + imag*1j) noise_hf = abs(np.convolve(whitenoise, high_pass)) quickplt(noise_hf) noisy_ecg = ecg + noise_hf quickplt(noisy_ecg)
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
To smoothen the noisy signal back to normal, the low pass filter shoud be able to does the job:
recovered_ecg = np.convolve(noisy_ecg, impulse_response) quickplt(recovered_ecg)
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
Bonus In this section, we'll try to have some fun playing the signals using palace. While the main purpose of palace is positional audio rendering and environmental effect, it also provide a handy decoder base class, which can be easily derived:
!pip install palace from palace import BaseDecoder, Buffer, Context, Device class Dec(BaseDecoder): """Generator of elementary signals.""" def __init__(self, content): self.content, self.size = content.copy(), len(content) @BaseDecoder.frequency.getter def frequency(self) -> int: return int(s...
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
The input and output signals can then be played by running:
from time import sleep with Device() as d, Context(d) as c: with Buffer.from_decoder(Dec(input_1kHz_15kHz), 'input') as b, b.play() as s: sleep(1) with Buffer.from_decoder(Dec(output), 'lf') as b, b.play() as s: sleep(1) with Buffer.from_decoder(Dec(outputhf), 'hf') as b, b.play() as s: ...
usth/ICT2.9/practical/dsp.ipynb
McSinyx/hsg
gpl-3.0
and the system, where we, as we did in part I, only commit the orientation of the dipole moment to the particles and take the magnitude into account in the prefactor of Dipolar P3M (for more details see part I). Hint: It should be noted that we seed both the Langevin thermostat and the random number generator of numpy...
system = espressomd.System(box_l=(box_size,box_size,box_size)) system.time_step = dt system.thermostat.set_langevin(kT=kT, gamma=gamma, seed=1) # Lennard Jones interaction system.non_bonded_inter[0,0].lennard_jones.set_params(epsilon=lj_epsilon,sigma=lj_sigma,cutoff=lj_cut, shift="auto") # Random dipole moments np.r...
doc/tutorials/11-ferrofluid/11-ferrofluid_part3.ipynb
mkuron/espresso
gpl-3.0
The Python code below encodes a Tetrahedron type based solely on its six edge lengths. The code makes no attempt to determine the consequent angles. A complicated volume formula, mined from the history books and streamlined by mathematician Gerald de Jong, outputs the volume of said tetrahedron in both IVM and XYZ u...
from math import sqrt as rt2 from qrays import Qvector, Vector R =0.5 D =1.0 S3 = pow(9/8, 0.5) root2 = rt2(2) root3 = rt2(3) root5 = rt2(5) root6 = rt2(6) PHI = (1 + root5)/2.0 class Tetrahedron: """ Takes six edges of tetrahedron with faces (a,b,d)(b,c,e)(c,a,f)(d,e,f) -- returns volume in ivm a...
Computing Volumes.ipynb
4dsolutions/Python5
mit
The make_tet function takes three vectors from a common corner, in terms of vectors with coordinates, and computes the remaining missing lengths, thereby getting the information it needs to use the Tetrahedron class as before.
import unittest from qrays import Vector, Qvector class Test_Tetrahedron(unittest.TestCase): def test_unit_volume(self): tet = Tetrahedron(D, D, D, D, D, D) self.assertEqual(tet.ivm_volume(), 1, "Volume not 1") def test_e_module(self): e0 = D e1 = root3 * PHI**-1 e2 = ...
Computing Volumes.ipynb
4dsolutions/Python5
mit
<a data-flickr-embed="true" href="https://www.flickr.com/photos/kirbyurner/41211295565/in/album-72157624750749042/" title="Martian Multiplication"><img src="https://farm1.staticflickr.com/907/41211295565_59145e2f63.jpg" width="500" height="312" alt="Martian Multiplication"></a><script async src="//embedr.flickr.com/as...
a = 2 b = 4 c = 5 d = 3.4641016151377544 e = 4.58257569495584 f = 4.358898943540673 tetra = Tetrahedron(a,b,c,d,e,f) print("IVM volume of tetra:", round(tetra.ivm_volume(),5))
Computing Volumes.ipynb
4dsolutions/Python5
mit
Lets define a MITE, one of these 24 identical space-filling tetrahedrons, with reference to D=1, R=0.5, as this is how our Tetrahedron class is calibrated. The cubes 12 edges will all be √2/2. Edges 'a' 'b' 'c' fan out from the cube center, with 'b' going up to a face center, with 'a' and 'c' to adjacent ends of the f...
b = rt2(2)/4 a = c = rt2(3/8) d = e = 0.5 f = rt2(2)/2 mite = Tetrahedron(a, b, c, d, e, f) print("IVM volume of Mite:", round(mite.ivm_volume(),5)) print("XYZ volume of Mite:", round(mite.xyz_volume(),5))
Computing Volumes.ipynb
4dsolutions/Python5
mit
Allowing for floating point error, this space-filling right tetrahedron has a volume of 0.125 or 1/8. Since 24 of them form a cube, said cube has a volume of 3. The XYZ volume, on the other hand, is what we'd expect from a regular tetrahedron of edges 0.5 in the current calibration system.
regular = Tetrahedron(0.5, 0.5, 0.5, 0.5, 0.5, 0.5) print("MITE volume in XYZ units:", round(regular.xyz_volume(),5)) print("XYZ volume of 24-Mite Cube:", round(24 * regular.xyz_volume(),5))
Computing Volumes.ipynb
4dsolutions/Python5
mit
The MITE (minimum tetrahedron) further dissects into component modules, a left and right A module, then either a left or right B module. Outwardly, the positive and negative MITEs look the same. Here are some drawings from R. Buckminster Fuller's research, the chief popularizer of the A and B modules. In a different...
from math import sqrt as rt2 from tetravolume import make_tet, Vector ø = (rt2(5)+1)/2 e0 = Black_Yellow = rt2(3)*ø**-1 e1 = Black_Blue = 1 e3 = Yellow_Blue = (3 - rt2(5))/2 e6 = Black_Red = rt2((5 - rt2(5))/2) e7 = Blue_Red = 1/ø # E-mod is a right tetrahedron, so xyz is easy v0 = Vector((Black_Blue, 0, 0)) v1 = Vec...
Computing Volumes.ipynb
4dsolutions/Python5
mit
Compute and visualize ERDS maps This example calculates and displays ERDS maps of event-related EEG data. ERDS (sometimes also written as ERD/ERS) is short for event-related desynchronization (ERD) and event-related synchronization (ERS) :footcite:PfurtschellerLopesdaSilva1999. Conceptually, ERD corresponds to a decrea...
# Authors: Clemens Brunner <clemens.brunner@gmail.com> # Felix Klotzsche <klotzsche@cbs.mpg.de> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import mne from mne.datasets import eegbci from mne.io import concatenate_raws, read_raw_edf ...
0.23/_downloads/d12911920e4d160c9fd8c97cffdda6b7/time_frequency_erds.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
This allows us to use additional plotting functions like :func:seaborn.lineplot to plot confidence bands:
df = tfr.to_data_frame(time_format=None, long_format=True) # Map to frequency bands: freq_bounds = {'_': 0, 'delta': 3, 'theta': 7, 'alpha': 13, 'beta': 35, 'gamma': 140} df['band'] = pd.cut(df['freq'], list(freq_bounds.values()), ...
0.23/_downloads/d12911920e4d160c9fd8c97cffdda6b7/time_frequency_erds.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Polynomial regression
import numpy as np import numpy.random as rnd np.random.seed(42) m = 100 X = 6 * np.random.rand(m, 1) - 3 y = 0.5 * X**2 + X + 2 + np.random.randn(m, 1) plt.plot(X, y, "b.") plt.xlabel("$x_1$", fontsize=18) plt.ylabel("$y$", rotation=0, fontsize=18) plt.axis([-3, 3, 0, 10]) save_fig("quadratic_data_plot") plt.show()...
HandsOnML/code/04_training_linear_models.ipynb
atulsingh0/MachineLearning
gpl-3.0
Regularized models
from sklearn.linear_model import Ridge np.random.seed(42) m = 20 X = 3 * np.random.rand(m, 1) y = 1 + 0.5 * X + np.random.randn(m, 1) / 1.5 X_new = np.linspace(0, 3, 100).reshape(100, 1) def plot_model(model_class, polynomial, alphas, **model_kargs): for alpha, style in zip(alphas, ("b-", "g--", "r:")): m...
HandsOnML/code/04_training_linear_models.ipynb
atulsingh0/MachineLearning
gpl-3.0
Feeding Data from Python Code:
# Create python list constants: constantX = [ 1.0, 2.0, 3.0 ] constantY = [ 10.0, 20.0, 30.0 ] # Create addition operation (for constants): addConstants = tf.add( constantX, constantY ) # Create session: with tf.Session() as sess: # Run session on constants and print output: print sess.run( ...
tensorflow_tutorials/Tutorial_03_LoadingData.ipynb
Hebali/learning_machines
mit
Loading Data from File:
# Define file-reader function: def read_file(filepath): file_queue = tf.train.string_input_producer( [ filepath ] ) file_reader = tf.WholeFileReader() _, contents = file_reader.read( file_queue ) return contents # Create PNG image loader operation: load_op = tf.image.decode_png( read_file( 'data/tf.pn...
tensorflow_tutorials/Tutorial_03_LoadingData.ipynb
Hebali/learning_machines
mit
This works and is the correct product even if $v$ is not really a column vector:
A = np.array([[1, 2], [3, 4]]) v = np.array([5, 6]) A.dot(v)
Foundations/Math/linear-algebra_exercise.ipynb
aleph314/K2
gpl-3.0
This also works because $v$ is truly a row vector, so we have $1\times2$ times $2\times2$ and all is good:
v.dot(A)
Foundations/Math/linear-algebra_exercise.ipynb
aleph314/K2
gpl-3.0
2 - Using $\vec{v}$ above, compute the inner, or dot, product, $\vec{v} \cdot \vec{v}$. Is this quantity reminiscent of another vector quantity?
v.dot(v)
Foundations/Math/linear-algebra_exercise.ipynb
aleph314/K2
gpl-3.0
This quantity is the same as the norm squared:
np.linalg.norm(v)**2
Foundations/Math/linear-algebra_exercise.ipynb
aleph314/K2
gpl-3.0
3 - Create 3 matrices $\textbf{A}$, $\textbf{B}$, $\textbf{C}$ of dimension $2\times2$, $3\times2$, and $2\times3$ respectively such that $$\textbf{A} = \begin{bmatrix} 1 & 2 \ 3 & 4 \end{bmatrix} \textbf{B} = \begin{bmatrix} 1 & 2 \ 3 & 4 \ 5 & 6\end{bmatrix} \textbf{C} = \begin{bmatrix} 1 & 2 & 3\ 4 & 5 & 6 \end{bmat...
A = np.arange(1, 5).reshape(2, 2) B = np.arange(1, 7).reshape(3, 2) C = np.arange(1, 7).reshape(2, 3)
Foundations/Math/linear-algebra_exercise.ipynb
aleph314/K2
gpl-3.0
We can compute the product only if the number of columns of the first matrix is the same as the number of rows of the second:
for tab in [(x, y) for x in (A, B, C) for y in (A, B, C)]: try: if tab[0] is A: left = 'A' elif tab[0] is B: left = 'B' else: left = 'C' if tab[1] is A: right = 'A' elif tab[1] is B: right = 'B' else...
Foundations/Math/linear-algebra_exercise.ipynb
aleph314/K2
gpl-3.0
4 - Using $\textbf{A}$ and $\textbf{B}$ above, compute $(\textbf{BA})^T$ and $\textbf{A}^T \textbf{B}^T$. What can you say about your results? The result is the same:
print((B.dot(A)).T) print(A.T.dot(B.T))
Foundations/Math/linear-algebra_exercise.ipynb
aleph314/K2
gpl-3.0
5 - Using $\textbf{A}$, $\textbf{B}$, and $\textbf{C}$ above, compute the following sums: $\textbf{A+A}$, $\textbf{A+B}$, $\textbf{A+C}$, $\textbf{B+B}$, $\textbf{B+A}$, $\textbf{B+C}$, $\textbf{C+C}$, $\textbf{C+A}$, $\textbf{C+B}$. Comment on your results. We can only sum the matrices with themselves because they ha...
for tab in [(x, y) for x in (A, B, C) for y in (A, B, C)]: try: if tab[0] is A: left = 'A' elif tab[0] is B: left = 'B' else: left = 'C' if tab[1] is A: right = 'A' elif tab[1] is B: right = 'B' else...
Foundations/Math/linear-algebra_exercise.ipynb
aleph314/K2
gpl-3.0
6 - Construct three matrices $\textbf{I}_A$, $\textbf{I}_B$, and $\textbf{I}_C$ such that $\textbf{I}_A\textbf{A} = \textbf{A}$, $\textbf{I}_B\textbf{B} = \textbf{B}$, and $\textbf{I}_C\textbf{C} = \textbf{C}$.
Ia = np.eye(2) Ib = np.eye(3) Ic = np.eye(2) print(A) print(Ia.dot(A)) print(B) print(Ib.dot(B)) print(C) print(Ic.dot(C))
Foundations/Math/linear-algebra_exercise.ipynb
aleph314/K2
gpl-3.0
7 - Construct three matrices $\textbf{A}^{-1}$, $\textbf{B}^{-1}$, and $\textbf{C}^{-1}$ such that $\textbf{A}^{-1}\textbf{A} = \textbf{I}_A$, $\textbf{B}^{-1}\textbf{B} = \textbf{I}_B$, and $\textbf{C}^{-1}\textbf{C} = \textbf{I}_C$. Comment on your results. Hint This may not always be possible!
Ainv = np.linalg.inv(A) print(A) print(Ainv.dot(A)) print(B) print('Not possible because B is 3x2 and Ib is 3x3') print(C) print('Not possible because C is 2x3 and Ib is 2x2')
Foundations/Math/linear-algebra_exercise.ipynb
aleph314/K2
gpl-3.0