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 |
|---|---|---|---|---|---|
Test the Endpoint | runtime_client = boto3.client('runtime.sagemaker')
test_input = test.drop(columns=[target])[0:10]
test_input_csv = test_input.to_csv(index=False, header=False).split('\n')
test_labels = test[target][0:10]
for i, (single_test, single_label) in enumerate(zip(test_input_csv, test_labels)):
print('=== Test {} ===\n... | _____no_output_____ | Apache-2.0 | sagemaker/1_fill_missing_values.ipynb | awslabs/filling-in-missing-values-in-tabular-records |
Define new problem type and data reading functionWe'll use IMDB dataset as example | import tensorflow as tf
from tensorflow import keras
cd ../
from bert_multitask_learning import (get_or_make_label_encoder, FullTokenizer,
create_single_problem_generator, train_bert_multitask,
eval_bert_multitask, DynamicBatchSizeParams, TRAIN... | _____no_output_____ | MIT | notebooks/Run Self Defined Problem.ipynb | zsweet/bert-multitask-learning |
Train ModelPlease make sure you're using the correct checkpoint to initialize model. | params = DynamicBatchSizeParams()
params.init_checkpoint = 'models/cased_L-12_H-768_A-12'
tf.logging.set_verbosity(tf.logging.DEBUG)
train_bert_multitask(problem='imdb_cls', num_gpus=1,
num_epochs=10, params=params,
problem_type_dict=new_problem_type, processing_fn_dict=new_p... | Adding new problem imdb_cls, problem type: cls
INFO:tensorflow:Device is available but not used by distribute strategy: /device:CPU:0
INFO:tensorflow:Device is available but not used by distribute strategy: /device:XLA_CPU:0
INFO:tensorflow:Device is available but not used by distribute strategy: /device:XLA_GPU:0
INFO... | MIT | notebooks/Run Self Defined Problem.ipynb | zsweet/bert-multitask-learning |
Evaluate Model | print(eval_bert_multitask(problem='imdb_cls', num_gpus=1,
params=params, eval_scheme='acc',
problem_type_dict=new_problem_type, processing_fn_dict=new_problem_process_fn_dict)) | Params problem assigned. Problem list: ['imdb_cls']
INFO:tensorflow:Device is available but not used by distribute strategy: /device:CPU:0
INFO:tensorflow:Device is available but not used by distribute strategy: /device:XLA_CPU:0
INFO:tensorflow:Device is available but not used by distribute strategy: /device:XLA_GPU:0... | MIT | notebooks/Run Self Defined Problem.ipynb | zsweet/bert-multitask-learning |
Imports Import Libraries | import tarfile
import pandas as pd
import os
from google.colab import drive
drive.mount('/content/drive') | Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
| MIT | Developing_ipynb/project4.ipynb | chuchun2/ATMS-597-Project-4-Group-C |
Set Your Directory | YOUR_DIRECTORY = '/content/drive/My Drive/Colab Notebooks/ATMS597/project4/' | _____no_output_____ | MIT | Developing_ipynb/project4.ipynb | chuchun2/ATMS-597-Project-4-Group-C |
Import GFS data and save to pd.DataFrame | daily = tarfile.open(name = YOUR_DIRECTORY + 'daily.tar.gz') # Set the archive for opening
# Aggregate to PD DataFrame
cur_file = daily.next() # Initiate while loop using the first file in the tar archive
daily_gfs = pd.DataFrame(columns=['TMAX', 'TMIN', 'WMAX', 'RTOT'])
i = 0
while cur_file != None:
i += 1
if... | _____no_output_____ | MIT | Developing_ipynb/project4.ipynb | chuchun2/ATMS-597-Project-4-Group-C |
Import obs daily data | daily_obs = pd.read_csv(YOUR_DIRECTORY + 'KCMI_daily.csv', header=4, usecols=[0,1,2,3,4])
daily_obs
| _____no_output_____ | MIT | Developing_ipynb/project4.ipynb | chuchun2/ATMS-597-Project-4-Group-C |
Osnabrück University - Machine Learning (Summer Term 2018) - Prof. Dr.-Ing. G. Heidemann, Ulf Krumnack Exercise Sheet 06 IntroductionThis week's sheet should be solved and handed in before the end of **Sunday, May 20, 2018**. If you need help (and Google and other resources were not enough), feel free to contact your... | %matplotlib notebook
import numpy as np
import numpy.random as rnd
import matplotlib.colors as mplc
import matplotlib.pyplot as plt
from numpy.random import multivariate_normal as multNorm
from scipy.cluster.vq import kmeans, vq
from sklearn.decomposition.pca import PCA
def pdist2(x, y):
"""
Pairwise distan... | _____no_output_____ | MIT | sheet_06/sheet_06_machine-learning.ipynb | ArielMant0/ml2018 |
Assignment 2: Data Visualization and Chernoff Faces (6 Points) The following exercise contains no programming (unless you want to go through the implementation). Answer the questions that are posted below the code segment (and run the code before - it's really worth it!). In case you are even more interested - here is... | %matplotlib notebook
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Arc
from numpy.random import rand
import numpy as np
def cface(ax, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18):
"""
This implementation of chernov faces is taken from Abraham Flaxm... | _____no_output_____ | MIT | sheet_06/sheet_06_machine-learning.ipynb | ArielMant0/ml2018 |
a) Data Visualization TechniquesWhy do we need data visualization techniques and what are techniques to visualize high dimensional data? Automated analysis of high-dimensional data is rarely possible, but humans have remarkable pattern recognition abilities, so visualizing data for humans to analyze is an important fi... | # Initialization
condition_db = [{"food": 1, "bell": 0},
{"food": 0, "bell": 1},
{"food": 1, "bell": 1}]
trials = [0, 1, 2, 2, 1, 2, 1]
epsilon = 0.2
theta = 1/2
responses = []
weight_food = [1]
weight_bell = [0]
def calc_response(sample):
if weight_food[-1]*sample["food"] + wei... | | Food | | 1| | 0| | 1| | 1| | 0| | 1| | 0| |
| Bell | | 0| | 1| | 1| | 1| | 1| | 1| | 1| |
| Saliva | | 1| | 0| | 1| | 1| | 0| | 1| | 1| |
| w_Food |1.0| |1.2| |1.2| |1.4| |1.6| |1.6| |1.8| |1.8|
| w_Bell |0.0| |0.0| |0.0| |0.... | MIT | sheet_06/sheet_06_machine-learning.ipynb | ArielMant0/ml2018 |
Fancyarrow Demo | import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
styles = mpatches.ArrowStyle.get_styles()
ncol = 2
nrow = (len(styles) + 1) // ncol
figheight = (nrow + 0.5)
fig = plt.figure(figsize=(4 * ncol / 1.5, figheight / 1.5))
fontsize = 0.2 * 70
ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect=1.)... | _____no_output_____ | MIT | matplotlib/gallery_jupyter/text_labels_and_annotations/fancyarrow_demo.ipynb | kingreatwill/penter |
------------References""""""""""The use of the following functions, methods, classes and modules is shownin this example: | import matplotlib
matplotlib.patches
matplotlib.patches.ArrowStyle
matplotlib.patches.ArrowStyle.get_styles
matplotlib.axes.Axes.annotate | _____no_output_____ | MIT | matplotlib/gallery_jupyter/text_labels_and_annotations/fancyarrow_demo.ipynb | kingreatwill/penter |
Apple Health Extractor This code will parse your Apple Health export data, create multiple CSV and do some simple data checks and data analysis. Enjoy! -------- Extract Data and Export to CSVs from Apple Health's Export.xml * Command Line Tool to Process apple health's export.xml file * Create multiple CSV files for... | # %run -i 'apple-health-data-parser' 'export.xml'
%run -i 'apple-health-data-parser' 'data/export.xml' | Reading data from data/export.xml . . . done
Unexpected node of type ExportDate.
Tags:
ActivitySummary: 145
ExportDate: 1
Me: 1
Record: 291418
Workout: 11
Fields:
HKCharacteristicTypeIdentifierBiologicalSex: 1
HKCharacteristicTypeIdentifierBloodType: 1
HKCharacteristicTypeIdentifierCardioFitnessMedicationsUse: 1
HKCh... | MIT | apple_health/apple_health_extractor.ipynb | LeooDong/health_monitoring |
----- Apple Health Data Check and Simple Data Analysis | import numpy as np
import pandas as pd
import glob | _____no_output_____ | MIT | apple_health/apple_health_extractor.ipynb | LeooDong/health_monitoring |
---- Weight | weight = pd.read_csv("data/BodyMass.csv")
weight.tail()
weight.describe() | _____no_output_____ | MIT | apple_health/apple_health_extractor.ipynb | LeooDong/health_monitoring |
---- Steps | steps = pd.read_csv("data/StepCount.csv")
len(steps)
steps.columns
steps.describe()
steps.tail()
# total all-time steps
steps.value.sum() | _____no_output_____ | MIT | apple_health/apple_health_extractor.ipynb | LeooDong/health_monitoring |
------- Stand Count | stand = pd.read_csv("data/AppleStandHour.csv")
len(stand)
stand.columns
stand.describe()
stand.tail() | _____no_output_____ | MIT | apple_health/apple_health_extractor.ipynb | LeooDong/health_monitoring |
------ Resting Heart Rate (HR) | restingHR = pd.read_csv("data/RestingHeartRate.csv")
len(restingHR)
restingHR.describe() | _____no_output_____ | MIT | apple_health/apple_health_extractor.ipynb | LeooDong/health_monitoring |
--- Walking Heart Rate (HR) Average | walkingHR = pd.read_csv("data/WalkingHeartRateAverage.csv")
len(walkingHR)
walkingHR.describe() | _____no_output_____ | MIT | apple_health/apple_health_extractor.ipynb | LeooDong/health_monitoring |
--- Heart Rate Variability (HRV) | hrv = pd.read_csv("data/HeartRateVariabilitySDNN.csv")
len(hrv)
hrv.columns
hrv.describe()
hrv.tail() | _____no_output_____ | MIT | apple_health/apple_health_extractor.ipynb | LeooDong/health_monitoring |
------- VO2 Max | vo2max = pd.read_csv("data/VO2Max.csv")
len(vo2max)
vo2max.describe() | _____no_output_____ | MIT | apple_health/apple_health_extractor.ipynb | LeooDong/health_monitoring |
---- Blood Pressure | diastolic = pd.read_csv("data/BloodPressureDiastolic.csv")
systolic = pd.read_csv("data/BloodPressureSystolic.csv")
diastolic.describe()
systolic.describe() | _____no_output_____ | MIT | apple_health/apple_health_extractor.ipynb | LeooDong/health_monitoring |
------ Sleep | sleep = pd.read_csv("data/SleepAnalysis.csv")
sleep.tail()
sleep.describe() | _____no_output_____ | MIT | apple_health/apple_health_extractor.ipynb | LeooDong/health_monitoring |
Causal GamesCausal Inference is a new feature for pgmpy, so I wanted to develop a few examples which show off the features that we're developing! This particular notebook walks through the 5 games that used as examples for building intuition about backdoor paths in *The Book of Why* by Judea Peal. I have consistently... | import sys
!pip3 install -q daft
import matplotlib.pyplot as plt
%matplotlib inline
import daft
from daft import PGM
# We can now import the development version of pgmpy
from pgmpy.models.BayesianModel import BayesianModel
from pgmpy.inference.CausalInference import CausalInference
def convert_pgm_to_pgmpy(pgm):
... | Are there are active backdoor paths? True
If so, what's the possible backdoor adjustment sets? frozenset({frozenset({'B'})})
Ehat's the possible front adjustment sets? frozenset({frozenset({'A'})})
| MIT | examples/Causal Games.ipynb | arpan0317/pgmpy |
Matplotlib - Gráfico de linha - Parte 3 * Parte 3: Tipo da linha * Importando bibliotecas | import numpy as np
import matplotlib.pyplot as plt | _____no_output_____ | MIT | Data_Science/Matplotlib/2D/2D_Linha_Parte_3.ipynb | maledicente/cursos |
* Criando variável X | X = np.linspace(0,5,11) | _____no_output_____ | MIT | Data_Science/Matplotlib/2D/2D_Linha_Parte_3.ipynb | maledicente/cursos |
* Criando funções Y(X) e Z(X) | Y = np.power(X-2,2.0)
Z = np.exp(X/2.0) | _____no_output_____ | MIT | Data_Science/Matplotlib/2D/2D_Linha_Parte_3.ipynb | maledicente/cursos |
* Gráfico de Y e Z em função de X | plt.plot(X,Y,label='Y(X)')
plt.plot(X,Z,label='Z(X)')
plt.xlabel('Eixo X')
plt.ylabel('Eixo Y')
plt.show() | _____no_output_____ | MIT | Data_Science/Matplotlib/2D/2D_Linha_Parte_3.ipynb | maledicente/cursos |
* Alterando linha da função Z(X) | plt.plot(X,Y,label='Y(X)')
plt.plot(X,Z,label='Z(X)',linestyle='--')
plt.xlabel('Eixo X')
plt.ylabel('Eixo Y')
plt.show() | _____no_output_____ | MIT | Data_Science/Matplotlib/2D/2D_Linha_Parte_3.ipynb | maledicente/cursos |
* Usando nomes para os tipos de linhas | plt.plot(X,Y,label='Y(X)', linestyle='dashed')
plt.plot(X,Z,label='Z(X)',linestyle='dashdot')
plt.xlabel('Eixo X')
plt.ylabel('Eixo Y')
plt.show()
plt.plot(X,Y,label='Y(X)', linestyle='solid')
plt.plot(X,Z,label='Z(X)',linestyle='dotted')
plt.xlabel('Eixo X')
plt.ylabel('Eixo Y')
plt.show() | _____no_output_____ | MIT | Data_Science/Matplotlib/2D/2D_Linha_Parte_3.ipynb | maledicente/cursos |
Define classes and how many trials per class | C_OVR = [0,1] #MI classes, [0,1,2,3] for left hand, right hand, feet, tongue
_classes = C_OVR*10 #*trials per MI class
random.shuffle(_classes) #randomize sequence of MI classes
fileroot = 'E:\\Diamond\\own_expo\\'
filewrite = open(fileroot + 'record.txt','w')
filewrite.write('')
filewrite.close()
file_cross = ope... | _____no_output_____ | BSD-2-Clause | data_collect/eeg_data_collect_tcp_tag_openvibe.ipynb | s151202/EEG_data_streaming |
Bounding Box Visualizer | try:
import cv2
except ImportError:
cv2 = None
COLORS = [
"#6793be", "#990000", "#00ff00", "#ffbcc9", "#ffb9c7", "#fdc6d1",
"#fdc9d3", "#6793be", "#73a4d4", "#9abde0", "#9abde0", "#8fff8f", "#ffcfd8", "#808080", "#808080",
"#ffba00", "#6699ff", "#009933", "#1c1c1c", "#08375f", "#116ebf", "#e61d35",... | _____no_output_____ | MIT | notebooks/tensorflow-yolo/util_visualization.ipynb | pcrete/SKIL_demo |
Chapter 8 Lists 8.1 A list is a sequence | # list of integers
[10, 20, 30, 40]
# list of strings
['frog','toad','salamander','newt']
# mixed list
[10,'twenty',30.0,[40, 45]]
cheeses = ['Cheddar','Mozzarella','Gouda','Swiss']
numbers = [27, 42]
empty = []
print(cheeses, numbers, empty) | ['Cheddar', 'Mozzarella', 'Gouda', 'Swiss'] [27, 42] []
| BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.2 Lists are mutable | numbers = [27, 62]
numbers[1] = 42
print(numbers)
cheeses = ['Cheddar','Mozzarella','Gouda','Swiss']
'Swiss' in cheeses
'Brie' in cheeses | _____no_output_____ | BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.3 Traversing a list | cheeses = ['Cheddar','Mozzarella','Gouda','Swiss']
for cheese in cheeses:
print(cheese)
numbers = [10, 20, 30, 40]
for i in range(len(numbers)):
numbers[i] = numbers[i] + 2
print(numbers)
empty = []
for x in empty:
print('This never happens.')
len(['spam', 1, ['sun','moon','stars'], [1,2,3]]) | _____no_output_____ | BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.4 List operations | a = [1,2,3]
b = [4,5,6]
c = a + b
print(c)
[0]*4
[1,2,3]*3 | _____no_output_____ | BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.5 List slices | t = ['a','b','c','d','e','f']
t[1:3]
t[:4]
t[3:]
t[:]
t[1:3] = ['x','y']
print(t) | ['a', 'x', 'y', 'd', 'e', 'f']
| BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.6 List methods | t = ['a','b','c']
t.append('d')
print(t)
t1 = ['a','b','c']
t2 = ['d','e']
t1.extend(t2)
print(t1)
t = ['d','c','e','b','a']
t.sort()
print(t) | ['a', 'b', 'c', 'd', 'e']
| BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.7 Deleting elements | t = ['a','b','c']
x = t.pop(1)
print(t)
print(x)
t = ['a','b','c']
del t[1]
print(t)
t = ['a','b','c']
x = t.remove('b')
print(t)
t = ['a','b','c','b']
x = t.remove('b') #removes first instance
print(t)
t = ['a', 'b', 'c', 'd', 'e','f']
del t[1:5]
print(t) | ['a', 'f']
| BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.8 Lists and functions | nums = [3, 41, 12, 9, 74, 15]
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
print(sum(nums)/len(nums))
numlist = list()
while(True):
inp = input('Enter a number: ')
if inp == 'done': break
try:
value = float(inp)
numlist.append(value)
except:
print('That... | Enter a number: 4
Enter a number: 565
Enter a number: fg
| BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.9 Lists and strings | s = 'spam'
t = list(s)
print(t)
s = 'That there’s some good in this world, Mr. Frodo… and it’s worth fighting for.'
t = s.split()
print(t)
print(t[3])
s = 'spam-spam-spam'
delimiter = '-'
s.split(delimiter)
t = ['That', 'there’s', 'some', 'good', 'in', 'this', 'world,', 'Mr.', 'Frodo…', 'and', 'it’s', 'worth', 'fightin... | _____no_output_____ | BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.10 Parsing lines | fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From '): continue
words = line.split()
print(words[2]) | Sat
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Fri
Thu
Thu
Thu
Thu
Thu
Thu
| BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.11 Objects and values | # same object, two variables pointing to the same object
a = 'banana'
b = 'banana'
a is b
# same value because a and b point to the same object
a == b
# two separate objects
a = [1,2,3]
b = [1,2,3]
a is b
# same value
a == b | _____no_output_____ | BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.12 Aliasing | # b points to the same object as a
a = [1,2,3]
b = a
b is a
b[0] = 17
print(a) | [17, 2, 3]
| BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
8.13 List arguments | def delete_head(t):
del t[0]
letters = ['a','b','c']
delete_head(letters)
print(letters)
t1 = [1,2]
t2 = t1.append(3)
print(t1)
print(t2)
t1 = [1,2]
t3 = t1 + [3]
print(t3)
# changes t within the scope of the function but not
# the value of the variable passed to it
def bad_delete_head(t):
t = t[1:]
def tail(t... | ['b', 'c']
| BSD-3-Clause | 08-lists.ipynb | trailmarkerlib/dataExplore |
Fibonacci RabbitsFibonacci considers the growth of an idealized (biologically unrealistic) rabbit population, assuming that:1. A single newly born pair of rabbits (one male, one female) are put in a field;2. Rabbits are able to mate at the age of one month so that at the end of its second month a female can produce an... | def populate_iterative(remaining_months, infant_num = 2, mature_num = 0, month_count = 0):
"""
This function calculates the population of infant and mature rabbit population of
Fibonacci rabbits after a given amount of time(remaining_months) by utilizing a
while loop. The function assumes there is an in... | 7.86 µs ± 520 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
| MIT | mk003-fibonacci_rabbits.ipynb | karakose77/intro-to-cs-and-programming-in-python-exercises |
Analyze Data Quality with SageMaker Processing Jobs and SparkTypically a machine learning (ML) process consists of few steps. First, gathering data with various ETL jobs, then pre-processing the data, featurizing the dataset by incorporating standard techniques or prior knowledge, and finally training an ML model usin... | ingest_create_athena_table_tsv = False
%store -r ingest_create_athena_table_tsv
if not ingest_create_athena_table_tsv:
print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
print('[ERROR] YOU HAVE TO RUN THE NOTEBOOKS IN THE INGEST FOLDER FIRST.')
print('++++++++++++++++++++++++++++++++... | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Pull the Spark-Deequ Docker Image | public_image_uri='docker.io/datascienceonaws/spark-deequ:1.0.0'
!docker pull $public_image_uri | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Push the Image to a Private Docker Repo | private_docker_repo = 'spark-deequ'
private_docker_tag = '1.0.0'
import boto3
account_id = boto3.client('sts').get_caller_identity().get('Account')
region = boto3.session.Session().region_name
private_image_uri = '{}.dkr.ecr.{}.amazonaws.com/{}:{}'.format(account_id, region, private_docker_repo, private_docker_tag)
pr... | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Ignore `spark-deequ does not exist` error below | !aws ecr describe-repositories --repository-names $private_docker_repo || aws ecr create-repository --repository-name $private_docker_repo | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Ignore ^^ `spark-deequ does not exist` ^^ error above | !docker push $private_image_uri | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Run the Analysis Job using a SageMaker Processing JobNext, use the Amazon SageMaker Python SDK to submit a processing job. Use the Spark container that was just built with our Spark script. Review the Spark preprocessing script. | !pygmentize preprocess-deequ.py
!pygmentize preprocess-deequ.scala
from sagemaker.processing import ScriptProcessor
processor = ScriptProcessor(base_job_name='spark-amazon-reviews-analyzer',
image_uri=private_image_uri,
command=['/opt/program/submit'],
... | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Setup Output Data | from time import gmtime, strftime
timestamp_prefix = strftime("%Y-%m-%d-%H-%M-%S", gmtime())
output_prefix = 'amazon-reviews-spark-analyzer-{}'.format(timestamp_prefix)
processing_job_name = 'amazon-reviews-spark-analyzer-{}'.format(timestamp_prefix)
print('Processing job name: {}'.format(processing_job_name))
s3_ou... | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Start the Spark Processing Job_Notes on Invoking from Lambda:_* However, if we use the boto3 SDK (ie. with a Lambda), we need to copy the `preprocess.py` file to S3 and specify the everything include --py-files, etc.* We would need to do the following before invoking the Lambda: !aws s3 cp preprocess.py s3:///sage... | from sagemaker.processing import ProcessingOutput
processor.run(code='preprocess-deequ.py',
arguments=['s3_input_data', s3_input_data,
's3_output_analyze_data', s3_output_analyze_data,
],
# See https://github.com/aws/sagemaker-python-sdk/issues/1341
... | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Monitor the Processing Job | running_processor = sagemaker.processing.ProcessingJob.from_processing_name(processing_job_name=processing_job_name,
sagemaker_session=sagemaker_session)
processing_job_description = running_processor.describe()
print(processing_job_descripti... | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
_Please Wait Until the ^^ Processing Job ^^ Completes Above._ Inspect the Processed Output These are the quality checks on our dataset. _The next cells will not work properly until the job completes above._ | !aws s3 ls --recursive $s3_output_analyze_data/ | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Copy the Output from S3 to Local* dataset-metrics/* constraint-checks/* success-metrics/* constraint-suggestions/ | !aws s3 cp --recursive $s3_output_analyze_data ./amazon-reviews-spark-analyzer/ --exclude="*" --include="*.csv" | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Analyze Constraint Checks | import glob
import pandas as pd
import os
def load_dataset(path, sep, header):
data = pd.concat([pd.read_csv(f, sep=sep, header=header) for f in glob.glob('{}/*.csv'.format(path))], ignore_index = True)
return data
df_constraint_checks = load_dataset(path='./amazon-reviews-spark-analyzer/constraint-checks/', ... | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Analyze Dataset Metrics | df_dataset_metrics = load_dataset(path='./amazon-reviews-spark-analyzer/dataset-metrics/', sep='\t', header=0)
df_dataset_metrics | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Analyze Success Metrics | df_success_metrics = load_dataset(path='./amazon-reviews-spark-analyzer/success-metrics/', sep='\t', header=0)
df_success_metrics | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Analyze Constraint Suggestions | df_constraint_suggestions = load_dataset(path='./amazon-reviews-spark-analyzer/constraint-suggestions/', sep='\t', header=0)
df_constraint_suggestions.columns=['column_name', 'description', 'code']
df_constraint_suggestions | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
Save for the Next Notebook(s) | %store df_dataset_metrics
%%javascript
Jupyter.notebook.save_checkpoint();
Jupyter.notebook.session.delete(); | _____no_output_____ | Apache-2.0 | 05_explore/spark/98_Analyze_Data_Quality_ProcessingJob_Spark_BYOC.ipynb | MarcusFra/workshop |
CASE - Observation data - analysis> *© 2021, Joris Van den Bossche and Stijn Van Hoey (, ). Licensed under [CC BY 4.0 Creative Commons](http://creativecommons.org/licenses/by/4.0/)*--- | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-whitegrid') | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
1. Reading in the enriched observations data **EXERCISE**- Read in the `survey_data_completed.csv` file and save the resulting `DataFrame` as variable `survey_data_processed` (if you did not complete the previous notebook, a version of the csv file is available in the `data` folder).- Interpret the 'eventDate' column ... | survey_data_processed = pd.read_csv("data/survey_data_completed.csv",
parse_dates=['eventDate'], index_col="occurrenceID")
survey_data_processed.head()
survey_data_processed.info() | <class 'pandas.core.frame.DataFrame'>
Int64Index: 35550 entries, 1 to 35550
Data columns (total 19 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 verbatimLocality 35550 non-null int64
1 verbatimSex 33042 non-null object ... | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
2. Tackle missing values (NaN) and duplicate values See [pandas_08_missing_values.ipynb](pandas_08_missing_values.ipynb) for an overview of functionality to work with missing values. **EXERCISE**How many records in the data set have no information about the `species`? Use the `isna()` method to find out.Hints- Do NOT ... | survey_data_processed['species'].isna().sum() | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**How many duplicate records are present in the dataset? Use the method `duplicated()` to check if a row is a duplicate.Hints- The result of an (element-wise) condition returns a set of True/False values, corresponding to 1/0 values. The amount of True values is equal to the sum. | survey_data_processed.duplicated().sum() | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**- Select all duplicate data by filtering the `observations` data and assign the result to a new variable `duplicate_observations`. The `duplicated()` method provides a `keep` argument define which duplicates (if any) to mark.- Sort the `duplicate_observations` data on both the columns `eventDate` and `verba... | duplicate_observations = survey_data_processed[survey_data_processed.duplicated(keep=False)]
duplicate_observations.sort_values(["eventDate", "verbatimLocality"]).head(9) | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**- Exclude the duplicate values (i.e. keep the first occurrence while removing the other ones) from the `observations` data set and save the result as `survey_data_unique`. Use the `drop duplicates()` method from Pandas.- How many observations are still left in the data set?Hints- `keep=First` is the default... | survey_data_unique = survey_data_processed.drop_duplicates()
len(survey_data_unique) | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**Use the `dropna()` method to find out:- For how many observations (rows) we have all the information available (i.e. no NaN values in any of the columns)?- For how many observations (rows) we do have the `species_ID` data available ?Hints- `dropna` by default removes by default all rows for which _any_ of t... | len(survey_data_unique.dropna()), len(survey_data_unique.dropna(subset=['species'])) | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**Filter the `survey_data_unique` data and select only those records that do not have a `species` while having information on the `sex`. Store the result as variable `not_identified`.Hints- To combine logical operators element-wise in Pandas, use the `&` operator.- Pandas provides both a `isna()` and a `notn... | mask = survey_data_unique['species'].isna() & survey_data_unique['sex'].notna()
not_identified = survey_data_unique[mask]
not_identified.head() | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
__NOTE!__The `DataFrame` we will use in the further analyses contains species information: | survey_data = survey_data_unique.dropna(subset=['species']).copy()
survey_data['name'] = survey_data['genus'] + ' ' + survey_data['species'] | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**INFO**For biodiversity studies, absence values (knowing that something is not present) are useful as well to normalize the observations, but this is out of scope for these exercises. 3. Select subsets of the data | survey_data['taxa'].value_counts()
#survey_data.groupby('taxa').size() | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**- Select the observations for which the `taxa` is equal to 'Rabbit', 'Bird' or 'Reptile'. Assign the result to a variable `non_rodent_species`. Use the `isin` method for the selection.Hints- You do not have to combine three different conditions, but use the `isin` operator with a list of names. | non_rodent_species = survey_data[survey_data['taxa'].isin(['Rabbit', 'Bird', 'Reptile'])]
non_rodent_species.head()
len(non_rodent_species) | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**Select the observations for which the `name` starts with the characters 'r' (make sure it does not matter if a capital character is used in the 'taxa' name). Call the resulting variable `r_species`.Hints- Remember the `.str.` construction to provide all kind of string functionalities? You can combine multip... | r_species = survey_data[survey_data['name'].str.lower().str.startswith('r')]
r_species.head()
len(r_species)
r_species["name"].value_counts() | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**Select the observations that are not Birds. Call the resulting variable non_bird_species.Hints- Logical operators like `==`, `!=`, `>`,... can still be used. | non_bird_species = survey_data[survey_data['taxa'] != 'Bird']
non_bird_species.head()
len(non_bird_species) | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**Select the __Bird__ (taxa is Bird) observations from 1985-01 till 1989-12 using the `eventDate` column. Call the resulting variable `birds_85_89`.Hints- No hints, you can do this! (with the help of some `<=` and `&`, and don't forget the put brackets around each comparison that you combine) | birds_85_89 = survey_data[(survey_data["eventDate"] >= "1985-01-01")
& (survey_data["eventDate"] <= "1989-12-31 23:59")
& (survey_data['taxa'] == 'Bird')]
birds_85_89.head() | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
Alternative solution: | # alternative solution
birds_85_89 = survey_data[(survey_data["eventDate"].dt.year >= 1985)
& (survey_data["eventDate"].dt.year <= 1989)
& (survey_data['taxa'] == 'Bird')]
birds_85_89.head() | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**- Drop the observations for which no 'weight' (`wgt` column) information is available.- On the filtered data, compare the median weight for each of the species (use the `name` column)- Sort the output from high to low median weight (i.e. descending)__Note__ You can do this all in a single line statement, bu... | # Multiple lines
obs_with_weight = survey_data.dropna(subset=["wgt"])
median_weight = obs_with_weight.groupby(['name'])["wgt"].median()
median_weight.sort_values(ascending=False)
# Single line statement
(survey_data
.dropna(subset=["wgt"])
.groupby(['name'])["wgt"]
.median()
.sort_values(ascending=F... | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
4. Species abundance **EXERCISE**Which 8 species (use the `name` column to identify the different species) have been observed most over the entire data set?Hints- Pandas provide a function to combine sorting and showing the first n records, see [here](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataF... | survey_data.groupby("name").size().nlargest(8)
survey_data['name'].value_counts()[:8] | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**- What is the number of different species in each of the `verbatimLocality` plots? Use the `nunique` method. Assign the output to a new variable `n_species_per_plot`.- Define a Matplotlib `Figure` (`fig`) and `Axes` (`ax`) to prepare a plot. Make an horizontal bar chart using Pandas `plot` function linked t... | n_species_per_plot = survey_data.groupby(["verbatimLocality"])["name"].nunique()
fig, ax = plt.subplots(figsize=(6, 6))
n_species_per_plot.plot(kind="barh", ax=ax, color="lightblue")
ax.set_ylabel("plot number")
# Alternative option:
# inspired on the pivot table we already had:
# species_per_plot = survey_data.reset... | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**- What is the number of plots (`verbatimLocality`) each of the species have been observed in? Assign the output to a new variable `n_plots_per_species`. Sort the counts from low to high.- Make an horizontal bar chart using Pandas `plot` function to show the number of plots each of the species was found (usi... | n_plots_per_species = survey_data.groupby(["name"])["verbatimLocality"].nunique().sort_values()
fig, ax = plt.subplots(figsize=(8, 8))
n_plots_per_species.plot(kind="barh", ax=ax, color='0.4')
ax.set_xlabel("Number of plots");
ax.set_ylabel(""); | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**- Starting from the `survey_data`, calculate the amount of males and females present in each of the plots (`verbatimLocality`). The result should return the counts for each of the combinations of `sex` and `verbatimLocality`. Assign to a new variable `n_plot_sex` and ensure the counts are in a column named ... | n_plot_sex = survey_data.groupby(["sex", "verbatimLocality"]).size().rename("count").reset_index()
n_plot_sex.head()
pivoted = n_plot_sex.pivot(columns="sex", index="verbatimLocality", values="count")
pivoted.head() | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
To check, we can use the variable `pivoted` to plot the result: | pivoted.plot(kind='bar', figsize=(12, 6), rot=0) | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**Recreate the previous plot with the `catplot` function from the Seaborn library starting from `n_plot_sex`.Hints- Check the `kind` argument of the `catplot` function to figure out to specify you want a barplot with given x and y values.- To link a column to different colors, use the `hue` argument | sns.catplot(data=n_plot_sex, x="verbatimLocality", y="count",
hue="sex", kind="bar", height=3, aspect=3) | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**Recreate the previous plot with the `catplot` function from the Seaborn library directly starting from `survey_data`.Hints- Check the `kind`argument of the `catplot` function to find out how to use counts to define the bars instead of a `y` value.- To link a column to different colors, use the `hue` argumen... | sns.catplot(data=survey_data, x="verbatimLocality",
hue="sex", kind="count", height=3, aspect=3) | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**- Make a summary table with the number of records of each of the species in each of the plots (also called `verbatimLocality`). Each of the species `name`s is a row index and each of the `verbatimLocality` plots is a column name.- Using the Seaborn documentation to make a heatmap.Hints- Make sure to pass th... | species_per_plot = survey_data.pivot_table(index="name",
columns="verbatimLocality",
values="datasetName",
aggfunc='count')
# alternative ways to calculate this
#species_per_plot = survey_da... | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
5. Observations over time **EXERCISE**Make a plot visualizing the evolution of the number of observations for each of the individual __years__ (i.e. annual counts) using the `resample` method.Hints- You want to `resample` the data using the `eventDate` column to create annual counts. If the index is not a datetime-ind... | survey_data.resample('A', on='eventDate').size().plot() | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
To evaluate the intensity or number of occurrences during different time spans, a heatmap is an interesting representation. **EXERCISE**- Create a table, called `heatmap_prep`, based on the `survey_data` DataFrame with the row index the individual years, in the column the months of the year (1-> 12) and as values of th... | heatmap_prep = survey_data.pivot_table(index=survey_data['eventDate'].dt.year,
columns=survey_data['eventDate'].dt.month,
values='species', aggfunc='count')
fig, ax = plt.subplots(figsize=(10, 8))
ax = sns.heatmap(heatmap_prep, cmap='Reds') | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
Remark that we started from a `tidy` data format (also called *long* format) and converted to *short* format with in the row index the years, in the column the months and the counts for each of these year/month combinations as values. (OPTIONAL SECTION) 6. Evolution of species during monitoring period *In this section... | merriami = survey_data[survey_data["name"] == "Dipodomys merriami"]
fig, ax = plt.subplots()
merriami.groupby(merriami['eventDate'].dt.month).size().plot(kind="barh", ax=ax)
ax.set_xlabel("number of occurrences");
ax.set_ylabel("Month of the year"); | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**Plot, for the species 'Dipodomys merriami', 'Dipodomys ordii', 'Reithrodontomys megalotis' and 'Chaetodipus baileyi', the monthly number of records as a function of time during the monitoring period. Plot each of the individual species in a separate subplot and provide them all with the same y-axis scaleHin... | subsetspecies = survey_data[survey_data["name"].isin(['Dipodomys merriami', 'Dipodomys ordii',
'Reithrodontomys megalotis', 'Chaetodipus baileyi'])]
month_evolution = subsetspecies.groupby("name").resample('M', on='eventDate').size()
species_evolution = month_evolut... | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**Recreate the same plot as in the previous exercise using Seaborn `relplot` functon with the `month_evolution` variable. Hints- We want to have the `counts` as a function of `eventDate`, so link these columns to y and x respectively.- To create subplots in Seaborn, the usage of _facetting_ (splitting data... | # Given as solution..
subsetspecies = survey_data[survey_data["name"].isin(['Dipodomys merriami', 'Dipodomys ordii',
'Reithrodontomys megalotis', 'Chaetodipus baileyi'])]
month_evolution = subsetspecies.groupby("name").resample('M', on='eventDate').size().rename("co... | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
Plotting with seaborn: | sns.relplot(data=month_evolution, x='eventDate', y="counts",
row="name", kind="line", hue="name", height=2, aspect=5) | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**Plot the annual amount of occurrences for each of the 'taxa' as a function of time using Seaborn. Plot each taxa in a separate subplot and do not share the y-axis among the facets.Hints- Combine `resample` and `groupby`!- Check out the previous exercise for the plot function.- Pass the `sharey=False` to the... | year_evolution = survey_data.groupby("taxa").resample('A', on='eventDate').size()
year_evolution.name = "counts"
year_evolution = year_evolution.reset_index()
sns.relplot(data=year_evolution, x='eventDate', y="counts",
col="taxa", col_wrap=2, kind="line", height=2, aspect=5,
facet_kws={"sharey":... | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
**EXERCISE**The observations where taken by volunteers. You wonder on which day of the week the most observations where done. Calculate for each day of the week (`dayofweek`) the number of observations and make a bar plot.Hints- Did you know the Python standard Library has a module `calendar` which contains names of we... | fig, ax = plt.subplots()
survey_data.groupby(survey_data["eventDate"].dt.dayofweek).size().plot(kind='barh', color='#66b266', ax=ax)
import calendar
xticks = ax.set_yticklabels(calendar.day_name) | _____no_output_____ | BSD-3-Clause | _solved/case2_observations_analysis.ipynb | jonasvdd/DS-python-data-analysis |
Classify Images using Residual Network with 50 layers (ResNet-50) Import Turi CreatePlease follow the repository README instructions to install the Turi Create package.**Note**: Turi Create is currently only compatible with Python 2.7 | import turicreate as turi | _____no_output_____ | MIT | notebooks/Classify Image Example-ResNet50.ipynb | AFathi/TuriCreate-Notebook |
Reference the dataset path | url = "data/food_images" | _____no_output_____ | MIT | notebooks/Classify Image Example-ResNet50.ipynb | AFathi/TuriCreate-Notebook |
Label the datasetIn the following block of code we will labels the image in the dataset of **Egg** and **Soup** images. Then we will export it as an `SFrame` data object to use it for training the image classification model.1. The first line of code loads the folder images content using the `image_analysis` property. ... | data = turi.image_analysis.load_images(url)
data["foodType"] = data["path"].apply(lambda path: "Eggs" if "eggs" in path else "Soup")
data.save("egg_or_soup.sframe")
data.explore() | _____no_output_____ | MIT | notebooks/Classify Image Example-ResNet50.ipynb | AFathi/TuriCreate-Notebook |
Load the labeled SFrameIn the following line of code we are loading the `SFrame` object that contains the images in our dataset with their labels. | dataBuffer = turi.SFrame("egg_or_soup.sframe") | _____no_output_____ | MIT | notebooks/Classify Image Example-ResNet50.ipynb | AFathi/TuriCreate-Notebook |
Create training and test data using our existing datasetHere, we're randomly splitting the data.- 90% of the data in the `SFrame` object will be used for training the image classifier.- 10% of the data in the `SFrame` object will be used for testing the image classifier. | trainingBuffers, testingBuffers = dataBuffer.random_split(0.9) | _____no_output_____ | MIT | notebooks/Classify Image Example-ResNet50.ipynb | AFathi/TuriCreate-Notebook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.