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 |
|---|---|---|---|---|---|
2.3 Answering the Research Question | #define function that shuffles the data in one column
def shuffle_data(features, feature_index):
'''
Shuffles the data in the column denoted by feature_index. All other data remain unchanged
features: 2D array, each row stands for one instance, each column for one feature
feature_index: the entries in... | 0.0 %
10.0 %
20.0 %
30.0 %
40.0 %
50.0 %
60.0 %
70.0 %
80.0 %
90.0 %
error rate, linear regression:
0.005183430036888673
0.0 %
10.0 %
20.0 %
30.0 %
40.0 %
50.0 %
60.0 %
70.0 %
80.0 %
90.0 %
error rate, regression tree:
0.005268014302182951
| MIT | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning |
To obtain the following results we run the code from above several times. The first row stands for the results from the unshuffled dataset, the other rows from the shuffled datasets. One can see that the error of some of the rows corresponding to a dataset with shuffled color rating are lower than the error from the or... | err_data = pd.read_csv("errors.txt", sep=",", index_col=False)
err_data | _____no_output_____ | MIT | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning |
2.4 How to Lie With Statistics We already found a choice of features that does not reveal a skin color bias. So we try to find a choice of features that shows such a bias. We choose the "rating" column as the only feature. We only apply the Linear Regression model to the data, because our task is to find one example o... | Y = df["percentageReds"].to_numpy()
X = df[["rating"]].to_numpy()
df_mean = df_mean[["rating", "percentageReds"]]
#number of folds
L = 20
#create L folds
N = len(X)
indices = np.random.choice(N, N, replace=False)
X_folds = np.array(np.array_split(X[indices], L), dtype=object)
Y_folds = np.array(np.array_split(Y[ind... | 0.0 %
5.0 %
10.0 %
15.0 %
20.0 %
25.0 %
30.0 %
35.0 %
40.0 %
45.0 %
50.0 %
55.00000000000001 %
60.0 %
65.0 %
70.0 %
75.0 %
80.0 %
85.0 %
90.0 %
95.0 %
error rate, linear regression:
0.005248877638861473
| MIT | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning |
After running the code above 20 times we can find a skin color bias this time: The mean squared error for the shuffled data is always higher than the error for the original dataset. 2.5 Alternative Hypotheses This exercise assumes that a correlation between the skin color and the probability to get a red card exists. ... | #compute covariance matrices
Y = df["percentageReds"].to_numpy()
X = df["weight"].to_numpy()
print(np.cov(X,Y))
Y = df["rating"].to_numpy()
print(np.cov(X,Y), "\n")
Y = df["percentageReds"].to_numpy()
X = df["Position_Back"].to_numpy()
print(np.cov(X,Y))
Y = df["rating"].to_numpy()
print(np.cov(X,Y)) | [[5.12806150e+01 3.60300072e-03]
[3.60300072e-03 5.17986190e-03]]
[[ 5.12806150e+01 -4.98876945e-02]
[-4.98876945e-02 8.25710800e-02]]
[[0.21255133 0.00071554]
[0.00071554 0.00517986]]
[[ 0.21255133 -0.00133118]
[-0.00133118 0.08257108]]
| MIT | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning |
Random Forest Classification Required Packages | import warnings
import numpy as np
import pandas as pd
import seaborn as se
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_rep... | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
InitializationFilepath of CSV file | #filepath
file_path= "" | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
List of features which are required for model training . | #x_values
features=[] | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
Target feature for prediction. | #y_value
target='' | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
Data FetchingPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. | df=pd.read_csv(file_path)
df.head() | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
Feature SelectionsIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.We will assign all the required input features to... | X = df[features]
Y = df[target] | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
Data PreprocessingSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the da... | def NullClearner(df):
if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])):
df.fillna(df.mean(),inplace=True)
return df
elif(isinstance(df, pd.Series)):
df.fillna(df.mode()[0],inplace=True)
return df
else:return df
def EncodeX(df):
return pd.get_du... | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
Correlation MapIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. | f,ax = plt.subplots(figsize=(18, 18))
matrix = np.triu(X.corr())
se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)
plt.show() | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
Distribution Of Target Variable | plt.figure(figsize = (10,6))
se.countplot(Y) | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
Data SplittingThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of th... | X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 123)#performing datasplitting | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
ModelA random forest is a meta estimator that fits a number of decision tree classifiers on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. The sub-sample size is controlled with the max_samples parameter if bootstrap=True (default), otherwise the whol... | # Build Model here
model = RandomForestClassifier(n_jobs = -1,random_state = 123)
model.fit(X_train, y_train) | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
Model Accuracyscore() method return the mean accuracy on the given test data and labels.In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. | print("Accuracy score {:.2f} %\n".format(model.score(X_test,y_test)*100)) | Accuracy score 88.75 %
| Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
Confusion MatrixA confusion matrix is utilized to understand the performance of the classification model or algorithm in machine learning for a given test set where results are known. | plot_confusion_matrix(model,X_test,y_test,cmap=plt.cm.Blues) | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
Classification ReportA Classification report is used to measure the quality of predictions from a classification algorithm. How many predictions are True, how many are False.* **where**: - Precision:- Accuracy of positive predictions. - Recall:- Fraction of positives that were correctly identified. - f1-score... | print(classification_report(y_test,model.predict(X_test))) | precision recall f1-score support
0 0.94 0.88 0.91 50
1 0.82 0.90 0.86 30
accuracy 0.89 80
macro avg 0.88 0.89 0.88 80
weighted avg 0.89 0.89 0.89 ... | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
Feature Importances.The Feature importance refers to techniques that assign a score to features based on how useful they are for making the prediction. | plt.figure(figsize=(8,6))
n_features = len(X.columns)
plt.barh(range(n_features), model.feature_importances_, align='center')
plt.yticks(np.arange(n_features), X.columns)
plt.xlabel("Feature importance")
plt.ylabel("Feature")
plt.ylim(-1, n_features) | _____no_output_____ | Apache-2.0 | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed |
convert strokes matrix from absolute to relative coordinates | from copy import deepcopy
unique_photos = np.unique(S1.photoID)
r = pd.DataFrame(columns=list(S1.keys()))
run_this = False
if run_this:
for i, p in enumerate(unique_photos):
print 'Processing ' + p + ': ' + str(i+1) + ' of ' + str(len(unique_photos)) + ' photos.'
s1 = S1[S1.photoID==p]
uniq... | _____no_output_____ | MIT | predict/tf_sketchy.ipynb | judithfan/pix2svg |
quality assurance make sure that image classification is working as advertised based on triplet features | import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn import svm
from sklearn import linear_model
# reminders:
# S1 is stroke matrix
# F1 is feature matrix
# PF is photo-feature matrix
# SF is sketch-feature matrix/
# get np.array of ... | dimensionality of train/test split
(536, 1024) (536,)
(135, 1024) (135,)
Accuracy: 0.43 (+/- 0.01)
| MIT | predict/tf_sketchy.ipynb | judithfan/pix2svg |
compute pairwise euclidean distances between sketches of same class vs. different class | ### this was done on 9/11/17 in order to debug the vgg embedding
print 'Why are there fewer sketch intermediate files than total sketch files?'
print str(len(os.listdir('./tiny/sketch/airplane'))) + ' total sketch files.'
all_sketches = os.listdir('./tiny/sketch/airplane')
all_sketches_with_intermediates = [s.split('/... | _____no_output_____ | MIT | predict/tf_sketchy.ipynb | judithfan/pix2svg |
draft of model for single minibatch | RANDOM_SEED = 42
tf.set_random_seed(RANDOM_SEED)
# reset entire graph
tf.reset_default_graph()
sess = tf.InteractiveSession()
# weight on offset loss
offset_weight = 100.
# learning rate
learning_rate = 0.01
# get minibatch
batch_size = 10
F_batch = F_train[:batch_size,:]
S_batch = S_train.head(n=batch_size)
# res... | _____no_output_____ | MIT | predict/tf_sketchy.ipynb | judithfan/pix2svg |
run multiple batches of MLP version | RANDOM_SEED = 42
tf.set_random_seed(RANDOM_SEED)
# reset entire graph
tf.reset_default_graph()
# weight on offset loss
offset_weight = 0.1
# amount to multiply predicted offset values by
offset_multiplier = 100.
# learning rate
learning_rate = 0.001
# set batch size
batch_size = 10
# epoch counter
epoch_num = 0
... | _____no_output_____ | MIT | predict/tf_sketchy.ipynb | judithfan/pix2svg |
simpler version that goes from last pen offset to next pen offset | ## now try simpler version that just tries to predict the next offset based on previous offset
RANDOM_SEED = 42
tf.set_random_seed(RANDOM_SEED)
# reset entire graph
tf.reset_default_graph()
# weight on offset loss
offset_weight = 0.8
# amount to multiply predicted offset values by
offset_multiplier = 100.
# learn... | _____no_output_____ | MIT | predict/tf_sketchy.ipynb | judithfan/pix2svg |
predict next offset on basis of previous 4 offsets | RANDOM_SEED = 42
tf.set_random_seed(RANDOM_SEED)
# reset entire graph
tf.reset_default_graph()
# weight on offset loss
offset_weight = 1.
# amount to multiply predicted offset values by
offset_multiplier = 100.
# learning rate
learning_rate = 0.001
# set batch size
batch_size = 10
# epoch counter
epoch_num = 0
#... | _____no_output_____ | MIT | predict/tf_sketchy.ipynb | judithfan/pix2svg |
now trying to predict mixture of gaussians rather than naive nonlinear function... because pen offsets can't be modeled by any function reverting to trying to predict next pen offset based on single most recent pen offset | ## now trying to predict mixture of gaussians rather than naive nonlinear function... because pen offsets can't be modeled by any function
import mdn as mdn ## import mixture density network helpers
reload(mdn)
RANDOM_SEED = 42
tf.set_random_seed(RANDOM_SEED)
# reset entire graph
tf.reset_default_graph()
# weight o... | _____no_output_____ | MIT | predict/tf_sketchy.ipynb | judithfan/pix2svg |
run rnn version | # RANDOM_SEED = 42
# tf.set_random_seed(RANDOM_SEED)
# # reset entire graph
# tf.reset_default_graph()
# # weight on offset loss
# offset_weight = 1000.
# # learning rate
# learning_rate = 0.01
# # set batch size
# batch_size = 10
# # epoch counter
# epoch_num = 0
# # max strokes
# max_strokes = 200
# # initiali... | _____no_output_____ | MIT | predict/tf_sketchy.ipynb | judithfan/pix2svg |
TensorFlow Mnist手写识别 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, optimizers, datasets
(x, y), (x_val, y_val) = datasets.mnist.load_data()
x = tf.convert_to_tensor(x, dtype=tf.float32) / 255.
y = tf.convert_to_tensor(y, dtype=tf.int32)
... | 0 0 loss: 2.0240273
0 100 loss: 0.9473155
0 200 loss: 0.7345356
1 0 loss: 0.69385874
1 100 loss: 0.6878035
1 200 loss: 0.56050974
2 0 loss: 0.5645488
2 100 loss: 0.5928352
2 200 loss: 0.48700562
3 0 loss: 0.49895468
3 100 loss: 0.5390559
3 200 loss: 0.44372237
4 0 loss: 0.45752183
4 100 loss: 0.5022621
4 200 loss: 0.41... | MIT | TensorFlow-2.0/02-Tensorflow-Demo/01-HelloWorld.ipynb | silence1016/machine-learning |
Brainstorm auditory tutorial datasetHere we compute the evoked from raw for the auditory Brainstormtutorial dataset. For comparison, see [1]_ and the associated`brainstorm site `_.Experiment: - One subject, 2 acquisition runs 6 minutes each. - Each run contains 200 regular beeps and 40 easy deviant beeps. - R... | # Authors: Mainak Jas <mainak.jas@telecom-paristech.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Jaakko Leppakangas <jaeilepp@student.jyu.fi>
#
# License: BSD (3-clause)
import os.path as op
import pandas as pd
import numpy as np
import mne
from mne import combine_evoked
from mne.minimum_norm impor... | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
To reduce memory consumption and running time, some of the steps areprecomputed. To run everything from scratch change this to False. With``use_precomputed = False`` running time of this script can be severalminutes even on a fast computer. | use_precomputed = True | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
The data was collected with a CTF 275 system at 2400 Hz and low-passfiltered at 600 Hz. Here the data and empty room data files are read toconstruct instances of :class:`mne.io.Raw`. | data_path = bst_auditory.data_path()
subject = 'bst_auditory'
subjects_dir = op.join(data_path, 'subjects')
raw_fname1 = op.join(data_path, 'MEG', 'bst_auditory',
'S01_AEF_20131218_01.ds')
raw_fname2 = op.join(data_path, 'MEG', 'bst_auditory',
'S01_AEF_20131218_02.ds')
erm_fn... | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
In the memory saving mode we use ``preload=False`` and use the memoryefficient IO which loads the data on demand. However, filtering and someother functions require the data to be preloaded in the memory. | preload = not use_precomputed
raw = read_raw_ctf(raw_fname1, preload=preload)
n_times_run1 = raw.n_times
mne.io.concatenate_raws([raw, read_raw_ctf(raw_fname2, preload=preload)])
raw_erm = read_raw_ctf(erm_fname, preload=preload) | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Data channel array consisted of 274 MEG axial gradiometers, 26 MEG referencesensors and 2 EEG electrodes (Cz and Pz).In addition: - 1 stim channel for marking presentation times for the stimuli - 1 audio channel for the sent signal - 1 response channel for recording the button presses - 1 ECG bipolar - 2 EOG bipol... | raw.set_channel_types({'HEOG': 'eog', 'VEOG': 'eog', 'ECG': 'ecg'})
if not use_precomputed:
# Leave out the two EEG channels for easier computation of forward.
raw.pick_types(meg=True, eeg=False, stim=True, misc=True, eog=True,
ecg=True) | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
For noise reduction, a set of bad segments have been identified and storedin csv files. The bad segments are later used to reject epochs that overlapwith them.The file for the second run also contains some saccades. The saccades areremoved by using SSP. We use pandas to read the data from the csv files. Youcan also vie... | annotations_df = pd.DataFrame()
offset = n_times_run1
for idx in [1, 2]:
csv_fname = op.join(data_path, 'MEG', 'bst_auditory',
'events_bad_0%s.csv' % idx)
df = pd.read_csv(csv_fname, header=None,
names=['onset', 'duration', 'id', 'label'])
print('Events from run ... | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Here we compute the saccade and EOG projectors for magnetometers and addthem to the raw data. The projectors are added to both runs. | saccade_epochs = mne.Epochs(raw, saccades_events, 1, 0., 0.5, preload=True,
reject_by_annotation=False)
projs_saccade = mne.compute_proj_epochs(saccade_epochs, n_mag=1, n_eeg=0,
desc_prefix='saccade')
if use_precomputed:
proj_fname = op.join(data_... | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Visually inspect the effects of projections. Click on 'proj' button at thebottom right corner to toggle the projectors on/off. EOG events can beplotted by adding the event list as a keyword argument. As the bad segmentsand saccades were added as annotations to the raw data, they are plotted aswell. | raw.plot(block=True) | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Typical preprocessing step is the removal of power line artifact (50 Hz or60 Hz). Here we notch filter the data at 60, 120 and 180 to remove theoriginal 60 Hz artifact and the harmonics. The power spectra are plottedbefore and after the filtering to show the effect. The drop after 600 Hzappears because the data was fil... | if not use_precomputed:
meg_picks = mne.pick_types(raw.info, meg=True, eeg=False)
raw.plot_psd(tmax=np.inf, picks=meg_picks)
notches = np.arange(60, 181, 60)
raw.notch_filter(notches, phase='zero-double', fir_design='firwin2')
raw.plot_psd(tmax=np.inf, picks=meg_picks) | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
We also lowpass filter the data at 100 Hz to remove the hf components. | if not use_precomputed:
raw.filter(None, 100., h_trans_bandwidth=0.5, filter_length='10s',
phase='zero-double', fir_design='firwin2') | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Epoching and averaging.First some parameters are defined and events extracted from the stimuluschannel (UPPT001). The rejection thresholds are defined as peak-to-peakvalues and are in T / m for gradiometers, T for magnetometers andV for EOG and EEG channels. | tmin, tmax = -0.1, 0.5
event_id = dict(standard=1, deviant=2)
reject = dict(mag=4e-12, eog=250e-6)
# find events
events = mne.find_events(raw, stim_channel='UPPT001') | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
The event timing is adjusted by comparing the trigger times on detectedsound onsets on channel UADC001-4408. | sound_data = raw[raw.ch_names.index('UADC001-4408')][0][0]
onsets = np.where(np.abs(sound_data) > 2. * np.std(sound_data))[0]
min_diff = int(0.5 * raw.info['sfreq'])
diffs = np.concatenate([[min_diff + 1], np.diff(onsets)])
onsets = onsets[diffs > min_diff]
assert len(onsets) == len(events)
diffs = 1000. * (events[:, 0... | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
We mark a set of bad channels that seem noisier than others. This can alsobe done interactively with ``raw.plot`` by clicking the channel name(or the line). The marked channels are added as bad when the browser windowis closed. | raw.info['bads'] = ['MLO52-4408', 'MRT51-4408', 'MLO42-4408', 'MLO43-4408'] | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
The epochs (trials) are created for MEG channels. First we find the picksfor MEG and EOG channels. Then the epochs are constructed using these picks.The epochs overlapping with annotated bad segments are also rejected bydefault. To turn off rejection by bad segments (as was done earlier withsaccades) you can use keywor... | picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,
exclude='bads')
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), reject=reject, preload=False,
proj=True) | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
We only use first 40 good epochs from each run. Since we first drop the badepochs, the indices of the epochs are no longer same as in the originalepochs collection. Investigation of the event timings reveals that firstepoch from the second run corresponds to index 182. | epochs.drop_bad()
epochs_standard = mne.concatenate_epochs([epochs['standard'][range(40)],
epochs['standard'][182:222]])
epochs_standard.load_data() # Resampling to save memory.
epochs_standard.resample(600, npad='auto')
epochs_deviant = epochs['deviant'].load_data()
epochs_de... | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
The averages for each conditions are computed. | evoked_std = epochs_standard.average()
evoked_dev = epochs_deviant.average()
del epochs_standard, epochs_deviant | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Typical preprocessing step is the removal of power line artifact (50 Hz or60 Hz). Here we lowpass filter the data at 40 Hz, which will remove allline artifacts (and high frequency information). Normally this would be doneto raw data (with :func:`mne.io.Raw.filter`), but to reduce memoryconsumption of this tutorial, we ... | for evoked in (evoked_std, evoked_dev):
evoked.filter(l_freq=None, h_freq=40., fir_design='firwin') | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Here we plot the ERF of standard and deviant conditions. In both conditionswe can see the P50 and N100 responses. The mismatch negativity is visibleonly in the deviant condition around 100-200 ms. P200 is also visible around170 ms in both conditions but much stronger in the standard condition. P300is visible in deviant... | evoked_std.plot(window_title='Standard', gfp=True, time_unit='s')
evoked_dev.plot(window_title='Deviant', gfp=True, time_unit='s') | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Show activations as topography figures. | times = np.arange(0.05, 0.301, 0.025)
evoked_std.plot_topomap(times=times, title='Standard', time_unit='s')
evoked_dev.plot_topomap(times=times, title='Deviant', time_unit='s') | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
We can see the MMN effect more clearly by looking at the difference betweenthe two conditions. P50 and N100 are no longer visible, but MMN/P200 andP300 are emphasised. | evoked_difference = combine_evoked([evoked_dev, -evoked_std], weights='equal')
evoked_difference.plot(window_title='Difference', gfp=True, time_unit='s') | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Source estimation.We compute the noise covariance matrix from the empty room measurementand use it for the other runs. | reject = dict(mag=4e-12)
cov = mne.compute_raw_covariance(raw_erm, reject=reject)
cov.plot(raw_erm.info)
del raw_erm | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
The transformation is read from a file. More information about coregisteringthe data, see `ch_interactive_analysis` or:func:`mne.gui.coregistration`. | trans_fname = op.join(data_path, 'MEG', 'bst_auditory',
'bst_auditory-trans.fif')
trans = mne.read_trans(trans_fname) | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
To save time and memory, the forward solution is read from a file. Set``use_precomputed=False`` in the beginning of this script to build theforward solution from scratch. The head surfaces for constructing a BEMsolution are read from a file. Since the data only contains MEG channels, weonly need the inner skull surface... | if use_precomputed:
fwd_fname = op.join(data_path, 'MEG', 'bst_auditory',
'bst_auditory-meg-oct-6-fwd.fif')
fwd = mne.read_forward_solution(fwd_fname)
else:
src = mne.setup_source_space(subject, spacing='ico4',
subjects_dir=subjects_dir, overwrite=Tru... | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
The sources are computed using dSPM method and plotted on an inflated brainsurface. For interactive controls over the image, use keyword``time_viewer=True``.Standard condition. | stc_standard = mne.minimum_norm.apply_inverse(evoked_std, inv, lambda2, 'dSPM')
brain = stc_standard.plot(subjects_dir=subjects_dir, subject=subject,
surface='inflated', time_viewer=False, hemi='lh',
initial_time=0.1, time_unit='s')
del stc_standard, brain | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Deviant condition. | stc_deviant = mne.minimum_norm.apply_inverse(evoked_dev, inv, lambda2, 'dSPM')
brain = stc_deviant.plot(subjects_dir=subjects_dir, subject=subject,
surface='inflated', time_viewer=False, hemi='lh',
initial_time=0.1, time_unit='s')
del stc_deviant, brain | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Difference. | stc_difference = apply_inverse(evoked_difference, inv, lambda2, 'dSPM')
brain = stc_difference.plot(subjects_dir=subjects_dir, subject=subject,
surface='inflated', time_viewer=False, hemi='lh',
initial_time=0.15, time_unit='s') | _____no_output_____ | BSD-3-Clause | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io |
Lazy execution Here we discuss some of the concepts behind dask, and lazy execution of code. You do not need to go through this material if you are eager to get on with the tutorial, but it may help understand the concepts underlying dask, how these things fit in with techniques you might already be using, and how to... | from dask import delayed
@delayed
def inc(x):
return x + 1
@delayed
def add(x, y):
return x + y | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
Here we have used the delayed annotation to show that we want these functions to operate lazily — to save the set of inputs and execute only on demand. `dask.delayed` is also a function which can do this, without the annotation, leaving the original function unchanged, e.g.,```python delayed_inc = delayed(inc)``` | # this looks like ordinary code
x = inc(15)
y = inc(30)
total = add(x, y)
# incx, incy and total are all delayed objects.
# They contain a prescription of how to execute | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
Calling a delayed function created a delayed object (`incx, incy, total`) - examine these interactively. Making these objects is somewhat equivalent to constructs like the `lambda` or function wrappers (see below). Each holds a simple dictionary describing the task graph, a full specification of how to carry out the co... | total.visualize() | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
But so far, no functions have actually been executed. This demonstrated the division between the graph-creation part of Dask (`delayed()`, in this example) and the graph execution part of Dask.To run the "graph" in the visualization, and actually get a result, do: | # execute all tasks
total.compute() | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
**Why should you care about this?**By building a specification of the calculation we want to carry out before executing anything, we can pass the specification to an *execution engine* for evaluation. In the case of Dask, this execution engine could be running on many nodes of a cluster, so you have access to the full ... | %run prep.py -d accounts
import pandas as pd
import os
filenames = [os.path.join('data', 'accounts.%d.csv' % i) for i in [0, 1, 2]]
filenames
%%time
# normal, sequential code
a = pd.read_csv(filenames[0])
b = pd.read_csv(filenames[1])
c = pd.read_csv(filenames[2])
na = len(a)
nb = len(b)
nc = len(c)
total = sum([na,... | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
Your task is to recreate this graph again using the delayed function on the original Python code. The three functions you want to delay are `pd.read_csv`, `len` and `sum`.. ```pythondelayed_read_csv = delayed(pd.read_csv)a = delayed_read_csv(filenames[0])...total = ... execute%time total.compute() ``` | # your verbose code here | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
Next, repeat this using loops, rather than writing out all the variables. | # your concise code here
## verbose version
delayed_read_csv = delayed(pd.read_csv)
a = delayed_read_csv(filenames[0])
b = delayed_read_csv(filenames[1])
c = delayed_read_csv(filenames[2])
delayed_len = delayed(len)
na = delayed_len(a)
nb = delayed_len(b)
nc = delayed_len(c)
delayed_sum = delayed(sum)
total = delaye... | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
**Notes**Delayed objects support various operations:```python x2 = x + 1``` if `x` was a delayed result (like `total`, above), then so is `x2`. Supported operations include arithmetic operators, item or slice selection, attribute access and method calls - essentially anything that could be phrased as a `lambda` expr... | import re
splitter = re.compile('\w+')
with open('README.md', 'r') as f:
data = f.read()
result = len(splitter.findall(data))
result | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
The trouble with this approach is that it does not scale - if the file is very large, it, and the generated list of words, might fill up memory. We can easily avoid that, because we only need a simple sum, and each line is totally independent of the others. Now we evaluate each piece of data and immediately free up the... | result = 0
with open('README.md', 'r') as f:
for line in f:
result += len(splitter.findall(line))
result | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
Example 2: background execution There are many tasks that take a while to complete, but don't actually require much of the CPU, for example anything that requires communication over a network, or input from a user. In typical sequential programming, execution would need to halt while the process completes, and then co... | # Edit sources.py to configure source locations
import sources
sources.lazy_url
import threading
import queue
import urllib
def get_webdata(url, q):
u = urllib.request.urlopen(url)
# raise ValueError
q.put(u.read())
q = queue.Queue()
t = threading.Thread(target=get_webdata, args=(sources.lazy_url, q))
t.s... | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
Consider: what would you see if there had been an exception within the `get_webdata` function? You could uncomment the `raise` line, above, and re-execute the two cells. What happens? Is there any way to debug the execution to find the root cause of the error? Example 3: delayed execution There are many ways in Python... | def add(x, y):
return x + y
# Sometimes we defer computations with strings
x = 15
y = 30
z = "add(x, y)"
eval(z)
# we can use lambda or other "closure"
x = 15
y = 30
z = lambda: add(x, y)
z()
# A very similar thing happens in functools.partial
import functools
z = functools.partial(add, x, y)
z()
# Python generat... | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
Dask graphs Any Dask object, such as `total`, above, has an attribute which describes the calculations necessary to produce that result. Indeed, this is exactly the graph that we have been talking about, which can be visualized. We see that it is a simple dictionary, the keys are unique task identifiers, and the value... | total.dask
dict(total.dask) | _____no_output_____ | BSD-3-Clause | 01x_lazy.ipynb | fbidu/dask-tutorial |
Setup | # Dependencies
import pandas as pd
from splinter import Browser
from bs4 import BeautifulSoup
from webdriver_manager.chrome import ChromeDriverManager
import requests | _____no_output_____ | ADSL | Mission_to_Mars/mission_to_mars.ipynb | ahowellgates/web-scraping-challenge |
Webscraping Nasa Mars News | # Setup splinter
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=False)
# URL of page to be scraped
url = 'https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_s... | _____no_output_____ | ADSL | Mission_to_Mars/mission_to_mars.ipynb | ahowellgates/web-scraping-challenge |
Mars Image | # Setup splinter
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=False)
# URL of page to be scraped
url = 'https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/index.html'
browser.visit(url)
# Create BeautifulSoup object; parse with 'html... | _____no_output_____ | ADSL | Mission_to_Mars/mission_to_mars.ipynb | ahowellgates/web-scraping-challenge |
Mars Facts |
# Setup splinter
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=False)
# URL of page to be scraped
url = 'https://space-facts.com/mars/'
browser.visit(url)
# Create BeautifulSoup object; parse with 'html.parser'
html = browser.html
soup = ... | _____no_output_____ | ADSL | Mission_to_Mars/mission_to_mars.ipynb | ahowellgates/web-scraping-challenge |
Mars Hemispheres |
# Setup splinter
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=False)
# URL of page to be scraped
url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
browser.visit(url)
# Create BeautifulSoup objec... | _____no_output_____ | ADSL | Mission_to_Mars/mission_to_mars.ipynb | ahowellgates/web-scraping-challenge |
Project 3: Implement SLAM --- Project OverviewIn this project, you'll implement SLAM for robot that moves and senses in a 2 dimensional, grid world!SLAM gives us a way to both localize a robot and build up a map of its environment as a robot moves and senses in real-time. This is an active area of research in the fie... | import numpy as np
from helpers import make_data
# your implementation of slam should work with the following inputs
# feel free to change these input values and see how it responds!
# world parameters
num_landmarks = 5 # number of landmarks
N = 20 # time steps
world_size = ... |
Landmarks: [[34, 47], [75, 78], [61, 26], [22, 23], [18, 28]]
Robot: [x=4.99479 y=14.12768]
| MIT | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree |
A note on `make_data`The function above, `make_data`, takes in so many world and robot motion/sensor parameters because it is responsible for:1. Instantiating a robot (using the robot class)2. Creating a grid world with landmarks in it**This function also prints out the true location of landmarks and the *final* robot... | # print out some stats about the data
time_step = 0
print('Example measurements: \n', data[time_step][0])
print('\n')
print('Example motion: \n', data[time_step][1]) | Example measurements:
[(0, -15.805152385054228, -1.6297997068679546), (1, 24.73944299319771, 27.886589594025597), (2, 11.24343039872742, -23.753067256378262), (3, -29.045748066570592, -26.05459794794534), (4, -33.78771405750095, -23.207245892649965)]
Example motion:
[-19.96316170483412, -1.213332084239246]
| MIT | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree |
Try changing the value of `time_step`, you should see that the list of measurements varies based on what in the world the robot sees after it moves. As you know from the first notebook, the robot can only sense so far and with a certain amount of accuracy in the measure of distance between its location and the location... | def initialize_constraints(N, num_landmarks, world_size):
''' This function takes in a number of time steps N, number of landmarks, and a world_size,
and returns initialized constraint matrices, omega and xi.'''
## Recommended: Define and store the size (rows/cols) of the constraint matrix in a var... | _____no_output_____ | MIT | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree |
Test as you goIt's good practice to test out your code, as you go. Since `slam` relies on creating and updating constraint matrices, `omega` and `xi` to account for robot sensor measurements and motion, let's check that they initialize as expected for any given parameters.Below, you'll find some test code that allows ... | # import data viz resources
import matplotlib.pyplot as plt
from pandas import DataFrame
import seaborn as sns
%matplotlib inline
# define a small N and world_size (small for ease of visualization)
N_test = 5
num_landmarks_test = 2
small_world = 10
# initialize the constraints
initial_omega, initial_xi = initialize_co... | _____no_output_____ | MIT | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree |
--- SLAM inputs In addition to `data`, your slam function will also take in:* N - The number of time steps that a robot will be moving and sensing* num_landmarks - The number of landmarks in the world* world_size - The size (w/h) of your world* motion_noise - The noise associated with motion; the update confidence fo... | ## TODO: Complete the code to implement SLAM
## slam takes in 6 arguments and returns mu,
## mu is the entire path traversed by a robot (all x,y poses) *and* all landmarks locations
def slam(data, N, num_landmarks, world_size, motion_noise, measurement_noise):
omega, xi = initialize_constraints(N, num_landma... | _____no_output_____ | MIT | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree |
Helper functionsTo check that your implementation of SLAM works for various inputs, we have provided two helper functions that will help display the estimated pose and landmark locations that your function has produced. First, given a result `mu` and number of time steps, `N`, we define a function that extracts the po... | # a helper function that creates a list of poses and of landmarks for ease of printing
# this only works for the suggested constraint architecture of interlaced x,y poses
def get_poses_landmarks(mu, N):
# create a list of poses
poses = []
for i in range(N):
poses.append((mu[2*i].item(), mu[2*i+1].it... | _____no_output_____ | MIT | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree |
Run SLAMOnce you've completed your implementation of `slam`, see what `mu` it returns for different world sizes and different landmarks! What to ExpectThe `data` that is generated is random, but you did specify the number, `N`, or time steps that the robot was expected to move and the `num_landmarks` in the world (whi... | # call your implementation of slam, passing in the necessary parameters
mu = slam(data, N, num_landmarks, world_size, motion_noise, measurement_noise)
# print out the resulting landmarks and poses
if(mu is not None):
# get the lists of poses and landmarks
# and print them out
poses, landmarks = get_poses_l... |
Estimated Poses:
[50.000, 50.000]
[28.772, 50.255]
[9.040, 48.680]
[19.858, 30.140]
[32.972, 12.416]
[54.058, 17.762]
[73.279, 23.062]
[92.841, 26.185]
[74.158, 29.875]
[53.182, 33.724]
[33.776, 36.440]
[13.402, 41.439]
[1.908, 58.052]
[17.273, 45.079]
[33.424, 32.976]
[49.007, 21.488]
[64.699, 8.518]
[45.340, 9.972]... | MIT | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree |
Visualize the constructed worldFinally, using the `display_world` code from the `helpers.py` file (which was also used in the first notebook), we can actually visualize what you have coded with `slam`: the final position of the robot and the positon of landmarks, created from only motion and measurement data!**Note th... | # import the helper function
from helpers import display_world
# Display the final world!
# define figure size
plt.rcParams["figure.figsize"] = (20,20)
# check if poses has been created
if 'poses' in locals():
# print out the last pose
print('Last pose: ', poses[-1])
# display the last position of the ro... | Last pose: (5.954003287856551, 12.454091677416208)
| MIT | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree |
Question: How far away is your final pose (as estimated by `slam`) compared to the *true* final pose? Why do you think these poses are different?You can find the true value of the final pose in one of the first cells where `make_data` was called. You may also want to look at the true landmark locations and compare the... | # Here is the data and estimated outputs for test case 1
test_data1 = [[[[1, 19.457599255548065, 23.8387362100849], [2, -13.195807561967236, 11.708840328458608], [3, -30.0954905279171, 15.387879242505843]], [-12.2607279422326, -15.801093326936487]], [[[2, -0.4659930049620491, 28.088559771215664], [4, -17.8663823748909... |
Estimated Poses:
[50.000, 50.000]
[69.181, 45.665]
[87.743, 39.703]
[76.270, 56.311]
[64.317, 72.176]
[52.257, 88.154]
[44.059, 69.401]
[37.002, 49.918]
[30.924, 30.955]
[23.508, 11.419]
[34.180, 27.133]
[44.155, 43.846]
[54.806, 60.920]
[65.698, 78.546]
[77.468, 95.626]
[96.802, 98.821]
[75.957, 99.971]
[70.200, 81.... | MIT | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree |
# Python ≥3.5 is required
import sys
# Scikit-Learn ≥0.20 is required
import sklearn
# Common imports
import numpy as np
import os
# To plot pretty figures
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('axes', labelsize=14)
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=... | _____no_output_____ | MIT | Assignments/DSCI_633_Assn_3.ipynb | niranjana1997/RIT-DSCI-633-FDS | |
Bilayer Sonophore model: pre-computation of intermolecular pressureProfiled simulations of the mechanical model in isolation reveal that the spatial integration of intermolecular pressure $P_M$ is by far the longest internal computation at each iteration. Hence, we seek to decrease its computational cost.Luckily, desp... | import logging
import time
import numpy as np
import matplotlib.pyplot as plt
from PySONIC.utils import logger, rmse, rsquared
from PySONIC.neurons import getPointNeuron
from PySONIC.core import BilayerSonophore, PmCompMethod, AcousticDrive
from PySONIC.constants import *
# Set logging level
logger.setLevel(logging.I... | _____no_output_____ | MIT | notebooks/BLS model/BLS model - intermolecular pressure.ipynb | scbao/pysonic |
Functions | def plotPmavg(bls, Z, fs=15):
fig, ax = plt.subplots(figsize=(5, 3))
for skey in ['right', 'top']:
ax.spines[skey].set_visible(False)
ax.set_xlabel('Z (nm)', fontsize=fs)
ax.set_ylabel('Pressure (kPa)', fontsize=fs)
ax.set_xticks([0, bls.a * 1e9])
ax.set_xticklabels(['0', 'a'])
ax.se... | _____no_output_____ | MIT | notebooks/BLS model/BLS model - intermolecular pressure.ipynb | scbao/pysonic |
Parameters | pneuron = getPointNeuron('RS')
bls = BilayerSonophore(32e-9, pneuron.Cm0, pneuron.Qm0)
US_source = AcousticDrive(500e3, 100e3)
Qm = pneuron.Qm0 | _____no_output_____ | MIT | notebooks/BLS model/BLS model - intermolecular pressure.ipynb | scbao/pysonic |
Profiles comparison over deflection range | Z = np.linspace(-0.4 * bls.Delta_, bls.a, 1000)
fig = plotPmavg(bls, Z) | _____no_output_____ | MIT | notebooks/BLS model/BLS model - intermolecular pressure.ipynb | scbao/pysonic |
Error quantification over a typical acoustic cycle | fig, Z1, Z2, tcomp_ratio = plotZprofiles(bls, US_source, Qm)
error_Z = rmse(Z1, Z2)
r2_Z = rsquared(Z1, Z2)
err_pct = error_Z / (Z1.max() - Z1.min()) * 1e2
print(f'Z-error: R2 = {r2_Z:.4f}, RMSE = {error_Z:.4f} nm ({err_pct:.4f}% dZ)')
print(f'computational boost: {tcomp_ratio:.1f}-fold') | 30/01/2020 17:15:24: BilayerSonophore(32.0 nm): simulation @ f = 500.00 kHz, A = 100.00 kPa, Q = -71.90 nC/cm2
| MIT | notebooks/BLS model/BLS model - intermolecular pressure.ipynb | scbao/pysonic |
--- BigDL-Nano Resnet example on CIFAR10 dataset---This example illustrates how to apply bigdl-nano optimizations on a image recognition case based on pytorch-lightning framework. The basic image recognition module is implemented with Lightning and trained on [CIFAR10](https://www.cs.toronto.edu/~kriz/cifar.html) image... | from time import time
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from pl_bolts.datamodules import CIFAR10DataModule
from pl_bolts.transforms.dataset_normalizations import cifar10_normalization
from pytorch_lightning import LightningModule, seed_everything
from pytor... | _____no_output_____ | Apache-2.0 | python/nano/notebooks/pytorch/cifar10/nano-trainer-example.ipynb | Forest216/BigDL |
CIFAR10 Data Module---Import the existing data module from bolts and modify the train and test transforms.You could access [CIFAR10](https://www.cs.toronto.edu/~kriz/cifar.html) for a view of the whole dataset. | def prepare_data(data_path, batch_size, num_workers):
train_transforms = transforms.Compose(
[
transforms.RandomCrop(32, 4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
cifar10_normalization()
]
)
test_transforms = transforms.Com... | _____no_output_____ | Apache-2.0 | python/nano/notebooks/pytorch/cifar10/nano-trainer-example.ipynb | Forest216/BigDL |
Resnet---Modify the pre-existing Resnet architecture from TorchVision. The pre-existing architecture is based on ImageNet images (224x224) as input. So we need to modify it for CIFAR10 images (32x32). | def create_model():
model = torchvision.models.resnet18(pretrained=False, num_classes=10)
model.conv1 = nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
model.maxpool = nn.Identity()
return model | _____no_output_____ | Apache-2.0 | python/nano/notebooks/pytorch/cifar10/nano-trainer-example.ipynb | Forest216/BigDL |
Lightning Module---Check out the [configure_optimizers](https://pytorch-lightning.readthedocs.io/en/stable/common/lightning_module.htmlconfigure-optimizers) method to use custom Learning Rate schedulers. The OneCycleLR with SGD will get you to around 92-93% accuracy in 20-30 epochs and 93-94% accuracy in 40-50 epochs.... | class LitResnet(LightningModule):
def __init__(self, learning_rate=0.05, steps_per_epoch=45000 , batch_size=32):
super().__init__()
self.save_hyperparameters()
self.model = create_model()
def forward(self, x):
out = self.model(x)
return F.log_softmax(out, dim=1)
de... | Global seed set to 7
| Apache-2.0 | python/nano/notebooks/pytorch/cifar10/nano-trainer-example.ipynb | Forest216/BigDL |
TrainUse Trainer from bigdl.nano.pytorch.trainer for BigDL-Nano pytorch.This Trainer extends PyTorch Lightning Trainer by adding various options to accelerate pytorch training.``` :param num_processes: number of processes in distributed training. default: 4. :param use_ipex: whether we use ipex as accelerator fo... | model = LitResnet(learning_rate=0.05)
model.datamodule = data_module
checkpoint_callback = ModelCheckpoint(dirpath="checkpoints/", save_top_k=1, monitor="val_loss", filename="renet18_single_none")
basic_trainer = Trainer(num_processes = 1,
use_ipex = False,
progress_bar_refresh_rate=... | GPU available: False, used: False
TPU available: False, using: 0 TPU cores
IPU available: False, using: 0 IPUs
| Apache-2.0 | python/nano/notebooks/pytorch/cifar10/nano-trainer-example.ipynb | Forest216/BigDL |
Single Process with IPEX--- | model = LitResnet(learning_rate=0.05)
model.datamodule = data_module
checkpoint_callback = ModelCheckpoint(dirpath="checkpoints/", save_top_k=1, monitor="val_loss", filename="renet18_single_ipex", save_weights_only=True)
single_ipex_trainer = Trainer(num_processes=1,
use_ipex = True,
... | /home/mingzhi/anaconda3/envs/nanoWithPytorch/lib/python3.7/site-packages/pytorch_lightning/callbacks/model_checkpoint.py:446: UserWarning: Checkpoint directory checkpoints/ exists and is not empty.
rank_zero_warn(f"Checkpoint directory {dirpath} exists and is not empty.")
GPU available: False, used: False
TPU availab... | Apache-2.0 | python/nano/notebooks/pytorch/cifar10/nano-trainer-example.ipynb | Forest216/BigDL |
Multiple Processes with IPEX--- | model = LitResnet(learning_rate=0.1, batch_size=64)
model.datamodule = data_module
checkpoint_callback = ModelCheckpoint(dirpath="checkpoints/", save_top_k=1, monitor="val_loss", filename="renet18_multi_ipex", save_weights_only=True)
multi_ipex_trainer = Trainer(num_processes=2,
use_ipex=True,
... |
| Precision | Fit Time(s) | Accuracy(%) |
| Basic | 4559.45 | 90.29 |
| Single With Ipex | 4380.92 | 89.94 |
| Multiple With Ipex| 2633.85 | 89.18 |
| Apache-2.0 | python/nano/notebooks/pytorch/cifar10/nano-trainer-example.ipynb | Forest216/BigDL |
Apply CNN Classifier to DESI Spectra and visualize results with gradCAMMini-SV2 tiles from February-March 2020:- https://desi.lbl.gov/trac/wiki/TargetSelectionWG/miniSV2See also the DESI tile picker with (limited) SV0 tiles from March 2020:- https://desi.lbl.gov/svn/data/tiles/trunk/- https://desi.lbl.gov/svn/data/til... | import sys
sys.path.append('/global/homes/p/palmese/desi/timedomain/desitrip/py/') #Note:change this path as needed!
sys.path.append('/global/homes/p/palmese/desi/timedomain/timedomain/')
from desispec.io import read_spectra, write_spectra
from desispec.spectra import Spectra
from desispec.coaddition import coadd_came... | _____no_output_____ | MIT | cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb | divijsharma18/timedomain |
Select a Date & Tile from matches files |
matches_filename='matches_DECam.npy'
file_arr=np.load('matches_DECam.npy', allow_pickle=True)
obsdates = file_arr[:,0]
tile_ids = file_arr[:,1]
petal_ids = file_arr[:,2]
target_ids = file_arr[:,3]
tamuids = file_arr[:,6]
# Access redux folder.
zbfiles = []
cafiles = []
redux='/global/project/projectdirs/desi/spec... | 585
585
585
585
585
| MIT | cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb | divijsharma18/timedomain |
Load the Keras ModelLoad a model trained on real or simulated data using the native Keras output format. In the future this could be updated to just load the Keras weights. | tfmodel = '/global/homes/l/lehsani/timedomain/desitrip/docs/nb/models_9label_first/6_b65_e200_9label/b65_e200_9label_model'
#tfmodel = '/global/homes/s/sybenzvi/desi/timedomain/desitrip/docs/nb/6label_cnn_restframe'
if os.path.exists(tfmodel):
classifier = keras.models.load_model(tfmodel)
else:
classifier = Non... | Model: "SNnet"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
Input_Spec (InputLayer) [(None, 150, 1)] 0
_________________________________________... | MIT | cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb | divijsharma18/timedomain |
Loop Through Spectra and Classify | # Loop through zbest and coadd files for each petal.
# Extract the fibermaps, ZBEST tables, and spectra.
# Keep only BGS targets passing basic event selection.
allzbest = None
allfmap = None
allwave = None
allflux = None
allivar = None
allmask = None
allres = None
handy_table = []
color_string = 'brz'
count = 0
for ... | _____no_output_____ | MIT | cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb | divijsharma18/timedomain |
Selection on Classifier OutputTo be conservative we can select only spectra where the classifier is very confident in its output, e.g., ymax > 0.99. See the [CNN training notebook](https://github.com/desihub/timedomain/blob/master/desitrip/docs/nb/cnn_multilabel-restframe.ipynb) for the motivation behind this cut. | idx = np.argwhere(ymax > 0.0) #0.99
labels = np.argmax(pred, axis=1)
idx.shape
label_names = ['Galaxy',
'SN Ia',
'SN Ib',
'SN Ib/c',
'SN Ic',
'SN IIn',
'SN IIL/P',
'SN IIP',
'KN'] | _____no_output_____ | MIT | cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb | divijsharma18/timedomain |
Save spectra and classification to file | # Save classification info to a table.
classification = Table()
classification['TARGETID'] = allfmap[idx]['TARGETID']
classification['CNNPRED'] = pred[idx]
classification['CNNLABEL'] = label_names_arr[labels[idx]]
# Merge the classification and redrock fit to the fibermap.
#Temporary fix for candidate mismatch
fmap = ... | 6
| MIT | cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb | divijsharma18/timedomain |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.