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 |
|---|---|---|---|---|---|
Now lets construct a more complicated loop to do what we want First we do some things we don't need to do in the loop. Let's reload our atlas, and re-initiate our masker and correlation_measure | from nilearn.input_data import NiftiLabelsMasker
from nilearn.connectome import ConnectivityMeasure
from nilearn import datasets
# load atlas
multiscale = datasets.fetch_atlas_basc_multiscale_2015()
atlas_filename = multiscale.scale064
# initialize masker (change verbosity)
masker = NiftiLabelsMasker(labels_img=atlas... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Okay -- now that we have that taken care of, let's run our big loop! **NOTE**: On a laptop, this might a few minutes. | all_features = [] # here is where we will put the data (a container)
for i,sub in enumerate(data):
# extract the timeseries from the ROIs in the atlas
time_series = masker.fit_transform(sub, confounds=confounds[i])
# create a region x region correlation matrix
correlation_matrix = correlation_measure.f... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
In case you do not want to run the full loop on your computer, you can load the output of the loop here! | feat_file = 'MAIN_BASC064_subsamp_features.npz'
X_features = np.load(feat_file)['a']
X_features.shape | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Okay so we've got our features. We can visualize our feature matrix | import matplotlib.pyplot as plt
plt.imshow(X_features, aspect='auto')
plt.colorbar()
plt.title('feature matrix')
plt.xlabel('features')
plt.ylabel('subjects') | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Get Y (our target) and assess its distribution | # Let's load the phenotype data
pheno_path = os.path.join(wdir, 'participants.tsv')
import pandas
pheno = pandas.read_csv(pheno_path, sep='\t').sort_values('participant_id')
pheno.head() | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Looks like there is a column labeling age. Let's capture it in a variable | y_age = pheno['Age'] | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Maybe we should have a look at the distribution of our target variable | import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot(y_age) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Prepare data for machine learningHere, we will define a "training sample" where we can play around with our models. We will also set aside a "validation" sample that we will not touch until the end We want to be sure that our training and test sample are matched! We can do that with a "stratified split". This dataset ... | age_class = pheno['AgeGroup']
age_class.value_counts()
from sklearn.model_selection import train_test_split
# Split the sample to training/validation with a 60/40 ratio, and
# stratify by age class, and also shuffle the data.
X_train, X_val, y_train, y_val = train_test_split(
... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Let's visualize the distributions to be sure they are matched | sns.distplot(y_train)
sns.distplot(y_val) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Run your first model!Machine learning can get pretty fancy pretty quickly. We'll start with a fairly standard regression model called a Support Vector Regressor (SVR). While this may seem unambitious, simple models can be very robust. And we probably don't have enough data to create more complex models (but we can try... | from sklearn.svm import SVR
l_svr = SVR(kernel='linear') # define the model
l_svr.fit(X_train, y_train) # fit the model | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Well... that was easy. Let's see how well the model learned the data! |
# predict the training data based on the model
y_pred = l_svr.predict(X_train)
# caluclate the model accuracy
acc = l_svr.score(X_train, y_train)
| _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Let's view our results and plot them all at once! | # print results
print('accuracy (R2)', acc)
sns.regplot(y_pred,y_train)
plt.xlabel('Predicted Age') | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
HOLY COW! Machine learning is amazing!!! Almost a perfect fit!...which means there's something wrong. What's the problem here? | from sklearn.model_selection import train_test_split
# Split the sample to training/test with a 75/25 ratio, and
# stratify by age class, and also shuffle the data.
age_class2 = pheno.loc[y_train.index,'AgeGroup']
X_train2, X_test, y_train2, y_test = train_test_split(
... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Not perfect, but as predicting with unseen data goes, not too bad! Especially with a training sample of "only" 69 subjects. But we can do better! For example, we can increase the size our training set while simultaneously reducing bias by instead using 10-fold cross-validation | from sklearn.model_selection import cross_val_predict, cross_val_score
# predict
y_pred = cross_val_predict(l_svr, X_train, y_train, cv=10)
# scores
acc = cross_val_score(l_svr, X_train, y_train, cv=10)
mae = cross_val_score(l_svr, X_train, y_train, cv=10, scoring='neg_mean_absolute_error') | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
We can look at the accuracy of the predictions for each fold of the cross-validation | for i in range(10):
print('Fold {} -- Acc = {}, MAE = {}'.format(i, acc[i],-mae[i])) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
We can also look at the overall accuracy of the model | from sklearn.metrics import r2_score
overall_acc = r2_score(y_train, y_pred)
overall_mae = mean_absolute_error(y_train,y_pred)
print('R2:',overall_acc)
print('MAE:',overall_mae)
sns.regplot(y_pred, y_train)
plt.xlabel('Predicted Age') | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Not too bad at all! But more importantly, this is a more accurate estimation of our model's predictive efficacy. Our sample size is larger and this is based on several rounds of prediction of unseen data. For example, we can now see that the effect is being driven by the model's successful parsing of adults vs. childre... | # Create a log transformer function and log transform Y (age)
from sklearn.preprocessing import FunctionTransformer
log_transformer = FunctionTransformer(func = np.log, validate=True)
log_transformer.fit(y_train.values.reshape(-1,1))
y_train_log = log_transformer.transform(y_train.values.reshape(-1,1))[:,0]
sns.dist... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Now let's go ahead and cross-validate our model once again with this new log-transformed target | # predict
y_pred = cross_val_predict(l_svr, X_train, y_train_log, cv=10)
# scores
acc = r2_score(y_train_log, y_pred)
mae = mean_absolute_error(y_train_log,y_pred)
print('R2:',acc)
print('MAE:',mae)
sns.regplot(y_pred, y_train_log)
plt.xlabel('Predicted Log Age')
plt.ylabel('Log Age') | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Seems like a definite improvement, right? I think we can agree on that. But we can't forget about interpretability? The MAE is much less interpretable now. Tweak the hyperparametersMany machine learning algorithms have hyperparameters that can be "tuned" to optimize model fitting. Careful parameter tuning can really i... | SVR? | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
One way is to plot a "Validation Curve" -- this will let us view changes in training and validation accuracy of a model as we shift its hyperparameters. We can do this easily with sklearn. | from sklearn.model_selection import validation_curve
C_range = 10. ** np.arange(-3, 8) # A range of different values for C
train_scores, valid_scores = validation_curve(l_svr, X_train, y_train_log,
param_name= "C",
param_rang... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
It looks like accuracy is better for higher values of C, and plateaus somewhere between 0.1 and 1. The default setting is C=1, so it looks like we can't really improve by changing C. But our SVR model actually has two hyperparameters, C and epsilon. Perhaps there is an optimal combination of settings for these two para... | from sklearn.model_selection import GridSearchCV
C_range = 10. ** np.arange(-3, 8)
epsilon_range = 10. ** np.arange(-3, 8)
param_grid = dict(epsilon=epsilon_range, C=C_range)
grid = GridSearchCV(l_svr, param_grid=param_grid, cv=10)
grid.fit(X_train, y_train_log) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Now that the grid search has completed, let's find out what was the "best" parameter combination | print(grid.best_params_) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
And if redo our cross-validation with this parameter set? | y_pred = cross_val_predict(SVR(kernel='linear',C=0.10,epsilon=0.10, gamma='auto'),
X_train, y_train_log, cv=10)
# scores
acc = r2_score(y_train_log, y_pred)
mae = mean_absolute_error(y_train_log,y_pred)
print('R2:',acc)
print('MAE:',mae)
sns.regplot(y_pred, y_train_log)
plt.xlabel('Predic... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Perhaps unsurprisingly, the model fit is actually exactly the same as what we had with our defaults. There's a reason they are defaults ;-)Grid search can be a powerful and useful tool. But can you think of a way that, if not properly utilized, it could lead to overfitting? You can find a nice set of tutorials with lin... | validation_curve?
from sklearn.model_selection import validation_curve
degree_range = list(range(1,8)) # A range of different values for C
train_scores, valid_scores = validation_curve(SVR(kernel='poly',
gamma='scale'
)... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
It appears that we cannot improve our model by increasing the complexity of the fit. If one looked only at the training data, one might surmise that a 2nd order fit could be a slightly better model. But that improvement does not generalize to the validation data. | # y_pred = cross_val_predict(SVR(kernel='rbf', gamma='scale'), X_train, y_train_log, cv=10)
# # scores
# acc = r2_score(y_train_log, y_pred)
# mae = mean_absolute_error(y_train_log,y_pred)
# print('R2:',acc)
# print('MAE:',mae)
# sns.regplot(y_pred, y_train_log)
# plt.xlabel('Predicted Log Age')
# plt.ylabel('Log Ag... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Feature selectionRight now, we have 2016 features. Are all of those really going to contribute to the model stably? Intuitively, models tend to perform better when there are fewer, more important features than when there are many, less imortant features. The tough part is figuring out which features are useful or impo... | from sklearn.feature_selection import SelectPercentile, f_regression
from sklearn.model_selection import KFold
from sklearn.pipeline import Pipeline
# Build a tiny pipeline that does feature selection (top 20% of features),
# and then prediction with our linear svr model.
model = Pipeline([
('feature_selection',S... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Alrighty, let's see if only using the top 20% of features improves the model at all... | acc = r2_score(y_train_log[y_index], y_pred)
mae = mean_absolute_error(y_train_log[y_index],y_pred)
print('R2:',acc)
print('MAE:',mae)
sns.regplot(np.array(y_pred), y_train_log[y_index])
plt.xlabel('Predicted Log Age')
plt.ylabel('Log Age')
| _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Nope, in fact it got a bit worse. It seems we're getting "value at the margins" so to speak. This is a very good example of how significance != prediction, as demonstrated in this figure from Bzdok et al., 2018 *bioRxiv*)[:,0] | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
And now for the moment of truth! No cross-validation needed here. We simply fit the model with the training data and use it to predict the testing dataI'm so nervous. Let's just do it all in one cell | l_svr.fit(X_train, y_train_log) # fit to training data
y_pred = l_svr.predict(X_val) # classify age class using testing data
acc = l_svr.score(X_val, y_val_log) # get accuracy (r2)
mae = mean_absolute_error(y_val_log, y_pred) # get mae
# print results
print('accuracy (r2) =', acc)
print('mae = ',mae)
# plot results
s... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
***Wow!!*** Congratulations. You just trained a machine learning model that used real rs-fmri data to predict the age of real humans.The proper thing to do at this point would be to repeat the train-validation split multiple times. This will ensure the results are not specific to this validation set, and will give you ... | # SPACE FOR YOUR ASSIGNMENT
| _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
So, it seems like something in this data does seem to be systematically related to age ... but what? Interpreting model feature importancesInterpreting the feature importances of a machine learning model is a real can of worms. This is an area of active research. Unfortunately, it's hard to trust the feature importa... | l_svr.coef_ | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
lets plot these weights to see their distribution better | plt.bar(range(l_svr.coef_.shape[-1]),l_svr.coef_[0])
plt.title('feature importances')
plt.xlabel('feature')
plt.ylabel('weight') | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Or perhaps it will be easier to visualize this information as a matrix similar to the one we started withWe can use the correlation measure from before to perform an inverse transform | correlation_measure.inverse_transform(l_svr.coef_).shape
from nilearn import plotting
feat_exp_matrix = correlation_measure.inverse_transform(l_svr.coef_)[0]
plotting.plot_matrix(feat_exp_matrix, figure=(10, 8),
labels=range(feat_exp_matrix.shape[0]),
reorder=False,
... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Let's see if we can throw those features onto an actual brain.First, we'll need to gather the coordinates of each ROI of our atlas | coords = plotting.find_parcellation_cut_coords(atlas_filename) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
And now we can use our feature matrix and the wonders of nilearn to create a connectome map where each node is an ROI, and each connection is weighted by the importance of the feature to the model | plotting.plot_connectome(feat_exp_matrix, coords, colorbar=True) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Whoa!! That's...a lot to process. Maybe let's threshold the edges so that only the most important connections are visualized | plotting.plot_connectome(feat_exp_matrix, coords, colorbar=True, edge_threshold=0.035) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
That's definitely an improvement, but it's still a bit hard to see what's going on.Nilearn has a new feature that let's use view this data interactively! | plotting.view_connectome(feat_exp_matrix, coords, threshold='98%') | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Iterators Often an important piece of data analysis is repeating a similar calculation, over and over, in an automated fashion.For example, you may have a table of a names that you'd like to split into first and last, or perhaps of dates that you'd like to convert to some standard format.One of Python's answers to th... | for i in range(10):
print(i, end=' ') | 0 1 2 3 4 5 6 7 8 9 | CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
Here we're going to dig a bit deeper.It turns out that in Python 3, ``range`` is not a list, but is something called an *iterator*, and learning how it works is key to understanding a wide class of very useful Python functionality. Iterating over listsIterators are perhaps most easily understood in the concrete case o... | for value in [2, 4, 6, 8, 10]:
# do some operation
print(value + 1, end=' ') | 3 5 7 9 11 | CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
The familiar "``for x in y``" syntax allows us to repeat some operation for each value in the list.The fact that the syntax of the code is so close to its English description ("*for [each] value in [the] list*") is just one of the syntactic choices that makes Python such an intuitive language to learn and use.But the f... | iter([2, 4, 6, 8, 10]) | _____no_output_____ | CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
It is this iterator object that provides the functionality required by the ``for`` loop.The ``iter`` object is a container that gives you access to the next object for as long as it's valid, which can be seen with the built-in function ``next``: | I = iter([2, 4, 6, 8, 10])
print(next(I))
print(next(I))
print(next(I)) | 6
| CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
What is the purpose of this level of indirection?Well, it turns out this is incredibly useful, because it allows Python to treat things as lists that are *not actually lists*. ``range()``: A List Is Not Always a ListPerhaps the most common example of this indirect iteration is the ``range()`` function in Python 3 (nam... | range(10) | _____no_output_____ | CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
``range``, like a list, exposes an iterator: | iter(range(10)) | _____no_output_____ | CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
So Python knows to treat it *as if* it's a list: | for i in range(10):
print(i, end=' ') | 0 1 2 3 4 5 6 7 8 9 | CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
The benefit of the iterator indirection is that *the full list is never explicitly created!*We can see this by doing a range calculation that would overwhelm our system memory if we actually instantiated it (note that in Python 2, ``range`` creates a list, so running the following will not lead to good things!): | N = 10 ** 12
for i in range(N):
if i >= 10: break
print(i, end=', ') | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, | CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
If ``range`` were to actually create that list of one trillion values, it would occupy tens of terabytes of machine memory: a waste, given the fact that we're ignoring all but the first 10 values!In fact, there's no reason that iterators ever have to end at all!Python's ``itertools`` library contains a ``count`` functi... | from itertools import count
for i in count():
if i >= 10:
break
print(i, end=', ') | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, | CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
Had we not thrown-in a loop break here, it would go on happily counting until the process is manually interrupted or killed (using, for example, ``ctrl-C``). Useful IteratorsThis iterator syntax is used nearly universally in Python built-in types as well as the more data science-specific objects we'll explore in later... | L = [2, 4, 6, 8, 10]
for i in range(len(L)):
print(i, L[i]) | 0 2
1 4
2 6
3 8
4 10
| CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
Although this does work, Python provides a cleaner syntax using the ``enumerate`` iterator: | for i, val in enumerate(L):
print(i, val) | 0 2
1 4
2 6
3 8
4 10
| CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
This is the more "Pythonic" way to enumerate the indices and values in a list. ``zip``Other times, you may have multiple lists that you want to iterate over simultaneously.You could certainly iterate over the index as in the non-Pythonic example we looked at previously, but it is better to use the ``zip`` iterator, wh... | L = [2, 4, 6, 8, 10]
R = [3, 6, 9, 12, 15]
for lval, rval in zip(L, R):
print(lval, rval) | 2 3
4 6
6 9
8 12
10 15
| CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
Any number of iterables can be zipped together, and if they are different lengths, the shortest will determine the length of the ``zip``. ``map`` and ``filter``The ``map`` iterator takes a function and applies it to the values in an iterator: | # find the first 10 square numbers
square = lambda x: x ** 2
for val in map(square, range(10)):
print(val, end=' ') | 0 1 4 9 16 25 36 49 64 81 | CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
The ``filter`` iterator looks similar, except it only passes-through values for which the filter function evaluates to True: | # find values up to 10 for which x % 2 is zero
is_even = lambda x: x % 2 == 0
for val in filter(is_even, range(10)):
print(val, end=' ') | 0 2 4 6 8 | CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
The ``map`` and ``filter`` functions, along with the ``reduce`` function (which lives in Python's ``functools`` module) are fundamental components of the *functional programming* style, which, while not a dominant programming style in the Python world, has its outspoken proponents (see, for example, the [pytoolz](https... | print(*range(10)) | 0 1 2 3 4 5 6 7 8 9
| CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
So, for example, we can get tricky and compress the ``map`` example from before into the following: | print(*map(lambda x: x ** 2, range(10))) | 0 1 4 9 16 25 36 49 64 81
| CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
Using this trick lets us answer the age-old question that comes up in Python learners' forums: why is there no ``unzip()`` function which does the opposite of ``zip()``?If you lock yourself in a dark closet and think about it for a while, you might realize that the opposite of ``zip()`` is... ``zip()``! The key is that... | L1 = (1, 2, 3, 4)
L2 = ('a', 'b', 'c', 'd')
z = zip(L1, L2)
print(*z)
z = zip(L1, L2)
new_L1, new_L2 = zip(*z)
print(new_L1, new_L2) | (1, 2, 3, 4) ('a', 'b', 'c', 'd')
| CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
Ponder this for a while. If you understand why it works, you'll have come a long way in understanding Python iterators! Specialized Iterators: ``itertools``We briefly looked at the infinite ``range`` iterator, ``itertools.count``.The ``itertools`` module contains a whole host of useful iterators; it's well worth your ... | from itertools import permutations
p = permutations(range(3))
print(*p) | (0, 1, 2) (0, 2, 1) (1, 0, 2) (1, 2, 0) (2, 0, 1) (2, 1, 0)
| CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
Similarly, the ``itertools.combinations`` function iterates over all unique combinations of ``N`` values within a list: | from itertools import combinations
c = combinations(range(4), 2)
print(*c) | (0, 1) (0, 2) (0, 3) (1, 2) (1, 3) (2, 3)
| CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
Somewhat related is the ``product`` iterator, which iterates over all sets of pairs between two or more iterables: | from itertools import product
p = product('ab', range(3))
print(*p) | ('a', 0) ('a', 1) ('a', 2) ('b', 0) ('b', 1) ('b', 2)
| CC0-1.0 | 10-Iterators.ipynb | jas076100/WhirlwindTourOfPython-master |
Content under Creative Commons Attribution license CC-BY 4.0, code under MIT license (c)2014 L.A. Barba, G.F. Forsyth, C.D. Cooper. Spreading out We're back! This is the fourth notebook of _Spreading out: parabolic PDEs,_ Module 4 of the course [**"Practical Numerical Methods with Python"**](https://openedx.seas.gwu... | import numpy
from scipy import linalg
def lhs_operator(M, N, sigma):
"""
Assembles and returns the implicit operator
of the system for the 2D diffusion equation.
We use a Dirichlet condition at the left and
bottom boundaries and a Neumann condition
(zero-gradient) at the right and top boundaries... | _____no_output_____ | CC-BY-3.0 | lessons/04_spreadout/04_04_Heat_Equation_2D_Implicit.ipynb | Fluidentity/numerical-mooc |
The solution of the linear system $(T^{n+1}_\text{int})$ contains the temperatures of the interior points at the next time step in a 1D array. We will also create a function that will take the values of $T^{n+1}_\text{int}$ and put them in a 2D array that resembles the physical domain. | def map_1d_to_2d(T_1d, nx, ny, Tb):
"""
Maps a 1D array of the temperature at the interior points
to a 2D array that includes the boundary values.
Parameters
----------
T_1d : numpy.ndarray
The temperature at the interior points as a 1D array of floats.
nx : integer
Numb... | _____no_output_____ | CC-BY-3.0 | lessons/04_spreadout/04_04_Heat_Equation_2D_Implicit.ipynb | Fluidentity/numerical-mooc |
And to advance in time, we will use | def btcs_implicit_2d(T0, nt, dt, dx, alpha, Tb):
"""
Computes and returns the distribution of the
temperature after a given number of time steps.
The 2D diffusion equation is integrated using
Euler implicit in time and central differencing
in space, with a Dirichlet condition at the left
... | _____no_output_____ | CC-BY-3.0 | lessons/04_spreadout/04_04_Heat_Equation_2D_Implicit.ipynb | Fluidentity/numerical-mooc |
Remember, we want the function to tell us when the center of the plate reaches $70^\circ C$. Dig deeper For demonstration purposes, these functions are very explicit. But you can see a trend here, right? Say we start with a matrix with `1/sigma+4` in the main diagonal, and `-1` on the 4 other corresponding diagonals. ... | # Set parameters.
Lx = 0.01 # length of the plate in the x direction
Ly = 0.01 # length of the plate in the y direction
nx = 21 # number of points in the x direction
ny = 21 # number of points in the y direction
dx = Lx / (nx - 1) # grid spacing in the x direction
dy = Ly / (ny - 1) # grid spacing in the y direct... | _____no_output_____ | CC-BY-3.0 | lessons/04_spreadout/04_04_Heat_Equation_2D_Implicit.ipynb | Fluidentity/numerical-mooc |
We are ready to go! | # Set the time-step size based on CFL limit.
sigma = 0.25
dt = sigma * min(dx, dy)**2 / alpha # time-step size
nt = 300 # number of time steps to compute
# Compute the temperature along the rod.
T = btcs_implicit_2d(T0, nt, dt, dx, alpha, Tb) | [time step 257] Center at T=70.00 at t=0.16 s
| CC-BY-3.0 | lessons/04_spreadout/04_04_Heat_Equation_2D_Implicit.ipynb | Fluidentity/numerical-mooc |
And plot, | from matplotlib import pyplot
%matplotlib inline
# Set the font family and size to use for Matplotlib figures.
pyplot.rcParams['font.family'] = 'serif'
pyplot.rcParams['font.size'] = 16
# Plot the filled contour of the temperature.
pyplot.figure(figsize=(8.0, 5.0))
pyplot.xlabel('x [m]')
pyplot.ylabel('y [m]')
levels =... | _____no_output_____ | CC-BY-3.0 | lessons/04_spreadout/04_04_Heat_Equation_2D_Implicit.ipynb | Fluidentity/numerical-mooc |
Try this out with different values of `sigma`! You'll see that it will always give a stable solution!Does this result match the explicit scheme from the previous notebook? Do they take the same amount of time to reach $70^\circ C$ in the center of the plate? Now that we can use higher values of `sigma`, we need fewer t... | from IPython.core.display import HTML
css_file = '../../styles/numericalmoocstyle.css'
HTML(open(css_file, 'r').read()) | _____no_output_____ | CC-BY-3.0 | lessons/04_spreadout/04_04_Heat_Equation_2D_Implicit.ipynb | Fluidentity/numerical-mooc |
DATA 512: A1 Data Curation AssignmentBy: Megan Nalani Chun Step 1: Gathering the data Gather Wikipedia traffic from Jan 1, 2008 - August 30, 2020 - Legacy Pagecounts API provides desktop and mobile traffic data from Dec. 2007 - July 2016 - Pageviews API provides desktop, mobile web, and mobile app traffic data from J... | import json
import requests | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Second, set the location of the endpoints and header information. This information is needed to call the Pagecounts and Pageviews APIs. | endpoint_legacy = 'https://wikimedia.org/api/rest_v1/metrics/legacy/pagecounts/aggregate/{project}/{access-site}/{granularity}/{start}/{end}'
endpoint_pageviews = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/aggregate/{project}/{access}/{agent}/{granularity}/{start}/{end}'
headers = {
'User-Agent': 'https... | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Third, define a function to call the APIs taking in the endpoint and parameters. This function returns the data in json format. | def api_call(endpoint, parameters):
call = requests.get(endpoint.format(**parameters), headers=headers)
response = call.json()
return response | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Fourth, define a function to make the api_call() with the correct parameters and save the output to json file in format apiname_accesstype_startyearmonth_endyearmonth.json | def get_data(api, access_dict, params, endpoint, access_name):
start = 0 #index of start date
end = 1 #index of end data
year_month = 6 #size of YYYYMM
for access_type, start_end_dates in access_dict.items(): #get data for all access types in API
params[access_name] = access_type
data ... | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Fifth, define the parameters for the legacy page count API and call the get_data function. This will pull the data and save it. | api = "pagecounts"
access_type_legacy = {"desktop-site": ["2008010100", "2016070100"], #access type: start year_month, end year_month
"mobile-site": ["2014100100", "2016070100"]} #used to save outputs with correct filenames
#https://wikimedia.org/api/rest_v1/#!/Legacy_data/get_metrics_legacy_page... | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Sixth, define the parameters for the page views API and call the get_data function. This will pull the data and save it. | api = "pageviews"
start_end_dates = ["2015070100", "2020080100"] #start year_month, end year_month
access_type_pageviews = {"desktop": start_end_dates, #access type: start year_month, end year_month
"mobile-app": start_end_dates,
"mobile-web": start_end_dates }
#ht... | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Step 2: Processing the data First, create a function to read in all data files and extract the list of records from items. | def read_json(filename):
with open(filename, 'r') as f:
return json.load(f)["items"] | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Second, use the read_json function to get a list of records for each file. | pageviews_mobile_web = read_json("pageviews_mobile-web_201507_202008.json")
pageviews_mobile_app = read_json("pageviews_mobile-app_201507_202008.json")
pageviews_desktop = read_json("pageviews_desktop_201507_202008.json")
pagecounts_mobile = read_json("pagecounts_mobile-site_201410_201607.json")
pagecounts_desktop = re... | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Third, create a total mobile traffic count for each month using the mobile-app and mobile-web data from the pageviews API. The list of [timestamp, view_count] pairs data structure will enable easy transformation into a dataframe. | pageviews_mobile = [[r1["timestamp"], r0["views"] + r1["views"]] for r0 in pageviews_mobile_web for r1 in pageviews_mobile_app if r0["timestamp"] == r1["timestamp"]] | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Fourth, get the timestamps and values in the [timestamp, view_count] format for the desktop pageviews, desktop pagecounts, and mobile pagecounts. | pageviews_desktop = [[record["timestamp"], record["views"]] for record in pageviews_desktop]
pagecounts_desktop = [[record["timestamp"], record["count"]] for record in pagecounts_desktop]
pagecounts_mobile = [[record["timestamp"], record["count"]] for record in pagecounts_mobile] | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Fifth, import pandas library and transform data into dataframes. | import pandas as pd
pageview_desktop_views = pd.DataFrame(pageviews_desktop, columns=["timestamp", "pageview_desktop_views"])
pageview_mobile_views = pd.DataFrame(pageviews_mobile, columns=["timestamp", "pageview_mobile_views"])
pagecounts_desktop = pd.DataFrame(pagecounts_desktop, columns=["timestamp", "pagecount_des... | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Sixth, join page view dataframes and calculate total for all views. | df_pageviews = pd.merge(pageview_desktop_views, pageview_mobile_views, how="outer", on="timestamp")
df_pageviews["pageview_all_views"] = df_pageviews["pageview_desktop_views"] + df_pageviews["pageview_mobile_views"]
df_pageviews.head() | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Seventh, join page count dataframes. Then fill in NaN values with 0 to calculate total for all counts. | df_pagecounts = pd.merge(pagecounts_desktop, pagecounts_mobile, how="outer", on="timestamp")
df_pagecounts["pagecount_mobile_views"] = df_pagecounts["pagecount_mobile_views"].fillna(0)
df_pagecounts["pagecount_all_views"] = df_pagecounts["pagecount_desktop_views"] + df_pagecounts["pagecount_mobile_views"]
df_pagecounts... | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Eighth, join page count and page view dataframes into one table. Filling in missing values with 0. | df = pd.merge(df_pagecounts, df_pageviews, how="outer", on="timestamp")
df = df.fillna(0)
df.head() | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Ninth, separate the timestamp into the year and month in YYYY and MM format for all the data. Remove the timestamp column. | df["year"] = df["timestamp"].apply(lambda date: date[:4])
df["month"] = df["timestamp"].apply(lambda date: date[4:6])
df.drop("timestamp", axis=1, inplace=True)
df.head() | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Tenth, save processed data to csv file without the index column. | df.to_csv("en-wikipedia_traffic_200801-202008.csv", index=False) | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Step 3: Analyze the data First, fill 0 values with numpy.nan values so these values are not plotted on the chart. | import numpy as np
df.replace(0, np.nan, inplace=True) | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Second, transform the year and month into a datetime.date type which will be used for the x-axis in the chart. | from datetime import date
date = df.apply(lambda r: date(int(r["year"]), int(r["month"]), 1), axis=1) | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Third, divide all page view counts by 1e6 so the chart is easier to read. Y-axis will be the values shown x 1,000,000. | pc_mobile = df["pagecount_mobile_views"] / 1e6
pv_mobile = df["pageview_mobile_views"] / 1e6
pc_desktop = df["pagecount_desktop_views"] / 1e6
pv_desktop = df["pageview_desktop_views"] / 1e6
pv_total = df["pageview_all_views"] / 1e6
pc_total = df["pagecount_all_views"] / 1e6 | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
Fourth, plot the data in a time series for desktop (main site), mobile, and the total all up. The dashed lines are data from the pagecount API and the solid lines are the data from the pageview API without crawler traffic. | import matplotlib.pyplot as plt
from matplotlib.dates import YearLocator
#create plot and assign time series to plot
fig, ax1 = plt.subplots(figsize=(18,6))
ax1.plot(date, pc_desktop, label="main site", color="green", ls="--")
ax1.plot(date, pv_desktop, label="_Hidden label", color="green", ls="-")
ax1.plot(date, pc_... | _____no_output_____ | MIT | data-512-a1/StepByStepNotebook.ipynb | NalaniKai/data-512 |
İki saniye periyotlu kare dalga Sekil 3.24 | # Tanimlar
import matplotlib.pyplot as plt
import numpy as np
t=np.linspace(0,10, 1000)
freqs=np.r_[0.5:6.5]
fig, ax=plt.subplots(7,1, sharex=True, sharey=True)
sumSines=np.zeros(t.shape);
cnt=1;
for f in freqs:
s= np.sin(2*np.pi*f*t)/(2*f)
ax[cnt].plot(t,s)
sumSines+=s
cnt+=1
ax[0].plot(t,sumSin... | _____no_output_____ | Apache-2.0 | tr/Sekil_3_26.ipynb | bosmanoglu/Digital_Image_Processing_Book |
load data and embedding | # load confing
import yaml
import pickle
with open('config.yaml', 'r') as f:
conf = yaml.load(f)
BATCH_SIZE = conf["MODEL"]["BATCH_SIZE"]
MAX_EPOCHS = conf["MODEL"]["MAX_EPOCHS"]
WORD2VEC_MODEL = conf["EMBEDDING"]["WORD2VEC_MODEL"]
print('load data ...')
X_train = np.load('data/X_train.npy')
y_train = np.load('data... | _____no_output_____ | Apache-2.0 | train.ipynb | jsandersen/WU-RNN |
train model | lstm = get_model(2, embedding_layer)
callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2)
lstm.compile(
loss='binary_crossentropy',
optimizer=tf.keras.optimizers.Adam(0.0001),
metrics=['accuracy'])
lstm.summary()
# train model
history = lstm.fit(
X_train, y_train,
batch_size=B... | _____no_output_____ | Apache-2.0 | train.ipynb | jsandersen/WU-RNN |
history | from matplotlib import pyplot as plt
# "Accuracy"
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# "Loss"
plt.plot(history.history['loss'])
plt.plot(history.his... | _____no_output_____ | Apache-2.0 | train.ipynb | jsandersen/WU-RNN |
Define Functions | # Performce cross validation using xgboost
def xgboostcv(X, y, fold, n_estimators, lr, depth, n_jobs, gamma, min_cw, subsample, colsample):
uid = np.unique(fold)
model_pred = np.zeros(X.shape[0])
model_valid_loss = np.zeros(len(uid))
model_train_loss = np.zeros(len(uid))
for i in uid:
x_vali... | _____no_output_____ | BSD-3-Clause | hourly_model/XGB.ipynb | NREL/TrafficVolumeEstimation |
Parameter Values | # Set a few values
validation_only = False # Whether test model with test data
n_nodes = 96 # Number of computing nodes used for hyperparamter tunning
trained = False # If a trained model exits
cols_drop = ['StationId', 'Date', 'PenRate', 'NumberOfLanes', 'Dir', 'FC', 'Month'] # Columns to be dropped
if trained:
pa... | _____no_output_____ | BSD-3-Clause | hourly_model/XGB.ipynb | NREL/TrafficVolumeEstimation |
Read Data | if validation_only:
raw_data_train = pd.read_csv("final_train_data.csv")
data = raw_data_train.drop(cols_drop, axis=1)
if 'Dir' in data.columns:
data[['Dir']] = data[['Dir']].astype('category')
one_hot = pd.get_dummies(data[['Dir']])
data = data.drop(['Dir'], axis = 1)
data =... | _____no_output_____ | BSD-3-Clause | hourly_model/XGB.ipynb | NREL/TrafficVolumeEstimation |
Cross Validation & Hyperparameter Optimization | # Set hyperparameter ranges for Bayesian optimization
xgboostBO = BayesianOptimization(xgboostcv_mse,
{'n': (1, 10),
'p': (-4, 0),
'depth': (2, 10),
'g': (-3, 0),
... | _____no_output_____ | BSD-3-Clause | hourly_model/XGB.ipynb | NREL/TrafficVolumeEstimation |
Model Test | # Build a xgboost using all the training data with the optimal hyperparameter
xgb = XGBRegressor(n_estimators=int(params['n'])*100, learning_rate=10**params['p'], max_depth = int(params['depth']),
n_jobs = n_nodes, gamma = 10**params['g'], min_child_weight = params['min_cw'],
sub... | _____no_output_____ | BSD-3-Clause | hourly_model/XGB.ipynb | NREL/TrafficVolumeEstimation |
Plot Estimations vs. Observations | # Prepare data to plot estimated and observed values
if validation_only:
if trained:
plot_df = pd.read_csv("train_data_pred.csv")
else:
plot_df = train_data_pred
else:
if trained:
plot_df = pd.read_csv("test_data_pred.csv")
else:
plot_df = test_data_pred
plot_df = plot_d... | _____no_output_____ | BSD-3-Clause | hourly_model/XGB.ipynb | NREL/TrafficVolumeEstimation |
First import the "datavis" module | import sys
sys.path.append('..')
import numpy as np
import datavis
import vectorized_datavis
def test_se_to_sd():
"""
Test that the value returned is a float value
"""
sdev = datavis.se_to_sd(0.5, 1000)
assert isinstance(sdev, float),\
"Returned data type is not a float number"
test_se_to_sd() ... | _____no_output_____ | MIT | examples/Unit Tests.ipynb | Genes-N-Risks/genocode |
IDS Instruction: Regression(Lisa Mannel) Simple linear regression First we import the packages necessary fo this instruction: | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error | _____no_output_____ | Apache-2.0 | IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb | pmnatos/DataScience |
Consider the data set "df" with feature variables "x" and "y" given below. | df1 = pd.DataFrame({'x': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 'y': [1, 3, 2, 5, 7, 8, 8, 9, 10, 12]})
print(df1) | x y
0 0 1
1 1 3
2 2 2
3 3 5
4 4 7
5 5 8
6 6 8
7 7 9
8 8 10
9 9 12
| Apache-2.0 | IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb | pmnatos/DataScience |
To get a first impression of the given data, let's have a look at its scatter plot: | plt.scatter(df1.x, df1.y, color = "y", marker = "o", s = 40)
plt.xlabel('x')
plt.ylabel('y')
plt.title('first overview of the data')
plt.show() | _____no_output_____ | Apache-2.0 | IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb | pmnatos/DataScience |
We can already see a linear correlation between x and y. Assume the feature x to be descriptive, while y is our target feature. We want a linear function, y=ax+b, that predicts y as accurately as possible based on x. To achieve this goal we use linear regression from the sklearn package. | #define the set of descriptive features (in this case only 'x' is in that set) and the target feature (in this case 'y')
descriptiveFeatures1=df1[['x']]
targetFeature1=df1['y']
#define the classifier
classifier = LinearRegression()
#train the classifier
model1 = classifier.fit(descriptiveFeatures1, targetFeature1) | _____no_output_____ | Apache-2.0 | IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb | pmnatos/DataScience |
Now we can use the classifier to predict y. We print the predictions as well as the coefficient and bias (*intercept*) of the linear function. | #use the classifier to make prediction
targetFeature1_predict = classifier.predict(descriptiveFeatures1)
print(targetFeature1_predict)
#print coefficient and intercept
print('Coefficients: \n', classifier.coef_)
print('Intercept: \n', classifier.intercept_) | [ 1.23636364 2.40606061 3.57575758 4.74545455 5.91515152 7.08484848
8.25454545 9.42424242 10.59393939 11.76363636]
Coefficients:
[1.16969697]
Intercept:
1.2363636363636399
| Apache-2.0 | IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb | pmnatos/DataScience |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.