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
We can inspect the pipeline definition in JSON format:
import json definition = json.loads(pipeline.definition()) definition
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
After upserting its definition, we can start the pipeline with the `Pipeline` object's `start` method:
pipeline.upsert(role_arn=role) execution = pipeline.start()
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
We can now confirm that the pipeline is executing. In the log output below, confirm that `PipelineExecutionStatus` is `Executing`.
execution.describe()
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Typically this pipeline should take about 10 minutes to complete. We can wait for completion by invoking `wait()`. After execution is complete, we can list the status of the pipeline steps.
execution.wait() execution.list_steps()
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
Check the score reportAfter the batch scoring job in the pipeline is complete, the batch scoring report is uploaded to S3. For simplicity, this report simply states the test MSE, but in general reports can include as much detail as desired. Reports such as these also can be formatted for use in conditional approval ...
report_path = f"{step_batch.outputs[0].destination}/score-report.txt" !aws s3 cp {report_path} ./score-report.txt && cat score-report.txt
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
ML Lineage Tracking SageMaker ML Lineage Tracking creates and stores information about the steps of a ML workflow from data preparation to model deployment. With the tracking information you can reproduce the workflow steps, track model and dataset lineage, and establish model governance and audit standards.Let's now ...
from sagemaker.lineage.visualizer import LineageTableVisualizer viz = LineageTableVisualizer(sagemaker.session.Session()) for execution_step in reversed(execution.list_steps()): if execution_step['StepName'] == 'TF2WorkflowTrain': display(viz.show(pipeline_execution_step=execution_step))
_____no_output_____
Apache-2.0
notebooks/tf-2-workflow-smpipelines.ipynb
yegortokmakov/amazon-sagemaker-workshop
link: https://www.kaggle.com/jindongwang92/crossposition-activity-recognitionhttps://archive.ics.uci.edu/ml/datasets/pamap2+physical+activity+monitoring DSADSColumns 1~405 are features, listed in the order of 'Torso', 'Right Arm', 'Left Arm', 'Right Leg', and 'Left Leg'. Each position contains 81 columns of fea...
import scipy.io import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt filename = "dsads" mat = scipy.io.loadmat('../Dataset/DASDS/'+filename+".mat") mat raw = pd.DataFrame(mat["data_dsads"]) raw.head() columns = ["Feat"+str(i) for...
['sitting' 'standing' 'lying on back side' 'lying on right side' 'ascending stairs' 'descending stairs' 'standing in an elevator still' 'moving around in an elevator' 'walking in a parking lot' 'walking on a treadmill1' 'walking on a treadmill2' 'running on a treadmill3' 'exercising on a stepper' 'exercising on a ...
MIT
Reports/v0/DSADS Dataset.ipynb
hillshadow/continual-learning-for-HAR
#@title Calculation of density of gases #@markdown Demonstration of ideal gas law and equations of state. An introduction to equations of state can be seen in the [EoS Wikipedia pages](https://en.wikipedia.org/wiki/Equation_of_state). #@markdown <br><br>This document is part of the module ["Introduction to Gas Processi...
_____no_output_____
Apache-2.0
notebooks/thermodynamics/density_of_gas.ipynb
EvenSol/testneqsim
Comparison of ideal and real gas behaviourIn the following example we use the ideal gas law and the PR/SRK-EOS to calculate the density of a pure component gas. At low pressure we see that the ideal gas and the real density are the same, at higher pressures the real gas density is higher, while at very high pressures...
#@title Select component and equation of state. Set temperature [K] and pressure range [bara]. { run: "auto" } componentName = "CO2" #@param ["methane", "ethane", "propane", "CO2", "nitrogen"] temperature = 323.0 #@param {type:"number"} minPressure = 1.0 #@param {type:"number"} maxPressure = 350.0 #@param {type:"nu...
molar mass of CO2 is 44.01 kg/mol
Apache-2.0
notebooks/thermodynamics/density_of_gas.ipynb
EvenSol/testneqsim
Pressure of gas as function of volume1 m3 methane at 1 bar and 25 C is compressed to 200 bar and cooled to 25 C. What isthe volume of the gas? What is the density of the compressed gas?
componentName = "nitrogen" #@param ["methane", "ethane", "propane", "CO2", "nitrogen"] temperature = 298.15 #@param {type:"number"} initialVolume = 1.0 #@param {type:"number"} initialPressure = 1.0 #@param {type:"number"} endPressure = 10.0 #@param {type:"number"} R = 8.314 # J/mol/K initialMoles = initialPressur...
initialVolume 1.0000083601119607 m3 initial gas density 1.1301476964655142 kg/m3 initial gas compressiility 0.9999527817885948 [-] end volume 0.09997979623211148 m3 volume ratio 0.09997896039680884 m3/m3 end gas density 11.30767486281327 kg/m3 end gas compressibility 0.9997423956912075 [-]
Apache-2.0
notebooks/thermodynamics/density_of_gas.ipynb
EvenSol/testneqsim
Calculation of density of LNGThe density of liquified methane at the boiling point at atomspheric pressure can be calcuated as demonstrated in the following example. In this case we use the SRK EoS and the PR-EoS.
# Creating a fluid in neqsim eos = 'srk' #@param ["srk", "pr"] pressure = 1.01325 #@param {type:"number"} temperature = -162.0 #@param {type:"number"} fluid1 = fluid(eos) #create a fluid using the SRK-EoS fluid1.addComponent('methane', 1.0) fluid1.setTemperature(temperature) fluid1.setPressure(pressure) bubt(fluid1) fl...
temperature at boiling point -161.1441471093413 C LNG density 428.1719693971862 kg/m3
Apache-2.0
notebooks/thermodynamics/density_of_gas.ipynb
EvenSol/testneqsim
Accuracy of EoS for calculating the densityThe density calculated with any equation of state will have an uncertainty. The GERG-2008 is a reference equation of state with high accuracy in prediction of thermodynamic properties. In the following example we compare the gas density calculations of SRK/PR with the GERG-(2...
#@title Select component and equation of state. Set temperature [K] and pressure range [bara]. { run: "auto" } componentName = "methane" #@param ["methane", "ethane", "propane", "CO2", "nitrogen"] temperature = 298.0 #@param {type:"number"} minPressure = 1.0 #@param {type:"number"} maxPressure = 500.0 #@param {type...
_____no_output_____
Apache-2.0
notebooks/thermodynamics/density_of_gas.ipynb
EvenSol/testneqsim
Calculation of density and compressibility factor for a natual gas mixtureIn the following example we calculate the density of a multicomponent gas mixture.
#@title Select equation of state and set temperature [C] and pressure [bara] { run: "auto" } temperature = 15.0 #@param {type:"number"} pressure = 100.0 #@param {type:"number"} eosname = "srk" #@param ["srk", "pr"] fluid1 = fluid(eosname) fluid1.addComponent('nitrogen', 1.2) fluid1.addComponent('CO2', 2.6) fluid1...
gas compressibility 0.7735308707131694 - gas density 102.2871090151433 kg/m3
Apache-2.0
notebooks/thermodynamics/density_of_gas.ipynb
EvenSol/testneqsim
![image.png](attachment:d6a8cd51-df64-466f-ba92-34ac05fff01f.png)
import torch import h5py import numpy as np import csv
_____no_output_____
MIT
intro_PyTorch/3.1.ipynb
caffeflow/intro_pytorch
加载数据, 创建tensor
wine_path = "./data/chapter3/winequality-white.csv" wine_data = np.loadtxt(fname=wine_path,delimiter=';',skiprows=1) # 第一行是标签 wine_data.shape wine_label = next(csv.reader(open(wine_path),delimiter=';')) wine_label = np.array(wine_label) wine_label.shape # ndarray转为tensor wine_data = torch.from_numpy(wine_data)
_____no_output_____
MIT
intro_PyTorch/3.1.ipynb
caffeflow/intro_pytorch
预处理张量
# 划分出评分做为ground_truth wine_content = wine_data[:,:-1] wine_score = wine_data[:,-1] wine_content.shape,wine_score.shape wine_score
_____no_output_____
MIT
intro_PyTorch/3.1.ipynb
caffeflow/intro_pytorch
特征缩放
# 标准化 content_mean = wine_content.mean(dim=0) content_var = wine_content.var(dim=0) content_normalized = (wine_content - content_mean)/torch.sqrt(content_var)
_____no_output_____
MIT
intro_PyTorch/3.1.ipynb
caffeflow/intro_pytorch
数据审查
# 酒分3个等级 content_bad = wine_content[torch.lt(wine_score,6)] content_mid = wine_content[torch.ge(wine_score,6) & torch.lt(wine_score,8)] content_good = wine_content[torch.gt(wine_score,8)] content_bad.shape # 对酒中的化学含量做平均值 content_bad = content_bad.mean(dim=0) content_mid = content_mid.mean(dim=0) content_good = content...
0 fixed acidity 6.96 6.81 7.42 1 volatile acidity 0.31 0.26 0.30 2 citric acid 0.33 0.33 0.39 3 residual sugar 7.05 6.08 4.12 4 chlorides 0.05 0.04 0.03 5 free sulfur dioxide 35.34 35.21 33.40 6 total sulfur dioxide 148.60 133.64 116.00 7 de...
MIT
intro_PyTorch/3.1.ipynb
caffeflow/intro_pytorch
**[Python Micro-Course Home Page](https://www.kaggle.com/learn/python)**--- These exercises accompany the tutorial on [functions and getting help](https://www.kaggle.com/colinmorris/functions-and-getting-help).As before, don't forget to run the setup code below before jumping into question 1.
# SETUP. You don't need to worry for now about what this code does or how it works. from learntools.core import binder; binder.bind(globals()) from learntools.python.ex2 import * print('Setup complete.')
Setup complete.
MIT
Project Notes/Kaggle Learn/01 Python/exercise02 functions and getting help.ipynb
JoaoAnt/Projects
Exercises 1.Complete the body of the following function according to its docstring.HINT: Python has a builtin function `round`
def round_to_two_places(num): """Return the given number rounded to two decimal places. >>> round_to_two_places(3.14159) 3.14 """ return round(num,2) pass round_to_two_places(3.14) q1.check() # Uncomment the following for a hint #q1.hint() # Or uncomment the following to peek at the soluti...
_____no_output_____
MIT
Project Notes/Kaggle Learn/01 Python/exercise02 functions and getting help.ipynb
JoaoAnt/Projects
2.The help for `round` says that `ndigits` (the second argument) may be negative.What do you think will happen when it is? Try some examples in the following cell?Can you think of a case where this would be useful?
# Put your test code here round(105.8555, -1) print('Yes') #q2.solution()
_____no_output_____
MIT
Project Notes/Kaggle Learn/01 Python/exercise02 functions and getting help.ipynb
JoaoAnt/Projects
3.In a previous programming problem, the candy-sharing friends Alice, Bob and Carol tried to split candies evenly. For the sake of their friendship, any candies left over would be smashed. For example, if they collectively bring home 91 candies, they'll take 30 each and smash 1.Below is a simple function that will cal...
def to_smash(total_candies, number_friends=3): """Return the number of leftover candies that must be smashed after distributing the given number of candies evenly between 3 friends. >>> to_smash(91) 1 """ return total_candies % number_friends q3.check() #q3.hint() #q3.solution()
_____no_output_____
MIT
Project Notes/Kaggle Learn/01 Python/exercise02 functions and getting help.ipynb
JoaoAnt/Projects
4.It may not be fun, but reading and understanding error messages will be an important part of your Python career.Each code cell below contains some commented-out buggy code. For each cell...1. Read the code and predict what you think will happen when it's run.2. Then uncomment the code and run it to see what happens....
round_to_two_places(9.9999) x = -10 y = 5 # Which of the two variables above has the smallest absolute value? smallest_abs = min(abs(x),abs(y)) def f(x): y = abs(x) return y print(f(5))
5
MIT
Project Notes/Kaggle Learn/01 Python/exercise02 functions and getting help.ipynb
JoaoAnt/Projects
Channel Flow Example
# Written for JHTDB by German G Saltar Rivera (2019) # To use K3D capabilities, use Firefox or Chrome browser. # Safari has trouble with K3D generated objects # import pyJHTDB from pyJHTDB import libJHTDB import time as tt import numpy as np import k3d #https://github.com/K3D-tools/K3D-jupyter import ipywidgets as wid...
_____no_output_____
Apache-2.0
examples/JHTDB_visualization_with_K3D.ipynb
lento234/pyJHTDB
Forced Isotropic Turbulence Example
#Set domain to be queried #Generates a 3D plot of Q iso-surface with overlayed kinetic energy volume #rendering in a [0,0.5]^3 subcube in isotropic turbulence time1 = 3.00 nx1=80 ny1=80 nz1=80 xmin1, xmax1 = 0, 0.5 ymin1, ymax1 = 0, 0.5 zmin1, zmax1 = 0, 0.5 #Creates query points and arranges their coordinates int...
_____no_output_____
Apache-2.0
examples/JHTDB_visualization_with_K3D.ipynb
lento234/pyJHTDB
Kobart tokenizer sampleTokenizer를 간단하게 살펴봅니다.
from kobart import get_kobart_tokenizer
_____no_output_____
Apache-2.0
src/summarization/2. tokenizer_sample.ipynb
youngerous/kobart-voice-summarization
tokenize
tok = get_kobart_tokenizer() # only tokenize tokenized = tok.tokenize('비정형데이터분석 팀 식사과정입니다. 무야호!') tokenized # convert to indice tok.convert_tokens_to_ids(tokenized) # encode = tokenize + convert_tokens_to_ids tok.encode('비정형데이터분석 팀 식사과정입니다. 무야호!')
_____no_output_____
Apache-2.0
src/summarization/2. tokenizer_sample.ipynb
youngerous/kobart-voice-summarization
check vocab
vocab = dict(sorted(tok.vocab.items(), key=lambda item: item[1])) len(vocab) vocab
_____no_output_____
Apache-2.0
src/summarization/2. tokenizer_sample.ipynb
youngerous/kobart-voice-summarization
DraftKings NFL Constraint Satisfaction===This is the companion code to a [blog post](https://zwlevonian.medium.com/integer-linear-programming-with-pulp-optimizing-a-draftkings-nfl-lineup-5e7524dd42d3) I wrote on Medium.
import pandas as pd import pulp
_____no_output_____
MIT
_notebook/DraftKingsNFLConstraintSatisfaction.ipynb
levon003/ml-visualized
Load in the weekly data
df = pd.read_csv('DKSalaries.csv') len(df) df.sample(n=5) # trim any postponed games, since those can't be included in a lineup df = df[df['Game Info'] != 'Postponed'] len(df) exclude_list = ['Dak Prescott'] df = df[~df['Name'].isin(exclude_list)] len(df) # this is equivalent to an extra constraint that requires playin...
_____no_output_____
MIT
_notebook/DraftKingsNFLConstraintSatisfaction.ipynb
levon003/ml-visualized
Create the constraint problemGoal: maximize AvgPointsPerGame - TotalPlayers = 9 - TotalSalary <= 50000 - TotalPosition_WR = 3 - TotalPosition_RB = 2 - TotalPosition_TE = 1 - TotalPosition_QB = 1 - TotalPosition_FLEX = 1 - TotalPosition_DST = 1 - Each player in only one position (relevant only for FLEX)
prob = pulp.LpProblem('DK_NFL_weekly', pulp.LpMaximize) player_vars = [pulp.LpVariable(f'player_{row.ID}', cat='Binary') for row in df.itertuples()] # total assigned players constraint prob += pulp.lpSum(player_var for player_var in player_vars) == 9 # position constraints # TODO fix this, currently won't work # as it ...
RB/FLEX Dalvin Cook MIN 8200 28.65 QB Russell Wilson SEA 7600 32.01 WR/FLEX Tyler Lockett SEA 6800 22.07 WR/FLEX Corey Davis TEN 5900 17.98 RB/FLEX Melvin Gordon III DEN 5300 15.72 WR/FLEX CeeDee Lamb DAL 4900 14.21 TE/FLEX Hunter Henry LAC 4000 9.63 WR/FLEX Keelan Cole JAX 4000 12.37 DST Colts IND 3300 11.71
MIT
_notebook/DraftKingsNFLConstraintSatisfaction.ipynb
levon003/ml-visualized
Python Crash CourseMaster in Data Science - Sapienza UniversityHomework 2: Python ChallengesA.A. 2017/18Tutor: Francesco Fabbri![time_to_code.jpg](attachment:time_to_code.jpg) InstructionsSo guys, here we are! **Finally** you're facing your first **REAL** homework. Are you ready to fight?We're going to apply all the P...
n=12 x=1 while n>1: x=x*n n=n-1 print(x)
479001600
MIT
02/homework_day2.ipynb
Py101/py101-assignments-andremarco
2. More math...Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 0 and 1000 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. (range and CFS)
ris=[] for x in range(0,1001): if x%7==0 and x%5!=0: ris.append(str(x)) r2=','.join(ris) print(r2)
7,14,21,28,42,49,56,63,77,84,91,98,112,119,126,133,147,154,161,168,182,189,196,203,217,224,231,238,252,259,266,273,287,294,301,308,322,329,336,343,357,364,371,378,392,399,406,413,427,434,441,448,462,469,476,483,497,504,511,518,532,539,546,553,567,574,581,588,602,609,616,623,637,644,651,658,672,679,686,693,707,714,721,7...
MIT
02/homework_day2.ipynb
Py101/py101-assignments-andremarco
2. Count capital lettersIn this exercises you're going to deal with YOUR DATA. Indeed, in the list below there are stored your Favorite Tv Series. But, as you can see, there is something weird. There are too much CaPITal LeTTErs. Your task is to count the capital letters in all the strings and then print the total num...
tv_series = ['Game of THRroneS', 'big bang tHeOrY', 'MR robot', 'WesTWorlD', 'fIRefLy', "i haven't", 'HOW I MET your mothER', 'friENds', 'bRon broen', 'gossip girl', 'prISon break', ...
_____no_output_____
MIT
02/homework_day2.ipynb
Py101/py101-assignments-andremarco
3. A remarkUsing the list above, create a dictionary where the keys are Unique IDs and values the TV Series.You have to do the exercise keeping in mind these 2 constraints: 1. The order of the IDs has to be **dependent on the alphabetical order of the titles**, i.e. 0: first_title_in_alphabetical_order and so on...2. ...
lista=[] for i in tv_series: lista.append(i.title()) idx=list(range(0+1,12+1)) dic_one=dict(zip(sorted(lista),idx)) print(dic_one)
{'Big Bang Theory': 1, 'Breaking Bad': 2, 'Bron Broen': 3, 'Firefly': 4, 'Friends': 5, 'Game Of Thrrones': 6, 'Gossip Girl': 7, 'How I Met Your Mother': 8, "I Haven'T": 9, 'Mr Robot': 10, 'Prison Break': 11, 'Westworld': 12}
MIT
02/homework_day2.ipynb
Py101/py101-assignments-andremarco
4. Dictionary to its maximumInvert the keys with the values in the dictionary built before.
inv_dic={v: k for k, v in dic_one.items()} inv_dic
_____no_output_____
MIT
02/homework_day2.ipynb
Py101/py101-assignments-andremarco
Have you done in **one line of code**? If not, try now! 4. Other boring mathLet's talk about our beloved exams. Starting from the exams and CFU below, are you able to compute the weighted mean of them?Let's do it and print the result.Description of the data:exams[1] = $(title_1, grade_1)$cfu[1] = $CFU_1$
exams = [('BIOINFORMATICS', 29), ('DATA MANAGEMENT FOR DATA SCIENCE', 30), ('DIGITAL EPIDEMIOLOGY', 26), ('NETWORKING FOR BIG DATA AND LABORATORY',28), ('QUANTITATIVE MODELS FOR ECONOMIC ANALYSIS AND MANAGEMENT','30 e lode'), ('DATA MINING TECHNOLOGY FOR BUSINESS AND SOCIETY...
29.095238095238095
MIT
02/homework_day2.ipynb
Py101/py101-assignments-andremarco
5. Palindromic numbersWrite a script which finds all the Palindromic numbers, in the range [0,**N**] (bounds included). The numbers obtained should be printed in a comma-separated sequence on a single line.What is **N**?Looking at the exercise before:**N** = (Total number of CFU) x (Sum of all the grades)(details: htt...
top=cfu*sum(voti) tot_num=list(range(1,top)) def palindo(s): return str(s)==str(s)[::-1] tt=[] for i in tot_num: c=palindo(i) if c==True: tt.append(str(i)) r6=','.join(tt) print(r6)
1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,88,99,101,111,121,131,141,151,161,171,181,191,202,212,222,232,242,252,262,272,282,292,303,313,323,333,343,353,363,373,383,393,404,414,424,434,444,454,464,474,484,494,505,515,525,535,545,555,565,575,585,595,606,616,626,636,646,656,666,676,686,696,707,717,727,737,747,757,767,777,787...
MIT
02/homework_day2.ipynb
Py101/py101-assignments-andremarco
6. StackOverflow Let's start using your new best friend. Now I'm going to give other task, slightly more difficult BUT this time, just googling, you will find easily the answer on the www.stackoverflow.com. You can use the code there for solving the exercise BUT you have to understand the solution there **COMMENTING**...
# you start with a try statement: if python can do this statement you will find "Hello". try: print("HELLO") # in the other case will be execute the except statement. In this case it will be execute only if there is an ImportError except ImportError: print ("NO module found")
HELLO
MIT
02/homework_day2.ipynb
Py101/py101-assignments-andremarco
6. BGiving this list of words below, after copying in a variable, explain and provide me a code for obtaining a **Bag of Words** from them.(Hint: use dictionaries and loops) ['theory', 'of', 'bron', 'firefly', 'thrones', 'break', 'bad', 'mother', 'firefly', "haven't", 'prison', 'big', 'friends', 'girl', 'westworld', '...
list_6=['theory', 'of', 'bron', 'firefly', 'thrones', 'break', 'bad', 'mother', 'firefly', "haven't", 'prison', 'big', 'friends', 'girl', 'westworld', 'bad', "haven't", 'gossip', 'thrones', 'your', 'big', 'how', 'friends', 'theory', 'your', 'bron', 'bad', 'bad', 'breaking', 'met', 'breaking', 'breaking', 'game', 'bron'...
{'theory': 79, 'of': 74, 'bron': 34, 'firefly': 99, 'thrones': 77, 'break': 88, 'bad': 98, 'mother': 83, "haven't": 46, 'prison': 70, 'big': 90, 'friends': 80, 'girl': 14, 'westworld': 15, 'gossip': 91, 'your': 100, 'how': 76, 'breaking': 36, 'met': 97, 'game': 95, 'bang': 89, 'i': 94, 'robot': 92, 'broen': 84}
MIT
02/homework_day2.ipynb
Py101/py101-assignments-andremarco
6. CAnd now, write down a code which computes the first 10 Fibonacci numbers(details: https://en.wikipedia.org/wiki/Fibonacci_number)
y=0 z=1 rr=[] for count in range(1,11): v=0 v=z z=y+z y=v count=count+1 rr.append(z) print(rr)
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
MIT
02/homework_day2.ipynb
Py101/py101-assignments-andremarco
SVM
# evaluate a logistic regression model using k-fold cross-validation from numpy import mean from numpy import std from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.model_selection import ShuffleSplit from sklearn.linear_model import LogisticRegression # create ...
_____no_output_____
MIT
Diabetics Prediction (ML) CV=5.ipynb
AmitHasanShuvo/Prediction-of-Clinical-Risk-Factors-of-Diabetes-Using-ML-Resolving-Class-Imbalance
LR
from numpy import mean from numpy import std from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.model_selection import ShuffleSplit from sklearn.linear_model import LogisticRegression # create dataset #X, y = make_classification(n_samples=1000, n_features=20, n_i...
_____no_output_____
MIT
Diabetics Prediction (ML) CV=5.ipynb
AmitHasanShuvo/Prediction-of-Clinical-Risk-Factors-of-Diabetes-Using-ML-Resolving-Class-Imbalance
RF
from numpy import mean from numpy import std from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import ShuffleSplit # create dataset #X, y = make_classification(n_samples=1000, n_features=20, n_i...
_____no_output_____
MIT
Diabetics Prediction (ML) CV=5.ipynb
AmitHasanShuvo/Prediction-of-Clinical-Risk-Factors-of-Diabetes-Using-ML-Resolving-Class-Imbalance
DT
from numpy import mean from numpy import std from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.model_selection import ShuffleSplit from sklearn.tree import DecisionTreeClassifier # create dataset #X, y = make_classification(n_samples=1000, n_features=20, n_info...
_____no_output_____
MIT
Diabetics Prediction (ML) CV=5.ipynb
AmitHasanShuvo/Prediction-of-Clinical-Risk-Factors-of-Diabetes-Using-ML-Resolving-Class-Imbalance
ANN
import keras from keras.models import Sequential from keras.layers import Dense,Dropout classifier=Sequential() classifier.add(Dense(units=256, kernel_initializer='uniform',activation='relu',input_dim=24)) classifier.add(Dense(units=128, kernel_initializer='uniform',activation='relu')) classifier.add(Dropout(p=0.1)) cl...
Accuracy: 0.8886 (+/- 0.0027) [Ensemble]
MIT
Diabetics Prediction (ML) CV=5.ipynb
AmitHasanShuvo/Prediction-of-Clinical-Risk-Factors-of-Diabetes-Using-ML-Resolving-Class-Imbalance
Define data convert functions
def peek(iterable): try: first = next(iterable) except StopIteration: return None return first, itertools.chain([first], iterable) def json_to_feather(filename, new_filename_base, records_per_file = 1000000, pipe_func = None): records = map(json.loads, open(filename)) records_p...
_____no_output_____
MIT
capstone.ipynb
jasonbossert/TDI_Capstone
Convert Data to Feather
filename = "yelp_academic_dataset_business.json" new_filename_base = "yelp_business" business_drop = partial(pipeable_drop, labels = ["address", "is_open", "attributes", "hours"]) json_to_feather(filename, new_filename_base, pipe_func = business_drop) filename = "yelp_academic_dataset_user.json" new_filename_base = "...
_____no_output_____
MIT
capstone.ipynb
jasonbossert/TDI_Capstone
GBDT
regr = GradientBoostingRegressor(max_depth=20, random_state=0,max_features=2,n_estimators=333) regr.fit(X_train, Y_trainmin/90000) regr2 = GradientBoostingRegressor(max_depth=20, random_state=0,max_features=2,n_estimators=333) regr2.fit(X_train, Y_trainmax/100000) from sklearn.metrics import mean_squared_error from s...
_____no_output_____
MIT
src/Prediction/salary/presalary.ipynb
chenshihang/Analysis-of-College-Graduates-Employment-Orientation
T1053.002 - Scheduled Task/Job: At (Windows)Adversaries may abuse the at.exe utility to perform task scheduling for initial or recurring execution of malicious code. The [at](https://attack.mitre.org/software/S0110) utility exists as an executable within Windows for scheduling tasks at a specified time and date. Using...
#Import the Module before running the tests. # Checkout Jupyter Notebook at https://github.com/cyb3rbuff/TheAtomicPlaybook to run PS scripts. Import-Module /Users/0x6c/AtomicRedTeam/atomics/invoke-atomicredteam/Invoke-AtomicRedTeam.psd1 - Force
_____no_output_____
MIT
playbook/tactics/privilege-escalation/T1053.002.ipynb
haresudhan/The-AtomicPlaybook
Atomic Test 1 - At.exe Scheduled taskExecutes cmd.exeNote: deprecated in Windows 8+Upon successful execution, cmd.exe will spawn at.exe and create a scheduled task that will spawn cmd at a specific time.**Supported Platforms:** windows Attack Commands: Run with `command_prompt````command_promptat 13:20 /interactive cm...
Invoke-AtomicTest T1053.002 -TestNumbers 1
_____no_output_____
MIT
playbook/tactics/privilege-escalation/T1053.002.ipynb
haresudhan/The-AtomicPlaybook
Image ClassificationIn this project, you'll classify images from the [CIFAR-10 dataset](https://www.cs.toronto.edu/~kriz/cifar.html). The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be norm...
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if present floyd_cifar10...
All files found!
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Explore the DataThe dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named `data_batch_1`, `data_batch_2`, etc.. Each batch contains the labels and images that are one of the following:* airplane* automobile* bird* cat* deer* dog* frog* hor...
%matplotlib inline %config InlineBackend.figure_format = 'retina' import helper import numpy as np # Explore the dataset batch_id = 1 sample_id = 5 helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id)
Stats of batch 1: Samples: 10000 Label Counts: {0: 1005, 1: 974, 2: 1032, 3: 1016, 4: 999, 5: 937, 6: 1030, 7: 1001, 8: 1025, 9: 981} First 20 Labels: [6, 9, 9, 4, 1, 1, 2, 7, 8, 3, 4, 7, 7, 2, 9, 9, 9, 3, 2, 6] Example of Image 5: Image - Min Value: 0 Max Value: 252 Image - Shape: (32, 32, 3) Label - Label Id: 1 Nam...
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Implement Preprocess Functions NormalizeIn the cell below, implement the `normalize` function to take in image data, `x`, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as `x`.
def normalize(x): """ Normalize a list of sample image data in the range of 0 to 1 : x: List of image data. The image shape is (32, 32, 3) : return: Numpy array of normalize data """ x_norm = x.reshape(x.size) x_norm = (x_norm - min(x_norm))/(max(x_norm)-min(x_norm)) return x_n...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
One-hot encodeJust like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the `one_hot_encode` function. The input, `x`, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are...
def one_hot_encode(x): """ One hot encode a list of sample labels. Return a one-hot encoded vector for each label. : x: List of sample Labels : return: Numpy array of one-hot encoded labels """ one_hot_array = np.zeros((len(x), 10)) for index in range(len(x)): val_index = x[index] ...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Randomize DataAs you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset. Preprocess all the data and save itRunning the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also...
""" DON'T MODIFY ANYTHING IN THIS CELL """ # Preprocess Training, Validation, and Testing Data helper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode)
_____no_output_____
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Check PointThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.
""" DON'T MODIFY ANYTHING IN THIS CELL """ import pickle import problem_unittests as tests import helper # Load the Preprocessed Validation data valid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb'))
_____no_output_____
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Build the networkFor the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittest...
import tensorflow as tf def neural_net_image_input(image_shape): """ Return a Tensor for a batch of image input : image_shape: Shape of the images : return: Tensor for image input. """ return tf.placeholder(tf.float32, shape=(None, image_shape[0], image_shape[1], image_shape[2]), name='x') d...
Image Input Tests Passed. Label Input Tests Passed. Keep Prob Tests Passed.
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Convolution and Max Pooling LayerConvolution layers have a lot of success with images. For this code cell, you should implement the function `conv2d_maxpool` to apply convolution then max pooling:* Create the weight and bias using `conv_ksize`, `conv_num_outputs` and the shape of `x_tensor`.* Apply a convolution to `x...
def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides): """ Apply convolution then max pooling to x_tensor :param x_tensor: TensorFlow Tensor :param conv_num_outputs: Number of outputs for the convolutional layer :param conv_ksize: kernal size 2-D Tuple fo...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Flatten LayerImplement the `flatten` function to change the dimension of `x_tensor` from a 4-D tensor to a 2-D tensor. The output should be the shape (*Batch Size*, *Flattened Image Size*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [Tens...
def flatten(x_tensor): """ Flatten x_tensor to (Batch Size, Flattened Image Size) : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions. : return: A tensor of size (Batch Size, Flattened Image Size). """ shaped = x_tensor.get_shape().as_list() reshaped = tf.resha...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Fully-Connected LayerImplement the `fully_conn` function to apply a fully connected layer to `x_tensor` with the shape (*Batch Size*, *num_outputs*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tens...
def fully_conn(x_tensor, num_outputs): """ Apply a fully connected layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_out...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Output LayerImplement the `output` function to apply a fully connected layer to `x_tensor` with the shape (*Batch Size*, *num_outputs*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/ap...
def output(x_tensor, num_outputs): """ Apply a output layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Create Convolutional ModelImplement the function `conv_net` to create a convolutional neural network model. The function takes in a batch of images, `x`, and outputs logits. Use the layers you created above to create this model:* Apply 1, 2, or 3 Convolution and Max Pool layers* Apply a Flatten Layer* Apply 1, 2, or ...
def conv_net(x, keep_prob): """ Create a convolutional neural network model : x: Placeholder tensor that holds image data. : keep_prob: Placeholder tensor that hold dropout keep probability. : return: Tensor that represents logits """ # Play around with different number of outputs, kernel...
Neural Network Built!
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Train the Neural Network Single OptimizationImplement the function `train_neural_network` to do a single optimization. The optimization should use `optimizer` to optimize in `session` with a `feed_dict` of the following:* `x` for image input* `y` for labels* `keep_prob` for keep probability for dropoutThis function w...
def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch): """ Optimize the session on a batch of images and labels : session: Current TensorFlow session : optimizer: TensorFlow optimizer function : keep_probability: keep probability : feature_batch: Batch of Num...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Show StatsImplement the function `print_stats` to print loss and validation accuracy. Use the global variables `valid_features` and `valid_labels` to calculate validation accuracy. Use a keep probability of `1.0` to calculate the loss and validation accuracy.
def print_stats(session, feature_batch, label_batch, cost, accuracy): """ Print information about loss and validation accuracy : session: Current TensorFlow session : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data : cost: TensorFlow cost function : accuracy...
_____no_output_____
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
HyperparametersTune the following parameters:* Set `epochs` to the number of iterations until the network stops learning or start overfitting* Set `batch_size` to the highest number that your machine has memory for. Most people set them to common sizes of memory: * 64 * 128 * 256 * ...* Set `keep_probability` to the ...
# TODO: Tune Parameters epochs = 20 batch_size = 128 keep_probability = 0.5
_____no_output_____
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Train on a Single CIFAR-10 BatchInstead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section.
""" DON'T MODIFY ANYTHING IN THIS CELL """ print('Checking the Training on a Single Batch...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): batch_i = 1 for batch_features, batch_label...
Checking the Training on a Single Batch... Epoch 1, CIFAR-10 Batch 1: Loss: 2.09 Valid Accuracy: 0.321 Epoch 2, CIFAR-10 Batch 1: Loss: 1.93 Valid Accuracy: 0.397 Epoch 3, CIFAR-10 Batch 1: Loss: 1.81 Valid Accuracy: 0.432 Epoch 4, CIFAR-10 Batch 1: Loss: 1.68 Valid Accuracy: 0.458 Epoch 5, CIF...
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Fully Train the ModelNow that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches.
""" DON'T MODIFY ANYTHING IN THIS CELL """ save_model_path = './image_classification' print('Training...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): # Loop over all batches n_batc...
Training... Epoch 1, CIFAR-10 Batch 1: Loss: 2.1 Valid Accuracy: 0.31 Epoch 1, CIFAR-10 Batch 2: Loss: 1.8 Valid Accuracy: 0.391 Epoch 1, CIFAR-10 Batch 3: Loss: 1.64 Valid Accuracy: 0.411 Epoch 1, CIFAR-10 Batch 4: Loss: 1.61 Valid Accuracy: 0.438 Epoch 1, CIFAR-10 Batch 5: Loss: 1.65 ...
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
CheckpointThe model has been saved to disk. Test ModelTest your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters.
""" DON'T MODIFY ANYTHING IN THIS CELL """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import tensorflow as tf import pickle import helper import random # Set batch size if not already set try: if batch_size: pass except NameError: batch_size = 64 save_model_path = './image_clas...
INFO:tensorflow:Restoring parameters from ./image_classification Testing Accuracy: 0.6132318037974683
MIT
image-classification/dlnd_image_classification.ipynb
cfcdavidchan/Deep-Learning-Foundation-Nanodegree
Learn the standard library to at least know what's there itertools and collections have very useful features - chain - product - permutations - combinations - izip
%matplotlib inline %config InlineBackend.figure_format='retina' import matplotlib.pyplot as plt import seaborn as sns sns.set_context('talk') sns.set_style('darkgrid') plt.rcParams['figure.figsize'] = 12, 8 # plotsize import numpy as np import pandas as pd # plot residuals from itertools import groupby # NOT REGUL...
_____no_output_____
MIT
notebooks/09-Extras.ipynb
jbwhit/WSP-312-Tips-and-Tricks
Challenge (Easy)Write a function to return the total number of digits in a given string, and those digits.
test_string = """de3456yghj87654edfghuio908ujhgyuY^YHJUi8ytgh gtyujnh y7""" count = 0 digits = [] for x in test_string: try: int(x) count += 1 digits.append(int(x)) except: pass print("Number of digits:", str(count) + ";") print("They are:", digits)
_____no_output_____
MIT
notebooks/09-Extras.ipynb
jbwhit/WSP-312-Tips-and-Tricks
Challenge (Tricky)Same as above -- but were consecutive digits are available, return as a single number. Ex. "2a78b123" returns "3 numbers, they are: 2, 78, 123"
test_string groups = [] uniquekeys = [] for k, g in groupby(test_string, lambda x: x.isdigit()): groups.append(list(g)) uniquekeys.append(k) print(groups) print(uniquekeys) numbers = [] for x, y in izip(groups, uniquekeys): if y: numbers.append(int(''.join([j for j in x]))) print("Number:", np.sum(...
_____no_output_____
MIT
notebooks/09-Extras.ipynb
jbwhit/WSP-312-Tips-and-Tricks
Challenge (Tricky)Same as above, but do it a second way.
def solution_3(test_string): """Regular expressions can be a very powerful and useful tool.""" groups = [int(j) for j in re.findall(r'\d+', test_string)] return len(groups), groups solution_3(test_string)
_____no_output_____
MIT
notebooks/09-Extras.ipynb
jbwhit/WSP-312-Tips-and-Tricks
Challenge (Hard)Same as above, but all valid numbers expressed in digits, commas, and decimal points. Ex. "a23.42dx9,331nm87,55" -> 4; 23.42, 9331, 87, 55Left as an exercise :) Don't spend much time on this one. Generators
def ex1(num): """A stupid example generator to prove a point.""" while num > 1: num += 1 yield num hey = ex1(5) hey.next() hey.next()
_____no_output_____
MIT
notebooks/09-Extras.ipynb
jbwhit/WSP-312-Tips-and-Tricks
GotchasModifying a dictionary's keys while iterating over it. ```pythonfor key in dictionary: if key == "bat": del dictionary[key]```If you have to do someeven_better_name like this: ```pythonlist_of_keys = dictionary.keys()for key in list_of_keys: if key == "bat": del dictionary[key]```
even_better_name = 5 even_better_name = 5 even_better_name = 5 even_better_name = 5 even_better_name = 5 even_better_name = 5
_____no_output_____
MIT
notebooks/09-Extras.ipynb
jbwhit/WSP-312-Tips-and-Tricks
1. Store .csv files into dataframe individually
# import .csv into dataframe of big cities health data # organized the big cities health data in the excel sheet big_cities_csv_file = "data/Big_Cities_Health_Data_Inventory.csv" big_cities_health_df = pd.read_csv(big_cities_csv_file) big_cities_health_df.head() # import 2010 hospital beds by ownership types; test res...
_____no_output_____
MIT
ETL_Cities_Health_Data_Project.ipynb
erikayi/Project-2-ETL-Cities-Health-Data
2. Extract the data sources A. cleaning the Big Cities Health Data for year and state; plus, any information that needs to be cleaned out before loading into the sql database
# for references of created dataframe for big cities health data: # big_cities_csv_file = "data/Big_Cities_Health_Data_Inventory.csv" # big_cities_health_df = pd.read_csv(big_cities_csv_file) # big_cities_health_df.head() # Extract information of the cities data by year, category, indicator, gender, race/ethnicity, ...
_____no_output_____
MIT
ETL_Cities_Health_Data_Project.ipynb
erikayi/Project-2-ETL-Cities-Health-Data
B. cleaning the hospital beds data for year and state; plus any necessary data that needs to be cleaned, such as null values
# show hospital bed rate in dataframe structure that we made earlier hosp_df.head() hosp_df.tail() # check the rows if it's matching same as earlier after joining them together hosp_df.shape # rename each columns for hospital bed data for each year and state, state local gov, non-profit, for-profit, and total new_hosp...
_____no_output_____
MIT
ETL_Cities_Health_Data_Project.ipynb
erikayi/Project-2-ETL-Cities-Health-Data
C. Cleaning the data before joining
# look into the data where the columns type sort_city_data.info() # convert the year object into integers sort_city_data['year'] = sort_city_data['year'].astype(int) # check if the year turned into integer sort_city_data.info() # check hospital bed data column type hospital_df.info() # convert the column type into st...
_____no_output_____
MIT
ETL_Cities_Health_Data_Project.ipynb
erikayi/Project-2-ETL-Cities-Health-Data
Loading the extracted data into SQL database
# import dependencies from pin import username, password # make a connection string for the database on localhost, and create engine for the database we made rds_connection_string = (f"{username}:{password}@localhost:5432/healthcities_db") engine = create_engine(f'postgresql://{rds_connection_string}')
_____no_output_____
MIT
ETL_Cities_Health_Data_Project.ipynb
erikayi/Project-2-ETL-Cities-Health-Data
Check the table names
engine.table_names()
_____no_output_____
MIT
ETL_Cities_Health_Data_Project.ipynb
erikayi/Project-2-ETL-Cities-Health-Data
Use Pandas to load csv converted DataFrame into SQL database
cleaned_city.to_sql(name='health_cities', con=engine, if_exists='append', index=False) cleaned_city.shape hospital_df.to_sql(name='hospital_data', con=engine, if_exists='append', index=False) hospital_df.shape # this is where I previously loaded each converted DataFrame into SQL database, and tried to join them using S...
_____no_output_____
MIT
ETL_Cities_Health_Data_Project.ipynb
erikayi/Project-2-ETL-Cities-Health-Data
Confirm if the data has been added into SQL database query successfully for health_cities database.
cities_df = pd.read_sql_query('SELECT * FROM health_cities', con=engine) cities_df.head() cities_df.shape cities_df.tail() cleaned_hospital_df = pd.read_sql_query('SELECT * FROM hospital_data', con=engine) cleaned_hospital_df.head() cleaned_hospital_df.tail() cleaned_hospital_df.shape # This is just individual query th...
_____no_output_____
MIT
ETL_Cities_Health_Data_Project.ipynb
erikayi/Project-2-ETL-Cities-Health-Data
Merging the data together using SQL database
merged_health_data = pd.read_sql_query('SELECT hc.category, hc.cause_of_death, hc.gender, hc.race_ethnicity, hc.death_rate, ho.state, hc.year, ho.state_local_gov, ho.non_profit, ho.profit, ho.total FROM health_cities hc INNER JOIN hospital_data ho ON hc.year = ho.year AND hc.state = ho.state ORDER BY hc.year ASC', ...
_____no_output_____
MIT
ETL_Cities_Health_Data_Project.ipynb
erikayi/Project-2-ETL-Cities-Health-Data
Source we used
# Data Source 1- Health Status across US urban cities # https://data.world/health/big-cities-health # Data Source 2 - Hospital Data # https://www.kff.org/other/state-indicator/beds-by-ownership/?currentTimeframe=10&sortModel=%7B%22colId%22:%22Location%22,%22sort%22:%22asc%22%7D
_____no_output_____
MIT
ETL_Cities_Health_Data_Project.ipynb
erikayi/Project-2-ETL-Cities-Health-Data
1. Inspecting transfusion.data fileBlood transfusion saves lives - from replacing lost blood during major surgery or a serious injury to treating various illnesses and blood disorders. Ensuring that there's enough blood in supply whenever needed is a serious challenge for the health professionals. According to WebMD, ...
# Print out the first 5 lines from the transfusion.data file !head -n 5 datasets/transfusion.data
Recency (months),Frequency (times),Monetary (c.c. blood),Time (months),"whether he/she donated blood in March 2007" 2 ,50,12500,98 ,1 0 ,13,3250,28 ,1 1 ,16,4000,35 ,1 2 ,20,5000,45 ,1
MIT
DataCamp/Give Life: Predict Blood Donations/notebook.ipynb
lukzmu/data-courses
2. Loading the blood donations dataWe now know that we are working with a typical CSV file (i.e., the delimiter is ,, etc.). We proceed to loading the data into memory.
# Import pandas import pandas as pd # Read in dataset transfusion = pd.read_csv('datasets/transfusion.data') # Print out the first rows of our dataset transfusion.head()
_____no_output_____
MIT
DataCamp/Give Life: Predict Blood Donations/notebook.ipynb
lukzmu/data-courses
3. Inspecting transfusion DataFrameLet's briefly return to our discussion of RFM model. RFM stands for Recency, Frequency and Monetary Value and it is commonly used in marketing for identifying your best customers. In our case, our customers are blood donors.RFMTC is a variation of the RFM model. Below is a descriptio...
# Print a concise summary of transfusion DataFrame transfusion.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 748 entries, 0 to 747 Data columns (total 5 columns): Recency (months) 748 non-null int64 Frequency (times) 748 non-null int64 Monetary (c.c. blood) 748 non-null int64 Time (months) ...
MIT
DataCamp/Give Life: Predict Blood Donations/notebook.ipynb
lukzmu/data-courses
4. Creating target columnWe are aiming to predict the value in whether he/she donated blood in March 2007 column. Let's rename this it to target so that it's more convenient to work with.
# Rename target column as 'target' for brevity transfusion.rename( columns={'whether he/she donated blood in March 2007': 'target'}, inplace=True ) # Print out the first 2 rows transfusion.head(2)
_____no_output_____
MIT
DataCamp/Give Life: Predict Blood Donations/notebook.ipynb
lukzmu/data-courses
5. Checking target incidenceWe want to predict whether or not the same donor will give blood the next time the vehicle comes to campus. The model for this is a binary classifier, meaning that there are only 2 possible outcomes:0 - the donor will not give blood1 - the donor will give bloodTarget incidence is defined as...
# Print target incidence proportions, rounding output to 3 decimal places transfusion.target.value_counts(normalize=True).round(3)
_____no_output_____
MIT
DataCamp/Give Life: Predict Blood Donations/notebook.ipynb
lukzmu/data-courses
6. Splitting transfusion into train and test datasetsWe'll now use train_test_split() method to split transfusion DataFrame.Target incidence informed us that in our dataset 0s appear 76% of the time. We want to keep the same structure in train and test datasets, i.e., both datasets must have 0 target incidence of 76%....
# Import train_test_split method from sklearn.model_selection import train_test_split # Split transfusion DataFrame into # X_train, X_test, y_train and y_test datasets, # stratifying on the `target` column X_train, X_test, y_train, y_test = train_test_split( transfusion.drop(columns='target'), transfusion.targ...
_____no_output_____
MIT
DataCamp/Give Life: Predict Blood Donations/notebook.ipynb
lukzmu/data-courses
7. Selecting model using TPOTTPOT is a Python Automated Machine Learning tool that optimizes machine learning pipelines using genetic programming.TPOT will automatically explore hundreds of possible pipelines to find the best one for our dataset. Note, the outcome of this search will be a scikit-learn pipeline, meanin...
# Import TPOTClassifier and roc_auc_score from tpot import TPOTClassifier from sklearn.metrics import roc_auc_score # Instantiate TPOTClassifier tpot = TPOTClassifier( generations=5, population_size=20, verbosity=2, scoring='roc_auc', random_state=42, disable_update_check=True, config_dict=...
_____no_output_____
MIT
DataCamp/Give Life: Predict Blood Donations/notebook.ipynb
lukzmu/data-courses
8. Checking the varianceTPOT picked LogisticRegression as the best model for our dataset with no pre-processing steps, giving us the AUC score of 0.7850. This is a great starting point. Let's see if we can make it better.One of the assumptions for linear regression models is that the data and the features we are givin...
# X_train's variance, rounding the output to 3 decimal places pd.DataFrame.var(X_train).round(3)
_____no_output_____
MIT
DataCamp/Give Life: Predict Blood Donations/notebook.ipynb
lukzmu/data-courses
9. Log normalizationMonetary (c.c. blood)'s variance is very high in comparison to any other column in the dataset. This means that, unless accounted for, this feature may get more weight by the model (i.e., be seen as more important) than any other feature.One way to correct for high variance is to use log normalizat...
# Import numpy import numpy as np # Copy X_train and X_test into X_train_normed and X_test_normed X_train_normed, X_test_normed = X_train.copy(), X_test.copy() # Specify which column to normalize col_to_normalize = 'Monetary (c.c. blood)' # Log normalization for df_ in [X_train_normed, X_test_normed]: # Add log ...
_____no_output_____
MIT
DataCamp/Give Life: Predict Blood Donations/notebook.ipynb
lukzmu/data-courses
10. Training the linear regression modelThe variance looks much better now. Notice that now Time (months) has the largest variance, but it's not the orders of magnitude higher than the rest of the variables, so we'll leave it as is.We are now ready to train the linear regression model.
# Importing modules from sklearn import linear_model # Instantiate LogisticRegression logreg = linear_model.LogisticRegression( solver='liblinear', random_state=42 ) # Train the model logreg.fit(X_train_normed, y_train) # AUC score for tpot model logreg_auc_score = roc_auc_score(y_test, logreg.predict_proba(...
AUC score: 0.7891
MIT
DataCamp/Give Life: Predict Blood Donations/notebook.ipynb
lukzmu/data-courses
11. ConclusionThe demand for blood fluctuates throughout the year. As one prominent example, blood donations slow down during busy holiday seasons. An accurate forecast for the future supply of blood allows for an appropriate action to be taken ahead of time and therefore saving more lives.In this notebook, we explore...
# Importing itemgetter from operator import itemgetter # Sort models based on their AUC score from highest to lowest sorted( [('tpot', tpot_auc_score), ('logreg', logreg_auc_score)], key=itemgetter(1), reverse=True, )
_____no_output_____
MIT
DataCamp/Give Life: Predict Blood Donations/notebook.ipynb
lukzmu/data-courses
IntroductionIn this chapter, we will use Game of Thrones as a case study to practice our newly learnt skills of network analysis.It is suprising right? What is the relationship between a fatansy TV show/novel and network science or Python(not dragons).If you haven't heard of Game of Thrones, then you must be really go...
from nams import load_data as cf books = cf.load_game_of_thrones_data()
_____no_output_____
MIT
notebooks/05-casestudies/01-gameofthrones.ipynb
khanin-th/Network-Analysis-Made-Simple
The resulting DataFrame books has 5 columns: Source, Target, Type, weight, and book. Source and target are the two nodes that are linked by an edge. As we know a network can have directed or undirected edges and in this network all the edges are undirected. The weight attribute of every edge tells us the number of inte...
# We also add this weight_inv to our dataset. # Why? we will discuss it in a later section. books['weight_inv'] = 1/books.weight books.head()
_____no_output_____
MIT
notebooks/05-casestudies/01-gameofthrones.ipynb
khanin-th/Network-Analysis-Made-Simple
From the above data we can see that the characters Addam Marbrand and Tywin Lannister have interacted 6 times in the first book.We can investigate this data by using the pandas DataFrame. Let's find all the interactions of Robb Stark in the third book.
robbstark = ( books.query("book == 3") .query("Source == 'Robb-Stark' or Target == 'Robb-Stark'") ) robbstark.head()
_____no_output_____
MIT
notebooks/05-casestudies/01-gameofthrones.ipynb
khanin-th/Network-Analysis-Made-Simple
As you can see this data easily translates to a network problem. Now it's time to create a network.We create a graph for each book. It's possible to create one `MultiGraph`(Graph with multiple edges between nodes) instead of 5 graphs, but it is easier to analyse and manipulate individual `Graph` objects rather than a `...
# example of creating a MultiGraph # all_books_multigraph = nx.from_pandas_edgelist( # books, source='Source', target='Target', # edge_attr=['weight', 'book'], # create_using=nx.MultiGraph) # we create a list of graph objects using # nx.from_pandas_edgelist and specifying # the edge at...
_____no_output_____
MIT
notebooks/05-casestudies/01-gameofthrones.ipynb
khanin-th/Network-Analysis-Made-Simple