markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
**Expected Output**: **dW1** [[-0.25604646 0.12298827 -0.28297129] [-0.17706303 0.34536094 -0.4410571 ]] **dW2** [[ 0.79276486 0.85133918] [-0.0957219 -0.01720463] [-0.13100772 -0.03750433]] **dW3** [[-1.77691347 -0.11832... | parameters = model(train_X, train_Y, lambd = 0.7)
print ("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters) | Cost after iteration 0: 0.6974484493131264
Cost after iteration 10000: 0.2684918873282239
Cost after iteration 20000: 0.2680916337127301
| MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
Congrats, the test set accuracy increased to 93%. You have saved the French football team!You are not overfitting the training data anymore. Let's plot the decision boundary. | plt.title("Model with L2-regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y) | _____no_output_____ | MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
**Observations**:- The value of $\lambda$ is a hyperparameter that you can tune using a dev set.- L2 regularization makes your decision boundary smoother. If $\lambda$ is too large, it is also possible to "oversmooth", resulting in a model with high bias.**What is L2-regularization actually doing?**:L2-regularization r... | # GRADED FUNCTION: forward_propagation_with_dropout
def forward_propagation_with_dropout(X, parameters, keep_prob = 0.5):
"""
Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
Arguments:
X -- input dataset, of shape (2, number of example... | A3 = [[ 0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]]
| MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
**Expected Output**: **A3** [[ 0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]] 3.2 - Backward propagation with dropout**Exercise**: Implement the backward propagation with dropout. As before, you are training a 3 layer network. Add dropout to the first and second h... | # GRADED FUNCTION: backward_propagation_with_dropout
def backward_propagation_with_dropout(X, Y, cache, keep_prob):
"""
Implements the backward propagation of our baseline model to which we added dropout.
Arguments:
X -- input dataset, of shape (2, number of examples)
Y -- "true" labels vector... | dA1 = [[ 0.36544439 0. -0.00188233 0. -0.17408748]
[ 0.65515713 0. -0.00337459 0. -0. ]]
dA2 = [[ 0.58180856 0. -0.00299679 0. -0.27715731]
[ 0. 0.53159854 -0. 0.53159854 -0.34089673]
[ 0. 0. -0.00292733 0. -0. ... | MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
**Expected Output**: **dA1** [[ 0.36544439 0. -0.00188233 0. -0.17408748] [ 0.65515713 0. -0.00337459 0. -0. ]] **dA2** [[ 0.58180856 0. -0.00299679 0. -0.27715731] [ 0. 0.53159854 -0.... | parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3)
print ("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters) | Cost after iteration 0: 0.6543912405149825
| MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
Dropout works great! The test accuracy has increased again (to 95%)! Your model is not overfitting the training set and does a great job on the test set. The French football team will be forever grateful to you! Run the code below to plot the decision boundary. | plt.title("Model with dropout")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y) | _____no_output_____ | MIT | Course_2/Regularization.ipynb | karanchawla/DeepLearningSpecialization-Coursera |
Table of Contents* [1c. Fixed flux spinodal decomposition on a T shaped domain](1c.-Fixed-flux-spinodal-decomposition-on-a-T-shaped-domain) * [Use Binder For Live Examples](Use-Binder-For-Live-Examples) * [Define $f_0$](Define-$f_0$) * [Define the Equation](Define-the-Equation) * [Solve the Equation](Solve-the-Equatio... | %matplotlib inline
import sympy
import fipy as fp
import numpy as np
A, c, c_m, B, c_alpha, c_beta = sympy.symbols("A c_var c_m B c_alpha c_beta")
f_0 = - A / 2 * (c - c_m)**2 + B / 4 * (c - c_m)**4 + c_alpha / 4 * (c - c_alpha)**4 + c_beta / 4 * (c - c_beta)**4
print f_0
sympy.diff(f_0, c, 2) | _____no_output_____ | MIT | hackathons/hackathon1/fipy/1c.ipynb | wd15/chimad-phase-field |
The first step in implementing any problem in FiPy is to define the mesh. For [Problem 1a]({{ site.baseurl }}/hackathons/hackathon1/problems.ipynb/1.a-Square-Periodic) the solution domain is just a square domain, but the boundary conditions are periodic, so a `PeriodicGrid2D` object is used. No other boundary condition... | mesh = fp.Grid2D(dx=0.5, dy=0.5, nx=40, ny=200) + (fp.Grid2D(dx=0.5, dy=0.5, nx=200, ny=40) + [[-40],[100]]) | _____no_output_____ | MIT | hackathons/hackathon1/fipy/1c.ipynb | wd15/chimad-phase-field |
The next step is to define the parameters and create a solution variable. | c_alpha = 0.05
c_beta = 0.95
A = 2.0
kappa = 2.0
c_m = (c_alpha + c_beta) / 2.
B = A / (c_alpha - c_m)**2
D = D_alpha = D_beta = 2. / (c_beta - c_alpha)
c_0 = 0.45
q = np.sqrt((2., 3.))
epsilon = 0.01
c_var = fp.CellVariable(mesh=mesh, name=r"$c$", hasOld=True) | _____no_output_____ | MIT | hackathons/hackathon1/fipy/1c.ipynb | wd15/chimad-phase-field |
Now we need to define the initial conditions given by,Set $c\left(\vec{r}, t\right)$ such that$$ c\left(\vec{r}, 0\right) = \bar{c}_0 + \epsilon \cos \left( \vec{q} \cdot \vec{r} \right) $$ | r = np.array((mesh.x, mesh.y))
c_var[:] = c_0 + epsilon * np.cos((q[:, None] * r).sum(0))
viewer = fp.Viewer(c_var) | _____no_output_____ | MIT | hackathons/hackathon1/fipy/1c.ipynb | wd15/chimad-phase-field |
Define $f_0$ To define the equation with FiPy first define `f_0` in terms of FiPy. Recall `f_0` from above calculated using Sympy. Here we use the string representation and set it equal to `f_0_var` using the `exec` command. | out = sympy.diff(f_0, c, 2)
exec "f_0_var = " + repr(out)
#f_0_var = -A + 3*B*(c_var - c_m)**2 + 3*c_alpha*(c_var - c_alpha)**2 + 3*c_beta*(c_var - c_beta)**2
f_0_var | _____no_output_____ | MIT | hackathons/hackathon1/fipy/1c.ipynb | wd15/chimad-phase-field |
Define the Equation | eqn = fp.TransientTerm(coeff=1.) == fp.DiffusionTerm(D * f_0_var) - fp.DiffusionTerm((D, kappa))
eqn | _____no_output_____ | MIT | hackathons/hackathon1/fipy/1c.ipynb | wd15/chimad-phase-field |
Solve the Equation To solve the equation a simple time stepping scheme is used which is decreased or increased based on whether the residual decreases or increases. A time step is recalculated if the required tolerance is not reached. | elapsed = 0.0
steps = 0
dt = 0.01
total_sweeps = 2
tolerance = 1e-1
total_steps = 10
c_var[:] = c_0 + epsilon * np.cos((q[:, None] * r).sum(0))
c_var.updateOld()
from fipy.solvers.pysparse import LinearLUSolver as Solver
solver = Solver()
while steps < total_steps:
res0 = eqn.sweep(c_var, dt=dt, solver=solver)
... | _____no_output_____ | MIT | hackathons/hackathon1/fipy/1c.ipynb | wd15/chimad-phase-field |
Run the Example Locally The following cell will dumpy a file called `fipy_hackathon1c.py` to the local file system to be run. The images are saved out at each time step. | %%writefile fipy_hackathon_1c.py
import fipy as fp
import numpy as np
mesh = fp.Grid2D(dx=0.5, dy=0.5, nx=40, ny=200) + (fp.Grid2D(dx=0.5, dy=0.5, nx=200, ny=40) + [[-40],[100]])
c_alpha = 0.05
c_beta = 0.95
A = 2.0
kappa = 2.0
c_m = (c_alpha + c_beta) / 2.
B = A / (c_alpha - c_m)**2
D = D_alpha = D_beta = 2. / (c_b... | Overwriting fipy_hackathon_1c.py
| MIT | hackathons/hackathon1/fipy/1c.ipynb | wd15/chimad-phase-field |
Movie of Evolution The movie of the evolution for 600 steps.The movie was generated with the output files of the form `image*.png` using the following commands, $ rename 's/\d+/sprintf("%05d",$&)/e' image* $ ffmpeg -f image2 -r 6 -i 'image%05d.png' output.mp4 | from IPython.display import YouTubeVideo
scale = 1.5
YouTubeVideo('aZk38E7OxcQ', width=420 * scale, height=315 * scale, rel=0) | _____no_output_____ | MIT | hackathons/hackathon1/fipy/1c.ipynb | wd15/chimad-phase-field |
아래 URL의 NBA 데이터를 크롤링하여 판다스 데이터 프레임으로 나타내세요. - http://stats.nba.com/teams/traditional/?sort=GP&dir=-1 | from selenium import webdriver
import pandas as pd
def Nba():
try:
driver = webdriver.Chrome()
driver.get("http://stats.nba.com/teams/traditional/?sort=GP&dir=-1")
# column_list
columns = driver.find_elements_by_css_selector(".nba-stat-table__overflow > table > \
thead > t... | _____no_output_____ | MIT | web/00_quiz/crawling_quiz.ipynb | hyelansgithub/fastcampus-programming |
셀레니움을 이용하여 네이버 IT/과학 기사의 10 페이지 까지의 최신 제목 리스트를 크롤링하세요.- http://news.naver.com/main/main.nhn?mode=LSD&mid=shm&sid1=105 | def News():
try:
driver = webdriver.Chrome()
driver.get("http://news.naver.com/main/main.nhn?mode=LSD&mid=shm&sid1=105")
# news = pd.DataFrame(columns = ["Number of Articles","Article Headline"])
for i in range(10):
results = driver.find_elements_by_css_selector("... | _____no_output_____ | MIT | web/00_quiz/crawling_quiz.ipynb | hyelansgithub/fastcampus-programming |
IMPORTS | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt | _____no_output_____ | MIT | Laptop_Price_Predict/laptop_price_main.ipynb | Andy666Fox/TINY_DS_PROJECTS |
READ THE DATA | data = pd.read_csv('./input/laptops.csv', encoding='latin-1')
data.head(10) | _____no_output_____ | MIT | Laptop_Price_Predict/laptop_price_main.ipynb | Andy666Fox/TINY_DS_PROJECTS |
MAIN EDA BLOCK | print(f'Data Shape\nRows: {data.shape[0]}\nColumns: {data.shape[1]}')
print('=' * 30)
data.info()
data.describe()
data['Product'] = data['Product'].str.split('(').apply(lambda x: x[0])
data['CPu_Speed'] = data['Cpu'].str.split(' ').apply(lambda x: x[-1]).str.replace('GHz', '')
data['Cpu_Vender'] = data['Cpu'].str.split... | R2 score 0.8578750665087866
MAE 0.16211150811805436
| MIT | Laptop_Price_Predict/laptop_price_main.ipynb | Andy666Fox/TINY_DS_PROJECTS |
训练 | model.fit(X, y, total_steps=20) | WARNING:tensorflow:From /Users/geyingli/Library/Python/3.8/lib/python/site-packages/tensorflow/python/util/dispatch.py:201: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.
Instructions for updating:
Please use `rate` instead of `keep_prob`. Rate ... | Apache-2.0 | examples/ALBERTBinaryClassifier.ipynb | Anychnn/unif |
推理 | model.predict(X) | INFO:tensorflow:Time usage 0m-2.16s, 0.46 steps/sec, 1.85 examples/sec
| Apache-2.0 | examples/ALBERTBinaryClassifier.ipynb | Anychnn/unif |
评分 | model.score(X, y) | INFO:tensorflow:Time usage 0m-0.98s, 1.02 steps/sec, 4.10 examples/sec
| Apache-2.0 | examples/ALBERTBinaryClassifier.ipynb | Anychnn/unif |
АНАЛИЗ ЗВУКА И ГОЛОСА**Преподаватель**: Рыбин Сергей Витальевич**Группа**: 6304**Студент**: Белоусов Евгений Олегович Классификация акустических шумов*Необоходимый результат: неизвестно* | import os
import IPython
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import librosa
import librosa.display
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
from tqdm.notebook import tqdm
from tensorflow.keras import losses, models, optimizers
from t... | _____no_output_____ | MIT | Lab 2 - Acoustic Noise Classification/[SVA]_Lab_2_Acoustic_Noise_Classification.ipynb | northuraldude/ETU-2021-SVA |
COMP5318 - Machine Learning and Data Mining: Assignment 2 Group 86 tlin4302 | 470322974 | Jenny Tsai-chen Lin jsun4242 | 500409987 | Jiawei Sun jyan2937 | 480546614 | Jinxuan Yang The notebook includes sections : Section 0. Hardware and software specifications Section 1. Library and general functions S... | import os, platform
print('OS name:', os.name, ', system:', platform.system(), ', release:', platform.release())
import sys
print("Anaconda version:")
#!conda list anaconda
print("Python version: ", sys.version)
print("Python version info: ", sys.version_info)
import PIL
from PIL import Image
print("PIL version: ", PIL... | OS name: nt , system: Windows , release: 10
Anaconda version:
Python version: 3.8.3 (default, Jul 2 2020, 17:30:36) [MSC v.1916 64 bit (AMD64)]
Python version info: sys.version_info(major=3, minor=8, micro=3, releaselevel='final', serial=0)
PIL version: 7.2.0
Matplotlib version: 3.2.2
OpenCV version: 4.4.0
nump v... | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Section 0. Switches (Default settings is great for demo purpose) Load saved model or run training? | load_saved_model = True | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Run preprocessing benchmark or not? | run_preprocessing_benchmark = True | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Run test code for 3 classifiers? | run_test_code_for_classifiers = True | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
number of threads when preprocessing images | g_thread_num = 6 | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Run hyper parameter tuning? (Slow if turned on!) | # Caution: Slow if turned on.
do_hyper_parameter_tuning = False | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Run 10-fold cross validation? (Slow if turned on) | # Caution: Slow if turned on.
run_ten_fold = False | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Section 1. Library and general functions | # Go to anaconda prompt to install package imblearn
# anaconda: conda install -c glemaitre imbalanced-learn
#pip install kmeans-smote
from skimage import io, transform
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import cv2
import time | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
global variables | # choose one of below two line depend file location******
g_dataset_dir = "./dataset/"
#g_dataset_dir = "../dataset/"
a_random_file = "./dataset/train/1b1B1b2-2pK2q1-4p1rB-7k-8-8-3B4-3rb3.jpeg"
#a_random_file = "../dataset/train/1b1B1b2-2pK2q1-4p1rB-7k-8-8-3B4-3rb3.jpeg"
saved_model_path = "./saved_model/"
a... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Helper codes for label & board | #DataHelper.py
import os
import cv2
from skimage import io
import numpy as np
import glob
import h5py
# get clean name by a path, where in our case this gets the FEN conviniently
def GetCleanNameByPath(file_name):
return os.path.splitext(os.path.basename(file_name))[0]
# get full paths to the files in a direct... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Section 2. Data pre-processing Pre-processing - generic | # split into 64 small square from 1 board
# image resized to 400x 400 to 200x 200. 64 square at 25x 25 each
def PreprocessImage(image):
image = transform.resize(image, (g_down_sampled_size, g_down_sampled_size), mode='constant')
# 1st and 2nd dim is 8
grids = ImageToGrids(image, g_down_sampled_gri... | x type : <class 'numpy.ndarray'>
x shape: (1, 64, 25, 25, 3)
y type : <class 'numpy.ndarray'>
y shape: (1, 64, 13)
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Pre-processing - canny | # Processing image with canny
import cv2
def PreprocessImage_canny(image):
image = cv2.Canny(image,100,200)
image = transform.resize(image, (g_down_sampled_size, g_down_sampled_size), mode='constant')
# 1st and 2nd dim is 8
image = image[..., np.newaxis]
grids = ImageToGrids_grey(image, g_down_samp... | x type : <class 'list'>
x[0] type : <class 'numpy.ndarray'>
x[0] shape: (64, 25, 25)
y type : <class 'list'>
y[0] type : <class 'numpy.ndarray'>
y[0] shape: (64,)
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Pre-processing - SIFT | # Processing image with sift
import cv2
def ExtractSIFTForGrid(board_image, row, col, center_x = 25, center_y = 25, radius = 45):
kps = [cv2.KeyPoint(x = center_x + 50 * col, y = center_y + 50 * row, _size = 45)]
# USE THE CORRECT VERSION OF CV2
if cv2.__version__ == "4.4.0":
keypoints, descri... | x type : <class 'list'>
x[0] type : <class 'numpy.ndarray'>
x[0] shape: (64, 128)
y type : <class 'list'>
y[0] type : <class 'numpy.ndarray'>
y[0] shape: (64,)
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Example of image input, canny, SIFT | import cv2
from skimage.filters import sobel
#print("Sift: decriptor size:", cv2.SIFT_create().descriptorSize())
img = ReadImage(a_random_file)
img1 = cv2.Canny(img,100,200)
img2= sobel(img[:,:,0])
print(img.shape)
print(img1.shape)
print(img2.shape)
kp, desc = ExtractSIFTForGrid(img, 0, 1)
kp2, desc2 = ExtractSIFTFo... | (400, 400, 3)
(400, 400)
(400, 400)
file name: ./dataset/train/1b1B1b2-2pK2q1-4p1rB-7k-8-8-3B4-3rb3.jpeg
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Read image - generic, canny, sift - run time | if run_preprocessing_benchmark:
start_time = time.time()
num_train = 100
train_file_names = GetFileNamesInDir(g_train_dir, extension = "jpeg",num_return = num_train)
X_org,Y_org = func_generator(train_file_names)
print('runnning time for generic 100 images')
print('--- {} seconds ---'.format(ti... | runnning time for generic 100 images
--- 1.9594979286193848 seconds ---
runnning time for sift 100 images
--- 28.49899911880493 seconds ---
runnning time for canny 100 images
--- 0.7249987125396729 seconds ---
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Subset train data - high quality (image level) | #https://www.researchgate.net/post/How_to_use_clustering_to_reduce_data_set_samples
#subset data of high quality image (at image level)
#Output is
def file_names_highquality(image_file_names, min_piece =15):
names = np.array(image_file_names)
idx_sub = []
for idx in range(len(image_file_names)):
... | reduced file number from 100 to 21
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Undersempling -square (grid level) | # install the package if needed.
if run_preprocessing_benchmark:
!pip install imblearn
#subset data (in square level)
#ref: #https://www.researchgate.net/post/How_to_use_clustering_to_reduce_data_set_samples
# implement using https://imbalanced-learn.readthedocs.io/en/stable/generated/imblearn.under_sampling.Cluste... | --- 5.019449710845947 seconds ---
reduce grid number from 6400 to 455
--- 4.656001806259155 seconds ---
reduce grid number from 6400 to 455
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Read Image - parallel version | from joblib import Parallel, delayed
# note: functions are first-class objects in Python. we pass it directly as parameter.
def Preprocess_parallel(func, file_names, job_count = 6):
result = Parallel(n_jobs=job_count)(delayed(func)(file_name) for file_name in file_names)
return zip(*result)
if run_preprocessin... | --- 1.9814999103546143 seconds ---
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Read file names | if do_hyper_parameter_tuning:
# Using FEN to identify grid with chess
num_train = 500 # small bath train
num_test= 500 # small bath train
# Reading lables
train_file_names = GetFileNamesInDir(g_train_dir, extension = "jpeg",num_return = num_train)
test_file_names = GetFileNamesInDir(g_test_d... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Section 3. Implement algorithms Section 3.0 AdaBoostClassifier (ABC) Prototype Import data - SIFT output ( n x 128) | if do_hyper_parameter_tuning:
# import data - train
start_time = time.time()
#xs_train, ys_train = Preprocess_parallel(train_file_names)
xs_train_sift, ys_train_sift = Preprocess_parallel(func_sift, train_file_names) #[JL - I broke Preprocess_parallel. use this instead ]
print('xs_train_sift, ys... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
intital prediction accuracy in sift data | if do_hyper_parameter_tuning:
xs_train_sift2= np.array(xs_train_sift).reshape(500*64,128)
ys_train_sift2 = np.array(ys_train_sift).reshape(500*64)
print('shape of train data:',np.array(xs_train_sift2).shape, np.array(ys_train_sift2).shape)
# ABC classifier
from sklearn.ensemble import AdaBoostClas... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Import data - canny output ( n x 25 x 25 ) | if do_hyper_parameter_tuning:
# import data - train 500
start_time = time.time()
#xs_train, ys_train = Preprocess_parallel(train_file_names)
xs_train_canny, ys_train_canny = func_generator_canny(train_file_names) #[JL - I broke Preprocess_parallel. use this instead ]
print('xs_train_canny, ys_tr... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
intital prediction accuracy in canny data | if do_hyper_parameter_tuning:
xs_train_canny2= np.array(xs_train_canny).reshape(500*64,25*25)
ys_train_canny2 = np.array(ys_train_canny).reshape(500*64)
print('shape of train data:',np.array(xs_train_canny2).shape, np.array(ys_train_canny2).shape)
# ABC classifier
from sklearn.ensemble import AdaB... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Proceed with canny data Split train to train and validation | if do_hyper_parameter_tuning:
#split 500 training data
start_time = time.time()
test_size=0.33
from sklearn.model_selection import train_test_split
X_train, X_val, Y_train, Y_val = train_test_split(
xs_train_canny,ys_train_canny, test_size=0.33, random_state=0)
print(np.array(X_train).... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Undersampling traing set | if do_hyper_parameter_tuning:
# test sift -resampled
start_time = time.time()
X_resampled, Y_resampled = undersampling_ClusterCentroids_canny(X_train,Y_train)
print('--- {} seconds ---'.format(time.time() - start_time))
print('reduce grid number from',len(np.array(Y_train))*64,'to',len(np.array(Y_... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Base classifier- Tree (with canny & canny resampling) | if do_hyper_parameter_tuning:
# Tree classifier - Canny data
from sklearn.tree import DecisionTreeClassifier
start_time = time.time()
#Apply pre-pruning by limiting the depth of the tree - max_depth=2
tree = DecisionTreeClassifier(criterion='gini', max_depth=5)
tree.fit(X_train, Y_train)
#... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
AdaBoostClassifier- Tree (with canny & canny resampling) | if do_hyper_parameter_tuning:
# ABC classifier- Canny data
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
start_time = time.time()
ada = AdaBoostClassifier(n_estimators=50,
... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Hyper parameter tunning | ###https://machinelearningmastery.com/adaboost-ensemble-in-python/
if do_hyper_parameter_tuning:
from sklearn.ensemble import AdaBoostClassifier
from sklearn.model_selection import GridSearchCV
# AdaBoost
param_grid = [{'n_estimators': np.arange(10,50,5),
'learning_rate': [0.01,... | Hyper parameter tuning skipped.
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
GridSearchCV Result |
if do_hyper_parameter_tuning:
# Print grid search results
from sklearn.metrics import classification_report
means = abc.cv_results_['mean_test_score']
stds = abc.cv_results_['std_test_score']
params = abc.cv_results_['params']
print('Grid search mean and stdev:\n')
for mean, std, p in z... | Adaboost: Hyper parameter report skipped.
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Section 3.1 SVM Classifier (SVC) Base class for all classifiers | import abc
# interface of the classifiers
class IClassifier:
# this method should accept a list of file names of the training data
@abc.abstractmethod
def Train(self, train_file_names):
raise NotImplementedError()
# this should accept a 400 * 400 * 3 numpy array as query data, and returns the... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Class definition for SVC | from sklearn import svm
import numpy as np
# image io and plotting
from skimage import io, transform
import skimage.util
from skimage.util.shape import view_as_blocks
from matplotlib import pyplot as plt
# parallel processing
from joblib import Parallel, delayed
# model save and load
import pickle
import os
# profili... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Test code for SVC | if run_test_code_for_classifiers:
svc = SVCClassifier()
train_names = GetFileNamesInDir(g_train_dir)
if load_saved_model:
print("svc: loading model from " + svc_model_file)
svc.LoadModel(svc_model_file)
else:
svc.Train(train_names[:500])
y_truth = FENtoL(GetCleanNameByPath(... | svc: loading model from ./saved_model/svc_dump.pkl
truth: 0b0B0b0000pK00q00000p0rB0000000k0000000000000000000B0000000rb000
pred : 000B0000000K00000000p0rB0000000k0000000000000000000B0000000r0000
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Section 3.2 Convolutional Neural Network Classifier (CNN) Class definition for CNN | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import cv2
from skimage import io, transform
import numpy as np
import os
#import tensorflow as tf
#from tensorflow import keras
#from tf.keras.models import Sequential
#from tf.keras.layers.core import Flatten, Dense, Dropout, A... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
test code for CNN | if run_test_code_for_classifiers:
if not load_saved_model:
cnn = CNNClassifier()
train_names = GetFileNamesInDir(g_train_dir)
cnn.Train(train_names)
cnn.SaveModel(cnn_model_file)
else:
cnn = CNNClassifier()
cnn.PrintModel()
print("cnn: loading model from "... | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 23, 23, 32) 896
____________________________________... | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Section 3.3 AdaBoost Classifier class definition | from sklearn.ensemble import AdaBoostClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
import numpy as np
# image io and plotting
from skimage import io, transform
import skimage.util
from skimage.util.shape import view_as_blocks
from matp... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Test code for ABC | if run_test_code_for_classifiers:
abc = ABClassifier()
train_names = GetFileNamesInDir(g_train_dir)
if load_saved_model:
print("abc: loading model from " + abc_model_file)
abc.LoadModel(abc_model_file)
else:
abc.Train(train_names)
y_truth = FENtoL(GetCleanNameByPath(a_rando... | abc: loading model from ./saved_model/abc_dump.pkl
truth: 0b0B0b0000pK00q00000p0rB0000000k0000000000000000000B0000000rb000
pred : 0k0B0k0000pP00q00000p0rB0000000k0000000000000000000B0000000rb000
| MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
10-fold cross validation for 3 classifiers Cv referencehttps://scikit-learn.org/stable/modules/cross_validation.htmloptions for 10 fold 1. https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.ShuffleSplit.html 2. https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.Strat... | # filters accepts a list of file names, and return the data matrix and labels
import random
from sklearn.metrics import confusion_matrix
# get balanced accuracy from confusion matrix
def BalancedAccuracyFromConfusionMatrix(cm):
ret = np.empty((cm.shape[0]))
for idx, row in enumerate(cm):
ret[idx] ... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
10-fold routine | if run_ten_fold:
# 10-fold for ABC
train_file_names = GetFileNamesInDir(g_train_dir, extension = "jpeg")
# random sampling rate of the each fold in 10-fold
abc_random_sampling_rate = 0.005
abc_tf = ABClassifier()
confusion_matrices_abc, accuracies_abc, accuracies_balanced_abc, train_time_cost_... | training started: SVCClassifier for fold # 0 # train files: 720
svc: reading image.
svc: finished reading image, 4.1754982471466064 sec.
svc: start training.
svc: finished. 275.877498626709 sec.
training finished: SVCClassifier for fold # 0 time: 280.06999683380127s
predicting started: SVCClassifier for fold #... | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Serialize the results (export to hard drive) | if run_ten_fold:
# dump the matrices for report.
os.makedirs(os.path.dirname(ten_fold_result_path), exist_ok = True)
np.save(ten_fold_result_path + "confusion_matrices_abc.npy", confusion_matrices_abc)
np.save(ten_fold_result_path + "accuracies_abc.npy", accuracies_abc)
np.save(ten_fold_result_path... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Read the results from hard drive | if not run_ten_fold:
import numpy as np
confusion_matrices_abc = np.load(ten_fold_result_path + "confusion_matrices_abc.npy")
accuracies_abc = np.load(ten_fold_result_path + "accuracies_abc.npy")
accuracies_balanced_abc = np.load(ten_fold_result_path + "accuracies_balanced_abc.npy")
train_time_... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Plot the results | import matplotlib.pyplot as plt
def plot_accuracy(mat_abc, mat_cnn, mat_svc, title):
line, = plt.plot([i for i in range(len(mat_abc))],mat_abc)
line.set_label('AdaBoost')
line, = plt.plot([i for i in range(len(mat_cnn))],mat_cnn)
line.set_label('CNN')
line, = plt.plot([i for i in range(len(mat_svc))... | _____no_output_____ | MIT | group86_other_algorithms.ipynb | dukeNashor/ChessMaster |
Visualizing invasive and non-invasive EEG data[Liberty Hamilton, PhD](https://csd.utexas.edu/research/hamilton-lab)Assistant Professor, University of Texas at AustinDepartment of Speech, Language, and Hearing Sciencesand Department of Neurology, Dell Medical School Welcome! In this notebook we will be discussing how t... | !pip install matplotlib==3.2
import mne # This is the mne library
import numpy as np # This gives us the power of numpy, which is just generally useful for array manipulation
%matplotlib inline
from matplotlib import pyplot as plt
from matplotlib import cm
datasets = {'ecog': '/home/jovyan/data/we_eeg_viz_data/ecog/s... | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
1.1. Choose which dataset to look at (start with EEG)For the purposes of this tutorial, we'll be looking at some scalp EEG and intracranial EEG datasets from my lab. Participants provided written informed consent for participation in our research. These data were collected from two distinct participants listening to ... | data_type = 'eeg' # Can choose from 'eeg' or 'ecog' | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
1.2. Load the dataThis next command loads the data from our fif file of interest. The `preload=True` flag means that the data will be loaded (necessary for some operations). If `preload=False`, you can still perform some aspects of this tutorial, and this is a great option if you have a large dataset and would like to... | raw = mne.io.read_raw_fif(datasets[data_type], preload=True) | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
There is a lot of useful information in the info structure. For example, we can get the sampling frequency (`raw.info['sfreq']`), the channel names (`raw.info['ch_names']`), the channel types and locations (in `raw.info['chs']`), and whether any filtering operations have been performed already (`raw.info['highpass']` a... | print(raw.info)
sampling_freq = raw.info['sfreq']
nchans = raw.info['nchan']
print('The sampling frequency of our data is %d'%(sampling_freq))
print('Here is our list of %d channels: '%nchans)
print(raw.ch_names)
eeg_colors = {'eeg': 'k', 'eog': 'steelblue'}
fig = raw.plot(show=False, color=eeg_colors, scalings='auto... | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
2. Let's make some plots!MNE-python makes creating some plots *super easy*, which is great for data quality checking, exploration, and eventually manuscript figure generation. For example, one might wish to plot the power spectral density (PSD), which 2.2. Power spectral density | raw.plot_psd(); | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
2.3. Sensor positions (for EEG)For EEG, MNE-python also has convenient functions for showing the location of the sensors used. Here, we have a 64-channel montage. You can also use this information to help interpret some of your plots if you're plotting a single channel or a group of channels.For ECoG, we will not be p... | if data_type == 'eeg':
raw.plot_sensors(kind='topomap',show_names=True);
| _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Ok, awesome! So now we know where the sensors are, how densely they tile the space, and what their names are. *Knowledge = Power!*So what if we wanted to look at the power spectral density plot we saw above by channel? We can use `plot_psd_topo` for that! There are also customizable options for playing with the colors. | if data_type == 'eeg':
raw.plot_psd_topo(fig_facecolor='w', axis_facecolor='w', color='k'); | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Finally, this one works for both EEG and ECoG. Here we are looking at the power spectral density plot again, but taking the average across trials and showing +/- 1 standard deviation from the mean across channels. | raw.plot_psd(area_mode='std', average=True); | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Finally, we can plot these same figures using a narrower frequency range, and looking at a smaller set of channels using `picks`. For `plot_psd` and other functions, `picks` is a list of integer indices corresponding to your channels of interest. You can choose these by their number, or you can use the convenient `mne.... | if data_type == 'eeg':
picks = mne.pick_channels(raw.ch_names, include=['Pz','CPz','Cz','FCz','Fz','C1','C2','FC1','FC2','CP1','CP2'])
elif data_type == 'ecog':
picks = mne.pick_channels(raw.ch_names, include=['RPPST9','RPPST10','RPPST11'])
raw.plot_psd(picks = picks, fmin=1, fmax=raw.info['sfreq']/2, xscale='... | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Plotting responses to eventsOk, so this is all well and good. We can plot our raw data, the power spectrum, and the locations of the sensors. But what if we care about responses to the stimuli we described above? What if we want to look at responses to specific sentences, or the average response across all sentences, ... | # Load some events. The format of these is start sample, end sample, and event ID.
events = mne.read_events(event_files[data_type])
print(events)
num_events = len(events)
unique_stimuli = np.unique(np.array(events)[:,2])
num_unique = len(unique_stimuli)
print('There are %d total events, corresponding to %d unique stim... | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
EpochsGreat. So now that we have the events, we will "epoch" our data, which basically uses these timings to split up our data into trials of a given length. We will also set some parameters for data rejection to get rid of noisy trials. | # Set some rejection criteria. This will be based on the peak-to-peak
# amplitude of your data.
if data_type=='eeg':
reject = {'eeg': 60e-6} # Higher than peak to peak amplitude of 60 µV will be rejected
scalings = None
units = None
elif data_type=='ecog':
reject = {'ecog': 10} # Higher than Z-score of... | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
So what's in this epochs data structure? If we look at it, we can see that we have an entry for each event ID, and we can see how many times that stimulus was played. You can also see whether baseline correction was done and for what time period, and whether any data was rejected. | epochs | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Now, you could decide at this point that you just want to work with the data directly as a numpy array. Luckily, that's super easy to do! We can just call `get_data()` on our epochs data structure, and this will output a matrix of `[events x channels x time points]`. If you do not limit the channel type, you will get a... | ep_data = epochs.get_data()
print(ep_data.shape) | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Plotting Epoched dataOk... so we are getting ahead of ourselves. MNE-python provides a lot of ways to plot our data so that we don't have to deal with writing functions to do this ourselves! For example, if we'd like to plot the EEG/ECoG for all of the single trials we just loaded, along with an average across all of ... | epochs.plot_image(combine='mean', scalings=scalings, units=units) | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
As before, we can choose specific channels to look at instead of looking at all of them at once. For which method do you think this would make the most difference? Why? | if data_type == 'eeg':
picks = mne.pick_channels(raw.ch_names, include=['Fz','FCz','Cz','CPz','Pz'])
elif data_type == 'ecog':
picks = mne.pick_channels(raw.ch_names, include=['RPPST9','RPPST10','RPPST11'])
epochs.plot_image(picks = picks, combine='mean', scalings=scalings, units=units) | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
We can also sort the trials, if we would like. This can be very convenient if you have reaction times or some other portion of the trial where reordering would make sense. Here, we'll just pick a channel and order by the mean activity within each trial. | if data_type == 'eeg':
picks = mne.pick_channels(raw.ch_names, include=['CP6'])
elif data_type == 'ecog':
picks = mne.pick_channels(raw.ch_names, include=['RPPST2'])
# Get the data as a numpy array
eps_data = epochs.get_data()
# Sort the data
new_order = eps_data[:,picks[0],:].mean(1).argsort(0)
epochs.plot... | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Other ways to view epoched dataFor EEG, another way to view these epochs by trial is using the scalp topography information. This allows us to quickly assess differences across the scalp in response to the stimuli. What do you notice about the responses? | if data_type == 'eeg':
epochs.plot_topo_image(vmin=-30, vmax=30, fig_facecolor='w',font_color='k'); | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Comparing epochs of different trial typesSo far we have just shown averages of activity across many different sentences. However, as mentioned above, the sentences come from multiple male and female talkers. So -- one quick split we could try is just to compare the responses to female vs. male talkers. This is relativ... | # Make lists of the event ID numbers corresponding to "f" and "m" sentences
f_evs = []
m_evs = []
for k in event_id.keys():
if k[0] == 'f':
f_evs.append(event_id[k])
elif k[0] == 'm':
m_evs.append(event_id[k])
print(unique_stimuli)
f_evs_new = [v for v in f_evs if v in unique_stimuli]
m_evs_new... | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Now we can plot the epochs just as we did above. | f_epochs.plot_image(combine='mean', show=False, scalings=scalings, units=units)
m_epochs.plot_image(combine='mean', show=False, scalings=scalings, units=units) | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Cool! So now we have a separate plot for the "f" and "m" talkers. However, it's not super convenient to compare the traces this way... we kind of want them on the same axis. MNE easily allows us to do this too! Instead of using the epochs, we can create `evoked` data structures, which are averaged epochs. You can [read... | evokeds = {'female': f_epochs.average(), 'male': m_epochs.average()}
mne.viz.plot_compare_evokeds(evokeds, show_sensors='upper right',picks=picks); | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
If we actually want errorbars on this plot, we need to do this a bit differently. We can use the `iter_evoked()` method on our epochs structures to create a dictionary of conditions for which we will plot our comparisons with `plot_compare_evokeds`. | evokeds = {'f':list(f_epochs.iter_evoked()), 'm':list(m_epochs.iter_evoked())}
mne.viz.plot_compare_evokeds(evokeds, picks=picks);
| _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Plotting scalp topographyFor EEG, another common plot you may see is a topographic map showing activity (or other data like p-values, or differences between conditions). In this example, we'll show the activity at -0.2, 0, 0.1, 0.2, 0.3, and 1 second. You can also of course choose just one time to look at. | if data_type == 'eeg':
times=[tmin, 0, 0.1, 0.2, 0.3, tmax]
epochs.average().plot_topomap(times, ch_type='eeg', cmap='PRGn', res=32,
outlines='skirt', time_unit='s'); | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
We can also plot arbitrary data using `mne.viz.plot_topomap`, and passing in a vector of data matching the number of EEG channels, and `raw.info` to give specifics on those channel locations. | if data_type == 'eeg':
chans = mne.pick_types(raw.info, eeg=True)
data = np.random.randn(len(chans),)
plt.figure()
mne.viz.plot_topomap(data, raw.info, show=True)
| _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
We can even animate these topo maps! This won't work well in jupyterhub, but feel free to try on your own! | if data_type == 'eeg':
fig,anim=epochs.average().animate_topomap(blit=False, times=np.linspace(tmin, tmax, 100)) | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
A few more fancy EEG plotsIf we want to get especially fancy, we can also use `plot_joint` with our evoked data (or averaged epoched data, as shown below). This allows us to combine the ERPs for individual channels with topographic maps at time points that we specify. Pretty awesome! | if data_type == 'eeg':
epochs.average().plot_joint(picks='eeg', times=[0.1, 0.2, 0.3]) | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
What if I need more control? - matplotlib alternativesIf you feel you need more specific control over your plots, it's easy to get the data into a usable format for plotting with matplotlib. You can export both the raw and epoched data using the `get_data()` function, which will allow you to save your data as a numpy ... | if data_type == 'eeg':
picks = mne.pick_channels(raw.ch_names, include=['Fz','FCz','Cz','CPz','Pz'])
elif data_type == 'ecog':
picks = mne.pick_channels(raw.ch_names, include=['RPPST9','RPPST10','RPPST11'])
f_data = f_epochs.get_data(picks=picks)
m_data = m_epochs.get_data(picks=picks)
times = f_epochs.tim... | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Plot evoked data with errorbars We can recreate some similar plots to those in MNE-python with some of the matplotlib functions. Here we'll create something similar to what was plotted in `plot_compare_evokeds`. | def plot_errorbar(x, ydata, label=None, axlines=True, alpha=0.5, **kwargs):
'''
Plot the mean +/- standard error of ydata.
Inputs:
x : vector of x values
ydata : matrix of your data (this will be averaged along the 0th dimension)
label : A string containing the label for this plot
... | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
ECoG Exercise:1. If you wanted to look at each ECoG electrode individually to find which ones have responses to the speech data, how would you do this?2. Can you plot the comparison between "f" and "m" trials for each electrode as a subplot (try using `plt.subplot()` from `matplotlib`) | # Get the data for f trials
# Get the data for m trials
# Loop through each channel, and create a set of subplots for each | _____no_output_____ | CC-BY-4.0 | we-visualizing-eeg-hamilton/EEG_viz_mne.ipynb | bastivkl/nh2020-curriculum |
Binary Horse Poo Model> Simple model to detect HorsePoo vs noHorsePoo export data | %load_ext autoreload
%autoreload 2
#!rm -R data/tmp/horse_poo/ && rm -R data/tmp/no_horse_poo/
#!prodigy db-out binary_horse_poo ./data/tmp | _____no_output_____ | Apache-2.0 | nbs/03_binaryHorsePoo.ipynb | SubmitCode/PooDetector |
DescriptionWith this model we will start of with a very simple binary classification. We will try to use most of the default settings from fastai. This will also be our benchmark model for further investigations. | #export
from fastai.vision import *
from fastai.callbacks import EarlyStoppingCallback
from prodigy.util import read_jsonl, write_jsonl
from prodigy.components.db import connect
from PooDetector.dataset_operations import extract_jsonl_to_binary_folders
import os
import shutil
from fastscript import *
#export
def prepa... | _____no_output_____ | Apache-2.0 | nbs/03_binaryHorsePoo.ipynb | SubmitCode/PooDetector |
MDN-transformer with examples- What kind of data can be predicted by a mixture density network Transformer? - Continuous sequential data- Drawing data and RoboJam Touch Screem would be good examples for this, continuous values yield high resolution in 2d space. 1. Kanji Generation- Firstly, let's try modelling som... | # Setup and modules
import sys
!{sys.executable} -m pip install keras-mdn-layer
!{sys.executable} -m pip install tensorflow
!{sys.executable} -m pip install tensorflow-probability
!{sys.executable} -m pip install matplotlib
!{sys.executable} -m pip install pandas
!{sys.executable} -m pip install svgwrite
import mdn
i... | _____no_output_____ | MIT | transformer-mdn-kanji.ipynb | cpmpercussion/keras-transformer-mdn |
Download and process the data set | # Train from David Ha's Kanji dataset from Sketch-RNN: https://github.com/hardmaru/sketch-rnn-datasets
# Other datasets in "Sketch 3" format should also work.
import urllib.request
url = 'https://github.com/hardmaru/sketch-rnn-datasets/raw/master/kanji/kanji.rdp25.npz'
urllib.request.urlretrieve(url, './kanji.rdp25.n... | _____no_output_____ | MIT | transformer-mdn-kanji.ipynb | cpmpercussion/keras-transformer-mdn |
DatasetIncludes about 11000 handwritten kanji characters divied into training, validation, and testing sets. | with np.load('./kanji.rdp25.npz', allow_pickle=True) as data:
train_set = data['train']
valid_set = data['valid']
test_set = data['test']
print("Training kanji:", len(train_set))
print("Validation kanji:", len(valid_set))
print("Testing kanji:", len(test_set))
# Functions for slicing up data
def slice_... | _____no_output_____ | MIT | transformer-mdn-kanji.ipynb | cpmpercussion/keras-transformer-mdn |
Constructing the MDN TransformerOur MDN Transformer has the following settings:- an embedding layer with positional embedding- a transformer encoder- a transformer decoder- a three-dimensional mixture layer with 10 mixtures- train for sequence length ___- training for ___ epochs with a batch size of ___Here's a diagra... | class PositionalEmbedding(layers.Layer):
def __init__(self, sequence_length, input_dim, output_dim, **kwargs):
super().__init__(**kwargs)
self.token_embeddings = layers.Dense(output_dim)
self.position_embeddings = layers.Embedding(
input_dim=sequence_length, output_dim=output_dim... | _____no_output_____ | MIT | transformer-mdn-kanji.ipynb | cpmpercussion/keras-transformer-mdn |
Generating drawingsFirst need some helper functions to view the output. | def zero_start_position():
"""A zeroed out start position with pen down"""
out = np.zeros((1, 1, 3), dtype=np.float32)
out[0, 0, 2] = 1 # set pen down.
return out
def generate_sketch(model, start_pos, num_points=100):
return None
def cutoff_stroke(x):
return np.greater(x,0.5) * 1.0
def plot_... | _____no_output_____ | MIT | transformer-mdn-kanji.ipynb | cpmpercussion/keras-transformer-mdn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.