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
標籤選擇器 選擇元素
#引入requests好爬取html檔案給bs4使用 import requests response = requests.get('http://ntumail.cc.ntu.edu.tw') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') #印出物包含外框標籤 print(soup.title) print(type(soup.title)) #回傳一個tag print(soup.head) print...
<title>NTU Mail-臺灣大學電子郵件系統</title> <class 'bs4.element.Tag'> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <title>NTU Mail-臺灣大學電子郵件系統</title> <link href="images/style.css" rel="stylesheet" type="text/css"/> </head> <a href="http://www.ntu.edu.tw/">臺大首頁 NTU Home</a>
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
獲取名稱、內容
#引入requests好爬取html檔案給bs4使用 import requests response = requests.get('http://ntumail.cc.ntu.edu.tw') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') print(soup.title.name) #列印tag名稱 print(soup.title.string) #列印tag裡面的內容
title NTU Mail-臺灣大學電子郵件系統
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
獲取屬性
#引入requests好爬取html檔案給bs4使用 import requests response = requests.get('http://ntumail.cc.ntu.edu.tw') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') #列印attribute print(soup.img.attrs['src']) print(soup.img['src'])
images/mail20.png images/mail20.png
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
嵌套選擇
#引入requests好爬取html檔案給bs4使用 import requests response = requests.get('http://ntumail.cc.ntu.edu.tw') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') print(soup.head.title.string) #選擇head裡的title的文本
NTU Mail-臺灣大學電子郵件系統
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
子節點、子孫節點
#引入requests好爬取html檔案給bs4使用 import requests response = requests.get('http://ntumail.cc.ntu.edu.tw') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') #獲取所有子節點,返回list print(soup.head.contents) #把head裡的文本按照行數讀取出來 #引入requests好爬取html檔案給bs...
<generator object descendants at 0x00000290B724A0A0> 0 1 <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> 2 3 <title>NTU Mail-臺灣大學電子郵件系統</title> 4 NTU Mail-臺灣大學電子郵件系統 5 6 <link href="images/style.css" rel="stylesheet" type="text/css"/> 7
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
父節點、祖父節點
#引入requests好爬取html檔案給bs4使用 import requests response = requests.get('http://ntumail.cc.ntu.edu.tw') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') #獲取所有父節點 print(soup.img.parent) #引入requests好爬取html檔案給bs4使用 import requests response =...
[(0, <div id="imgcss"><img src="images/mail20.png"/></div>), (1, <div id="mail"> <div id="imgcss"><img src="images/mail20.png"/></div> <div id="content"> <h1><a href="https://mail.ntu.edu.tw/">NTU Mail 2.0</a></h1> <ul> <li><img align="absmiddle" src="images/face01-01.gif"/> 服務對象 <ol> <li>教職員帳號 \ Faculty ...
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
兄弟節點
#引入requests好爬取html檔案給bs4使用 import requests response = requests.get('http://ntumail.cc.ntu.edu.tw') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') #獲取兄弟節點 print(list(enumerate(soup.div.next_siblings))) print(list(enumerate(soup.div....
[(0, '\n'), (1, <div id="wrapper"> <div id="banner"></div> <div id="mail"> <div id="imgcss"><img src="images/mail20.png"/></div> <div id="content"> <h1><a href="https://mail.ntu.edu.tw/">NTU Mail 2.0</a></h1> <ul> <li><img align="absmiddle" src="images/face01-01.gif"/> 服務對象 <ol> <li>教職員帳號 \ Faculty Accoun...
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
標準選擇器 find_all(name, attrs, recursive, text, **kwargs),找全部元素 可以根據標籤名稱,屬性內容查找文檔 name
import requests response = requests.get('http://www.pythonscraping.com/pages/page3.html') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') print(soup.find_all('td')) print(soup.find_all('td')[0]) import requests response = requests.g...
[] [] [] [<img src="../img/gifts/img1.jpg"/>] [] [] [] [<img src="../img/gifts/img2.jpg"/>] [] [] [] [<img src="../img/gifts/img3.jpg"/>] [] [] [] [<img src="../img/gifts/img4.jpg"/>] [] [] [] [<img src="../img/gifts/img6.jpg"/>]
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
attrs
import requests response = requests.get('http://www.pythonscraping.com/pages/page3.html') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') print(soup.find_all(attrs={'id':'gift1'})) print(soup.find_all(attrs={'class':'gift'})) import...
[<tr class="gift" id="gift1"><td> Vegetable Basket </td><td> This vegetable basket is the perfect gift for your health conscious (or overweight) friends! <span class="excitingNote">Now with super-colorful bell peppers!</span> </td><td> $15.00 </td><td> <img src="../img/gifts/img1.jpg"/> </td></tr>] [<tr class="gift" id...
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
text
import requests response = requests.get('http://www.pythonscraping.com/pages/page3.html') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') print(soup.find_all(text='trained monkeys')) #不知道為什麼找不到
[]
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
find(name, attrs, recursive, text, **kwargs),返回第一個元素
import requests response = requests.get('http://www.pythonscraping.com/pages/page3.html') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') #特殊屬性可以直接使用 print(soup.find(id='gift1')) print(soup.find(class_='gift'))
<tr class="gift" id="gift1"><td> Vegetable Basket </td><td> This vegetable basket is the perfect gift for your health conscious (or overweight) friends! <span class="excitingNote">Now with super-colorful bell peppers!</span> </td><td> $15.00 </td><td> <img src="../img/gifts/img1.jpg"/> </td></tr> <tr class="gift" id="g...
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
find_parents()返回所有祖先節點, find_parent()返回父節點 find_next_siblings(), find_next_sibling() find_previous_siblings(), find_previous_sibling() find_all_next(), find_next() find_all_previous(), find_previous() CSS選擇器 select()可以直接傳入CSS選擇器即可完成
import requests response = requests.get('http://www.pythonscraping.com/pages/page3.html') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') print(soup.select('.gift')) #class前面加. print(soup.select('#gift1'))#id前面加# print(soup.select('...
[] [<td> Vegetable Basket </td>, <td> This vegetable basket is the perfect gift for your health conscious (or overweight) friends! <span class="excitingNote">Now with super-colorful bell peppers!</span> </td>, <td> $15.00 </td>, <td> <img src="../img/gifts/img1.jpg"/> </td>] [<td> Russian Nesting Dolls </td>, <td> Hand...
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
獲取屬性
import requests response = requests.get('http://ntumail.cc.ntu.edu.tw') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') for div in soup.select('div'): print(div['id']) print(div.attrs['id'])
top top wrapper wrapper banner banner mail mail imgcss imgcss content content webmail webmail imgcss imgcss content content footer footer
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
獲取文本內容
import requests response = requests.get('http://ntumail.cc.ntu.edu.tw') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') for li in soup.select('li'): print(li.get_text())
服務對象 教職員帳號 \ Faculty Account 公務、計畫、及短期帳號 \ Project and Short Term Account 所有在學學生帳號 \ Internal Student Account 教職員帳號 \ Faculty Account 公務、計畫、及短期帳號 \ Project and Short Term Account 所有在學學生帳號 \ Internal Student Account 立即前往 Go to Mail 2.0 Mail 2.0 FAQ 服務對象 校友帳號 \ Alumni Account 醫院員工帳號 \ ...
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
總結
推薦使用lxml解析庫,必要時使用html.parser 標籤選擇篩選功能弱,但是速度快 建議使用find(), find_all() 查詢匹配單個結果或多個結果 如果對CSS選擇器熟悉則用select() 記住常用的獲取attrs和text方法
_____no_output_____
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
Toggl Reports Downloader Script to Extract from Toggl API and create CSV Export of **Latest and Complete Timelogs** as as well as separate exports of Clients, Projects, Workspace Lists. Useful for back up purposes or additional data analysis. ---- Add Dependencies
import pandas as pd from datetime import datetime from dateutil.parser import parse import time import pytz # Toggl Wrapper API # https://github.com/matthewdowney/TogglPy import TogglPy
_____no_output_____
MIT
toggl/toggl_downloader.ipynb
Zackhardtoname/qs_ledger
---- Authentication
import json with open("credentials.json", "r") as file: credentials = json.load(file) toggl_cr = credentials['toggl'] APIKEY = toggl_cr['APIKEY'] toggl = TogglPy.Toggl() toggl.setAPIKey(APIKEY)
_____no_output_____
MIT
toggl/toggl_downloader.ipynb
Zackhardtoname/qs_ledger
----- User Data
user = toggl.request("https://www.toggl.com/api/v8/me") user_id = user['data']['id'] user['data']['fullname'] join_date = parse(user['data']['created_at']) join_date # today = datetime.now() def utcnow(): return datetime.now(tz=pytz.utc) today = utcnow() dates = list(pd.date_range(join_date, today)) print("Days Sin...
Days Since Joining: 2058
MIT
toggl/toggl_downloader.ipynb
Zackhardtoname/qs_ledger
----- Clients
user_clients = toggl.request("https://www.toggl.com/api/v8/clients") clients = pd.DataFrame() for i in list(range(0, len(user_clients))): clients_df_temp = pd.DataFrame.from_dict(user_clients) clients = pd.concat([clients_df_temp, clients]) clients.to_csv('data/toggl-clients.csv')
_____no_output_____
MIT
toggl/toggl_downloader.ipynb
Zackhardtoname/qs_ledger
----- Workplaces API Ref: https://github.com/toggl/toggl_api_docs/blob/master/chapters/workspaces.mdget-workspaces
workspaces_list = toggl.request("https://www.toggl.com/api/v8/workspaces") len(workspaces_list) workspaces = pd.DataFrame.from_dict(workspaces_list) workspaces_dict = dict(zip(workspaces.id, workspaces.name)) workspaces.to_csv('data/toggl-workspaces.csv')
_____no_output_____
MIT
toggl/toggl_downloader.ipynb
Zackhardtoname/qs_ledger
---- Workplace Projects * API Ref: https://github.com/toggl/toggl_api_docs/blob/master/chapters/workspaces.mdget-workspace-projects* Endpoint: https://www.toggl.com/api/v8/workspaces/{workspace_id}/projects
projects = pd.DataFrame() for i in list(range(0, len(workspaces_list))): projects_list = toggl.request("https://www.toggl.com/api/v8/workspaces/" + str(workspaces_list[i]['id']) + "/projects") projects_df_temp = pd.DataFrame.from_dict(projects_list) projects = pd.concat([projects_df_temp, projects]) len(pro...
_____no_output_____
MIT
toggl/toggl_downloader.ipynb
Zackhardtoname/qs_ledger
---- Collect Yearly Export of Detailed Timelogs
def get_detailed_reports(wid, since, until): # max 365 days uid = user_id param = { 'workspace_id': wid, 'since': since, 'until': until, 'uid': uid } #print(str(workspace_id) + " " + since) toggl.getDetailedReportCSV(param, "data/detailed/toggl-detailed-report-" + wi...
Generating CSV... for Workspace: 341257 from 2013-01-01 until 2013-12-31 Generating CSV... for Workspace: 341257 from 2014-01-01 until 2014-12-31 Generating CSV... for Workspace: 341257 from 2015-01-01 until 2015-12-31 Generating CSV... for Workspace: 341257 from 2016-01-01 until 2016-12-31 Generating CSV... for Worksp...
MIT
toggl/toggl_downloader.ipynb
Zackhardtoname/qs_ledger
----- Log of Latest Time Entries for that User * API Ref: https://github.com/toggl/toggl_api_docs/blob/master/chapters/time_entries.mdget-time-entries-started-in-a-specific-time-range* Endpoint: https://www.toggl.com/api/v8/time_entries * Note: start_date and end_date must be ISO 8601 date and time strings.
# latest_time_entries from last 9 days latest_time_entries = toggl.request("https://www.toggl.com/api/v8/time_entries") len(latest_time_entries) latest_time_entries[-1] latest_timelog = pd.DataFrame.from_dict(latest_time_entries) latest_timelog.tail() latest_timelog.head() latest_timelog.to_csv('data/toggl-timelog-late...
_____no_output_____
MIT
toggl/toggl_downloader.ipynb
Zackhardtoname/qs_ledger
----- BONUS: Extract Times Entries for Every Single Day Using Toggl API **NOTE:** A bit of a hackish solution. But this is a possible approach to getting individual day logs.
extract_date_start = join_date.strftime("%Y-%m-%d") # join date extract_date_end = today.strftime("%Y-%m-%d") # today # UNCOMMENT TO Overide Full Extract extract_date_start = "2018-05-23" # extract_date_end = "2018-05-01".strftime("%Y-%m-%d") # extract_date_end = today.strftime("%Y-%m-%d") # today # Function that tu...
_____no_output_____
MIT
toggl/toggl_downloader.ipynb
Zackhardtoname/qs_ledger
----- Simple Data Analysis (Using Exported CSV Logs)
import glob import os # import all days of time entries and create data frame path = 'data/detailed/' allFiles = glob.glob(path + "/*.csv") timelogs = pd.DataFrame() list_ = [] for file_ in allFiles: df = pd.read_csv(file_,index_col=None, header=0) list_.append(df) timelog = pd.concat(list_) timelog.head() len(...
_____no_output_____
MIT
toggl/toggl_downloader.ipynb
Zackhardtoname/qs_ledger
----- Combine to a Daily Project Time Number
# combine to daily number daily_project_time = timelog.groupby(['Start date'])['seconds'].sum() print('{:,} total project time data'.format(len(daily_project_time))) daily_project_time.to_csv('data/daily_project_time.csv') daily_project_time.tail(5)
1,924 total project time data
MIT
toggl/toggl_downloader.ipynb
Zackhardtoname/qs_ledger
Market Basket Analysis IntroductionAttribution Chris Moffitt at http://pbpython.com/ Assiciationsanalys anses generellt tillhöra de oövervakade inlärningsmetoderna och kan exempelvis användas för att hitta gemensamma mönster bland stora datamängder med transaktionsdata. Ett applikationsområde blir därmed den så kallad...
import pandas as pd from mlxtend.frequent_patterns import apriori from mlxtend.frequent_patterns import association_rules df = pd.read_excel('http://archive.ics.uci.edu/ml/machine-learning-databases/00352/Online%20Retail.xlsx') df.head()
_____no_output_____
Apache-2.0
Market_Basket_Intro.ipynb
UU-IM-EU/Code_along4
Som vanligt börjar vi med att bekanta oss med det data vi har, vad är det för typ av data?Därefter behöver vi (som alltid) städa vårt data och se till att dess format passar den typ av analys vi ska genomföra.
# Städa upp mellanslag och ta bort rader som inte har ett giltligt kvitto. df['Description'] = df['Description'].str.strip() df.dropna(axis=0, subset=['InvoiceNo'], inplace=True) #Ta bort kvitton från kreditkortstransaktioner df['InvoiceNo'] = df['InvoiceNo'].astype('str') df = df[~df['InvoiceNo'].str.contains('C')]
_____no_output_____
Apache-2.0
Market_Basket_Intro.ipynb
UU-IM-EU/Code_along4
För att kunna köra våra algoritmer behöver vi också se till att ändra om vårt data så att varje rad representerar en transaktion och varje produkt har en egen kolumn.
#Vi startar också med att enbart analysera data från köp gjorda i Frankrike så att det inte blir alltför mycket data. basket = (df[df['Country'] == "France"] .groupby(['InvoiceNo', 'Description'])['Quantity'] .sum().unstack().reset_index().fillna(0) .set_index('InvoiceNo'))
_____no_output_____
Apache-2.0
Market_Basket_Intro.ipynb
UU-IM-EU/Code_along4
Så här ser vårt dataset ut när vi format om det som vi vill ha det för vår associationsanalys.
basket.head()
_____no_output_____
Apache-2.0
Market_Basket_Intro.ipynb
UU-IM-EU/Code_along4
Hur många produkter säljer företaget i Frankrike?
# Titta på några av kolumnerna, vad är det vi ser? basket.iloc[:,[0,1,2,3,4,5,6, 7]].head()
_____no_output_____
Apache-2.0
Market_Basket_Intro.ipynb
UU-IM-EU/Code_along4
Vi behöver också koda om med `one-hot encoding` så att en produkt som inhandlats i en viss transaktion representeras av 1 och frånvaron av en specifik produkt i en transaktion representeras av 0. Det medför att vårt dataset blir väldigt glest, varför? **OBS!** One hot encoding kan göras på olika sätt!
# Konvertera till 1 för produkt köpt och 0 för produkt inte köpt. def encode_units(x): if x <= 0: return 0 if x >= 1: return 1 basket_sets = basket.applymap(encode_units) # Ta bort onödig data basket_sets.drop('POSTAGE', inplace=True, axis=1) basket_sets.head()
_____no_output_____
Apache-2.0
Market_Basket_Intro.ipynb
UU-IM-EU/Code_along4
Att mäta associeringsregler För att ta reda på vilka associationsregler som är värdefulla krävs mycket domänkunskap. Det finns dock också några mätvärden som kan användas för att hjälpa till att avgöra kvaliteten på reglerna och för att veta hur mycket vikt vi bör lägga vid en specifik regel. Det finns tre huvudsaklig...
frequent_itemsets = apriori(basket_sets, min_support=0.07, use_colnames=True) frequent_itemsets.head() # Skapa själva reglerna varvid de olika mätvärdena också beräknas. rules = association_rules(frequent_itemsets, metric="lift", min_threshold=1) rules #Beräkna antal antecendant för varje regel rules["num_antecedents"...
_____no_output_____
Apache-2.0
Market_Basket_Intro.ipynb
UU-IM-EU/Code_along4
Load an image from a URL
from geodatatool import visual visual.load_image_from_url("https://upload.wikimedia.org/wikipedia/commons/6/61/Remote_Sensing_Illustration.jpg")
_____no_output_____
MIT
docs/notebooks/visual_intro.ipynb
clancygeodata/geodatatool
Display a YouTube video
from geodatatool import visual visual.display_youtube("Ezn1ne2Fj6Y")
_____no_output_____
MIT
docs/notebooks/visual_intro.ipynb
clancygeodata/geodatatool
**Day 3 - Task 1**: Plot the boxplot (column imdb_score) of the colored and bw films
imdb_has_attr_color = imdb.dropna(subset=['color']) sns.boxplot(data = imdb_has_attr_color, x ="color", y="imdb_score") plt.gcf().set_size_inches(3, 6)
_____no_output_____
MIT
ImdbTasks.ipynb
cardosorrenan/alura-QuarentenaDados
**Day 3 - Task 2**: In the graph (budget x gross), we have a point with a high gross value (close to 2.5) and also a high loss, find this movie
imdb = imdb.drop_duplicates() imdb_usa = imdb.query("country == 'USA'") sns.scatterplot(x="budget", y="gross", data = imdb_usa) imdb_usa.query('budget > 250000000 & gross < 100000000')['movie_title']
_____no_output_____
MIT
ImdbTasks.ipynb
cardosorrenan/alura-QuarentenaDados
**Day 3 - Task 4**: What are the films that came before the 2WW decade and have high gains
imdb_usa['earnings'] = imdb_usa['gross'] - imdb_usa['budget'] sns.scatterplot(x="title_year", y="earnings", data = imdb_usa) imdb_usa.query('title_year > 1935 & title_year < 1940 & earnings > 150000000')[['movie_title', 'title_year', 'gross']]
_____no_output_____
MIT
ImdbTasks.ipynb
cardosorrenan/alura-QuarentenaDados
**Day 3 - Task 5**: In the graph (movies_per_director x gross), we have some strange points between 15 and 20. Confirm Paulo's theory that the director is Woody Allen
movies_director = imdb_usa.groupby('director_name')['director_name'].count().rename('movies_director') gross_director_movies = imdb_usa[['director_name', 'gross', 'movie_title']].merge(movies_director, on='director_name') sns.scatterplot(x="movies_director", y="gross", data = gross_director_movies) gross_director_movie...
_____no_output_____
MIT
ImdbTasks.ipynb
cardosorrenan/alura-QuarentenaDados
**Day 3 - Task 7**: Calculate the correlation of films only after the 2000s
imdb_usa_af2000 = imdb_usa.query('title_year > 2000') imdb_usa_af2000[["gross", "budget", "earnings", "title_year"]].corr()
_____no_output_____
MIT
ImdbTasks.ipynb
cardosorrenan/alura-QuarentenaDados
**Day 3 - Task 8**: Try to find a graph that looks like a line
sns.lineplot(data = imdb_usa.query('title_year > 2005').groupby('title_year')['gross'].mean())
_____no_output_____
MIT
ImdbTasks.ipynb
cardosorrenan/alura-QuarentenaDados
**Day 3 - Task 9**: Show the correlation between other variables present in the dataframe. Counting revisions per year can also be a resource.
imdb_usa[["num_user_for_reviews", "num_voted_users"]].corr() imdb_usa[["actor_1_facebook_likes", "cast_total_facebook_likes"]].corr() sns.lineplot(data = imdb_usa.groupby('title_year')['num_voted_users'].sum())
_____no_output_____
MIT
ImdbTasks.ipynb
cardosorrenan/alura-QuarentenaDados
Most examples work across multiple plotting backends, this example is also available for:* [Matplotlib Directed Airline Routes](../matplotlib/directed_airline_routes.ipynb)
import networkx as nx import holoviews as hv from holoviews import opts from holoviews.element.graphs import layout_nodes from bokeh.sampledata.airport_routes import routes, airports hv.extension('bokeh')
_____no_output_____
BSD-3-Clause
examples/gallery/demos/bokeh/directed_airline_routes.ipynb
ppwadhwa/holoviews
Declare data
# Create dataset indexed by AirportID and with additional value dimension airports = hv.Dataset(airports, ['AirportID'], ['Name', 'IATA', 'City']) label = 'Alaska Airline Routes' # Select just Alaska Airline routes as_graph = hv.Graph((routes[routes.Airline=='AS'], airports), ['SourceID', "DestinationID"], 'Airline',...
_____no_output_____
BSD-3-Clause
examples/gallery/demos/bokeh/directed_airline_routes.ipynb
ppwadhwa/holoviews
Plot
(as_graph * labels).opts( opts.Graph(directed=True, node_size=8, bgcolor='gray', xaxis=None, yaxis=None, edge_line_color='white', edge_line_width=1, width=800, height=800, arrowhead_length=0.01, node_fill_color='white', node_nonselection_fill_color='black'), opts.Labels(xoffset=-0....
_____no_output_____
BSD-3-Clause
examples/gallery/demos/bokeh/directed_airline_routes.ipynb
ppwadhwa/holoviews
Starbucks Capstone Challenge IntroductionThis data set contains simulated data that mimics customer behavior on the Starbucks rewards mobile app. Once every few days, Starbucks sends out an offer to users of the mobile app. An offer can be merely an advertisement for a drink or an actual offer such as a discount or BO...
import pandas as pd import numpy as np import math import json % matplotlib inline # read in the json files portfolio = pd.read_json('data/portfolio.json', orient='records', lines=True) profile = pd.read_json('data/profile.json', orient='records', lines=True) transcript = pd.read_json('data/transcript.json', orient='r...
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Reading The Datasets
portfolio.head(10) portfolio.shape[0] portfolio.shape[1] print('portfolio: rows = {} ,columns = {}'.format((portfolio.shape[0]),(portfolio.shape[1]))) portfolio.describe() portfolio.info() portfolio.offer_type.value_counts() portfolio.reward.value_counts() import matplotlib.pyplot as plt plt.figure(figsize=[6,6]) fig, ...
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Discount and bogo are equally given and on maximum times
plt.figure(figsize=[6,6]) fig, ax = plt.subplots() y_counts = portfolio['duration'].value_counts() y_counts.plot(kind='barh').invert_yaxis() for i, v in enumerate(y_counts): ax.text(v, i, str(v), color='black', fontsize=14) plt.title('Different offer types\' duartion')
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Here we can see that most of the offers are for the duration of 7 days Profile
profile.head(8) print('profile: rows = {} ,columns = {}'.format((profile.shape[0]),(profile.shape[1]))) profile.describe() profile.isnull().sum() profile.shape import seaborn as sns plt.figure(figsize=[6,6]) fig, ax = plt.subplots() y_counts = profile['gender'].value_counts() y_counts.plot(kind='bar...
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Mostly male are interested in the offers and they are the major ones Transcript
transcript.head(9) transcript.describe() transcript.info() print('transcript: rows = {} ,columns = {}'.format((profile.shape[0]),(profile.shape[1])))
transcript: rows = 17000 ,columns = 5
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Cleaning The Datasets PortfolioRenaming 'id' to 'offer_id'
portfolio.columns = ['channels', 'difficulty', 'duration', 'offer_id', 'offer_type', 'reward'] portfolio.columns portfolio.head()
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
ProfileRenaming 'id' to 'customer_id' , filling the missing values of age and income with mean value , filling the missing values of gender with mode
profile.columns profile.columns = ['age', 'became_member_on', 'gender', 'customer_id', 'income'] profile.columns profile['age'].fillna(profile['age'].mean()) #filling missing age with average age profile['income'].fillna(profile['income'].mean()) #filling missing income with average income profile['gender'].fillna(prof...
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
So there is not any missing value remaining in the profile dataframe TranscriptRenaming 'person' to 'customer_id' , splitting the 'value' column based on its keys anddropping the unnecessary columns
transcript.columns transcript.columns = ['event', 'customer_id', 'time', 'value'] #changing the column name transcript.head() transcript.value.astype('str').value_counts().to_dict() #converting the values in the column 'value' to dictionary transcript['offer_id'] = transcript.value.apply(lambda x: x.get('offer_id')) #s...
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Exploratory Data Analysis Now we will merge the dataframes
merge_df = pd.merge(portfolio, transcript, on='offer_id')#merging portfolio and transcript dataframes on the basis of 'offer_id' final_df = pd.merge(merge_df, profile, on='customer_id')#merging the merged dataframe of portfolio and transcript with profile dataframe on the basis of 'customer-id' #Exploring the final mer...
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Now we will see the different offer types and their counts
final_df['offer_type'].value_counts().plot.barh(title = 'Offer types with their counts')
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
So,we can see that discount and bogo are thr most given offer types Now we will see the different events and their counts
final_df['event'].value_counts().plot.barh(title = 'Different events and their counts')
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
So,in most of the cases offer is received by the user and it is not completed by him/her,means most of the people just ignore the offers they receive Now we will analyse this data on the basis of the age of the customers
sns.distplot(final_df['age'] , bins = 50 , hist_kws = {'alpha' : 0.4});
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
As we can see that the people after the age of 100 are just acting as outliers,so we will remove them
final_df = final_df[final_df['age']<=100] # Now seeing the distortion plot of age sns.distplot(final_df['age'] , bins = 50 , hist_kws = {'alpha' : 0.4});
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
We can observe that most of the customers are within the age group of 45-60 are the most frequent customers and more than any other group,this is quite interesting. Now,we will analyse this data on the basis of income of the customers
sns.distplot(final_df['income'] , bins = 50 , hist_kws = {'alpha' : 0.4}); final_df['income'].mean()
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Now we can see that most people who are the customers of Starbucks have their income within the range of 55k - 75k with a mean income of 66413.35 Now,we will see how our final dataframe is depedent on the 'gender' feature
final_df['gender'].value_counts().plot.barh(title = 'Analysing the gender of customers')
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
So,we can see that most of the customers are male We will analyse the dataframe on the basis of 'offer_type' on the basis of gender
sns.countplot(x = 'offer_type' , hue = 'gender' , data = final_df)
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
We can see that the count of gender weather it is male or female is approximately equal in the bogo and discount offers Now,we will see the relation between gender and events
sns.countplot(x = 'event' , hue = 'gender' , data = final_df)
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
So,from the exploratory data analysis we can see that most of the customers just receive the offers and they do not view them and the people who complete the offers they receive is quite less and most of the offers made by Starbuks are BOGO and Discount and most of the people that are the customers are within the age g...
final_df
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
We will now encode the categorical features like 'offer_type' , 'gender' , 'age' We will encode the offer_id and customer_id
final_df = pd.get_dummies(final_df , columns = ['offer_type' , 'gender' , 'age']) #processing offer_id offer_id = final_df['offer_id'].unique().tolist() offer_map = dict( zip(offer_id,range(len(offer_id))) ) final_df.replace({'offer_id': offer_map},inplace=True) #processing customer_id customer_id = final_df['custom...
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Now we will scale the numerical data including 'income' , 'difficulty' , 'duration' and many more...
from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() numerical_columns = ['income' , 'difficulty' , 'duration' , 'offer_reward' , 'time' , 'reward' , 'amount'] final_df[numerical_columns] = scaler.fit_transform(final_df[numerical_columns]) final_df.head()
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
We will encode the values in the 'event' column
final_df['event'] = final_df['event'].map({'offer received':1, 'offer viewed':2, 'offer completed':3}) final_df2 = final_df.drop('event' , axis = 1)
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Now encoding the channels column
final_df2['web'] = final_df2['channels'].apply(lambda x : 1 if 'web' in x else 0) final_df2['mobile'] = final_df2['channels'].apply(lambda x : 1 if 'mobile' in x else 0) final_df2['social'] = final_df2['channels'].apply(lambda x : 1 if 'social' in x else 0) final_df2['email'] = final_df2['channels'].apply(lambda x : 1 ...
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Training Our Dataset Now splitting our 'final_df' into training and test set
independent_variables = final_df2 #our dataset containing all the independent variables excluding the 'event' dependent_variable = final_df['event'] #our final dataset containing the 'event' from sklearn.model_selection import train_test_split # splitting our dataset into training and test set and the test set being th...
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Testing Our Dataset
# We will implement a number of classification machine learning methods and will determine which method is best for our model from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeCl...
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Implementing the KNN Model
knn = KNeighborsClassifier() f1_score_train_knn , f1_score_test_knn = train_test_f1(knn)#calculating the F1 scores
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Implementing the Logistic Regression
logistic = LogisticRegression() f1_score_train_logistic , f1_score_test_logistic = train_test_f1(logistic)#calculating the F1 scores
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Implementing the Random Forest Classifier
random_forest = RandomForestClassifier() f1_score_train_random , f1_score_test_random = train_test_f1(random_forest)#calculating the F1 scores
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Implementing the Decision Tree Classifier
decision_tree = DecisionTreeClassifier() f1_score_train_decision , f1_score_test_decision = train_test_f1(decision_tree)#calculating the F1 scores
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Concluding from the above models and scores
f1_scores_models = {'model_name' : [knn.__class__.__name__ , logistic.__class__.__name__ , random_forest.__class__.__name__ , decision_tree.__class__.__name__] , 'Training set F1 Score' : [f1_score_train_knn , f1_score_train_logistic , f1_score_train_random , f1_score_train_decision], ...
_____no_output_____
MIT
Capstone/Starbucks_Capstone_notebook.ipynb
mahajan-abhay/Nanodegree
Unit CommitmentKeywords: semi-continuous variables, cbc usage, gdp, disjunctive programming Imports
%matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd from IPython.display import display, HTML import shutil import sys import os.path if not shutil.which("pyomo"): !pip install -q pyomo assert(shutil.which("pyomo")) if not (shutil.which("cbc") or os.path.isfile("cbc")): ...
_____no_output_____
MIT
_build/html/_sources/notebooks/03/03.06-Unit-Commitment.ipynb
leonlan/MO-book
Problem statementA set of $N$ electrical generating units are available to meet a required demand $d_t$ for time period $t \in 1, 2, \ldots, T$. The power generated by unit $n$ for time period $t$ is denoted $x_{n,t}$. Each generating unit is either off, $x_{n,t} = 0$ or else operating in a range $[p_n^{min}, p_n^{ma...
# demand T = 20 T = np.array([t for t in range(0, T)]) d = np.array([100 + 100*np.random.uniform() for t in T]) fig, ax = plt.subplots(1,1) ax.bar(T+1, d) ax.set_xlabel('Time Period') ax.set_title('Demand')
_____no_output_____
MIT
_build/html/_sources/notebooks/03/03.06-Unit-Commitment.ipynb
leonlan/MO-book
Generating Units
# generating units N = 5 pmax = 2*max(d)/N pmin = 0.6*pmax N = np.array([n for n in range(0, N)]) a = np.array([0.5 + 0.2*np.random.randn() for n in N]) b = np.array([10*np.random.uniform() for n in N]) p = np.linspace(pmin, pmax) fig, ax = plt.subplots(1,1) for n in N: ax.plot(p, a[n]*p + b[n]) ax.set_xlim(0, p...
_____no_output_____
MIT
_build/html/_sources/notebooks/03/03.06-Unit-Commitment.ipynb
leonlan/MO-book
Pyomo model 1: Conventional implementation for emi-continuous variables
def unit_commitment(): m = pyo.ConcreteModel() m.N = pyo.Set(initialize=N) m.T = pyo.Set(initialize=T) m.x = pyo.Var(m.N, m.T, bounds = (0, pmax)) m.u = pyo.Var(m.N, m.T, domain=pyo.Binary) # objective m.cost = pyo.Objective(expr = sum(m.x[n,t]*a[n] + m.u[n,t]*b[n] for t in m.T for n ...
# ========================================================== # = Solver Results = # ========================================================== # ---------------------------------------------------------- # Problem Information # --------------------------------------------------...
MIT
_build/html/_sources/notebooks/03/03.06-Unit-Commitment.ipynb
leonlan/MO-book
Pyomo model 2: GDP implementation
def unit_commitment_gdp(): m = pyo.ConcreteModel() m.N = pyo.Set(initialize=N) m.T = pyo.Set(initialize=T) m.x = pyo.Var(m.N, m.T, bounds = (0, pmax)) # demand m.demand = pyo.Constraint(m.T, rule=lambda m, t: sum(m.x[n,t] for n in N) == d[t]) # representing the semicontinous vari...
# ========================================================== # = Solver Results = # ========================================================== # ---------------------------------------------------------- # Problem Information # --------------------------------------------------...
MIT
_build/html/_sources/notebooks/03/03.06-Unit-Commitment.ipynb
leonlan/MO-book
There is a problem here!Why are the results different? Somehow it appears values of the indicator variables are being ignored.
for n in N: for t in T: print("n = {0:2d} t = {1:2d} {2} {3} {4:5.2f}".format(n, t, m_gdp.sc1[n,t].indicator_var(), m_gdp.sc2[n,t].indicator_var(), m.x[n,t]()))
n = 0 t = 0 1.0 0.0 76.13 n = 0 t = 1 1.0 0.0 45.86 n = 0 t = 2 1.0 0.0 45.86 n = 0 t = 3 1.0 0.0 75.96 n = 0 t = 4 1.0 0.0 45.86 n = 0 t = 5 1.0 0.0 45.86 n = 0 t = 6 1.0 0.0 45.86 n = 0 t = 7 1.0 0.0 73.80 n = 0 t = 8 1.0 0.0 68.79 n = 0 t = 9 1.0 0.0 61.04 ...
MIT
_build/html/_sources/notebooks/03/03.06-Unit-Commitment.ipynb
leonlan/MO-book
Training Neural NetworksThe network we built in the previous part isn't so smart, it doesn't know anything about our handwritten digits. Neural networks with non-linear activations work like universal function approximators. There is some function that maps your input to the output. For example, images of handwritten ...
import torch from torch import nn import torch.nn.functional as F from torchvision import datasets, transforms # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)), ]) # Downl...
tensor(2.3011, grad_fn=<NllLossBackward>)
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
In my experience it's more convenient to build the model with a log-softmax output using `nn.LogSoftmax` or `F.log_softmax` ([documentation](https://pytorch.org/docs/stable/nn.htmltorch.nn.LogSoftmax)). Then you can get the actual probabilites by taking the exponential `torch.exp(output)`. With a log-softmax output, yo...
## Solution # Build a feed-forward network model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) # Define the loss criterion = nn.NLLLos...
tensor(2.2987, grad_fn=<NllLossBackward>)
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
AutogradNow that we know how to calculate a loss, how do we use it to perform backpropagation? Torch provides a module, `autograd`, for automatically calculating the gradients of tensors. We can use it to calculate the gradients of all our parameters with respect to the loss. Autograd works by keeping track of operati...
x = torch.randn(2,2, requires_grad=True) print(x) y = x**2 print(y)
tensor([[0.0357, 0.2308], [1.3125, 2.6173]], grad_fn=<PowBackward0>)
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
Below we can see the operation that created `y`, a power operation `PowBackward0`.
## grad_fn shows the function that generated this variable print(y.grad_fn)
<PowBackward0 object at 0x107e2e278>
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
The autograd module keeps track of these operations and knows how to calculate the gradient for each one. In this way, it's able to calculate the gradients for a chain of operations, with respect to any one tensor. Let's reduce the tensor `y` to a scalar value, the mean.
z = y.mean() print(z)
tensor(1.0491, grad_fn=<MeanBackward0>)
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
You can check the gradients for `x` and `y` but they are empty currently.
print(x.grad)
None
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
To calculate the gradients, you need to run the `.backward` method on a Variable, `z` for example. This will calculate the gradient for `z` with respect to `x`$$\frac{\partial z}{\partial x} = \frac{\partial}{\partial x}\left[\frac{1}{n}\sum_i^n x_i^2\right] = \frac{x}{2}$$
z.backward() print(x.grad) print(x/2)
tensor([[-0.0945, -0.2402], [ 0.5728, 0.8089]]) tensor([[-0.0945, -0.2402], [ 0.5728, 0.8089]], grad_fn=<DivBackward0>)
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
These gradients calculations are particularly useful for neural networks. For training we need the gradients of the weights with respect to the cost. With PyTorch, we run data forward through the network to calculate the loss, then, go backwards to calculate the gradients with respect to the loss. Once we have the grad...
# Build a feed-forward network model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) criterion = nn.NLLLoss() images, labels = next(iter(...
Before backward pass: None After backward pass: tensor([[ 2.9076e-04, 2.9076e-04, 2.9076e-04, ..., 2.9076e-04, 2.9076e-04, 2.9076e-04], [ 1.8523e-03, 1.8523e-03, 1.8523e-03, ..., 1.8523e-03, 1.8523e-03, 1.8523e-03], [-1.0316e-03, -1.0316e-03, -1.0316e-03, ..., -1.0316e...
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
Training the network!There's one last piece we need to start training, an optimizer that we'll use to update the weights with the gradients. We get these from PyTorch's [`optim` package](https://pytorch.org/docs/stable/optim.html). For example we can use stochastic gradient descent with `optim.SGD`. You can see how to...
from torch import optim # Optimizers require the parameters to optimize and a learning rate optimizer = optim.SGD(model.parameters(), lr=0.01)
_____no_output_____
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
Now we know how to use all the individual parts so it's time to see how they work together. Let's consider just one learning step before looping through all the data. The general process with PyTorch:* Make a forward pass through the network * Use the network output to calculate the loss* Perform a backward pass throug...
print('Initial weights - ', model[0].weight) images, labels = next(iter(trainloader)) images.resize_(64, 784) # Clear the gradients, do this because gradients are accumulated optimizer.zero_grad() # Forward pass, then backward pass, then update weights output = model(images) loss = criterion(output, labels) loss.bac...
Updated weights - Parameter containing: tensor([[ 0.0134, 0.0305, 0.0163, ..., -0.0268, 0.0101, -0.0027], [-0.0334, -0.0089, -0.0294, ..., 0.0047, -0.0106, -0.0214], [-0.0068, -0.0275, -0.0132, ..., -0.0203, 0.0075, 0.0117], ..., [-0.0147, 0.0041, 0.0312, ..., 0.0302, 0.01...
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
Training for realNow we'll put this algorithm into a loop so we can go through all the images. Some nomenclature, one pass through the entire dataset is called an *epoch*. So here we're going to loop through `trainloader` to get our training batches. For each batch, we'll doing a training pass where we calculate the l...
model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) criterion = nn.NLLLoss() optimizer = optim.SGD(model.parameters(), lr=0.003) epoch...
_____no_output_____
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
With the network trained, we can check out it's predictions.
%matplotlib inline import helper images, labels = next(iter(trainloader)) img = images[0].view(1, 784) # Turn off gradients to speed up this part with torch.no_grad(): logps = model(img) # Output of the network are log-probabilities, need to take exponential for probabilities ps = torch.exp(logps) helper.view_cl...
_____no_output_____
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Solution).ipynb
yangjue-han/deep-learning-v2-pytorch
Cleaning / Sampling
def cleanDF (df): r1 = re.compile('.*reporting') r2 = re.compile('.*imputed') cols_to_drop1 = list(filter((r1.match), df.columns)) cols_to_drop2 = list(filter((r2.match), df.columns)) cols_to_drop3 = ['admit_NICU'] cols_to_drop = cols_to_drop1 + cols_to_drop2 + cols_to_drop3 cols_to_keep =...
_____no_output_____
FTL
notebooks/richardkim/RK_modeling.ipynb
ConnorHaas03/CDC_capstone
Logistic Model Part 1
sample_size_list = [100] import warnings warnings.filterwarnings('ignore') #GLM with Cross Validation for sample_per_year in sample_size_list: dwnSmplDF = concat_df.groupby('birth_year',group_keys = False).apply(lambda x: x.sample(sample_per_year)) cl_df = dwnSmplDF[cols_to_keep] encoded_target = dwnSm...
_____no_output_____
FTL
notebooks/richardkim/RK_modeling.ipynb
ConnorHaas03/CDC_capstone
Logistic Model Part 2 Sampled in a way that1. Unknowns in `admit_NICU` column was thrown away.2. There are equal number of `Y`'s and `N`'s in `admit_NICU` column. (balanced sampling)
cl_df = cleanDF(totDF) nicu_allY = cl_df.loc[cl_df['admit_NICU']==1] nicu_allN = cl_df.loc[cl_df['admit_NICU']==0] #pure GLM with balanced sample (w/o stratified year) sample_size_list = [100] for sample_per_class in sample_size_list: sampN = nicu_allN.sample(sample_per_class) sampY = nicu_allY.sample(sample_...
sample size : 200 CPU times: user 79.9 ms, sys: 1.13 ms, total: 81 ms Wall time: 108 ms score : 0.774 --------------------------------------------------
FTL
notebooks/richardkim/RK_modeling.ipynb
ConnorHaas03/CDC_capstone
----- Session 06: OOP By: **Mohamed Fouad Fakhruldeen**, mohamed.fakhruldeen@epita.fr Class & Object
class ClassName: attributes methods
_____no_output_____
MIT
Session 06 - OOP.ipynb
FOU4D/ITI-Python
attributes
class My_Class: my_attr = "old Attribute Value Here" x = My_Class() print(x) print(x.my_attr) x.my_attr = "New Attribute Value" print(x.my_attr)
<__main__.My_Class object at 0x7f47c80e8130> old Attribute Value Here New Attribute Value
MIT
Session 06 - OOP.ipynb
FOU4D/ITI-Python
methods
class My_Class: my_attr = "New Attribute Value Here" # class attribute def my_method(self): print("Print my method") x = My_Class() print(x) print(x.my_attr) x.my_method() class My_Cars: def __init__(self, brand, model, year, price): ## instance attributes self.brand = brand sel...
Toyota Toyota Corolla made in 2016 with initial value 5000 Toyota Corolla made in 2016 with initial value 5000 has new value 3500.0 this only appears while printing this only appears while printing
MIT
Session 06 - OOP.ipynb
FOU4D/ITI-Python
Inheritance Child classes can override or extend the attributes and methods of parent classes. can also specify attributes and methods that are unique to themselves.
class MainClass: attr1 = "this is parent attribute" class ChildClass(MainClass): pass x = ChildClass() print(x.attr1) class MainClass2: attr12 = "this is parent attribute" class ChildClass2(MainClass2): attr12 = "This one from child" x2 = ChildClass2() print(x2.attr12)
This one from child
MIT
Session 06 - OOP.ipynb
FOU4D/ITI-Python
multiple inheretance
class Base1: pass class Base2: pass class MultiDerived(Base1, Base2): pass class Base: pass class Derived1(Base): pass class Derived2(Derived1): pass
_____no_output_____
MIT
Session 06 - OOP.ipynb
FOU4D/ITI-Python