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 |
|---|---|---|---|---|---|
4. SMOTE + ENN | from imblearn.combine import SMOTEENN
smenn = SMOTEENN()
X_train_smenn, y_train_smenn = smenn.fit_resample(X_train, y_train)
def evaluate_model(clf, X_test, y_test, model_name, oversample_type):
print('--------------------------------------------')
print('Model ', model_name)
print('Data Type ', oversample_t... | _____no_output_____ | MIT | Notebooks/FetalHealthClassification_Imbalanced.ipynb | codeshruti/HealthCheck |
Hyperparameter Tuning | param_grid = {
'criterion':['gini', 'entropy'],
'max_depth': [10, 20, 40, 80, 100],
'max_features': ['auto', 'sqrt'],
'n_estimators': [200, 400, 600, 800, 1000, 2000]
}
rfc = RandomForestClassifier(random_state=42)
rfc_cv = GridSearchCV(estimator=rfc, param_grid=param_grid, cv=5, verbose=2)
rfc_cv.fit(X_... | _____no_output_____ | MIT | Notebooks/FetalHealthClassification_Imbalanced.ipynb | codeshruti/HealthCheck |
Printing the columns of the dataset, as well as their types. This is an important step because depending of the type of data that we have, the treatment that we have to perform differs. | data.columns
data.describe()
data.pivot_table(index='neighbourhood_group',columns='room_type',values='price',aggfunc='mean') | _____no_output_____ | MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
The relation among neighbourhood group, room type and price give a geneneral idea about the data. | data.drop(columns=['id', 'name', 'host_id', 'host_name'], inplace=True)
#visualize the categorical values for the neighbourhood_group
plt.figure(figsize=(6,4))
count_neigh = data.neighbourhood_group.value_counts()
(count_neigh/data.shape[0]).plot(kind='bar');
plt.title('Percent of neighbourhood group', fontsize = 12)
p... | _____no_output_____ | MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
In the listed neighborhood group the amount of business in Manhattan is largest and in Staten Island is the smallest. This is expected because in Manhattan and Brooklyn the amount of tourist is higher than the other because of their diiferent attarction of tourists in the area. | #visualize the categorical values for the room_type
plt.figure(figsize=(7,5))
count_room = data.room_type.value_counts()
(count_room/data.shape[0]).plot(kind='bar');
plt.title('room_type')
plt.ylabel('the percent of every room type') | _____no_output_____ | MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
This variable is an indication of the human prefence with the nature of house and status of privacy. In all nighborhood the amount of people serving in home/apartment and private room is higher than shared room. Shared room business in this specific area is generally not significance. | # reference: https://seaborn.pydata.org/generated/seaborn.catplot.html
plt.figure(figsize=(12,12))
sns.set_context("paper")
sns.set(style="darkgrid", font_scale=.9)
sns.catplot(x="room_type", y="price", data=data);
data.groupby('room_type')[['price','number_of_reviews']].mean() | _____no_output_____ | MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
The Entire rooms/apartments cost are more than just a shared room, where as the differece in price of a shared room and a private one is about 20 dollars. In contrast, the number of viewrs are higher in private room than the other. This small price differece between private room and shared room may lead to prefer the p... | def plot_price_wrt_room_type(data,title):
data2 = data.pivot(columns='room_type',values='price')
x1=list(data2[data2.columns[0]])
x2=list(data2[data2.columns[1]])
x3=list(data2[data2.columns[2]])
plt.figure(figsize=(8, 6))
plt.rc('legend',**{'fontsize':12})
plt.legend(fontsize=15)
plt.r... | No handles with labels found to put in legend.
No handles with labels found to put in legend.
| MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
Price distribution with room type is an indicator for the preference of the business by the customer. Hence, the graph indicates guests more prefer the private room and which it's price is relatively under the average of the others. | def plot_price_wrt_neigbourhood_group(data,title):
data2 = data.pivot(columns='neighbourhood_group',values='price')
x1=list(data2[data2.columns[0]])
x2=list(data2[data2.columns[1]])
x3=list(data2[data2.columns[2]])
x4=list(data2[data2.columns[3]])
x5=list(data2[data2.columns[4]])
plt.figure... | No handles with labels found to put in legend.
No handles with labels found to put in legend.
| MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
Neighbourhood Manhattan has highest price with high demand.The area is highly visited by the investor and having high demand and high price is expected. | #plt.subplot2grid((2,3), (0,0))
#data.room_type[data.neighbourhood_group == "..... "].value_counts(normalize = True).plot(kind = "bar", alpha= 0.5)
#plt.title("room_type with neigbourhood_group")
plt.figure(figsize=(8,6))
data.boxplot(column='price', return_type='axes')
plt.show() | _____no_output_____ | MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
This plot indicates the overall price distribution. The plot indicates the majority of the record is above the average price. | plt.figure(figsize = (9, 6))
plt.plot(data.groupby(['neighbourhood_group'])['price'].mean().keys(),data.groupby(['neighbourhood_group'])['price'].mean().values,'o')
plt.title('Newyork City Average Airbnb price per region')
plt.ylabel('Price')
plt.xlabel('Neighbourhood group')
color = ['DarkBlue']
plt.show()
| _____no_output_____ | MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
As we see that the average price in Manhattan is higher than in other regions. Manhattan is the most populated of Newyork City. it is among the world's major commerical, financial and cultural ceters. because of this the area has high tourists. | #boxplot neighbourhood_group and room availability
sns.set(style='whitegrid', rc={"grid.linewidth": 0.1})
sns.set_context("paper", font_scale=0.9)
plt.figure(figsize=(10,10))
plt.tight_layout() ... | _____no_output_____ | MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
Availability of one the key aprameter for this business and for anyother business. As the plot indicates there is a no enough supply for all neighborhood group for 365 days. Neighbourhood gorup colored by price | # reference: https://plot.ly/python/line-and-scatter/
regions_dict = {value: i for i,value in enumerate(data.neighbourhood_group.unique())}
reverse_regions_dict = {i:v for v,i in regions_dict.items()}
data = data.applymap(lambda s: regions_dict.get(s) if s in regions_dict.keys() else s)
# reference: https://plot.ly/pyt... | _____no_output_____ | MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
This graph is inlustrates another quantitative variables(longitude and latitude) with neighborhood group. |
for i,region in enumerate(data.groupby(['neighbourhood_group'])['price'].mean().keys()):
NY_data = data[data.neighbourhood_group == region]
plt.figure(figsize=(8, 5))
# xxx, sub = plt.subplots(1, 2)
plt.scatter(NY_data.latitude, NY_data.longitude, c = NY_data.price,cmap='PuBuGn')
plt.title('{} Pri... | _____no_output_____ | MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
When we look at the amount of owners per region, it is interesting to notice that in the regions where the rent price ishigher, the number of owners is also higher. That is probably due to the fact that as the apartments cost more in such regionsis harder to find owners of two or more houses there. | sns.heatmap(data[['latitude','longitude','price','minimum_nights','availability_365','number_of_reviews']].corr(),annot=True)
plt.show() | _____no_output_____ | MIT | NY_Airbnb_Data_Analysis.ipynb | fastest-parrot/ml1-lab1 |
!apt install ffmpeg
! pip install ffmpeg sk-video | Requirement already satisfied: ffmpeg in /usr/local/lib/python3.6/dist-packages (1.4)
Requirement already satisfied: sk-video in /usr/local/lib/python3.6/dist-packages (1.1.10)
Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from sk-video) (1.1.0)
Requirement already satisfied: numpy in ... | MIT | lipreading/Lipreading_Training_Demo_[Cleaner].ipynb | elekhtron/MathResearchQHSS | |
IO* Uploading data through google drive; ask jchen42703@gmail.com or j.chen3@qhss.org to share it with you. | import os
!mkdir s1
!mkdir s1_align
os.listdir()
!pip install -U -q PyDrive
s1_folder_id = '1B8cIYz6ljEbjYapG6EW1NrKHgcpZ2HzD'
s1_align_folder_id = '1swcuyFY-ZdNgFBou5GiigfEXsURcPO63'
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client impo... | /content
| MIT | lipreading/Lipreading_Training_Demo_[Cleaner].ipynb | elekhtron/MathResearchQHSS |
Model + IO | ! rm -r MathResearchQHSS
! git clone -b lipreading https://github.com/jchen42703/MathResearchQHSS.git
%cd MathResearchQHSS
!pip install -r requirements.txt
%cd '/content/'
from MathResearchQHSS.lipreading.io.generator import FrameGenerator
from MathResearchQHSS.lipreading.models import LipNet
from MathResearchQHSS.lipr... | _____no_output_____ | MIT | lipreading/Lipreading_Training_Demo_[Cleaner].ipynb | elekhtron/MathResearchQHSS |
What Drives MLB Game Attendance? Background Find Data* Step 1 - Identify and Source Data* Step 2 - Perform ETL on the Data: * Extract: original data sources and how the data was formatted (CSV, JSON, MySQL, etc). * Transform: what data cleaning or transformation was required. * Load: the final database, tabl... | # Import Dependencies
import pandas as pd
import numpy as np
import matplotlib
%matplotlib inline
from matplotlib import style
style.use('fivethirtyeight')
import matplotlib.pyplot as plt
import seaborn as sns
# Python SQL Toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automa... | _____no_output_____ | MIT | What-Drives-MLB Game-Attendance.ipynb | bigbluey/What-Drives-MLB-Game-Attendance |
Store CSV into DataFrame | # Files to Load
baseball_data_to_load = "./Resources/baseballdata.csv"
mlb_team_data_to_load = "./Resources/mlb_teams.csv"
mlb_beer_price_to_load = "./Resources/mlb_beer_prices.csv"
# Read All CSV's
baseball_data = pd.read_csv(baseball_data_to_load)
mlb_team_data = pd.read_csv(mlb_team_data_to_load)
mlb_beer_price = ... | _____no_output_____ | MIT | What-Drives-MLB Game-Attendance.ipynb | bigbluey/What-Drives-MLB-Game-Attendance |
Create New Data with Select Columns | # Clean DataFrame & Get Only the Data Needed
new_combined_mlb_df = combined_mlb_df[["Team Name", "Year", "HR", "RBI", "salary", "PPO", "Attendance"]].copy()
new_combined_mlb_df.head()
# Convert Attendance From String to a Float
new_combined_mlb_df.iloc[:,6] = new_combined_mlb_df.iloc[:,6].str.replace(',', '').astype(fl... | _____no_output_____ | MIT | What-Drives-MLB Game-Attendance.ipynb | bigbluey/What-Drives-MLB-Game-Attendance |
Visualizations with Matplotlib | # Plot 2013 Attendance Results in a Matplotlib Bar Chart
df_2013 = pd.DataFrame(attendance_2013, columns=["Team Name","Attendance"])
df_2013.set_index("Team Name", inplace=True)
df_2013.plot.bar(title="2013 MLB Team Attendance", figsize=(12,8))
plt.savefig("./Images/2013_MLB_Team_Attendance.png")
plt.show()
# Plot 2014... | /Users/josephyon/anaconda3/lib/python3.7/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either i... | MIT | What-Drives-MLB Game-Attendance.ipynb | bigbluey/What-Drives-MLB-Game-Attendance |
HHVM 背景介绍HHVM 是 Facebook (现 Meta) 开发的高性能 PHP 虚拟机,宣称达到了官方解释器的 9x 性能 为什么会有 HHVM 脚本语言 Pros一般我们使用脚本语言 (Perl,Python,PHP,JavaScript)是为了以下几个目的1. 大部分的脚本语言都拥有较为完备的外部库,能够帮助开发者快速的开发/测试 - 使用 Python 作为 ebt 的技术栈也是因为 `numpy`, `pandas` 等数据科学库的支持比别的编程语言更加的完备2. 动态语言的特性使得开发过程变得异常轻松,可以最大程度的实现可复用性和多态性,打个比方 - Python ```python def... | import pandas as pd
import matplotlib.pyplot as plt
benchmarks = pd.read_csv('./data/programming_language_benchmarks_game_all_measurements.csv')
benchmarks.head(10)
compile_lang_lst = ['clang', 'csharpcore', 'csharppgo', 'gcc', 'gfortran', 'go', 'gpp', 'java', 'rust', 'swift']
interpreter_lang_lst = ['node', 'perl', '... | _____no_output_____ | MIT | hhvm_tutorial/index.ipynb | Johnnyxcy/learn-hacklang |
通过以上数据可以显然看出与编译执行语言相比,解释执行的语言在 CPU 的处理性能有明显的优势,部分编译执行的语言在内存处理(申请与回收)上也有着异常优秀的表现。像 Meta 这样的巨型公司需要 host 的服务器是也是巨型的上图是 Meta 在 Oregon 的数据中心,据说这两个 building 的造价就高达了 *$750M* (约合 *¥47.78 亿*),并且在 2020 年中 Meta 又在边上造了两个如此巨型的数据中心的一大作用就是用来做 Facebook 的服务器主机,所以为了优化服务器的物理成本,从代码上优化服务器性能是必然的。我们都知道 Facebook 是用 PHP 实现的,据 HHVM 的项目主持者之一的 Ke... | class SomeClass:
def __init__(self):
pass
some_instance = SomeClass()
some_instance.a = 10
print(some_instance.a) | 10
| MIT | hhvm_tutorial/index.ipynb | Johnnyxcy/learn-hacklang |
为了实现这样的 feature,HipHop 还实现了一个 *property symbol table*,用于记录符号中的属性,当源码尝试访问实例/类属性时,会通过 PST 找到对应的符号。但是 HPHPc 的痛点就是- 无法支持 PHP 的动态方法 `eval()`, `create_function()` 等- 并且编译后部署上线的源码重量会比 PHP 要大很多,对于2千万行的源码,这种硬性的成本是毁灭性的 HHVM (HipHop Virtual Machine)会什么虚拟机能够解决传统解释器的问题呢? JIT (Just In Time)JVM,Numba 和 HHVM 都是对解释性语言的 jit 优化,但是尝试过 Nu... | def make_it_double(a: int) -> int:
return a * 2
%%timeit
make_it_double(10)
import numba
make_it_double_numba = numba.jit(make_it_double)
%%timeit
make_it_double_numba(10) | 90.7 ns ± 0.405 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
| MIT | hhvm_tutorial/index.ipynb | Johnnyxcy/learn-hacklang |
Módulo 2: Scraping con Selenium LATAM AirlinesVamos a scrapear el sitio de Latam para averiguar datos de vuelos en funcion el origen y destino, fecha y cabina. La información que esperamos obtener de cada vuelo es:- Precio(s) disponibles- Horas de salida y llegada (duración)- Información de las escalas**¡Empecemos!**U... | import requests
from bs4 import BeautifulSoup
url = 'https://www.latam.com/es_ar/apps/personas/booking?fecha1_dia=18&fecha1_anomes=2019-12&auAvailability=1&ida_vuelta=ida&vuelos_origen=Buenos%20Aires&from_city1=BUE&vuelos_destino=Madrid&to_city1=MAD&flex=1&vuelos_fecha_salida_ddmmaaaa=18/12/2019&cabina=Y&nadults=1&nchi... | <!DOCTYPE html>
<html lang="es">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"/>
<title>
Selecciona tus vuelos | LATAM Airlines
</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<li... | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C8. Demoras dinámicas.ipynb | Alejandro-sin/Learning_Notebooks |
Vemos que la respuesta de la página no contiene la información que buscamos, ya que la misma aparece recién después de ejecutar el código JavaSCript que está en la respuesta. Selenium Selenium es una herramienta que nos permitirá controlar un navegador y podremos utilizar las funcionalidades del motor de JavaScript pa... | from selenium import webdriver | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C8. Demoras dinámicas.ipynb | Alejandro-sin/Learning_Notebooks |
Paso 1: instanciar un **driver** del navegador | options = webdriver.ChromeOptions()
options.add_argument('--incognito')
driver = webdriver.Chrome(executable_path='../chromedriver', options=options) | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C8. Demoras dinámicas.ipynb | Alejandro-sin/Learning_Notebooks |
Paso 2: hacer que el navegador cargue la página web. | driver.get(url) | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C8. Demoras dinámicas.ipynb | Alejandro-sin/Learning_Notebooks |
Paso 3: extraer la información de la página | vuelos = driver.find_elements_by_xpath('//li[@class="flight"]')
vuelos
vuelo = vuelos[0]
vuelo
# Hora de salida
vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
# Hora de llegada
vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
# Duración del... | Se encontraron 12 vuelos.
Iniciando scraping...
| MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C8. Demoras dinámicas.ipynb | Alejandro-sin/Learning_Notebooks |
Paso 4: cerrar el navegador | driver.close() | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C8. Demoras dinámicas.ipynb | Alejandro-sin/Learning_Notebooks |
Accessing higher energy states with Qiskit Pulse In most quantum algorithms/applications, computations are carried out over a 2-dimensional space spanned by $|0\rangle$ and $|1\rangle$. In IBM's hardware, however, there also exist higher energy states which are not typically used. The focus of this section is to explo... | import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import train_test_split
from qiskit import pulse # This is where we access all of our Pulse features!
from qiskit.... | Qubit 0 has an estimated frequency of 4.962374160530024 GHz.
Default anharmonicity is -0.3433479504893883 GHz.
| Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
We define some additional helper functions. | def get_job_data(job, average):
"""Retrieve data from a job that has already run.
Args:
job (Job): The job whose data you want.
average (bool): If True, gets the data assuming data is an average.
If False, gets the data assuming it is for single shots.
Return:
... | _____no_output_____ | Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
Next we include some default parameters for drive pulses. | # there are pulse parameters of the single qubit drive in IBM devices
x12_duration = 160
x12_sigma = 40 | _____no_output_____ | Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
Discriminating the $|0\rangle$, $|1\rangle$ and $|2\rangle$ states given we have already calibrated X gate in the qubit subspace, which is available as XGate instruction in the quantum circuit. Here we calibrate transition in the higher energy subspace with pulse gate. We focus on exciting the $|2\rangle$ state and ... | # smaller range sweep
num_freqs = 75
drive_power = 0.15
sweep_freqs = default_anharmonicity*GHz + np.linspace(-30*MHz, 30*MHz, num_freqs)
freq = Parameter('freq')
with pulse.build(backend=backend, default_alignment='sequential', name='Frequency sweep') as freq12_sweep_sched:
drive_chan = pulse.drive_channel(qubit)
... | _____no_output_____ | Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
Let's plot and fit the refined signal, using the standard Lorentzian curve. | def fit_function(x_values, y_values, function, init_params):
"""Fit a function using scipy curve_fit."""
fitparams, conv = curve_fit(function, x_values, y_values, init_params, maxfev = 50000)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
# do fit in Hz
(excited_sweep_fit_params,
... | Our updated estimate for the 1->2 transition frequency is 4.6186648 GHz.
| Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
1->2 Rabi Experiment Now that we have a good estimate for the $1\rightarrow2$ frequency, we perform a Rabi experiment to obtain the $\pi$ pulse amplitude for the $1\rightarrow2$ transition. To do so, we apply a $0\rightarrow1$ $\pi$ pulse and then sweep over drive amplitudes at the $1\rightarrow2$ frequency. | # experimental configuration
num_rabi_points = 75 # number of experiments (ie amplitudes to sweep out)
# Drive amplitude values to iterate over: 75 amplitudes evenly spaced from 0 to 1.0
drive_amp_min = 0
drive_amp_max = 1.0
drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points)
amp = Parameter('amp')... | _____no_output_____ | Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
We plot and fit our data as before. | print(f"Our updated estimate for the 1->2 transition frequency is "
f"{round(qubit_12_freq/GHz, 7)} GHz.")
print(f"Pi Amplitude (1->2) = {pi_amp_12}") | Our updated estimate for the 1->2 transition frequency is 4.6186648 GHz.
Pi Amplitude (1->2) = 0.16461038080918777
| Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
Build the 0, 1, 2 discriminator Finally, we build our discriminator for the $|0\rangle$, $|1\rangle$ and $|2\rangle$ states. As a review, our three circuits are (again, recalling that our system starts in the $|0\rangle$ state): 1. Measure the $|0\rangle$ state directly (obtain $|0\rangle$ centroid).2. Apply $0\righ... | with pulse.build(backend=backend, default_alignment='sequential', name='x12 schedule') as x12_sched:
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(qubit_12_freq, drive_chan)
pulse.play(pulse.Gaussian(duration=x12_duration,
amp=pi_amp_12,
... | _____no_output_____ | Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
We construct the program and plot the centroids in the IQ plane. | # Assemble the schedules into a program
IQ_012_job = backend.run([qc_ground, qc_one, qc_x12],
meas_level=1,
meas_return='single',
shots=NUM_SHOTS)
job_monitor(IQ_012_job)
# Get job data (single); split for zero, one and two
IQ_012_data = g... | _____no_output_____ | Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
Now it is time to actually build the discriminator. We will use a machine learning technique called Linear Discriminant Analysis (LDA). LDA classifies an arbitrary data set into a set of categories (here $|0\rangle$, $|1\rangle$ and $|2\rangle$) by maximizing the distance between the means of each category and minimizi... | def reshape_complex_vec(vec):
"""Take in complex vector vec and return 2d array w/ real, imag entries. This is needed for the learning.
Args:
vec (list): complex vector of data
Returns:
list: vector w/ entries given by (real(vec], imag(vec))
"""
length = len(vec)
vec_reshaped = n... | _____no_output_____ | Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
We begin by shaping the data for LDA. | # Create IQ vector (split real, imag parts)
zero_data_reshaped = reshape_complex_vec(zero_data)
one_data_reshaped = reshape_complex_vec(one_data)
two_data_reshaped = reshape_complex_vec(two_data)
IQ_012_data = np.concatenate((zero_data_reshaped, one_data_reshaped, two_data_reshaped))
print(IQ_012_data.shape) # ver... | (3072, 2)
| Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
Next, we split our training and testing data. The testing data is a vector containing an array of `0`'s (for the zero schedule, `1`'s (for the one schedule) and `2`'s (for the two schedule). | # construct vector w/ 0's, 1's and 2's (for testing)
state_012 = np.zeros(NUM_SHOTS) # shots gives number of experiments
state_012 = np.concatenate((state_012, np.ones(NUM_SHOTS)))
state_012 = np.concatenate((state_012, 2*np.ones(NUM_SHOTS)))
print(len(state_012))
# Shuffle and split data into training and test sets
I... | 3072
| Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
Finally, we set up our model and train it. The accuracy of our fit is printed. | # Set up the LDA
LDA_012 = LinearDiscriminantAnalysis()
LDA_012.fit(IQ_012_train, state_012_train)
# test on some simple data
print(LDA_012.predict([[0, 0], [-10, 0], [-15, -5]]))
# Compute accuracy
score_012 = LDA_012.score(IQ_012_test, state_012_test)
print(score_012) | 0.8522135416666666
| Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
The last step is to plot the separatrix. | # Plot separatrix on top of scatter
def separatrixPlot(lda, x_min, x_max, y_min, y_max, shots):
nx, ny = shots, shots
xx, yy = np.meshgrid(np.linspace(x_min, x_max, nx),
np.linspace(y_min, y_max, ny))
Z = lda.predict_proba(np.c_[xx.ravel(), yy.ravel()])
Z = Z[:, 1].reshape(xx.s... | _____no_output_____ | Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
Now that we have 3 centroids, the separatrix is no longer a line, but rather a curve containing a combination of two lines. In order to discriminate between $|0\rangle$, $|1\rangle$ and $|2\rangle$ states, our model checks where the IQ point lies relative to the separatrix and classifies the point accordingly. Referen... | import qiskit.tools.jupyter
%qiskit_version_table | _____no_output_____ | Apache-2.0 | notebooks/ch-quantum-hardware/accessing_higher_energy_states.ipynb | qiskit-community/platypus |
PDI, Pn No water | cr = 0.001
scan_p0_1000_nowater = collections.defaultdict(list)
for f in sorted(os.listdir('scan_p_1000/no_water/')):
if f.startswith('polstat'):
k = float(f.split('_')[2])
if k != cr:
continue
d = np.loadtxt(os.path.join('scan_p_1000/no_water/', f))
header = open(os.path... | _____no_output_____ | Unlicense | paper/analysis/Statistics.ipynb | jkrajniak/paper-cg-md-simulations-of-polymerization-with-forward-and-backward-reactions |
Water | plt.rcParams['figure.figsize'] = figsize(0.9)
cr = 0.001
scan_p0_1000_water = collections.defaultdict(list)
for f in sorted(os.listdir('scan_p_1000/with_water/')):
if f.startswith('polstat'):
k = float(f.split('_')[2])
if k != cr:
continue
d = np.loadtxt(os.path.join('scan_p_1000... | _____no_output_____ | Unlicense | paper/analysis/Statistics.ipynb | jkrajniak/paper-cg-md-simulations-of-polymerization-with-forward-and-backward-reactions |
with water | plt.rcParams['figure.figsize'] = figsize(0.9)
cr = [0.1, 0.01, 0.001]
scan_p0_1000_water_rev = collections.defaultdict(list)
for f in sorted(os.listdir('scan_p_1000/with_water_rev/')):
if f.startswith('polstat'):
k = float(f.split('_')[2])
if k not in cr:
continue
k2 = float(f.sp... | _____no_output_____ | Unlicense | paper/analysis/Statistics.ipynb | jkrajniak/paper-cg-md-simulations-of-polymerization-with-forward-and-backward-reactions |
Loops | import pickle
with open('scan_p_1000/no_water/loops.pck', 'rb') as ib:
loops_no_water = pickle.load(ib)
loops_no_water = [l for x in loops_no_water for l in x]
# print np.average(loops_no_water), np.std(loops_no_water), np.min(loops_no_water), np.max(loops_no_water), np.sum(loops_no_water)
with open('sc... | [[10, 4, 6, 8, 4], [8, 4, 8, 10, 4, 8, 4, 4], [8, 20, 6, 6, 6, 6, 4, 6, 4, 4, 8], [4, 6, 6, 4], [8, 4, 6, 8, 4, 4, 4, 4, 6, 4, 4, 8, 4], [4, 6, 4, 4, 6, 6, 10, 4, 6, 4], [4, 4, 4, 12, 16, 4, 4, 4, 4, 4], [10, 8, 10, 4, 10, 4], [4, 34, 4, 12, 8, 6, 4, 10, 8, 4, 4], [28, 8, 6, 8, 4], [6, 8, 10, 8, 8, 6], [10, 8, 4, 4, 6,... | Unlicense | paper/analysis/Statistics.ipynb | jkrajniak/paper-cg-md-simulations-of-polymerization-with-forward-and-backward-reactions |
Group profiles Parameters | BASE_DIR = '/Users/efraflores/Desktop/EF/Contests/Datathon_202109/data/datos'
FOLDER_NAME = 'profiled'
CATALOG_NAME = 'Canarias_municipios.csv' | _____no_output_____ | Apache-2.0 | datathon2021/notebooks/02_Group_profiles.ipynb | Afroefras/datathon2021 |
Import | from mariachis.models import GroupProfiles
gp = GroupProfiles(BASE_DIR,FOLDER_NAME)
print(gp) | Path: /Users/efraflores/Desktop/EF/Contests/Datathon_202109/data/datos/profiled
With 7 profiled files
| Apache-2.0 | datathon2021/notebooks/02_Group_profiles.ipynb | Afroefras/datathon2021 |
Transform | df, pipe_obj = gp.full_pipeline(kbest=22, cluster_kwargs={'n_clusters':6, 'kmeans':False}, index='comunity_code', values='cluster', aggfunc=', '.join)
df.sample()
from mariachis.utils import tree_to_code
tree_to_code(df, df.columns) | 1.0
if max_cards <= 22.5:
if Valor_sum_Restaurantes <= 9433.5:
return [[128. 0. 0. 0. 0. 0.]]
else: # if Valor_sum_Restaurantes > 9433.5
return [[0. 0. 0. 0. 2. 0.]]
else: # if max_cards > 22.5
if count_cards <= 10488.5:
return [[0. 0. 0. 4. 0. 0.]]
else: # if count_ca... | Apache-2.0 | datathon2021/notebooks/02_Group_profiles.ipynb | Afroefras/datathon2021 |
Profiles | from mariachis.utils import profiles
prof = profiles(df)
for i,var in enumerate(prof.values()):
aux = var.fillna(0)
display(aux.style.format("{:.0f}").background_gradient('Blues'))
# aux.T.to_csv(f'Profiles_{i}.csv')
cluster_dict = {
'A':'Diversión para toda la familia',
'B':'La mejor fiesta tropi... | _____no_output_____ | Apache-2.0 | datathon2021/notebooks/02_Group_profiles.ipynb | Afroefras/datathon2021 |
Merge catalog | from pathlib import Path
from pandas import read_csv
cat = read_csv(Path(BASE_DIR).joinpath(CATALOG_NAME))
final = df[['final_cluster']].reset_index().merge(cat)
final.sample(2) | _____no_output_____ | Apache-2.0 | datathon2021/notebooks/02_Group_profiles.ipynb | Afroefras/datathon2021 |
Export | gp.export_result(final, 'grouped_3D.csv') | Exported succesfully!
File: grouped_3D.csv
Path: /Users/efraflores/Desktop/EF/Contests/Datathon_202109/data/datos
| Apache-2.0 | datathon2021/notebooks/02_Group_profiles.ipynb | Afroefras/datathon2021 |
Homework: going neural (6 pts)We've checked out statistical approaches to language models in the last notebook. Now let's go find out what deep learning has to offer.We're gonna use the same dataset as before, except this time we build a language model that's character-level, not word level. Before you go:* If you hav... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
Working on character level means that we don't need to deal with large vocabulary or missing words. Heck, we can even keep uppercase words in text! The downside, however, is that all our sequences just got a lot longer.However, we still need special tokens:* Begin Of Sequence (__BOS__) - this token is at the start of ... | BOS, EOS = ' ', '\n'
data = pd.read_json("./arxivData.json")
lines = data.apply(lambda row: (row['title'] + ' ; ' + row['summary'])[:512], axis=1) \
.apply(lambda line: BOS + line.replace(EOS, ' ') + EOS) \
.tolist()
# if you missed the seminar, download data here - https://yadi.sk/d/_nGyU2Iaj... | _____no_output_____ | MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
Our next step is __building char-level vocabulary__. Put simply, you need to assemble a list of all unique tokens in the dataset. | # get all unique characters from lines (including capital letters and symbols)
token_set = set()
list(map(lambda x: token_set.update(x), [list(line) for line in lines])) # add list to eager execution
tokens = list(token_set)
tokens = sorted(tokens)
n_tokens = len(tokens)
print ('n_tokens = ',n_tokens)
assert 100 < n_t... | n_tokens = 136
| MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
We can now assign each character with it's index in tokens list. This way we can encode a string into a torch-friendly integer vector. | # dictionary of character -> its identifier (index in tokens list)
token_to_id = {token:i for i, token in enumerate(tokens)}
assert len(tokens) == len(token_to_id), "dictionaries must have same size"
for i in range(n_tokens):
assert token_to_id[tokens[i]] == i, "token identifier must be it's position in tokens list... | Seems alright!
| MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
Our final step is to assemble several strings in a integet matrix `[batch_size, text_length]`. The only problem is that each sequence has a different length. We can work around that by padding short sequences with extra _EOS_ or cropping long sequences. Here's how it works: | def to_matrix(lines, max_len=None, pad=token_to_id[EOS], dtype=np.int64):
"""Casts a list of lines into torch-digestable matrix"""
max_len = max_len or max(map(len, lines))
lines_ix = np.full([len(lines), max_len], pad, dtype=dtype)
for i in range(len(lines)):
line_ix = list(map(token_to_id.get,... | [[ 1 66 67 68 0 0 0 0 0 0 0 0 0 0 0]
[ 1 66 67 66 68 66 67 66 0 0 0 0 0 0 0]
[ 1 66 67 68 18 19 20 21 22 23 24 25 26 17 0]]
| MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
Neural Language Model (2 points including training)Just like for N-gram LMs, we want to estimate probability of text as a joint probability of tokens (symbols this time).$$P(X) = \prod_t P(x_t \mid x_0, \dots, x_{t-1}).$$ Instead of counting all possible statistics, we want to train a neural network with parameters $\... | import torch
import torch.nn as nn
import torch.nn.functional as F
class FixedWindowLanguageModel(nn.Module):
def __init__(self, n_tokens=n_tokens, emb_size=16, hid_size=64):
"""
A fixed window model that looks on at least 5 previous symbols.
Note: fixed window LM is effectively pe... | _____no_output_____ | MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
We can now tune our network's parameters to minimize categorical crossentropy over training dataset $D$:$$ L = {\frac1{|D|}} \sum_{X \in D} \sum_{x_i \in X} - \log p(x_t \mid x_1, \dots, x_{t-1}, \theta) $$As usual with with neural nets, this optimization is performed via stochastic gradient descent with backprop. One... | def compute_mask(input_ix, eos_ix=token_to_id[EOS]):
""" compute a boolean mask that equals "1" until first EOS (including that EOS) """
cumsum = torch.cumsum(input_ix == eos_ix, dim=-1)
# print('cumsum', cumsum)
# print(cumsum[..., :-1] < 1)
return F.pad(torch.cumsum(input_ix == eos_ix, dim=-1)[...... | _____no_output_____ | MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
EvaluationYou will need two functions: one to compute test loss and another to generate samples. For your convenience, we implemented them both in your stead. | def score_lines(model, dev_lines, batch_size):
""" computes average loss over the entire dataset """
dev_loss_num, dev_loss_len = 0., 0.
with torch.no_grad():
for i in range(0, len(dev_lines), batch_size):
batch_ix = to_matrix(dev_lines[i: i + batch_size])
dev_loss_num += com... | _____no_output_____ | MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
Training loopFinally, let's train our model on minibatches of data | from sklearn.model_selection import train_test_split
train_lines, dev_lines = train_test_split(lines, test_size=0.25, random_state=42)
batch_size = 256
score_dev_every = 250
train_history, dev_history = [], []
model = FixedWindowLanguageModel()
opt = torch.optim.Adam(model.parameters())
# hint: if you ever wanted to ... | Final dev loss: 0.008852234311220123
Foress the trobles and cons as andse finasion thation late for as the ang arner andec ination thing
Ne whe s and se work serecentigo s ale tion are the des an ing and with al he whe the the s an thar
Ad pores mantion the prodeat des of amplesentitit formation lation of the s a... | MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
RNN Language Models (3 points including training)Fixed-size architectures are reasonably good when capturing short-term dependencies, but their design prevents them from capturing any signal outside their window. We can mitigate this problem by using a __recurrent neural network__:$$ h_0 = \vec 0 ; \quad h_{t+1} = RNN... | class RNNLanguageModel(nn.Module):
def __init__(self, n_tokens=n_tokens, emb_size=16, hid_size=256):
"""
Build a recurrent language model.
You are free to choose anything you want, but the recommended architecture is
- token embeddings
- one or more LSTM/GRU layers with hid ... | _____no_output_____ | MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
RNN trainingOur RNN language model should optimize the same loss function as fixed-window model. But there's a catch. Since RNN recurrently multiplies gradients through many time-steps, gradient values may explode, [ruining](https://raw.githubusercontent.com/yandexdataschool/nlp_course/master/resources/nan.jpg) your m... | batch_size = 64 # <-- please tune batch size to fit your CPU/GPU configuration
score_dev_every = 250
train_history, dev_history = [], []
model = RNNLanguageModel(n_tokens=136)
opt = torch.optim.Adam(model.parameters())
# score untrained model
dev_history.append((0, score_lines(model, dev_lines, batch_size)))
... | Final dev loss: 0.018180988125684784
Learning to Determination on Model Herning for Non-Low-Rank Neural Networks ; We present a multi-ana
An Event Sensing Approach for Image Convolutional Neural Networks ; Deep neural network to formaliza
A New Sparse Segmentation ; The algorithm in the parameter and complete theore... | MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
Alternative sampling strategies (1 point)So far we've sampled tokens from the model in proportion with their probability.However, this approach can sometimes generate nonsense words due to the fact that softmax probabilities of these words are never exactly zero. This issue can be somewhat mitigated with sampling temp... | def generate_nucleus(model, prefix=BOS, nucleus=0.9, max_len=100):
"""
Generate a sequence with nucleous sampling
:param prefix: a string containing space-separated previous tokens
:param nucleus: N from the formulae above, N \in [0, 1]
:param max_len: generate sequences with at most this many token... | Point of Multi-Reguling Optimization Based Graph ; A Classification algorithms in the properties of
The Variational Face Mutation Assessment of Bayesian Action Approach to Cameras ; We introduce the S
A Huper Analysis of Image Recognition in Latent Deformation of Results ; This paper and sensing a mu
Interest-base... | MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
Bonus quest I: Beam Search (2 pts incl. samples)At times, you don't really want the model to generate diverse outputs as much as you want a __single most likely hypothesis.__ A single best translation, most likely continuation of the search query given prefix, etc. Except, you can't get it. In order to find the exact ... | from IPython.display import HTML
# Here's what it looks like:
!wget -q https://raw.githubusercontent.com/yandexdataschool/nlp_course/2020/resources/beam_search.html
HTML("beam_search.html")
def generate_beamsearch(model, prefix=BOS, beam_size=4, length=5):
"""
Generate a sequence with nucleous sampling
:par... | _____no_output_____ | MIT | week03_lm/homework_pytorch.ipynb | jkneng/nlp_course |
Exploratory Data Analysis Using Python and BigQuery Learning Objectives1. Analyze a Pandas Dataframe2. Create Seaborn plots for Exploratory Data Analysis in Python 3. Write a SQL query to pick up specific fields from a BigQuery dataset4. Exploratory Analysis in BigQuery Introduction This lab is an introduction to line... | # Run the chown command to change the ownership
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# Install the Google Cloud BigQuery library
!pip install --user google-cloud-bigquery==1.25.0 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Please ignore any incompatibility warnings and errors. **Restart** the kernel before proceeding further (On the Notebook menu - Kernel - Restart Kernel). | # You can use any Python source file as a module by executing an import statement in some other Python source file.
# The import statement combines two operations; it searches for the named module, then it binds the results of that search
# to a name in the local scope.
import os
import pandas as pd
import numpy as np... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Load the Dataset Here, we create a directory called usahousing. This directory will hold the dataset that we copy from Google Cloud Storage. | # Create a directory to hold the dataset
if not os.path.isdir("../data/explore"):
os.makedirs("../data/explore") | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Next, we copy the Usahousing dataset from Google Cloud Storage. | # Copy the file using `gsutil cp` from Google Cloud Storage in the required directory
!gsutil cp gs://cloud-training/mlongcp/v3.0_MLonGC/toy_data/housing_pre-proc_toy.csv ../data/explore | Copying gs://cloud-training/mlongcp/v3.0_MLonGC/toy_data/housing_pre-proc_toy.csv...
/ [1 files][138.8 KiB/138.8 KiB]
Operation completed over 1 objects/138.8 KiB.
| Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Then we use the "ls" command to list files in the directory. This ensures that the dataset was copied. | # `ls` shows the working directory's contents.
# The `l` flag list the all files with permissions and details
!ls -l ../data/explore | total 140
-rw-r--r-- 1 jupyter jupyter 142150 Dec 24 11:35 housing_pre-proc_toy.csv
| Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Next, we read the dataset into a Pandas dataframe. | # TODO 1
# Read a comma-separated values (csv) file into a DataFrame using the read_csv() function
df_USAhousing = pd.read_csv('../data/explore/housing_pre-proc_toy.csv') | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Inspect the Data | # Get the first five rows using the head() method
df_USAhousing.head() | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Let's check for any null values. | # `isnull()` finds a null value in a column and `sum()` counts it
df_USAhousing.isnull().sum()
# Get some basic statistical details using describe() method
df_stats = df_USAhousing.describe()
# Transpose index and columns of the dataframe
df_stats = df_stats.transpose()
df_stats
# Get a concise summary of a DataFrame
d... | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 2500 entries, 0 to 2499
Data columns (total 10 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 longitude 2500 non-null float64
1 latitude 2500 non-null float64
2 housing_medi... | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Let's take a peek at the first and last five rows of the data for all columns. | print ("Rows : " ,df_USAhousing.shape[0])
print ("Columns : " ,df_USAhousing.shape[1])
print ("\nFeatures : \n" ,df_USAhousing.columns.tolist())
print ("\nMissing values : ", df_USAhousing.isnull().sum().values.sum())
print ("\nUnique values : \n",df_USAhousing
.nunique()) | Rows : 2500
Columns : 10
Features :
['longitude', 'latitude', 'housing_median_age', 'total_rooms', 'total_bedrooms', 'population', 'households', 'median_income', 'median_house_value', 'ocean_proximity']
Missing values : 0
Unique values :
longitude 265
latitude 275
housing_medi... | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Explore the DataLet's create some simple plots to check out the data! | # `heatmap` plots a rectangular data in a color-encoded matrix and
# `corr` finds the pairwise correlation of all columns in the dataframe
sns.heatmap(df_USAhousing.corr()) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Create a displot showing "median_house_value". | # TODO 2a
# Plot a univariate distribution of observations using seaborn `distplot()` function
sns.displot(df_USAhousing['median_house_value'])
# Set the aesthetic style of the plots
sns.set_style('whitegrid')
# Plot a histogram using `hist()` function
df_USAhousing['median_house_value'].hist(bins=30)
plt.xlabel('media... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Create a jointplot showing "median_income" versus "median_house_value". | # TODO 2b
# `joinplot()` draws a plot of two variables with bivariate and univariate graphs.
sns.jointplot(x='median_income',y='median_house_value',data=df_USAhousing)
# `countplot()` shows the counts of observations in each categorical bin using bars
sns.countplot(x = 'ocean_proximity', data=df_USAhousing)
# takes num... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
You can see below that this is the state of California! | x = df_USAhousing['latitude']
y = df_USAhousing['longitude']
# Scatter plot of y vs x and display all open figures
plt.scatter(x, y)
plt.show() | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Explore and create ML datasetsIn this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is muc... | # Import the python libraries
from google.cloud import bigquery
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up intere... | %%bigquery
# SQL query to get a fields from dataset which prints the 10 records
SELECT
FORMAT_TIMESTAMP(
"%Y-%m-%d %H:%M:%S %Z", pickup_datetime) AS pickup_datetime,
pickup_longitude, pickup_latitude, dropoff_longitude,
dropoff_latitude, passenger_count, trip_distance, tolls_amount,
fare_amount... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,0... | %%bigquery trips
SELECT
FORMAT_TIMESTAMP(
"%Y-%m-%d %H:%M:%S %Z", pickup_datetime) AS pickup_datetime,
pickup_longitude, pickup_latitude,
dropoff_longitude, dropoff_latitude,
passenger_count,
trip_distance,
tolls_amount,
fare_amount,
total_amount
FROM
`nyc-tlc.yellow.trips`
... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. | # TODO 4
# Use Seaborn `regplot()` function to plot the data and a linear regression model fit.
ax = sns.regplot(
x="trip_distance", y="fare_amount",
fit_reg=False, ci=None, truncate=True, data=trips)
ax.figure.set_size_inches(10, 8) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer ... | %%bigquery trips
# SQL query with where clause to save the results in the trips dataframe
SELECT
FORMAT_TIMESTAMP(
"%Y-%m-%d %H:%M:%S %Z", pickup_datetime) AS pickup_datetime,
pickup_longitude, pickup_latitude,
dropoff_longitude, dropoff_latitude,
passenger_count,
trip_distance,
tolls_a... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
What's up with the streaks around 45 dollars and 50 dollars? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's also examine whether the toll amount is captured in the total amount. | tollrides = trips[trips["tolls_amount"] > 0]
tollrides[tollrides["pickup_datetime"] == "2012-02-27 09:19:10 UTC"]
notollrides = trips[trips["tolls_amount"] == 0]
notollrides[notollrides["pickup_datetime"] == "2012-02-27 09:19:10 UTC"] | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
Looking at a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have t... | # Print the distribution of values within the columns using `describe()`
trips.describe() | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/launching_into_ml/solutions/python.BQ_explore_data.ipynb | shivchamkure/training-data-analyst |
In this notebook, we'll learn how to use GANs to do semi-supervised learning.In supervised learning, we have a training set of inputs $x$ and class labels $y$. We train a model that takes $x$ as input and gives $y$ as output.In semi-supervised learning, our goal is still to train a model that takes $x$ as input and gen... | %matplotlib inline
import pickle as pkl
import time
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
import tensorflow as tf
!mkdir data
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
data_dir = 'data/'
if not isdir(data_dir):
raise... | _____no_output_____ | MIT | deep-learning/udacity-deeplearning/semi-supervised/semi-supervised_learning_2.ipynb | HiteshDhola/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
When you run the fully implemented semi-supervised GAN, you should usually find that the test accuracy peaks at 69-71%. It should definitely stay above 68% fairly consistently throughout the last several epochs of training.This is a little bit better than a [NIPS 2014 paper](https://arxiv.org/pdf/1406.5298.pdf) that go... | _ = view_samples(-1, samples, 5, 10, figsize=(10,5))
!mkdir images
for ii in range(len(samples)):
fig, ax = view_samples(ii, samples, 5, 10, figsize=(10,5))
fig.savefig('images/samples_{:03d}.png'.format(ii))
plt.close() | _____no_output_____ | MIT | deep-learning/udacity-deeplearning/semi-supervised/semi-supervised_learning_2.ipynb | HiteshDhola/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
Covariance | sealed trait MyOption[A]
case class MySome[A](get: A) extends MyOption[A]
case class MyNone[A]() extends MyOption[A]
def f(a: MyOption[Any]) = a
f(MySome[Any](1))
f(MySome[Int](1))
sealed trait MyOption2[+A]
case class MySome2[A](get: A) extends MyOption2[A]
case class MyNone2[A]() extends MyOption2[A]
def f(a: MyOptio... | _____no_output_____ | MIT | scala/Covariance-and-contravariance.ipynb | ashishpatel26/learning |
Contravariance | def toS(a: Any) = a.toString
toS(List(1,2,3))
def f(a: String => String, s: String) = a(s)
// This works even though f is String => String
f(toS, "abc") | _____no_output_____ | MIT | scala/Covariance-and-contravariance.ipynb | ashishpatel26/learning |
READMEDo not blindly copy and paste. The parameter is hard-fixed with the `dataset`.For example: `SEQUENCE_LENGTH` | import torch
import torch.nn as nn
import torch.nn.functional as F
import pandas as pd
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm_notebook as tqdm
from sampler import ImbalancedDatasetSampler
torch.manual_seed(1249583)
# See the details in `Dataset` section
SEQUENCE_LENGTH = 19
COUNTRY_LEN... | _____no_output_____ | MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
Data Preparation | def str2ascii_arr(name):
"""
0-255
"""
arr = [ord(c) for c in name]
return arr, len(arr)
class RNNClassifier(nn.Module):
def __init__(self, input_size=256, hidden_size=256, output_size=18, n_layers=1):
"""
Because word embedding is working with ascii. It has to use `input_size=25... | _____no_output_____ | MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
Zero padding | def pad_sequences(vectorized_seqs, seq_lengths):
"""
Let the `SEQUENCE_LENGTH` is 19. According to the dataset
"""
seq_tensor = torch.zeros((len(vectorized_seqs), SEQUENCE_LENGTH), dtype=torch.long)
for idx, (seq, seq_len) in enumerate(zip(vectorized_seqs, seq_lengths)):
seq_tensor[idx, :seq... |
batch in: torch.Size([4, 19]),
batch out: torch.Size([1, 4, 18])
| MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
Utilities | import itertools
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function ... | _____no_output_____ | MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
Dataset | trainset = pd.read_csv('names_train.csv', header=None)
testset = pd.read_csv('names_test.csv', header=None)
headers = ['name', 'country']
trainset.columns = headers
testset.columns = headers
countries = sorted(list(trainset.country.drop_duplicates()))
country_counting = trainset.country.value_counts()
country_counting... | _____no_output_____ | MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
Use at `CrossEntropy` weights | counting_df.country.sum()
counting_df
test_counting = testset.country.value_counts()
test_counting
# Majority of dataset is `Russian`
trainset.country.value_counts().plot.pie()
# So as trainset
testset.country.value_counts().plot.pie()
trainset.iloc[0]['country'] | _____no_output_____ | MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
Find the longest name in the dataset | result = pd.concat([trainset, testset])
result['name_length'] = result.name.apply(lambda x: len(x)) | _____no_output_____ | MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
Longest name is 19 chars19 is the `sequence_length` | result['name_length'].max(), result['name_length'].idxmax()
result.iloc[7925]
class NameDataSet(Dataset):
def __init__(self, filename='names_train.csv'):
trainset = pd.read_csv(filename, header=None)
trainset.columns = ['name', 'country']
countries = sorted(list(trainset.country.drop_duplica... | CPU times: user 8.87 s, sys: 0 ns, total: 8.87 s
Wall time: 8.88 s
| MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.