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 |
|---|---|---|---|---|---|
Unique Değerleri Listeleme ve Sayısını Bulma | workerdf['Departman'].unique()
workerdf['Departman'].nunique() | _____no_output_____ | CC0-1.0 | pandas/3.0.pandas_methods_features.ipynb | enesonmez/data-science-tutorial-turkish |
Sütundaki Değerlerden Toplamda Kaçar Adet Var? | workerdf['Departman'].value_counts() | _____no_output_____ | CC0-1.0 | pandas/3.0.pandas_methods_features.ipynb | enesonmez/data-science-tutorial-turkish |
Değerler Üzerinde Fonksiyon Yardımı ile İşlemler Yapmak | workerdf['Maas'].apply(lambda maas : maas*0.66) | _____no_output_____ | CC0-1.0 | pandas/3.0.pandas_methods_features.ipynb | enesonmez/data-science-tutorial-turkish |
Dataframe'de Null Değer Var mı? | workerdf.isnull() | _____no_output_____ | CC0-1.0 | pandas/3.0.pandas_methods_features.ipynb | enesonmez/data-science-tutorial-turkish |
Pivot Table | characters = {'Karakter Sınıfı':['South Park','South Park','Simpson','Simpson','Simpson'],
'Karakter Ismi':['Cartman','Kenny','Homer','Bart','Bart'],
'Puan':[9,10,50,20,10]}
dfcharacters = pd.DataFrame(characters)
dfcharacters
dfcharacters.pivot_table(values='Puan',index=['Karakter Sınıfı','Kara... | _____no_output_____ | CC0-1.0 | pandas/3.0.pandas_methods_features.ipynb | enesonmez/data-science-tutorial-turkish |
Belli Bir Sütuna Göre Değerleri Sıralama (Sorting) | workerdf.sort_values(by='Maas', ascending=False) | _____no_output_____ | CC0-1.0 | pandas/3.0.pandas_methods_features.ipynb | enesonmez/data-science-tutorial-turkish |
Duplicate Veriler | employees = [('Stuti', 28, 'Varanasi'),
('Saumya', 32, 'Delhi'),
('Aaditya', 25, 'Mumbai'),
('Saumya', 32, 'Delhi'),
('Saumya', 32, 'Delhi'),
('Saumya', 32, 'Mumbai'),
('Aaditya', 40, 'Dehradun'),
('Seema', 32, 'Delhi')]
df = pd.Data... | _____no_output_____ | CC0-1.0 | pandas/3.0.pandas_methods_features.ipynb | enesonmez/data-science-tutorial-turkish |
Newswires Classification with Reuters Imports | import numpy as np # Numpy
from matplotlib import pyplot as plt # Matplotlib
import keras # Keras
import pandas as pd # Pandas
from keras.datasets import reuters # Reuters Dataset
from keras.uti... | _____no_output_____ | Apache-2.0 | ML Problems/Newswires Classification with Reuters - DLP/Models/Newswires_Classification_with_Reuters.ipynb | keivanipchihagh/Intro_to_DS_and_ML |
Load dataset | (train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words = 10000)
print('Size:', len(train_data))
print('Training Data:', train_data[0]) | _____no_output_____ | Apache-2.0 | ML Problems/Newswires Classification with Reuters - DLP/Models/Newswires_Classification_with_Reuters.ipynb | keivanipchihagh/Intro_to_DS_and_ML |
Get the feel of data | def decode(index): # Decoding the sequential integers into the corresponding words
word_index = reuters.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
decoded_newswire = ' '.join([reverse_word_index.get(i - 3, '?') for i in test_data[0]])
return decoded_newswi... | _____no_output_____ | Apache-2.0 | ML Problems/Newswires Classification with Reuters - DLP/Models/Newswires_Classification_with_Reuters.ipynb | keivanipchihagh/Intro_to_DS_and_ML |
Data Prep (One-Hot Encoding) | def vectorize_sequences(sequences, dimension = 10000): # Encoding the integer sequences into a binary matrix
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1.
return results
train_data = vectorize_sequences(train_data)
test_data = vectorize_... | _____no_output_____ | Apache-2.0 | ML Problems/Newswires Classification with Reuters - DLP/Models/Newswires_Classification_with_Reuters.ipynb | keivanipchihagh/Intro_to_DS_and_ML |
Building the model | model = keras.models.Sequential()
model.add(keras.layers.Dense(units = 64, activation = 'relu', input_shape = (10000,)))
model.add(keras.layers.Dense(units = 64, activation = 'relu'))
model.add(keras.layers.Dense(units = 46, activation = 'softmax'))
model.compile( optimizer = 'rmsprop', loss = 'categorical_crossentropy... | _____no_output_____ | Apache-2.0 | ML Problems/Newswires Classification with Reuters - DLP/Models/Newswires_Classification_with_Reuters.ipynb | keivanipchihagh/Intro_to_DS_and_ML |
Training the model | x_val = train_data[:1000]
train_data = train_data[1000:]
y_val = train_labels[:1000]
train_labels = train_labels[1000:]
history = model.fit(train_data, train_labels, batch_size = 512, epochs = 10, validation_data = (x_val, y_val), verbose = False) | _____no_output_____ | Apache-2.0 | ML Problems/Newswires Classification with Reuters - DLP/Models/Newswires_Classification_with_Reuters.ipynb | keivanipchihagh/Intro_to_DS_and_ML |
Evaluating the model | result = model.evaluate(train_data, train_labels)
print('Loss:', result[0])
print('Accuracy:', result[1] * 100) | _____no_output_____ | Apache-2.0 | ML Problems/Newswires Classification with Reuters - DLP/Models/Newswires_Classification_with_Reuters.ipynb | keivanipchihagh/Intro_to_DS_and_ML |
Statistics | epochs = range(1, len(history.history['loss']) + 1)
plt.plot(epochs, history.history['loss'], 'b', label = 'Training Loss')
plt.plot(epochs, history.history['val_loss'], 'r', label = 'Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
plt.clf()
plt.plot(epochs, history.history['accuracy'... | _____no_output_____ | Apache-2.0 | ML Problems/Newswires Classification with Reuters - DLP/Models/Newswires_Classification_with_Reuters.ipynb | keivanipchihagh/Intro_to_DS_and_ML |
Making predictions | prediction_index = random.randint(0, len(test_data))
prediction_data = test_data[prediction_index]
decoded_prediction_data = decode(prediction_index)
# Info
print('Random prediction index:', prediction_index)
print('Original prediction Data:', prediction_data)
print('Decoded prediction Data:', decoded_prediction_data)... | _____no_output_____ | Apache-2.0 | ML Problems/Newswires Classification with Reuters - DLP/Models/Newswires_Classification_with_Reuters.ipynb | keivanipchihagh/Intro_to_DS_and_ML |
Interpreting text models: IMDB sentiment analysis This notebook loads pretrained CNN model for sentiment analysis on IMDB dataset. It makes predictions on test samples and interprets those predictions using integrated gradients method.The model was trained using an open source sentiment analysis tutorials described i... | import spacy
import torch
import torchtext
import torchtext.data
import torch.nn as nn
import torch.nn.functional as F
from torchtext.vocab import Vocab
from captum.attr import LayerIntegratedGradients, TokenReferenceBase, visualization
nlp = spacy.load('en')
device = torch.device("cuda:5" if torch.cuda.is_availabl... | _____no_output_____ | Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
The dataset used for training this model can be found in: https://ai.stanford.edu/~amaas/data/sentiment/Redefining the model in order to be able to load it. | class CNN(nn.Module):
def __init__(self, vocab_size, embedding_dim, n_filters, filter_sizes, output_dim,
dropout, pad_idx):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx = pad_idx)
self.convs = nn.... | _____no_output_____ | Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
Loads pretrained model and sets the model to eval mode. The model is already in the provided in the 'models' folder. Download source: https://github.com/pytorch/captum/blob/master/tutorials/models/imdb-model-cnn.pt | model = torch.load('models/imdb-model-cnn.pt')
model.eval()
model = model.to(device) | /opt/anaconda3/lib/python3.7/site-packages/torch/serialization.py:593: SourceChangeWarning: source code of class 'torch.nn.modules.sparse.Embedding' has changed. you can retrieve the original source code by accessing the object's source attribute or set `torch.nn.Module.dump_patches = True` and use the patch tool to re... | Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
Load a small subset of test data using torchtext from IMDB dataset. | TEXT = torchtext.data.Field(lower=True, tokenize='spacy')
Label = torchtext.data.LabelField(dtype = torch.float)
| _____no_output_____ | Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
Download IMDB file 'aclImdb_v1.tar.gz' from https://ai.stanford.edu/~amaas/data/sentiment/ in a 'data' subfolder where this notebook is saved.Then unpack file using 'tar -xzf aclImdb_v1.tar.gz' | train, test = torchtext.datasets.IMDB.splits(text_field=TEXT,
label_field=Label,
train='train',
test='test',
path='data/aclImdb')
test, _ = test.split(split_ratio = 0.0... | _____no_output_____ | Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
Loading and setting up vocabulary for word embeddings using torchtext. | from torchtext import vocab
loaded_vectors = vocab.GloVe(name='6B', dim=50)
# If you prefer to use pre-downloaded glove vectors, you can load them with the following two command line
# loaded_vectors = torchtext.vocab.Vectors('data/glove.6B.50d.txt')
# source for downloading: https://github.com/uclnlp/inferbeddings/... | Vocabulary Size: 101982
| Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
Define the padding token. The padding token will also serve as the reference/baseline token used for the application of the Integrated Gradients. The padding token is used for this since it is one of the most commonly used references for tokens.This is then used with the Captum helper class `TokenReferenceBase` further... | PAD = 'pad'
PAD_INDEX = TEXT.vocab.stoi[PAD]
print(PAD, PAD_INDEX) | pad 6976
| Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
Let's create an instance of `LayerIntegratedGradients` using forward function of our model and the embedding layer.This instance of layer integrated gradients will be used to interpret movie rating review.Layer Integrated Gradients will allow us to assign an attribution score to each word/token embedding tensor in the ... | lig = LayerIntegratedGradients(model, model.embedding) | _____no_output_____ | Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
In the cell below, we define a generic function that generates attributions for each movie rating and stores them in a list using `VisualizationDataRecord` class. This will ultimately be used for visualization purposes. | def interpret_sentence(model, sentence, min_len = 7, label = 0):
# create input tensor from sentence
text_list = sentence_to_wordlist(sentence, min_len)
text_tensor, reference_tensor = wordlist_to_tensors(text_list)
# apply model forward function with sigmoid
model.zero_grad()
pred = to... | _____no_output_____ | Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
Below cells call `interpret_sentence` to interpret a couple handcrafted review phrases. | # reset accumulated data
vis_records = []
vis_records.append(interpret_sentence(model, 'It was a fantastic performance !', label=1))
vis_records.append(interpret_sentence(model, 'Best film ever', label=1))
vis_records.append(interpret_sentence(model, 'Such a great show!', label=1))
vis_records.append(interpret_sentenc... | pred: pos ( 0.99 ) , delta: tensor([0.0007])
pred: pos ( 0.71 ) , delta: tensor([0.0001])
pred: pos ( 0.95 ) , delta: tensor([0.0003])
pred: neg ( 0.22 ) , delta: tensor([0.0012])
pred: neg ( 0.38 ) , delta: tensor([0.0005])
pred: neg ( 0.01 ) , delta: tensor([0.0005])
pred: pos ( 0.66 ) , delta: tensor([... | Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
Below is an example of how we can visualize attributions for the text tokens. Feel free to visualize it differently if you choose to have a different visualization method. | vis_example = vis_records[-1]
# print(dir(vis_example))
print('raw input: ', vis_example.raw_input)
print('true class: ', vis_example.true_class)
print('pred class (prob): ', vis_example.pred_class, '(', vis_example.pred_prob, ')')
print('attr score (sum over word attributions): ', vis_example.attr_score)
print('word ... | Visualize attributions based on Integrated Gradients
| Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
Above cell generates an output similar to this: | from IPython.display import Image
Image(filename='img/sentiment_analysis.png')
| _____no_output_____ | Apache-2.0 | IMDB_TorchText_Interpret.ipynb | matthiaszimmermann/pytorch_torchtext_captum |
The Structure and Geometry of the Human Brain[Noah C. Benson](https://nben.net/) <[nben@uw.edu](mailto:nben@uw.edu)> [eScience Institute](https://escience.washingtonn.edu/) [University of Washington](https://www.washington.edu/) [Seattle, WA 98195](https://seattle.gov/) Introduction This notebook is designed... | # We will need os for paths:
import os
# Numpy, Scipy, and Matplotlib are effectively standard libraries.
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.pyplot as plt
# Ipyvolume is a 3D plotting library that is used by neuropythy.
import ipyvolume as ipv
# Nibabel is the library that... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
MRI and Volumetric Data The first section of this notebook will deal with MR images and volumetric data. We will start by loading in an MRImage. We will use the same image that was visualized in the lecture (if you are not using the Jupyterhub, you won't have access to this subject, but you can use the subject `'bert'... | subject_id = 'nben'
subject = ny.freesurfer_subject(subject_id)
# If you have configured the HCP credentials and wish to use an HCP
# subject instead of nben:
#
#subject_id = 111312
#subject = ny.hcp_subject(subject_id) | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
The `freesurfer_subject` function returns a `neuropythy` `Subject` object. | subject | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
--- Load an MRImage file. ---Let's load in an image file. FreeSurfer directories contain a subdirectory `mri/` that contains all of the volumetric/image data for the subject. This includes images that have been preprocessed as well as copies of the original T1-weighted image. We will load an image called `T1.mgz`. | # This function will load data from a subject's directory using neuropythy's
# builtin ny.load() function; in most cases, this calls down to nibabel's own
# nib.load() function.
im = subject.load('mri/T1.mgz')
# For an HCP subject, use this file instead:
#im = subject.load("T1w/T1w_acpc_dc.nii.gz")
# The return value... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
--- Visualize some slices of the image. ---Next, we will make 2D plots of some of the image slices. Feel free to change which slices you visualize; I have just chosen some defaults. | # What axis do we want to plot slices along? 0, 1, or 2 (for the first, second,
# or third 3D image axis).
axis = 2
# Which slices along this axis should we plot? These must be at least 0 and at
# most 255 (There are 256 slices in each dimension of these images).
slices = [75, 125, 175]
# Make a figure and axes using ... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
--- Visualize the 3D Image as a whole. ---Next we will use `ipyvolume` to render a 3D View of the volume. The volume plotting function is part of `ipyvolume` and has a variety of options that are beyond the scope of this demo. | # Note that this will generate a warning, which can be safely ignored.
fig = ipv.figure()
ipv.quickvolshow(subject.images['intensity_normalized'].dataobj)
ipv.show() | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
--- Load and visualize anatomical segments. ---FreeSurfer creates a segmentation image file called `aseg.mgz`, which we can load and use to identify ROIs. First, we will load this file and plot some slices from it. | # First load the file; any of these lines will work:
#aseg = subject.load('mri/aseg.mgz')
#aseg = nib.load(subject.path + '/mri/aseg.mgz')
aseg = subject.images['segmentation'] | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
We can plot this as-is, but we don't know what the values in the numbers correspond to. Nonetheless, let's go ahead. This code block is the same as the block we used to plot slices above except that it uses the new image `aseg` we just loaded. | # What axis do we want to plot slices along? 0, 1, or 2 (for the first, second,
# or third 3D image axis).
axis = 2
# Which slices along this axis should we plot? These must be at least 0 and at
# most 255 (There are 256 slices in each dimension of these images).
slices = [75, 125, 175]
# Make a figure and axes using ... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
Clearly, the balues in the plots above are discretized, but it's not clear what they correspond to. The map of numbers to characters and colors can be found in the various FreeSurfer color LUT files. These are all located in the FreeSurfer home directory and end with `LUT.txt`. They are essentially spreadsheets and are... | ny.config['freesurfer_home'].luts['aseg'] | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
So suppose we want to look at left cerebral cortex. In the table, this has value 3. We can find this value in the images we are plotting and plot only it to see the ROI in each the slices we plot. | # We want to plot left cerebral cortex (label ID = 3, per the LUT)
label = 3
(fig, axes) = plt.subplots(1, len(slices), figsize=(5, 5/len(slices)), dpi=144)
# Plot each of the slices:
for (ax, slice_num) in zip(axes, slices):
# Get the slice:
if axis == 0:
imslice = aseg.dataobj[slice_num,:,:]
elif... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
By plotting the LH cortex specifically, we can see that LEFT is in the direction of increasing rows (down the image slices, if you used `axis = 2`), thus RIGHT must be in the direction of decreasing rows in the image. Let's also make some images from these slices in which we replace each of the pixels in each slice wit... | # We are using this color LUT:
lut = ny.config['freesurfer_home'].luts['aseg']
# The axis:
axis = 2
(fig, axes) = plt.subplots(1, len(slices), figsize=(5, 5/len(slices)), dpi=144)
# Plot each of the slices:
for (ax, slice_num) in zip(axes, slices):
# Get the slice:
if axis == 0:
imslice = aseg.dataobj[... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
Cortical Surface Data Cortical surface data is handled and represented much differently than volumetric data. This section demonstrates how to interact with cortical surface data in a Jupyter notebook, primarily using `neuropythy`.To start off, however, we will just load a surface file using `nibabel` to see what one ... | # Each subject has a number of surface files; we will look at the
# left hemisphere, white surface.
hemi = 'lh'
surf = 'white'
# Feel free to change hemi to 'rh' for the RH and surf to 'pial'
# or 'inflated'.
# We load the surface from the subject's 'surf' directory in FreeSurfer.
# Nibabel refers to these files as "g... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
So when `nibabel` reads in one of these surface files, what we get back is an `n x 3` matrix of real numbers (coordiantes) and an `m x 3` matrix of integers (triangle indices).The `ipyvolume` module has support for plotting triangle meshes--let's see how it works. | # Extract the coordinates and triangle-faces.
(coords, faces) = surface_data
# And get the (x,y,z) from coordinates.
(x, y, z) = coords.T
# Now, plot the triangle mesh.
fig = ipv.figure()
ipv.plot_trisurf(x, y, z, triangles=faces)
# Adjust the plot limits (making them equal makes the plot look good).
ipv.pylab.xlim(-1... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
--- Hemisphere (`neuropythy.mri.Cortex`) objects ---Although one can load and plot cortical surfaces with `nibabel`, `neuropythy` builds on `nibabel` by providing a framework around which the cortical surface can be represented. It includes a number of utilities related specifically to cortical surface analysis, and a... | # Grab the hemisphere for our subject.
cortex = subject.hemis[hemi]
# Note that `cortex = subject.lh` and `cortex = subject.rh` are equivalent
# to `cortex = subject.hemis['lh']` and `cortex = subject.hemis['rh']`.
# What is cortex?
cortex | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
From this we can see which hemisphere we have selected, the number of triangle faces that it has, and the number of vertices that it has. Let's look at a few of its' properties. SurfacesEach hemisphere has a number of surfaces; we can view them through the `cortex.surfaces` dictionary. | cortex.surfaces.keys()
cortex.surfaces['white_smooth'] | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
The `'white_smooth'` mesh is a well-processed mesh of the white surface that has been well-smoothed. You might notice that there is a `'midgray'` surface, even though FreeSurfer does not include a mid-gray mesh file. The `'midgray'` mesh, however, can be made by averaging the white and pial mesh vertices.Recall that al... | np.array_equal(cortex.surfaces['white'].tess.faces,
cortex.surfaces['pial'].tess.faces) | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
Surfaces track a large amount of data about their meshes and vertices and inherit most of the properties of hemispheres that are discussed below. In addition, surfaces uniquely carry data about cortical distances and surface areas. For example: | # The area of each of the triangle-faces in nthe white surface mesh, in mm^2.
cortex.surfaces['white'].face_areas
# The length of each edge in the white surface mesh, in mm.
cortex.surfaces['white'].edge_lengths
# And the edges themselves, as indices like the faces.
cortex.surfaces['white'].tess.edges | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
Vertex Properties Properties arre values assigned to each surface vertex. They can include anatomical or geometric properties, such as ROI labels (i.e., a vector of values for each vertex: `True` if the vertex is in the ROI and `False` if not), cortical thickness (in mm), the vertex surface-area (in square mm), the cu... | sorted(cortex.properties.keys()) | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
A few thigs worth noting: First, not all FreeSurfer subjects will have all of the properties listed. This is because different versions of FreeSurfer include different files, and sometimes subjects are distributed without their full set of files (e.g., to save storage space). However, rather than go and try to load all... | ba1_label = cortex.prop('BA1_weight') >= 0.5 | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
We can now plot this property using `neuropythy`'s `cortex_plot()` function. | ny.cortex_plot(cortex.surfaces['white'], color=ba1_label) | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
**Improving this plot.** While this plot shows us where the ROI is, it's rather hard to interpret. Rather, we would prefer to plot the ROI in red and the rest of the brain using a binarized curvature map. `neuropythy` supports this kind of binarized curvature map as a default underlay, so, in fact, the easiest way to a... | ny.cortex_plot(cortex.surfaces['inflated'], color='r', mask=ba1_label) | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
We can optionally make this red ROI plot a little bit transparent as well. | ny.cortex_plot(cortex.surfaces['inflated'], color='r', mask=ba1_label, alpha=0.4) | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
**Plotting the weight instead of the label.** Alternately, we might have wanted to plot the weight / probability of the ROI. Continuous properties like probability can be plotted using color-maps, similar to how they are plotted in `matplotlib`. | ny.cortex_plot(cortex.surfaces['inflated'], color='BA1_weight',
cmap='hot', vmin=0, vmax=1, alpha=0.6) | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
**Another property.** Other properties can be very informative. For example, the cortical thickness property, which is stored in mm. This can tell us the parts of the brain that are thick or not thick. | ny.cortex_plot(cortex.surfaces['inflated'], color='thickness',
cmap='hot', vmin=1, vmax=6) | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
--- Interpolation (Surface to Image and Image to Surface) ---Hemisphere/Cortex objects also manage interpolation, both to/from image volumes as well as to/from the cortical surfaces of other subjects (we will demo interpolation between subjects in the last section). Here we will focus on the former: interpolation to a... | # We need a template image; the new image will have the same shape,
# affine, image type, and hader as the template image.
template_im = subject.images['brain']
# We can use just the template's header for this.
template = template_im.header
# We can alternately just provide information about the image geometry:
#templa... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
Now that we have made this new image, let's take a look at it by plotting some slices from it, once again. | # What axis do we want to plot slices along? 0, 1, or 2 (for the first, second,
# or third 3D image axis).
axis = 2
# Which slices along this axis should we plot? These must be at least 0 and at
# most 255 (There are 256 slices in each dimension of these images).
slices = [75, 125, 175]
# Make a figure and axes using ... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
**Image to Cortex Interpolation.** A good test of our interpolation methods is now to ensure that, when we interpolate data from the image we just created back to the cortex, we get approximately the same values. The values we interpolate back out of the volume will not be identical to the volumes we started with becau... | (lh_prop_interp, rh_prop_interp) = subject.image_to_cortex(new_im, method=method) | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
We can plot the hemispheres together to visualize the difference between the original thickenss and the thickness that was interpolated into an image then back onto the cortex. | fig = ny.cortex_plot(subject.lh, surface='midgray',
color=(lh_prop_interp - lh_prop)**2,
cmap='hot', vmin=0, vmax=2)
fig = ny.cortex_plot(subject.rh, surface='midgray',
color=(rh_prop_interp - rh_prop)**2,
cmap='hot', vmin=0, vmax=2,
... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
Intersubject Surface Alignment Comparison between multiple subjects is usually accomplished by first aligning each subject's cortical surface with that of a template surface (*fsaverage* in FreeSurfer, *fs_LR* in the HCP), then interpolating between vertices in the aligned arrangements. The alignment to the template a... | # Get the fsaverage subject.
fsaverage = ny.freesurfer_subject('fsaverage')
# Get the hemispheres we will be examining.
fsa_hemi = fsaverage.hemis[hemi]
sub_hemi = subject.hemis[hemi]
# Next, get the three registrations we want to plot.
sub_native_reg = sub_hemi.registrations['native']
sub_fsaverage_reg = sub_hemi.re... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
--- Interpolate Between Subjects ---Interpolation between subjects requires interpolating between a shared registration. For a subject and the *fsaverage*, this is the subject's *fsaverage*-aligned registration and *fsaverage*'s native. However, for two non-meta subjects, the *fsaverage*-aligned registration of both s... | # The property we're going to interpolate over to fsaverage:
sub_prop = sub_hemi.prop('thickness')
# The method we use ('nearest' or 'linear'):
method = 'linear'
# Interpolate the subject's thickness onto the fsaverage surface.
fsa_prop = sub_hemi.interpolate(fsa_hemi, sub_prop, method=method)
# Let's make a plot of... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
Okay, for our last exercise, let's interpolate back from the *fsaverage* subject to our subject. It is occasionally nice to be able to plot the *fsaverage*'s average curvature map as an underlay, so let's do that. | # This time we are going to interpolate curvature from the fsaverage
# back to the subject. When the property we are interpolating is a
# named property of the hemisphere, we can actually just specify it
# by name in the interpolation call.
fsa_curv_on_sub = fsa_hemi.interpolate(sub_hemi, 'curvature')
# We can make a ... | _____no_output_____ | CC-BY-4.0 | we-geometry-benson/class-notebook.ipynb | bastivkl/nh2020-curriculum |
Baye's Theorem IntroductionBefor starting with *Bayes Theorem* we can have a look at some definitions.**Conditional Probability :**Conditional Probability is the Probability of one event occuring with some Relationship to one or more events.Let A and B be the two interdependent event,where A has already occured then ... | #calculate P(B1|A) given P(B1),P(A|B1),P(A|B2),P(B2)
def bayes_theorem(p_b1,p_a_given_b1,p_a_given_b2,p_b2):
p_b1_given_a=(p_b1*p_a_given_b1)/((p_b1*p_a_given_b1)+(p_b2*p_a_given_b2))
return p_b1_given_a
#P(B1)
p_b1=0.001
#P(B2)
p_b2=0.999
#P(A|B1)
p_a_given_b1=0.9
#P(A|B2)
p_a_given_b2=0.01
result=bayes_theorem... | P(B1|A)= 8.264 %
| MIT | notebooks/Baye's Theorem Notebook.ipynb | Ritu7683/Statistics-and-Econometrics-for-Data-Science |
**Example 2 :** In a Quiz,a contestant either guesses or cheat or knows the answer to a multiple choice question with four choices.The Probability that he/she makes a guess is 1/3 and the Probability that he /she cheats the answer is 1/6.The Probability that his answer is correct,given that he cheated it,is 1/8.Find th... | #calculate P(B1|A) given P(B1),P(A|B1),P(A|B2),P(B2),P(B3),P(A|B3)
def bayes_theorem(p_b1,p_a_given_b1,p_a_given_b2,p_b2,p_b3,p_a_given_b3):
p_b3_given_a=(p_b3*p_a_given_b3)/((p_b1*p_a_given_b1)+(p_b2*p_a_given_b2)+(p_b3*p_a_given_b3))
return p_b3_given_a
#P(B1)
p_b1=1/3
#P(B2)
p_b2=1/6
#P(B3)
p_b3=1/2
#P(A|B1)
... | P(B3|A)= 82.759 %
| MIT | notebooks/Baye's Theorem Notebook.ipynb | Ritu7683/Statistics-and-Econometrics-for-Data-Science |
[learning-python3.ipynb]: https://gist.githubusercontent.com/kenjyco/69eeb503125035f21a9d/raw/learning-python3.ipynbRight-click -> "save link as" [https://gist.githubusercontent.com/kenjyco/69eeb503125035f21a9d/raw/learning-python3.ipynb][learning-python3.ipynb] to get most up-to-date version of this notebook file. Qui... | # Assigning some numbers to different variables
num1 = 10
num2 = -3
num3 = 7.41
num4 = -.6
num5 = 7
num6 = 3
num7 = 11.11
# Addition
num1 + num2
# Subtraction
num2 - num3
# Multiplication
num3 * num4
# Division
num4 / num5
# Exponent
num5 ** num6
# Increment existing variable
num7 += 4
num7
# Decrement existing variabl... | _____no_output_____ | MIT | learning-python3.ipynb | lsst-epo/jupyter-presentation |
Basic containers> Note: **mutable** objects can be modified after creation and **immutable** objects cannot.Containers are objects that can be used to group other objects together. The basic container types include:- **`str`** (string: immutable; indexed by integers; items are stored in the order they were added)- **`... | # Assign some containers to different variables
list1 = [3, 5, 6, 3, 'dog', 'cat', False]
tuple1 = (3, 5, 6, 3, 'dog', 'cat', False)
set1 = {3, 5, 6, 3, 'dog', 'cat', False}
dict1 = {'name': 'Jane', 'age': 23, 'fav_foods': ['pizza', 'fruit', 'fish']}
# Items in the list object are stored in the order they were added
li... | _____no_output_____ | MIT | learning-python3.ipynb | lsst-epo/jupyter-presentation |
Accessing data in containersFor strings, lists, tuples, and dicts, we can use **subscript notation** (square brackets) to access data at an index.- strings, lists, and tuples are indexed by integers, **starting at 0** for first item - these sequence types also support accesing a range of items, known as **slicing** ... | # Access the first item in a sequence
list1[0]
# Access the last item in a sequence
tuple1[-1]
# Access a range of items in a sequence
simple_string1[3:8]
# Access a range of items in a sequence
tuple1[:-3]
# Access a range of items in a sequence
list1[4:]
# Access an item in a dictionary
dict1['name']
# Access an elem... | _____no_output_____ | MIT | learning-python3.ipynb | lsst-epo/jupyter-presentation |
Python built-in functions and callablesA **function** is a Python object that you can "call" to **perform an action** or compute and **return another object**. You call a function by placing parentheses to the right of the function name. Some functions allow you to pass **arguments** inside the parentheses (separating... | # Use the type() function to determine the type of an object
type(simple_string1)
# Use the len() function to determine how many items are in a container
len(dict1)
# Use the len() function to determine how many items are in a container
len(simple_string2)
# Use the callable() function to determine if an object is call... | _____no_output_____ | MIT | learning-python3.ipynb | lsst-epo/jupyter-presentation |
Python object attributes (methods and properties)Different types of objects in Python have different **attributes** that can be referred to by name (similar to a variable). To access an attribute of an object, use a dot (`.`) after the object, then specify the attribute (i.e. `obj.attribute`)When an attribute of an ob... | # Assign a string to a variable
a_string = 'tHis is a sTriNg'
# Return a capitalized version of the string
a_string.capitalize()
# Return an uppercase version of the string
a_string.upper()
# Return a lowercase version of the string
a_string.lower()
# Notice that the methods called have not actually modified the string... | _____no_output_____ | MIT | learning-python3.ipynb | lsst-epo/jupyter-presentation |
Some methods on list objects- **`.append(item)`** to add a single item to the list- **`.extend([item1, item2, ...])`** to add multiple items to the list- **`.remove(item)`** to remove a single item from the list- **`.pop()`** to remove and return the item at the end of the list- **`.pop(index)`** to remove and return ... | # Define a new class called `Thing` that is derived from the base Python object
class Thing(object):
my_property = 'I am a "Thing"'
# Define a new class called `DictThing` that is derived from the `dict` type
class DictThing(dict):
my_property = 'I am a "DictThing"'
print(Thing)
print(type(Thing))
print(DictT... | I am a "DictThing"
| MIT | learning-python3.ipynb | lsst-epo/jupyter-presentation |
Lambda School Data Science - Making Data-backed AssertionsThis is, for many, the main point of data science - to create and support reasoned arguments based on evidence. It's not a topic to master in a day, but it is worth some focused time thinking about and structuring your approach to it. Lecture - generating a c... | # y = "health outcome" - predicted variable - dependent variable
# x = "drug usage" - explanatory variable - independent variable
import random
dir(random) # Reminding ourselves what we can do here
random.seed(10) # Random Seed for reproducibility
# Let's think of another scenario:
# We work for a company that sells a... | _____no_output_____ | MIT | NDoshi_DS4_114_Making_Data_backed_Assertions.ipynb | ndoshi83/DS-Unit-1-Sprint-1-Dealing-With-Data |
Assignment - what's going on here?Consider the data in `persons.csv` (already prepared for you, in the repo for the week). It has four columns - a unique id, followed by age (in years), weight (in lbs), and exercise time (in minutes/week) of 1200 (hypothetical) people.Try to figure out which variables are possibly rel... | # TODO - your code here
# Use what we did live in lecture as an example
# HINT - you can find the raw URL on GitHub and potentially use that
# to load the data with read_csv, or you can upload it yourself
# Import pandas library
import pandas as pd
# Load data into pandas dataframe
df = pd.read_csv('https://raw.git... | _____no_output_____ | MIT | NDoshi_DS4_114_Making_Data_backed_Assertions.ipynb | ndoshi83/DS-Unit-1-Sprint-1-Dealing-With-Data |
Visual Designer (Data Prep)In this exercise we will be building a pipeline in Azure Machine Learning using the [Visual Designer](https://docs.microsoft.com/azure/machine-learning/concept-designer). Traditionally the Visual Designer is used for training and deploying models. Here we will build a data prep pipeline that... | import azureml.core
from azureml.core import Workspace
# Load the workspace from the saved config file
ws = Workspace.from_config()
print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))
#TODO: Supply userid value for naming artifacts.
userid = ''
tabular_dataset_name = 'diabetes-data... | _____no_output_____ | MIT | workshops/workshop1/code/Visual Designer Data Prep Pipeline.ipynb | samleung314/mslearn-dp100 |
Step 2: Create target datasetsRegister datasets to use as targets for writing data from pipeline. | diabetes_ds = Dataset.Tabular.from_delimited_files(path=(datastore,'1-bronze/diabetes/' + userid + '/diabetes.csv'),validate=False,infer_column_types=False)
diabetes_ds.register(ws,name=tabular_dataset_name,create_new_version=True)
diabetes_ds = Dataset.Tabular.from_delimited_files(path=(datastore,'1-bronze/diabetes/'... | _____no_output_____ | MIT | workshops/workshop1/code/Visual Designer Data Prep Pipeline.ipynb | samleung314/mslearn-dp100 |
Steps for Handling the missing value1. Import Libraries2. Load data3. Seprate Input and Output attributes4. Find the missing values and handle it in either way a. Removing data b. Imputation | # Step 1: Import Libraries
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
# Step 2: Load Data
datasets = pd.read_csv('./Datasets/Data_for_Missing_Values.csv')
print("\nData :\n",datasets)
print("\nData statistics\n",datasets.describe())
# Step 3: Seprate Input an... |
New Input with Mean Value for NaN :
[['France' 44.0 72000.0]
['Spain' 27.0 48000.0]
['Germany' 30.0 54000.0]
['Spain' 38.0 61000.0]
['Germany' 40.0 62900.0]
['France' 35.0 58000.0]
['Spain' 39.4 52000.0]
['France' 48.0 79000.0]
['Germany' 50.0 83000.0]
['France' 37.0 67000.0]
['Spain' 45.0 55000.0]]
| MIT | Lab-2/3HandlingMissingValues.ipynb | yash-a-18/002_YashAmethiya |
Overview `clean_us_data.ipynb`: Fix data inconsistencies in the raw time series data from [`etl_us_data.ipynb`](./etl_us_data.ipynb).Inputs:* `outputs/us_counties.csv`: Raw county-level time series data for the United States, produced by running [etl_us_data.ipynb](./etl_us_data.ipynb)* `outputs/us_counties_meta.json`... | # Initialization boilerplate
import os
import json
import pandas as pd
import numpy as np
import scipy.optimize
import sklearn.metrics
import matplotlib.pyplot as plt
from typing import *
import text_extensions_for_pandas as tp
# Local file of utility functions
import util
# Allow environment variables to override... | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Read the CSV file from `etl_us_data.ipynb` and apply the saved type information | csv_file = os.path.join(_OUTPUTS_DIR, "us_counties.csv")
meta_file = os.path.join(_OUTPUTS_DIR, "us_counties_meta.json")
# Read column type metadata
with open(meta_file) as f:
cases_meta = json.load(f)
# Pandas does not currently support parsing datetime64 from CSV files.
# As a workaround, read the "Date" column... | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Replace missing values in the secondary datasets with zeros | for colname in ("Confirmed_NYT", "Deaths_NYT", "Confirmed_USAFacts", "Deaths_USAFacts"):
cases_vertical[colname].fillna(0, inplace=True)
cases_vertical[colname] = cases_vertical[colname].astype("int64")
cases_vertical | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Collapse each time series down to a single cellThis kind of time series data is easier to manipulate at the macroscopic level if each time series occupies a single cell of the DataFrame. We use the [TensorArray](https://text-extensions-for-pandas.readthedocs.io/en/latest/text_extensions_for_pandas.TensorArray) Pandas ... | cases, dates = util.collapse_time_series(cases_vertical, ["Confirmed", "Deaths", "Recovered",
"Confirmed_NYT", "Deaths_NYT",
"Confirmed_USAFacts", "Deaths_USAFacts"])
cases
# Note that the previous cell ... | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Correct for missing data for today in USAFacts dataThe USAFacts database only receives the previous day's updates late in the day,so it's often missing the last value. Substitute the previous day's value ifthat is the case. | # Last 10 days of the time series for the Bronx before this change
cases.loc[bronx_fips]["Deaths_USAFacts"].to_numpy()[-10:]
# last element <-- max(last element, second to last)
new_confirmed = cases["Confirmed_USAFacts"].to_numpy().copy()
new_confirmed[:, -1] = np.maximum(new_confirmed[:, -1], new_confirmed[:, -2])
ca... | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Validate the New York City confirmed cases dataOlder versions of the Johns Hopkins data coded all of New York city as beingin New York County. Each borough is actually in a different countywith a different FIPS code.Verify that this problem hasn't recurred. | max_bronx_confirmed = np.max(cases.loc[36005]["Confirmed"])
if max_bronx_confirmed == 0:
raise ValueError(f"Time series for the Bronx is all zeros again:\n{cases.loc[36005]['Confirmed']}")
max_bronx_confirmed | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Also plot the New York City confirmed cases time series to allow for manual validation. | new_york_county_fips = 36061
nyc_fips = [
36005, # Bronx County
36047, # Kings County
new_york_county_fips, # New York County
36081, # Queens County
36085, # Richmond County
]
util.graph_examples(cases.loc[nyc_fips], "Confirmed", {}, num_to_pick=5) | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Adjust New York City deaths dataPlot deaths for New York City in the Johns Hopkins data set. The jump in June is due to a change in reporting. | util.graph_examples(cases.loc[nyc_fips], "Deaths", {}, num_to_pick=5) | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
New York Times version of the time series for deaths in New York city: | util.graph_examples(cases.loc[nyc_fips], "Deaths_NYT", {}, num_to_pick=5) | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
USAFacts version of the time series for deaths in New York city: | util.graph_examples(cases.loc[nyc_fips], "Deaths_USAFacts", {}, num_to_pick=5) | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Currently the USAFacts version is cleanest, so we use that one. | new_deaths = cases["Deaths"].copy(deep=True)
for fips in nyc_fips:
new_deaths.loc[fips] = cases["Deaths_USAFacts"].loc[fips]
cases["Deaths"] = new_deaths
print("After:")
util.graph_examples(cases.loc[nyc_fips], "Deaths", {}, num_to_pick=5) | After:
| Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Clean up the Rhode Island dataThe Johns Hopkins data reports zero deaths in most of Rhode Island. Use the secondary data set from the New York Times for Rhode Island. | print("Before:")
util.graph_examples(cases, "Deaths", {}, num_to_pick=8,
mask=(cases["State"] == "Rhode Island"))
# Use our secondary data set for all Rhode Island data.
ri_fips = cases[cases["State"] == "Rhode Island"].index.values.tolist()
for colname in ["Confirmed", "Deaths"]:
new_series = ... | After:
| Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Clean up the Utah dataThe Johns Hopkins data for Utah is missing quite a few data points.Use the New York Times data for Utah. | print("Before:")
util.graph_examples(cases, "Confirmed", {}, num_to_pick=8,
mask=(cases["State"] == "Utah"))
# The Utah time series from the New York Times' data set are more
# complete, so we use those numbers.
ut_fips = cases[cases["State"] == "Utah"].index.values
for colname in ["Confirmed", "D... | After:
| Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Flag additional problematic and missing data pointsUse heuristics to identify and flag problematic data points across all the time series. Generate Boolean masks that show the locations of theseoutliers. | # Now we're done with the secondary data set, so drop its columns.
cases = cases.drop(columns=["Confirmed_NYT", "Deaths_NYT", "Confirmed_USAFacts", "Deaths_USAFacts"])
cases
# Now we need to find and flag obvious data-entry errors.
# We'll start by creating columns of "is outlier" masks.
# We use integers instead of Bo... | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Flag time series that go from zero to nonzero and back againOne type of anomaly that occurs fairly often involves a time seriesjumping from zero to a nonzero value, then back to zero again.Locate all instances of that pattern and mark the nonzero valuesas outliers. | def nonzero_then_zero(series: np.array):
empty_mask = np.zeros_like(series, dtype=np.int8)
if series[0] > 0:
# Special case: first value is nonzero
return empty_mask
first_nonzero_offset = 0
while first_nonzero_offset < len(series):
if series[first_nonzero_offset] > 0:
... | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Flag time series that drop to zero, then go back upAnother type of anomaly involves the time series dropping down to zero, then going up again. Since all three time series are supposedto be cumulative counts, this pattern most likely indicates missingdata.To correct for this problem, we mark any zero values after thef... | def zeros_after_first_nonzero(series: np.array, outliers: np.array):
nonzero_mask = (series != 0)
nonzero_and_not_outlier = nonzero_mask & (~outliers)
first_nonzero = np.argmax(nonzero_and_not_outlier)
if 0 == first_nonzero and series[0] == 0:
# np.argmax(nonzero_mask) will return 0 if there are... | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Precompute totals for the last 7 daysSeveral of the notebooks downstream of this one need the number of cases and deathsfor the last 7 days, so we compute those values here for convenience. | def last_week_results(s: pd.Series):
arr = s.to_numpy()
today = arr[:,-1]
week_ago = arr[:,-8]
return today - week_ago
cases["Confirmed_7_Days"] = last_week_results(cases["Confirmed"])
cases["Deaths_7_Days"] = last_week_results(cases["Deaths"])
cases.head() | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Write out cleaned time series dataBy default, output files go to the `outputs` directory. You can use the `COVID_OUTPUTS_DIR` environment variable to override that location. CSV outputComma separated value (CSV) files are a portable text-base format supported by a wide varietyof different tools. The CSV format does n... | # Break out our time series into multiple rows again for writing to disk.
cleaned_cases_vertical = util.explode_time_series(cases, dates)
cleaned_cases_vertical
# The outlier masks are stored as integers as a workaround for a Pandas
# bug. Convert them to Boolean values for writing to disk.
cleaned_cases_vertical["Conf... | Writing cleaned data to outputs/us_counties_clean.csv
| Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Feather outputThe [Feather](https://arrow.apache.org/docs/python/feather.html) file format supportsfast binary I/O over any data that can be represented using [Apache Arrow](https://arrow.apache.org/)Feather files also include schema and type information. | # Also write out the nested data in Feather format so that downstream
# notebooks don't have to re-nest it.
# No Feather serialization support for Pandas indices currently, so convert
# the index on FIPS code to a normal column
cases_for_feather = cases.reset_index()
cases_for_feather.head()
# Write to Feather and make... | _____no_output_____ | Apache-2.0 | notebooks/clean_us_data.ipynb | itsrawlinz-jeff/COVID19_VISUALIZATION-R_JEFF |
Comparing Gravitational waveforms to each other | # Install the software we need
import sys
!{sys.executable} -m pip install pycbc lalsuite ligo-common --no-cache-dir
%matplotlib inline
# We learn about the potential parameters of a source by comparing it to many different waveforms
# each of which represents a possible source with different properties.
import pylab
... | _____no_output_____ | MIT | PyCBC-Tutorials-master/examples/waveform_similarity.ipynb | basuparth/ICERM_Workshop |
___ ___ Scikit-learn Primer**Scikit-learn** (http://scikit-learn.org/) is an open-source machine learning library for Python that offers a variety of regression, classification and clustering algorithms.In this section we'll perform a fairly simple classification exercise with scikit-learn. In the next section we'll l... | import numpy as np
import pandas as pd
df = pd.read_csv('../TextFiles/smsspamcollection.tsv', sep='\t')
df.head()
len(df) | _____no_output_____ | Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
Check for missing values:Machine learning models usually require complete data. | df.isnull().sum() | _____no_output_____ | Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
Take a quick look at the *ham* and *spam* `label` column: | df['label'].unique()
df['label'].value_counts() | _____no_output_____ | Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
We see that 4825 out of 5572 messages, or 86.6%, are ham.This means that any machine learning model we create has to perform **better than 86.6%** to beat random chance. Visualize the data:Since we're not ready to do anything with the message text, let's see if we can predict ham/spam labels based on message length an... | df['length'].describe() | _____no_output_____ | Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
This dataset is extremely skewed. The mean value is 80.5 and yet the max length is 910. Let's plot this on a logarithmic x-axis. | import matplotlib.pyplot as plt
%matplotlib inline
plt.xscale('log')
bins = 1.15**(np.arange(0,50))
plt.hist(df[df['label']=='ham']['length'],bins=bins,alpha=0.8)
plt.hist(df[df['label']=='spam']['length'],bins=bins,alpha=0.8)
plt.legend(('ham','spam'))
plt.show() | _____no_output_____ | Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
It looks like there's a small range of values where a message is more likely to be spam than ham.Now let's look at the `punct` column: | df['punct'].describe()
plt.xscale('log')
bins = 1.5**(np.arange(0,15))
plt.hist(df[df['label']=='ham']['punct'],bins=bins,alpha=0.8)
plt.hist(df[df['label']=='spam']['punct'],bins=bins,alpha=0.8)
plt.legend(('ham','spam'))
plt.show() | _____no_output_____ | Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
This looks even worse - there seem to be no values where one would pick spam over ham. We'll still try to build a machine learning classification model, but we should expect poor results. ___ Split the data into train & test sets:If we wanted to divide the DataFrame into two smaller sets, we could use> `train, test = t... | # Create Feature and Label sets
X = df[['length','punct']] # note the double set of brackets
y = df['label'] | _____no_output_____ | Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
Additional train/test/split arguments:The default test size for `train_test_split` is 30%. Here we'll assign 33% of the data for testing.Also, we can set a `random_state` seed value to ensure that everyone uses the same "random" training & testing sets. | from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
print('Training Data Shape:', X_train.shape)
print('Testing Data Shape: ', X_test.shape) | Training Data Shape: (3733, 2)
Testing Data Shape: (1839, 2)
| Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.