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 |
|---|---|---|---|---|---|
ExerciseTransform the eigenvectors back into the coordinate system associated with $\mathbf{x}$. $$\mathbf{S} = \left[ \mathbf{u}_1, \ldots, \mathbf{u}_4 \right]$$ | S = np.linalg.inv(L.T) @ P
S
sys.coordinates | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
Exercise: visualize the modeshapesThe eigenmodes (mode shapes) are contained in each column of $\mathbf{S}$. Create a plot for each mode shape with these specifications:- The title of each plot should be the frequency of the corresponding modeshape in Hz.- The y axis should be made up of the values [0, 3, 6, 9, 12] me... | S[:, 0]
np.hstack((0, S[:, 0]))
u1 = S[:, 0]
u1
u1[::-1]
S[:, 2]
fig, axes = plt.subplots(1, 4)
for i in range(4):
axes[i].plot(np.hstack((0, S[:, i])), [0, 3, 6, 9, 12], marker='o')
axes[i].set_title('{:1.2f} Hz'.format(fs[i]))
plt.tight_layout()
fs[0]
S[:, 0]
sys.coordinates['x1'] = S[0, 2]
sys.coordina... | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
Simulating the trajectoryThe trajectory of building's coordinates can be found with:$$\mathbf{x}(t) = \sum_{i=1}^n c_i \sin(\omega_i t + \phi_i) \mathbf{u}_i$$where$$\phi_i = \arctan \frac{\omega_i \mathbf{v}_i^T \mathbf{q}_0}{\mathbf{v}_i^T \dot{\mathbf{q}}_0}$$and$$c_i = \frac{\mathbf{v}^T_i \mathbf{q}_0}{\sin\phi_i... | for i in range(4):
x0 = S[:, i]
xd0 = np.zeros(4)
print(x0)
q0 = L.T @ x0
qd0 = L.T @ xd0
phis = np.arctan2(ws * P.T @ q0, P.T @ xd0)
print(np.rad2deg(phis))
cs = P.T @ q0 / np.sin(phis)
print(cs)
print('=' * 40) | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
ExerciseCreate a function called `simulate()` that returns the trajectories of the coordinates given an array of monotonically increasing time values and the initial conditions of the system.It should look like:```pythondef simulate(t, x0, xd0): """Returns the state trajectory. Parameters ========== t ... | def simulate(t, x0, xd0):
q0 = L.T @ x0
qd0 = L.T @ xd0
phis = np.arctan2(ws * P.T @ q0, P.T @ xd0)
cs = P.T @ q0 / np.sin(phis)
x = np.zeros((len(x0), len(t)))
for ci, wi, phii, ui in zip(cs, ws, phis, S.T):
x += ci * np.sin(wi * t + phii) * np.tile(ui, (len(t), 1)).T
... | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
ExerciseUsing the plotting function below, show that the results found here are the same as the simulations from the `FourStoryBuildingSystem` given the same initial conditions. | def plot_trajectories(t, x):
fig, axes = plt.subplots(4, 1)
for i, ax in enumerate(axes.flatten()):
ax.plot(t, x[i])
ax.set_ylabel(r'$x_{}$ [m]'.format(i + 1))
ax.set_xlabel('Time [s]')
plt.tight_layout()
t = np.linspace(0, 50, num=50 * 60)
x0 = np.array([0.001, 0.010, 0.0... | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
This shows the plot of a single mode: | x = simulate(t, S[:, 0], np.zeros(4))
plot_trajectories(t, x) | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
from google.colab import drive
drive.mount('/content/drive')
!ls /content/drive/MyDrive/GitHub/bluebert | 1_data_prep_blue_bert.ipynb elmo mt-bluebert requirements.txt
bert LICENSE.txt NER_output tokenizer
bluebert mribert README.md
| Apache-2.0 | 1_data_prep.ipynb | LyaSolis/exBERT | |
Preprocess Data We will make 2 types of dataset: for BlueBERT pretraining and finetuning and for exBERT. Input file format for BlueBERT: 1. One sentence per line. These should ideally be actual sentences, not entire paragraphs or arbitrary spans of text. (Because we use the sentence boundaries for the "next sentence ... | import pandas as pd
df = pd.read_csv("/content/drive/MyDrive/GitHub/exBERT/data/paragrafs.csv")
df.head(1)
df = df.drop(['Unnamed: 0'], axis = 1)
df.head(1)
import re
# Testing patterns
text = "Patients with. chronic lymphocytic 's leukemia (. CL Patients with chronic. lymphocytic. leukemia (CL"
re.findall("\.(?= [a-z]... | _____no_output_____ | Apache-2.0 | 1_data_prep.ipynb | LyaSolis/exBERT |
2. Blank lines between documents. Document boundaries are needed so that the "next sentence prediction" task doesn't span between documents. | # Adding blank lines between docs
mask = df['articleids'].ne(df['articleids'].shift(-1))
df1 = pd.DataFrame('',index=mask.index[mask] + .5, columns=df.columns)
df = pd.concat([df, df1]).sort_index().reset_index(drop=True).iloc[:-1]
df.tail(3) | _____no_output_____ | Apache-2.0 | 1_data_prep.ipynb | LyaSolis/exBERT |
Now we will put updated text into text file | text_file = []
for row in df['sents']:
row = row.split('\n')
for i in row:
i = i.lstrip()
text_file.append(i)
text_file[:1]
save_file = "drive/MyDrive/GitHub/exBERT/data/bluebert_train_data.txt"
with open(save_file, 'w') as f:
for item in text_file:
f.write("%s\n" % item) | _____no_output_____ | Apache-2.0 | 1_data_prep.ipynb | LyaSolis/exBERT |
Preprocessed PubMed texts corpus used to pre-train the BlueBERT models contains ~4000M words extracted from the PubMed ASCII code version. Other operations include: - lowercasing the text - removing speical chars \x00-\x7F - tokenizing the text using the NLTK Treebank tokenizer | preprocessed_text = []
for line in text_file:
line = line.lower()
line = re.sub(r'[\r\n]+', ' ', line)
line = re.sub(r'[^\x00-\x7F]+', ' ', line)
preprocessed_text.append(line)
preprocessed_text[:1]
len(preprocessed_text)
from nltk import TreebankWordTokenizer
pubmed_sent_nltk = []
for line in preproce... | _____no_output_____ | Apache-2.0 | 1_data_prep.ipynb | LyaSolis/exBERT |
For exBERT text file needs to have paragraphs separated by new lines (no blank lines though). | df = pd.read_csv("/content/drive/MyDrive/GitHub/exBERT/data/paragrafs.csv")
text = df["txts"]
text.to_csv("/content/drive/MyDrive/GitHub/exBERT/data/exbert_train_data.txt", sep='\n', index=False, header=False) | _____no_output_____ | Apache-2.0 | 1_data_prep.ipynb | LyaSolis/exBERT |
`friction_factor` | from particula.util import friction_factor
help(friction_factor) | _____no_output_____ | MIT | docs/documentation/utilities/friction_factor.ipynb | Gorkowski/particula |
!pip install yfinance
!pip install --upgrade mplfinance
#Instalação da Biblioteca TA-lib
url = 'https://launchpad.net/~mario-mariomedina/+archive/ubuntu/talib/+files'
!wget $url/libta-lib0_0.4.0-oneiric1_amd64.deb -qO libta.deb
!wget $url/ta-lib0-dev_0.4.0-oneiric1_amd64.deb -qO ta.deb
!dpkg -i libta.deb ta.deb
!pip ... | 17.887107849121094
1788.7107849121094
dias negociados: 0, qtd_ações: 100, dinheiro: R$ 0, Total Value: R$ 1788.7107849121094, Lucro: R$ 0.0
17.8153076171875
1788.7107849121094
dias negociados: 1, qtd_ações: 100, dinheiro: R$ 0, Total Value: R$ 1781.53076171875, Lucro: R$ -7.180023193359375
17.49220848083496
1788.710784... | MIT | I2A2_PETR4_Multinomial_Naive_Bayes_+_ARIMA_Trading_System.ipynb | nakanoelio/I2A2-challenge-petr4-trad-sys | |
# We install the FER() library to perform facial recognition
# This installation will also take care of any of the above dependencies if they are missing
pip install fer
from fer import FER
import matplotlib.pyplot as plt
%matplotlib inline
test_image_one = plt.imread("/content/Image-One.jpeg")
emo_detector = FER(mtc... | _____no_output_____ | MIT | 06. Emotion Recognition using Facial Images/Code/Face_Emotion_Recognition_from_Images.ipynb | Jamess-ai/ai-with-python-series | |
Bổ trợ bài giảng về Đại số tuyến tính - Phần 1 MaSSP 2018, Computer ScienceTài liệu ngắn này đưa ra định nghĩa một số khái niệm cơ bản trong đại số tuyến tính liên quan đến vector và ma trận. 1. Một số khái niệm 1.1. Vô hướng (Scalar)Một `scalar` là một số bất kì thuộc tập số nào đó.Khi định nghĩa một số ta phải chỉ r... | x = 1
print(type(x))
y = 2.0
print(type(y)) | <class 'float'>
| MIT | Intro_vector_and_matrix.ipynb | vietthao2000/pre-program-package-2018-part-2 |
Hacker News aitextgenA demo on how aitextgen can be used to create bespoke Hacker News submission titles.**NOTE**: This is released as a proof of concept for mini-GPT-2 models; quality of titles may vary. | from aitextgen import aitextgen | _____no_output_____ | MIT | notebooks/hacker_news_demo.ipynb | thundercomb/aitextgen |
Loading the Hacker News ModelThe `minimaxir/hacker-news` model was finetuned on HN submissions up until May 12th with atleast 5 points.It uses a custom GPT-2 architecture that is only 30 MB on disk (compared to 124M GPT-2's 500MB on disk.)Running the cell will download the model and cache it into `/aitextgen`. | ai = aitextgen(model="minimaxir/hacker-news") | INFO:aitextgen:Loading minimaxir/hacker-news model from /aitextgen.
| MIT | notebooks/hacker_news_demo.ipynb | thundercomb/aitextgen |
GenerationSince the model is so small, generation happens almost immediately, even in bulk. | ai.generate()
ai.generate(5) | Ask HN: Should I start writing a blog post in Python?
==========
The Psychology of Human Misjudgment (2012)
==========
New York' New Year: $99 Linux PC
==========
C++11/12 Released
==========
Dynamic types in Go
| MIT | notebooks/hacker_news_demo.ipynb | thundercomb/aitextgen |
Prompted InputYou can seed input with a `prompt` to get specific types of HN posts. The prompt will be **bolded** in the output. | ai.generate(5, prompt="Ask HN")
ai.generate(5, prompt="Show HN")
ai.generate(5, prompt="Elon Musk")
ai.generate(5, prompt="Google says") | [1mGoogle says[0m its employees are working with Amazon and Apple
==========
[1mGoogle says[0m it’s peaked
==========
[1mGoogle says[0m it is flea banning visible to people who worked in U.S.
==========
[1mGoogle says[0m it will not allow enemy mine to secure sensitive information
==========
[1mGoogle says[0m... | MIT | notebooks/hacker_news_demo.ipynb | thundercomb/aitextgen |
Bulk Generation to FileYou can use `generate_to_file()` to create many HN titles. | ai.generate_to_file(1000, batch_size=20) | INFO:aitextgen:Generating 1,000 texts to ATG_20200517_235441_14821584.txt
| MIT | notebooks/hacker_news_demo.ipynb | thundercomb/aitextgen |
Week 2 January 11-15: Introduction to the course and start Variational Monte Carlo **Morten Hjorth-Jensen Email morten.hjorth-jensen@fys.uio.no**, Department of Physics and Center fo Computing in Science Education, University of Oslo, Oslo, Norway and Department of Physics and Astronomy and Facility for Rare Ion Bea... | # Common imports
import os
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "Results/VMCHarmonic"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exi... | _____no_output_____ | CC0-1.0 | doc/pub/week1/ipynb/.ipynb_checkpoints/week1-checkpoint.ipynb | Schoyen/ComputationalPhysics2 |
We proceed with the implementation of the Monte Carlo algorithm but list first the ansatz for the wave function and the expression for the local energy | %matplotlib inline
# VMC for the one-dimensional harmonic oscillator
# Brute force Metropolis, no importance sampling and no energy minimization
from math import exp, sqrt
from random import random, seed
import numpy as np
import matplotlib.pyplot as plt
from numba import jit
from decimal import *
# Trial wave functio... | _____no_output_____ | CC0-1.0 | doc/pub/week1/ipynb/.ipynb_checkpoints/week1-checkpoint.ipynb | Schoyen/ComputationalPhysics2 |
Note that in the Metropolis algorithm there is no need to compute thetrial wave function, mainly since we are just taking the ratio of twoexponentials. It is then from a computational point view, moreconvenient to compute the argument from the ratio and then calculatethe exponential. Here we have refrained from this pu... | # The Monte Carlo sampling with the Metropolis algo
# The jit decorator tells Numba to compile this function.
# The argument types will be inferred by Numba when the function is called.
def MonteCarloSampling():
NumberMCcycles= 100000
StepSize = 1.0
# positions
PositionOld = 0.0
PositionNew = 0.0
... | _____no_output_____ | CC0-1.0 | doc/pub/week1/ipynb/.ipynb_checkpoints/week1-checkpoint.ipynb | Schoyen/ComputationalPhysics2 |
Finally, the results are presented here with the exact energies and variances as well. | #Here starts the main program with variable declarations
MaxVariations = 20
Energies = np.zeros((MaxVariations))
ExactEnergies = np.zeros((MaxVariations))
ExactVariance = np.zeros((MaxVariations))
Variances = np.zeros((MaxVariations))
AlphaValues = np.zeros(MaxVariations)
(Energies, AlphaValues, Variances) = MonteCarlo... | _____no_output_____ | CC0-1.0 | doc/pub/week1/ipynb/.ipynb_checkpoints/week1-checkpoint.ipynb | Schoyen/ComputationalPhysics2 |
Домашнее задание «Доверительные интервалы. Статистическая проверка гипотез для несвязанных выборок» | import scipy.stats as stats
import pandas as pd
import numpy as np
import scipy as sp
| _____no_output_____ | MIT | confidence_intervals/confidence_intervals.ipynb | aleksander-ivanov/pyda_homeworks |
1. Найдите минимально необходимый объем выборки для построения интервальной оценки среднего с точностью ∆ = 3, дисперсией (stddev) σ^2 = 225 и уровнем доверия β = 0.95. | # β = 1 − α # формула уровня доверия, те вероятность принять неправильную нулевую гипотезу
# α = 1 − β # уровень значимости (обычно 5%), те вероятность отвергнуть правильную нулевую гипотезу (вероятность ошибки первого рода).
# p-value - минимальное значение уровня значимости, при котором мы отвергаем нулевую гипотезу
... | _____no_output_____ | MIT | confidence_intervals/confidence_intervals.ipynb | aleksander-ivanov/pyda_homeworks |
2. Вам даны две выборки роста мужчин и женщин. Докажите, используя t-Тест Стьдента, что различия между выборками незначительно, если уровень значимости равен 0.001 | np.random.seed(12)
population_men = stats.norm.rvs(loc=19,scale=171,size=11000000) # Выборка мужчин со средним ростом 171
population_women = stats.norm.rvs(loc=16,scale=165,size=12000) # Выборка женщин со средним ростом 165
t , p = stats.ttest_ind(population_men,population_women)
print("t = " + str(t))
print("p = " ... | _____no_output_____ | MIT | confidence_intervals/confidence_intervals.ipynb | aleksander-ivanov/pyda_homeworks |
3. Определите объем необходимой выборки для исследования среднего чека за кофе в случайном городе, если известно, что в этом городе стандартное отклонение = 150, уровень доверия = 95%. Погрешность 50 рублей. | sigma = 150
Z = 1.96 # 95%
e = 3
N = ((sigma*Z)/e)**2
N | _____no_output_____ | MIT | confidence_intervals/confidence_intervals.ipynb | aleksander-ivanov/pyda_homeworks |
4. Представьте, что вы хотите разоблачить "волшебника", который считает, что умеет предсказывать погоду на завтра. Отвечая просто: дождь или солнце. Вы пронаблюдали за ответами "волшебника" в течении какого периода времени и получили такие результаты (см.ниже). Можно ли сказать, что маг действительно умеет предсказыва... | observations = pd.DataFrame([[25,36],[15,44]],
index=['Дождь','Солнце'],
columns=['Ответ волшебника','Реальность'])
observations
oddsratio, pvalue = sp.stats.fisher_exact(observations)
pvalue | _____no_output_____ | MIT | confidence_intervals/confidence_intervals.ipynb | aleksander-ivanov/pyda_homeworks |
Вывод: значение pvalue больше уровня значимости, это значит мы не может отклонить нулевую гипотезу тк результат статистически не значим и мы не можем утверждать что волшебник действительно может предсказывать погоду. 5. Используя функцию mean_confidence_interval(data, confidence), постройте доверительный интервал с уро... | def mean_confidence_interval(data, confidence=0.95):
n = len(data)
m, se = np.mean(data), stats.sem(data)
h = se * stats.t.ppf((1 + confidence)/2, n)
return m-h,m, m+h#,h
data = [4,5,8,9,6,7,5,6,7,8,5,6,7,0,9,8,4,6,7,9,8,6,5,7,8,9,6,7,5,8,6,7,9,5,10]
mean_confidence_interval(data, 0.90) | _____no_output_____ | MIT | confidence_intervals/confidence_intervals.ipynb | aleksander-ivanov/pyda_homeworks |
6. Принадлежит ли выборка data_1 и data_2 одному множеству? Оцените это с помощью известных вам тестов проверки гипотез. | data_1 = [4,5,8,9,6,7,5,6,7,8,5,6,7,0,9,8,4,6,7,9,8,6,5,7,8,9,6,7,5,8,6,7,9,5,10]
data_2 = [8,5,6,7,0,1,8,4,6,7,0,2,6,5,7,5,3,5,3,5,3,5,5,8,7,6,4,5,3,5,4,6,4,5,3,2,6,4,2,6,1,0,4,3,5,4,3,4,5,4,3,4,5,4,3,4,5,3,4,4,1,2,4,3,1,2,4,3,2,1,5,3,4,6,4,5,3,2,4,5,6,4,3,1,3,5,3,4,4,4,2,5,3]
stats.ttest_ind(data_1,data_2) | _____no_output_____ | MIT | confidence_intervals/confidence_intervals.ipynb | aleksander-ivanov/pyda_homeworks |
По t-тесту Стьюдента мы получили достаточно высокое значение pvalue (> 0.05), соответственно отвергаем нулевую гипотезу, что означает две данные выборки не принадлежат одному множеству. 7. На примере датасета про жилье в New York City, мы сталкивались с примером, когда переменная имеет не совсем нормальное распределени... | np.random.seed(11)
A = stats.norm.rvs(scale=50,loc=10,size=300)
B = A+stats.norm.rvs(scale=10,loc=-1.25,size=300)
pd.DataFrame(A).hist(bins=120)
pd.DataFrame(B).hist(bins=120)
stats.ttest_ind(a=A,b=B,equal_var=False) | _____no_output_____ | MIT | confidence_intervals/confidence_intervals.ipynb | aleksander-ivanov/pyda_homeworks |
Testing our model on validation dataset which is taken as test_dataset | import torch
import albumentations
import numpy as np
import matplotlib.pyplot as plt
from torch.nn import functional as F
from PIL import Image, ImageFile
import sys
sys.path.append('../src')
from dataset import ClassificationDataset
from model import CaptchaModel
import glob
import os
from torch import nn
from sklear... | _____no_output_____ | MIT | notebooks/test.ipynb | saty101/Captcha-Text-Recognition |
Prediction of the model | from train import decode_predictions, remove_duplicates
preds = decode_predictions(x, lbl_enc)
preds | _____no_output_____ | MIT | notebooks/test.ipynb | saty101/Captcha-Text-Recognition |
The original Label of the Captcha | for t in temp2:
print(lbl_enc.classes_[t-1],end='') | 44c22 | MIT | notebooks/test.ipynb | saty101/Captcha-Text-Recognition |
Customize Scalar Bars {scalar_bar_example}=====================Walk through of all the different capabilities of scalar bars and how auser can customize scalar bars. | # sphinx_gallery_thumbnail_number = 2
import pyvista as pv
from pyvista import examples | _____no_output_____ | MIT | scalar-bars.ipynb | UttamBasu/ipygany_examples |
By default, when plotting a dataset with a scalar array, a scalar barfor that array is added. To turn off this behavior, a user could specify`show_scalar_bar=False` when calling `.add_mesh()`. Let\'s start with asample dataset provide via PyVista to demonstrate the default behaviorof scalar bar plotting: | # Load St Helens DEM and warp the topography
mesh = examples.download_st_helens().warp_by_scalar()
# First a default plot with jet colormap
p = pv.Plotter()
# Add the data, use active scalar for coloring, and show the scalar bar
p.add_mesh(mesh)
# Display the scene
p.show() | _____no_output_____ | MIT | scalar-bars.ipynb | UttamBasu/ipygany_examples |
We could also plot the scene with an interactive scalar bar to movearound and place where we like by specifying passing keyword argumentsto control the scalar bar via the `scalar_bar_args` parameter in`pyvista.BasePlotter.add_mesh`{.interpreted-text role="func"}. Thekeyword arguments to control the scalar bar are defin... | # create dictionary of parameters to control scalar bar
sargs = dict(interactive=True) # Simply make the bar interactive
p = pv.Plotter(notebook=False) # If in IPython, be sure to show the scene
p.add_mesh(mesh, scalar_bar_args=sargs)
p.show()
# Remove from plotters so output is not produced in docs
pv.plotting._ALL... | _____no_output_____ | MIT | scalar-bars.ipynb | UttamBasu/ipygany_examples |
Or manually define the scalar bar\'s location: | # Set a custom position and size
sargs = dict(height=0.25, vertical=True, position_x=0.05, position_y=0.05)
p = pv.Plotter()
p.add_mesh(mesh, scalar_bar_args=sargs)
p.show() | _____no_output_____ | MIT | scalar-bars.ipynb | UttamBasu/ipygany_examples |
The text properties of the scalar bar can also be controlled: | # Controlling the text properties
sargs = dict(
title_font_size=20,
label_font_size=16,
shadow=True,
n_labels=3,
italic=True,
fmt="%.1f",
font_family="arial",
)
p = pv.Plotter()
p.add_mesh(mesh, scalar_bar_args=sargs)
p.show() | _____no_output_____ | MIT | scalar-bars.ipynb | UttamBasu/ipygany_examples |
Labelling values outside of the scalar range | p = pv.Plotter()
p.add_mesh(mesh, clim=[1000, 2000],
below_color='blue', above_color='red',
scalar_bar_args=sargs)
p.show() | _____no_output_____ | MIT | scalar-bars.ipynb | UttamBasu/ipygany_examples |
Annotate values of interest using a dictionary. The key of thedictionary must be the value to annotate, and the value must be thestring label. | # Make a dictionary for the annotations
annotations = {
2300: "High",
805.3: "Cutoff value",
}
p = pv.Plotter()
p.add_mesh(mesh, scalars='Elevation', annotations=annotations)
p.show() | _____no_output_____ | MIT | scalar-bars.ipynb | UttamBasu/ipygany_examples |
Step 1: Import Libraries | # All imports
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import missingno
import seaborn as sns
from sklearn.feature_selection import SelectKBest, f_regression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linea... | data/vauxhall.csv
data/bmw.csv
data/unclean cclass.csv
data/vw.csv
data/hyundi.csv
data/audi.csv
data/unclean focus.csv
data/toyota.csv
data/ford.csv
data/focus.csv
data/skoda.csv
data/cclass.csv
data/merc.csv
| MIT | uk-used-car-data-set/eda-model.ipynb | tejeshreddy/kaggle-challenges |
Step 2: Reading the Data | data_vw = pd.read_csv("data/vw.csv")
data_vw.shape
data_vw.head()
data_vw.describe()
missingno.matrix(data_vw)
data_vw.isnull().sum() | _____no_output_____ | MIT | uk-used-car-data-set/eda-model.ipynb | tejeshreddy/kaggle-challenges |
Step 3: EDA | categorical_features = [feature for feature in data_vw.columns if data_vw[feature].dtype == 'O']
# Getting the count plot
for feature in categorical_features:
sns.countplot(y=data_vw[feature])
plt.show()
# Getting the barplot
plt.figure(figsize=(10,5), facecolor='w')
sns.barplot(x=data_vw['year'], y=data_vw['pr... | _____no_output_____ | MIT | uk-used-car-data-set/eda-model.ipynb | tejeshreddy/kaggle-challenges |
Step 4: Feature Engineering | data_vw.head() | _____no_output_____ | MIT | uk-used-car-data-set/eda-model.ipynb | tejeshreddy/kaggle-challenges |
Dropping the year column, but instead will create data on how old the car is | data_vw['age_of_car'] = 2020 - data_vw['year']
data_vw.drop(['year'], axis=1, inplace=True)
# Look at the frequency of the ages
sns.countplot(y=data_vw['age_of_car'])
# OHE the categorical variables
data_vw_extended = pd.get_dummies(data_vw)
data_vw_extended.shape
sc = StandardScaler()
data_vw_extended = pd.DataFrame(s... | _____no_output_____ | MIT | uk-used-car-data-set/eda-model.ipynb | tejeshreddy/kaggle-challenges |
Step 5: Feature Selection | # Select the k best features
no_of_features = []
r_2_train = []
r_2_test = []
for k in range(3, 40, 2):
selector = SelectKBest(f_regression, k=k)
X_train_selector = selector.fit_transform(X_train, y_train)
X_test_selector = selector.transform(X_test)
lin_reg = LinearRegression()
lin_reg.fit(X_t... | _____no_output_____ | MIT | uk-used-car-data-set/eda-model.ipynb | tejeshreddy/kaggle-challenges |
k=23 is providing us the best optimal result. Hence training the model on 23 | selector = SelectKBest(f_regression, k=23)
X_train_selector = selector.fit_transform(X_train, y_train)
X_test_selector = selector.transform(X_test)
column_name = data_vw_extended.drop(['price'], axis=1).columns
column_name[selector.get_support()] | _____no_output_____ | MIT | uk-used-car-data-set/eda-model.ipynb | tejeshreddy/kaggle-challenges |
Step 6: Model | def regressor_builder(model):
regressor = model
regressor.fit(X_train_selector, y_train)
score = regressor.score(X_test_selector, y_test)
return regressor, score
list_models = [LinearRegression(), Lasso(), Ridge(), SVR(), RandomForestRegressor(), MLPRegressor()]
model_performance = pd.DataFrame(columns=... | _____no_output_____ | MIT | uk-used-car-data-set/eda-model.ipynb | tejeshreddy/kaggle-challenges |
E2E ML on GCP: MLOps stage 2 : experimentation: get started with Vertex Training for Scikit-Learn View on GitHub Open in Google Cloud Notebooks OverviewThis tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : ex... | ONCE_ONLY = False
if ONCE_ONLY:
! pip3 install -U tensorflow==2.5 $USER_FLAG
! pip3 install -U tensorflow-data-validation==1.2 $USER_FLAG
! pip3 install -U tensorflow-transform==1.2 $USER_FLAG
! pip3 install -U tensorflow-io==0.18 $USER_FLAG
! pip3 install --upgrade google-cloud-aiplatform[tensorboa... | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Restart the kernelOnce you've installed the additional packages, you need to restart the notebook kernel so it can find the packages. | import os
if not os.getenv("IS_TESTING"):
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True) | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Set your project ID**If you don't know your project ID**, you may be able to get your project ID using `gcloud`. | PROJECT_ID = "[your-project-id]" # @param {type:"string"}
if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]":
# Get your GCP project id from gcloud
shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT_ID = shell_output[0]
print("Project ID:"... | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
RegionYou can also change the `REGION` variable, which is used for operationsthroughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.- Americas: `us-central1`- Europe: `europe-west4`- Asia Pacific: `asia-east1`You may not use a multi-regi... | REGION = "us-central1" # @param {type: "string"} | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
TimestampIf you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial. | from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Create a Cloud Storage bucket**The following steps are required, regardless of your notebook environment.**When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.Se... | BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]":
BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket. | ! gsutil mb -l $REGION $BUCKET_NAME | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Finally, validate access to your Cloud Storage bucket by examining its contents: | ! gsutil ls -al $BUCKET_NAME | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Set up variablesNext, set up some variables used throughout the tutorial. Import libraries and define constants | import google.cloud.aiplatform as aip | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Initialize Vertex AI SDK for PythonInitialize the Vertex AI SDK for Python for your project and corresponding bucket. | aip.init(project=PROJECT_ID, staging_bucket=BUCKET_NAME) | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Set hardware acceleratorsYou can set hardware accelerators for training and prediction.Set the variables `TRAIN_GPU/TRAIN_NGPU` and `DEPLOY_GPU/DEPLOY_NGPU` to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container image with 4 ... | if os.getenv("IS_TESTING_TRAIN_GPU"):
TRAIN_GPU, TRAIN_NGPU = (
aip.gapic.AcceleratorType.NVIDIA_TESLA_K80,
int(os.getenv("IS_TESTING_TRAIN_GPU")),
)
else:
TRAIN_GPU, TRAIN_NGPU = (None, None)
if os.getenv("IS_TESTING_DEPLOY_GPU"):
DEPLOY_GPU, DEPLOY_NGPU = (
aip.gapic.Accelerat... | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Set pre-built containersSet the pre-built Docker container image for training and prediction.For the latest list, see [Pre-built containers for training](https://cloud.google.com/ai-platform-unified/docs/training/pre-built-containers).For the latest list, see [Pre-built containers for prediction](https://cloud.google.... | TRAIN_VERSION = "scikit-learn-cpu.0-23"
DEPLOY_VERSION = "sklearn-cpu.0-23"
TRAIN_IMAGE = "{}-docker.pkg.dev/vertex-ai/training/{}:latest".format(
REGION.split("-")[0], TRAIN_VERSION
)
DEPLOY_IMAGE = "{}-docker.pkg.dev/vertex-ai/prediction/{}:latest".format(
REGION.split("-")[0], DEPLOY_VERSION
) | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Set machine typeNext, set the machine type to use for training.- Set the variable `TRAIN_COMPUTE` to configure the compute resources for the VMs you will use for for training. - `machine type` - `n1-standard`: 3.75GB of memory per vCPU. - `n1-highmem`: 6.5GB of memory per vCPU - `n1-highcpu`: 0.9 GB of me... | if os.getenv("IS_TESTING_TRAIN_MACHINE"):
MACHINE_TYPE = os.getenv("IS_TESTING_TRAIN_MACHINE")
else:
MACHINE_TYPE = "n1-standard"
VCPU = "4"
TRAIN_COMPUTE = MACHINE_TYPE + "-" + VCPU
print("Train machine type", TRAIN_COMPUTE) | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Introduction to Scikit-learn trainingOnce you have trained a Scikit-learn model, you will want to save it at a Cloud Storage location, so it can subsequently be uploaded to a `Vertex AI Model` resource. The Scikit-learn package does not have support to save the model to a Cloud Storage location. Instead, you will do t... | # Make folder for Python training script
! rm -rf custom
! mkdir custom
# Add package information
! touch custom/README.md
setup_cfg = "[egg_info]\n\ntag_build =\n\ntag_date = 0"
! echo "$setup_cfg" > custom/setup.cfg
setup_py = "import setuptools\n\nsetuptools.setup(\n\n install_requires=[\n\n 'wget',\n\n... | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Create the task script for the Python training packageNext, you create the `task.py` script for driving the training package. Some noteable steps include:- Command-line arguments: - `model-dir`: The location to save the trained model. When using Vertex AI custom training, the location will be specified in the envir... | %%writefile custom/trainer/task.py
import argparse
import logging
import os
import pickle
import zipfile
from typing import List, Tuple
import pandas as pd
import wget
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.model_selection import train_test_split
from sklearn.naive_b... | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Store training script on your Cloud Storage bucketNext, you package the training folder into a compressed tar ball, and then store it in your Cloud Storage bucket. | ! rm -f custom.tar custom.tar.gz
! tar cvf custom.tar custom
! gzip custom.tar
! gsutil cp custom.tar.gz $BUCKET_NAME/trainer_newsaggr.tar.gz | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Create and run custom training jobTo train a custom model, you perform two steps: 1) create a custom training job, and 2) run the job. Create custom training jobA custom training job is created with the `CustomTrainingJob` class, with the following parameters:- `display_name`: The human readable name for the custom tr... | DISPLAY_NAME = "newsaggr_" + TIMESTAMP
job = aip.CustomPythonPackageTrainingJob(
display_name=DISPLAY_NAME,
python_package_gcs_uri=f"{BUCKET_NAME}/trainer_newsaggr.tar.gz",
python_module_name="trainer.task",
container_uri=TRAIN_IMAGE,
model_serving_container_image_uri=DEPLOY_IMAGE,
project=PROJ... | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Prepare your command-line argumentsNow define the command-line arguments for your custom training container:- `args`: The command-line arguments to pass to the executable that is set as the entry point into the container. - `--model-dir` : For our demonstrations, we use this command-line argument to specify where to ... | MODEL_DIR = "{}/{}".format(BUCKET_NAME, TIMESTAMP)
DATASET_URL = "https://archive.ics.uci.edu/ml/machine-learning-databases/00359/NewsAggregatorDataset.zip"
DIRECT = False
if DIRECT:
CMDARGS = [
"--alpha=" + str(0.9),
"--dataset-url=" + DATASET_URL,
"--model_dir=" + MODEL_DIR,
]
else:
... | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Run the custom training jobNext, you run the custom job to start the training job by invoking the method `run`, with the following parameters:- `model_display_name`: The human readable name for the `Model` resource.- `args`: The command-line arguments to pass to the training script.- `replica_count`: The number of com... | if TRAIN_GPU:
model = job.run(
model_display_name="newsaggr_" + TIMESTAMP,
args=CMDARGS,
replica_count=1,
machine_type=TRAIN_COMPUTE,
accelerator_type=TRAIN_GPU.name,
accelerator_count=TRAIN_NGPU,
base_output_dir=MODEL_DIR,
sync=False,
)
else:
... | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
List a custom training job | _job = job.list(filter=f"display_name={DISPLAY_NAME}")
print(_job) | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Wait for completion of custom training jobNext, wait for the custom training job to complete. Alternatively, one can set the parameter `sync` to `True` in the `run()` method to block until the custom training job is completed. | model.wait() | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Delete a custom training jobAfter a training job is completed, you can delete the training job with the method `delete()`. Prior to completion, a training job can be canceled with the method `cancel()`. | job.delete() | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Cleaning upTo clean up all Google Cloud resources used in this project, you can [delete the Google Cloudproject](https://cloud.google.com/resource-manager/docs/creating-managing-projectsshutting_down_projects) you used for the tutorial.Otherwise, you can delete the individual resources you created in this tutorial:- D... | delete_all = True
if delete_all:
# Delete the dataset using the Vertex dataset object
try:
if "dataset" in globals():
dataset.delete()
except Exception as e:
print(e)
# Delete the model using the Vertex model object
try:
if "model" in globals():
mode... | _____no_output_____ | Apache-2.0 | notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb | mikegre-google/vertex-ai-samples |
Helper functions for processing data and basic transforms> Functions for getting, splitting, and labeling data, as well as generic transforms Get, split, and label For most data source creation we need functions to get a list of items, split them in to train/valid sets, and label them. fastai provides functions to ma... | path = untar_data(URLs.MNIST_TINY)
(path/'train').ls()
# export
def _get_files(p, fs, extensions=None):
p = Path(p)
res = [p/f for f in fs if not f.startswith('.')
and ((not extensions) or f'.{f.split(".")[-1].lower()}' in extensions)]
return res
# export
def get_files(path, extensions=None, recu... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
This is the most general way to grab a bunch of file names from disk. If you pass `extensions` (including the `.`) then returned file names are filtered by that list. Only those files directly in `path` are included, unless you pass `recurse`, in which case all child folders are also searched recursively. `folders` is ... | t3 = get_files(path/'train'/'3', extensions='.png', recurse=False)
t7 = get_files(path/'train'/'7', extensions='.png', recurse=False)
t = get_files(path/'train', extensions='.png', recurse=True)
test_eq(len(t), len(t3)+len(t7))
test_eq(len(get_files(path/'train'/'3', extensions='.jpg', recurse=False)),0)
test_eq(len(t... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
It's often useful to be able to create functions with customized behavior. `fastai.data` generally uses functions named as CamelCase verbs ending in `er` to create these functions. `FileGetter` is a simple example of such a function creator. | #export
def FileGetter(suf='', extensions=None, recurse=True, folders=None):
"Create `get_files` partial function that searches path suffix `suf`, only in `folders`, if specified, and passes along args"
def _inner(o, extensions=extensions, recurse=recurse, folders=folders):
return get_files(o/suf, exten... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
This is simply `get_files` called with a list of standard image extensions. | test_eq(len(t), len(get_image_files(path, recurse=True, folders='train')))
#export
def ImageGetter(suf='', recurse=True, folders=None):
"Create `get_image_files` partial that searches suffix `suf` and passes along `kwargs`, only in `folders`, if specified"
def _inner(o, recurse=recurse, folders=folders): return... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Same as `FileGetter`, but for image extensions. | test_eq(len(get_files(path/'train', extensions='.png', recurse=True, folders='3')),
len(ImageGetter( 'train', recurse=True, folders='3')(path)))
#export
def get_text_files(path, recurse=True, folders=None):
"Get text files in `path` recursively, only in `folders`, if specified."
ret... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Split The next set of functions are used to *split* data into training and validation sets. The functions return two lists - a list of indices or masks for each of training and validation sets. | # export
def RandomSplitter(valid_pct=0.2, seed=None):
"Create function that splits `items` between train/val with `valid_pct` randomly."
def _inner(o):
if seed is not None: torch.manual_seed(seed)
rand_idx = L(list(torch.randperm(len(o)).numpy()))
cut = int(valid_pct * len(o))
r... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Use scikit-learn train_test_split. This allow to *split* items in a stratified fashion (uniformely according to the ‘labels‘ distribution) | # export
def TrainTestSplitter(test_size=0.2, random_state=None, stratify=None, train_size=None, shuffle=True):
"Split `items` into random train and test subsets using sklearn train_test_split utility."
def _inner(o, **kwargs):
train,valid = train_test_split(range_of(o), test_size=test_size, random_stat... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Label The final set of functions is used to *label* a single item of data. | # export
def parent_label(o):
"Label `item` with the parent folder name."
return Path(o).parent.name | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Note that `parent_label` doesn't have anything customize, so it doesn't return a function - you can just use it directly. | test_eq(parent_label(fnames[0]), '3')
test_eq(parent_label("fastai_dev/dev/data/mnist_tiny/train/3/9932.png"), '3')
[parent_label(o) for o in fnames]
#hide
#test for MS Windows when os.path.sep is '\\' instead of '/'
test_eq(parent_label(os.path.join("fastai_dev","dev","data","mnist_tiny","train", "3", "9932.png") ), '... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
`RegexLabeller` is a very flexible function since it handles any regex search of the stringified item. Pass `match=True` to use `re.match` (i.e. check only start of string), or `re.search` otherwise (default).For instance, here's an example the replicates the previous `parent_label` results. | f = RegexLabeller(fr'{os.path.sep}(\d){os.path.sep}')
test_eq(f(fnames[0]), '3')
[f(o) for o in fnames]
f = RegexLabeller(r'(\d*)', match=True)
test_eq(f(fnames[0].name), '9932')
#export
class ColReader(DisplayedTransform):
"Read `cols` in `row` with potential `pref` and `suff`"
def __init__(self, cols, pref=''... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
`cols` can be a list of column names or a list of indices (or a mix of both). If `label_delim` is passed, the result is split using it. | df = pd.DataFrame({'a': 'a b c d'.split(), 'b': ['1 2', '0', '', '1 2 3']})
f = ColReader('a', pref='0', suff='1')
test_eq([f(o) for o in df.itertuples()], '0a1 0b1 0c1 0d1'.split())
f = ColReader('b', label_delim=' ')
test_eq([f(o) for o in df.itertuples()], [['1', '2'], ['0'], [], ['1', '2', '3']])
df['a1'] = df['a... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Categorize - | #export
class CategoryMap(CollBase):
"Collection of categories with the reverse mapping in `o2i`"
def __init__(self, col, sort=True, add_na=False, strict=False):
if is_categorical_dtype(col):
items = L(col.cat.categories, use_list=True)
#Remove non-used categories while keeping o... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Multicategorize - | # export
class MultiCategorize(Categorize):
"Reversible transform of multi-category strings to `vocab` id"
loss_func,order=BCEWithLogitsLossFlat(),1
def __init__(self, vocab=None, add_na=False): super().__init__(vocab=vocab,add_na=add_na,sort=vocab==None)
def setups(self, dsets):
if not dsets: ... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Works in conjunction with ` MultiCategorize` or on its own if you have one-hot encoded targets (pass a `vocab` for decoding and `do_encode=False` in this case) | _tfm = OneHotEncode(c=3)
test_eq(_tfm([0,2]), tensor([1.,0,1]))
test_eq(_tfm.decode(tensor([0,1,1])), [1,2])
tds = Datasets([['b', 'c'], ['a'], ['a', 'c'], []], [[MultiCategorize(), OneHotEncode()]])
test_eq(tds[1], [tensor([1.,0,0])])
test_eq(tds[3], [tensor([0.,0,0])])
test_eq(tds.decode([tensor([False, True, True])]... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
End-to-end dataset example with MNIST Let's show how to use those functions to grab the mnist dataset in a `Datasets`. First we grab all the images. | path = untar_data(URLs.MNIST_TINY)
items = get_image_files(path) | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Then we split between train and validation depending on the folder. | splitter = GrandparentSplitter()
splits = splitter(items)
train,valid = (items[i] for i in splits)
train[:3],valid[:3] | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Our inputs are images that we open and convert to tensors, our targets are labeled depending on the parent directory and are categories. | from PIL import Image
def open_img(fn:Path): return Image.open(fn).copy()
def img2tensor(im:Image.Image): return TensorImage(array(im)[None])
tfms = [[open_img, img2tensor],
[parent_label, Categorize()]]
train_ds = Datasets(train, tfms)
x,y = train_ds[3]
xd,yd = decode_at(train_ds,3)
test_eq(parent_label(train... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
ToTensor - | #export
class ToTensor(Transform):
"Convert item to appropriate tensor class"
order = 5 | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
IntToFloatTensor - | # export
class IntToFloatTensor(DisplayedTransform):
"Transform image to float tensor, optionally dividing by 255 (e.g. for images)."
order = 10 #Need to run after PIL transforms on the GPU
def __init__(self, div=255., div_mask=1): store_attr()
def encodes(self, o:TensorImage): return o.float().div_(sel... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Normalization - | # export
def broadcast_vec(dim, ndim, *t, cuda=True):
"Make a vector broadcastable over `dim` (out of `ndim` total) by prepending and appending unit axes"
v = [1]*ndim
v[dim] = -1
f = to_device if cuda else noop
return [f(tensor(o).view(*v)) for o in t]
# export
@docs
class Normalize(DisplayedTransf... | _____no_output_____ | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
Export - | #hide
from nbdev.export import notebook2script
notebook2script() | Converted 00_torch_core.ipynb.
Converted 01_layers.ipynb.
Converted 01a_losses.ipynb.
Converted 02_data.load.ipynb.
Converted 03_data.core.ipynb.
Converted 04_data.external.ipynb.
Converted 05_data.transforms.ipynb.
Converted 06_data.block.ipynb.
Converted 07_vision.core.ipynb.
Converted 08_vision.data.ipynb.
Converted... | Apache-2.0 | nbs/05_data.transforms.ipynb | hanshin-back/fastai |
[](https://colab.research.google.com/github/JohnSnowLabs/nlu/blob/master/examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_... | import os
! apt-get update -qq > /dev/null
# Install java
! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null
os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"
os.environ["PATH"] = os.environ["JAVA_HOME"] + "/bin:" + os.environ["PATH"]
! pip install nlu pyspark==2.4.4 > /dev/null
import nlu... | --2021-02-17 12:04:57-- http://ckl-it.de/wp-content/uploads/2021/02/chinese_news.csv
Resolving ckl-it.de (ckl-it.de)... 217.160.0.108, 2001:8d8:100f:f000::209
Connecting to ckl-it.de (ckl-it.de)|217.160.0.108|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 21914526 (21M) [text/csv]
Saving to: ... | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Analyzing chinese News Articles With NLU This notebook showcases how to extract Chinese Keywords Unsupervied with YAKE and Named Entities and translate them to English In addition, we will leverage the Chinese WordSegmenter and Lemmatizer to preprocess our data further and get a better view fof our data distribution | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu | |
[Chinese official daily news](https://www.kaggle.com/noxmoon/chinese-official-daily-news-since-2016) Xinwen Lianbo is a daily news programme produced by China Central Television. It is shown simultaneously by all local TV stations in main... | df = pd.read_csv('./chinese_news.csv')
df | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Depending how we pre-process our text, we will get different keywords extracted with YAKE. In This tutorial we will see the effect of **Lemmatization** and **Word Segmentation** and see how the distribution of Keywords changes - Lemmatization- Word Segmentation Apply YAKE - Keyword Extractor to the raw textFirst we d... | yake_df = nlu.load('yake').predict(df.headline)
yake_df | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
The predicted Chinese Keywords dont show up on Pandas Label and you probably do not speek Chinese! This is why we will translate each extracted Keyword into english and then take a look at the distribution again | yake_df.explode('keywords_classes').keywords_classes.value_counts()[0:100].plot.bar(title='Top 100 in Chinese News Articles. No Chinese Keywords :( So lets translate!', figsize=(20,8)) | _____no_output_____ | Apache-2.0 | examples/webinars_conferences_etc/multi_lingual_webinar/4_Unsupervise_Chinese_Keyword_Extraction_NER_and_Translation_from_Chinese_News.ipynb | UPbook-innovations/nlu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.