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 |
|---|---|---|---|---|---|
Storing the other elements on disk: | with open(os.path.join(PROCESSED_DATA, 'unit_span.lst'), 'w') as f:
f.write(str(unit_span))
_ = joblib.dump(labels_scaler, os.path.join(PROCESSED_DATA, 'labels_scaler.joblib')) | _____no_output_____ | MIT-0 | nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb | michaelhoarau/sagemaker-predictive-maintenance |
Memory cleanup | fig.clear()
plt.close(fig)
import gc
_ = gc.collect() | _____no_output_____ | MIT-0 | nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb | michaelhoarau/sagemaker-predictive-maintenance |
О вероятности попасть под удар фигуры, поставленной случайным образом на шахматную доску На шахматную доску случайным образом поставлены две фигуры. С какой вероятностью первая фигура бьёт вторую? В данном ноутбуке представлен расчёт этой вероятности для каждой шахматной фигуры как функции от размера доски. Рассмотрен... | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from string import ascii_uppercase as alphabet | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Функция создания доски Создание доски как пустого массива заданной формы. Также нам понадобится массив такой же формы для хранения цвета надписи на клетках.Заполнение доски: 0 - чёрные клетки, 1 - белые. | def get_board(board_size):
x, y = np.meshgrid(range(board_size), range(board_size))
board = np.empty(shape=(board_size, board_size), dtype='uint8')
text_colors = np.empty_like(board, dtype='<U5')
# force left bottom corner cell to be black
if board_size % 2 == 0:
extra_term = 1
else:
... | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Функция рисования доски Функция создаёт изображение шахматной доски, каждая клетка которой подписана соответствующим значением валентности. | def plot_board(board, text_colors, piece):
board_size = np.shape(board)[0]
x, y = np.meshgrid(range(board_size), range(board_size))
# let figure size be dependent on the board size
plt.figure(figsize=(3*board_size/4, 3*board_size/4))
ax = plt.subplot(111)
ax.imshow(board, cmap='gray', interp... | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Пешка Функция, возвращающая массив валентностей пешечного Графа Иллюстрирует изложенные ниже соображения. | def pawn(valencies):
valencies[0, :] = 0 # empty horizontal line
valencies[1:, 0] = valencies[1:, -1] = 1 # vertical edges
valencies[1:, 1:-1] = 2
return valencies | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Рассмотрим несколько частных случаев в поисках закономерности. | def special_cases(piece, board_sizes):
''' Plot boards of every board_size,
contained in board_sizes list for given piece.
'''
for board_size in board_sizes:
board, text_colors = get_board(board_size=board_size)
plot_board(board, text_colors, piece=piece)
special_cases(piece='Pawn', boar... | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Закономерность очевидна - всегда присутствует горизонталь (верхняя или нижняя - в зависимости от цвета фигуры), с которой пешка не бьёт ни одну клетку - все поля этой горизонтали $0$-валентны. Их количество равно $n$. На крайних вертикалях расположены $1$-валентные клетки, которых $2(n-1)$ штук.Все остальные поля - $2$... | def knight(valencies):
board_size = valencies.shape[0]
if board_size > 3:
# Four points in each corner are the same for any board size > 3.
# corner cells
valencies[0, 0] = valencies[0, -1] = \
valencies[-1, 0] = valencies[-1, -1] = 2
# cells horizontally/vert... | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Количество $2$- и $3$-валентных клеток фиксировано при любом $n\geq 4$. Первые расположены в углах, а вторые прилегают к ним по вертикали и горизонтали. Стало быть, количество $2$-валентных клеток равно $4$, а $3$-валентных - $8$, вдвое больше. $4$-валентные клетки образуют арифметическую прогрессию с начальным элемент... | def bishop_or_queen(piece, valencies):
board_size = np.shape(valencies)[0]
if piece == 'Bishop':
smallest_val = board_size-1
else:
smallest_val = 3*(board_size-1)
# external square
valencies[0, :] = valencies[:, 0] = \
valencies[:, -1] = valencies[-1, :] = sma... | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Видно, что эквивалентные клетки располагаются по периметрам образованных клетками концентрических квадратов. Поскольку при чётных $n$ в центре доски расположены $4$ поля с максимальной валентностью, а при нечётных - одно, случаи чётных и нечётных $n$ представляется удобным рассмотреть раздельно. Чётные $n$ Каково коли... | def rook(valencies):
board_size = np.shape(valencies)[0]
x, y = np.meshgrid(range(board_size), range(board_size))
for i, j in zip(x.flatten(), y.flatten()):
valencies[i, j] = 2*(board_size-1)
return valencies
special_cases(piece='Rook', board_sizes=range(4,6)) | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Известная особенность ладьи - независимо от расположения на доске, она всегда контролирует постоянное количество полей, а именно $2(n-1)$ - это сумма полей по горизонтали и вертикали минус поле, на котором стоит сама ладья.$$P(X_{rook}) = \frac{n^{2}\cdot 2(n-1)}{n^{2}(n^{2}-1)} = \frac{2}{(n+1)}.$$ Ферзь | special_cases(piece='Queen', board_sizes=range(4,8)) | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Поскольку ферзь сочетает в себе возможности офицера и ладьи, выражение для него может быть получено как сумма выражений для этих фигур: $$ P(X_{queen}) = \frac{2(2n-1)}{3n(n+1)} + \frac{2}{n+1} = \frac{2(2n-1) + 6n}{3n(n+1)} = \frac{{\color{Red} {4n}} - 2 + {\color{Red} {6n}}}{3n(n+1)} = \frac{10n - 2}{3n(n+1)} = \frac... | def king(valencies):
# corners : top left = top right = \
# bottom left = bottom right
valencies[0, 0] = valencies[0, -1] = \
valencies[-1, 0] = valencies[-1, -1] = 3
# edges : top, left, right, bottom
valencies[0, 1:-1] = valencies[1:-1, 0] = \
valencies[1:-1, ... | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Видно, что края доски, за исключением $3$-валентных углов, $5$-валентны, а всё оставшееся пространство $8$-валентно. Ввиду того, что краёв $4$, а $5$-валентных клеток на одном краю $(n-2)$ штук, имеем: $$ P(X_{king}) = \frac{4\cdot 3}{n^{2}(n^{2}-1)} +\frac{4(n-2)\cdot 5}{n^{2}(n^{2}-1)} +\frac{(n-2)^2\cdot 8}{n^{2}(n^... | def get_probabilities(piece, n):
# NOTE: Results can be incorrect for large n because of dividing by
# the huge denominator!
if piece == 'Pawn':
return 2*(n-1)/((n**2)*(n+1))
elif piece == 'Knight':
return 8*(n-2)/((n**2)*(n+1))
elif piece == 'Bishop':
return 2*(... | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Для проверки аналитических результатов используем метод вычисления вероятности «в лоб» - напрямую из массива валентностей. | def straightforward_prob(piece, board_size):
# Get probability directly from the board of valencies
board, _ = get_board(board_size)
val_board = get_valencies(piece, board)
unique, counts = np.unique(val_board, return_counts=True)
prob = np.dot(unique, counts)/((board_size)**2 * (board_size**2 ... | _____no_output_____ | MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
График, отображающий зависимость вероятности от размера доски, представлен как функция действительного переменного в целях наглядности. | start = 2
end = 16
step = 0.02
x = np.arange(start, end)
names_list = ['Pawn', 'Knight', 'Bishop', 'Rook', 'Queen', 'King']
# Check if analytical results match straightforward calculations
for name in names_list:
for board_size in x:
y = get_probabilities(name, board_size)
if not y == straightforwa... | Analytical results approved
| MIT | 01-Square Boards(RUS).ipynb | esimonov/chess_prob |
Collaborative Filtering on Google Analytics Data Learning objectives1. Prepare the user-item matrix and use it with WALS.2. Train a `WALSMatrixFactorization` within TensorFlow locally and on AI Platform.3. Visualize the embedding vectors with principal components analysis. OverviewThis notebook demonstrates how to i... | import os
PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID
BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME
REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
# Do not change these
os.environ["PROJECT"] = PROJECT
os.environ["BUCKET"] = BUCKET
os.environ["REGION"]... | 1.15.5
| Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/wals.ipynb | ssensalo/training-data-analyst |
Create raw datasetFor collaborative filtering, you don't need to know anything about either the users or the content. Essentially, all you need to know is userId, itemId, and rating that the particular user gave the particular item.In this case, you are working with newspaper articles. The company doesn't ask their us... | from google.cloud import bigquery
bq = bigquery.Client(project = PROJECT)
sql = """
WITH CTE_visitor_page_content AS (
SELECT
# Schema: https://support.google.com/analytics/answer/3437719?hl=en
# For a completely unique visit-session ID, you combine combination of fullVisitorId and visitNumber:
... | 1012012094517511217-1,299949290,1.0
1614877438160481626-349,29455408,1.0
1815317450115839569-235,299807267,0.8569622728727375
1950053456137072413-10,243386345,0.5474309284215766
2179122255490468209-180,299925086,0.03222095793478647
2477455524323251766-1,299936493,0.3514756604914127
277149937495438413-384,299777707,0.14... | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/wals.ipynb | ssensalo/training-data-analyst |
Create dataset for WALSThe raw dataset (above) won't work for WALS: The userId and itemId have to be 0,1,2 ... so you need to create a mapping from visitorId (in the raw data) to userId and contentId (in the raw data) to itemId. You will need to save the above mapping to a file because at prediction time, you'll need ... | import pandas as pd
import numpy as np
def create_mapping(values, filename):
with open(filename, 'w') as ofp:
value_to_id = {value:idx for idx, value in enumerate(values.unique())}
for value, idx in value_to_id.items():
ofp.write("{},{}\n".format(value, idx))
return value_to_id
df =... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/wals.ipynb | ssensalo/training-data-analyst |
Creating rows and columns datasets | import pandas as pd
import numpy as np
mapped_df = pd.read_csv(filepath_or_buffer = "data/collab_mapped.csv", header = None, names = ["userId", "itemId", "rating"])
mapped_df.head()
NITEMS = np.max(mapped_df["itemId"]) + 1
NUSERS = np.max(mapped_df["userId"]) + 1
mapped_df["rating"] = np.round(mapped_df["rating"].value... | total 36580
-rw-r--r-- 1 jupyter jupyter 14124035 May 16 17:32 collab_raw.csv
-rw-r--r-- 1 jupyter jupyter 3529114 May 16 17:32 users.csv
-rw-r--r-- 1 jupyter jupyter 82083 May 16 17:32 items.csv
-rw-r--r-- 1 jupyter jupyter 7667828 May 16 17:32 collab_mapped.csv
-rw-r--r-- 1 jupyter jupyter 2296476 May 16 17:33 ... | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/wals.ipynb | ssensalo/training-data-analyst |
To summarize, you created the following data files from collab_raw.csv: ```collab_mapped.csv``` is essentially the same data as in ```collab_raw.csv``` except that ```visitorId``` and ```contentId``` which are business-specific have been mapped to ```userId``` and ```itemId``` which are enumerated in 0,1,2,.... The ma... | import os
import tensorflow as tf
from tensorflow.python.lib.io import file_io
from tensorflow.contrib.factorization import WALSMatrixFactorization
def read_dataset(mode, args):
# TODO 2: Decode the example
def decode_example(protos, vocab_size):
features = {
"key": tf.FixedLenFeature(shape =... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/wals.ipynb | ssensalo/training-data-analyst |
This code is helpful in developing the input function. You don't need it in production. | def try_out():
with tf.Session() as sess:
fn = read_dataset(
mode = tf.estimator.ModeKeys.EVAL,
args = {"input_path": "data", "batch_size": 4, "nitems": NITEMS, "nusers": NUSERS})
feats, _ = fn()
print(feats["input_rows"].eval())
print(feats["input_r... | 5526,129,885
4712,2402,2620
2710,139,1001
885,5526,3450
202,370,2839
4972,1085,4505
4896,1687,2833
3418,5095,2702
3537,479,4896
1001,4516,2347
| Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/wals.ipynb | ssensalo/training-data-analyst |
Run as a Python moduleLet's run it as Python module for just a few steps. | os.environ["NITEMS"] = str(NITEMS)
os.environ["NUSERS"] = str(NUSERS)
%%bash
rm -rf wals.tar.gz wals_trained
gcloud ai-platform local train \
--module-name=walsmodel.task \
--package-path=${PWD}/walsmodel \
-- \
--output_dir=${PWD}/wals_trained \
--input_path=${PWD}/data \
--num_epochs=0.01 --ni... | Will train for 2 steps, evaluating once every 236 steps
| Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/wals.ipynb | ssensalo/training-data-analyst |
Run on Cloud | %%bash
gsutil -m cp data/* gs://${BUCKET}/wals/data
%%bash
OUTDIR=gs://${BUCKET}/wals/model_trained
JOBNAME=wals_$(date -u +%y%m%d_%H%M%S)
echo $OUTDIR $REGION $JOBNAME
gsutil -m rm -rf $OUTDIR
gcloud ai-platform jobs submit training $JOBNAME \
--region=$REGION \
--module-name=walsmodel.task \
--package-pat... | gs://qwiklabs-gcp-01-7f6e984e70dc/wals/model_trained us-central1 wals_220516_174236
jobId: wals_220516_174236
state: QUEUED
| Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/wals.ipynb | ssensalo/training-data-analyst |
This will take 10 minutes to complete. Rerun the above command until the jobs gets submitted. Get row and column factorsOnce you have a trained WALS model, you can get row and column factors (user and item embeddings) from the checkpoint file. You'll look at how to use these in the section on building a recommendation... | def get_factors(args):
with tf.Session() as sess:
estimator = tf.contrib.factorization.WALSMatrixFactorization(
num_rows = args["nusers"],
num_cols = args["nitems"],
embedding_dimension = args["n_embeds"],
model_dir = args["output_dir"])
row_... | INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_task_type': None, '_task_id': 0, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7fc3e9a79a10>, '_master': '', '_num_ps_replicas': 0, '_num_worker_replicas': 0, '_environment': 'local', '_is_chief': True, '_evaluation... | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/wals.ipynb | ssensalo/training-data-analyst |
You can visualize the embedding vectors using dimensional reduction techniques such as PCA. | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.decomposition import PCA
pca = PCA(n_components = 3)
pca.fit(user_embeddings)
# TODO 3: Apply the mapping (transform) to user embeddings
user_embeddings_pca = pca.transform(user_embeddings)
fig = plt.figure(figsize = (8,8))
ax = fig.... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/wals.ipynb | ssensalo/training-data-analyst |
To apply arbitrary forcing to a single degree of freedom linear or nonlinear system, you can do so with `SingleDoFNonLinearSystem` (`SingleDoFLinearSystem` does not support arbitrary forcing...yet).Add constants, a generalized coordinate, and a generalized speed to the system. | sys = SingleDoFNonLinearSystem()
sys.constants['m'] = 100 # kg
sys.constants['c'] = 1.1*1.2*0.5/2
sys.constants['k'] = 10
sys.constants['Fo'] = 1000 # N
sys.constants['Ft'] = 100 # N/s
sys.constants['to'] = 3.0 # s
sys.coordinates['x'] = 0.0
sys.speeds['v'] = 0.0 | _____no_output_____ | CC-BY-4.0 | content/materials/notebooks/2020/l13_arbitrary_inputs.ipynb | moorepants/eng122 |
Create a function that evaluates the first order form of the non-linear equations of motion. In this case:$$\dot{x} = v \\m\dot{v} + c \textrm{sgn}(v)v^2 + k \textrm{sgn}(x)x^2 = F(t)$$Make the arbitrary forcing term, $F$, an input to this function. | def eval_eom(x, v, m, c, k, F):
xdot = v
vdot = (F - np.sign(v)*c*v**2 - np.sign(x)*k*x**2) / m
return xdot, vdot | _____no_output_____ | CC-BY-4.0 | content/materials/notebooks/2020/l13_arbitrary_inputs.ipynb | moorepants/eng122 |
Note that you cannot add this to the system because `F` has not been defined. | sys.diff_eq_func = eval_eom | _____no_output_____ | CC-BY-4.0 | content/materials/notebooks/2020/l13_arbitrary_inputs.ipynb | moorepants/eng122 |
To rememdy this, create a function that returns the input value given the appropriate constants and time. | def eval_step_input(Fo, to, time):
if time < to:
return 0.0
else:
return Fo
import matplotlib.pyplot as plt
%matplotlib widget
ts = np.linspace(0, 10)
plt.plot(ts, eval_step_input(5.0, 3.0, ts))
ts < 3.0
def eval_step_input(Fo, to, time):
F = np.empty_like(time)
for i, ti in enumerate(ti... | _____no_output_____ | CC-BY-4.0 | content/materials/notebooks/2020/l13_arbitrary_inputs.ipynb | moorepants/eng122 |
Fit $k_{ij}$ and $r_c^{ABij}$ interactions parameter of Ethanol and CPMEThis notebook has te purpose of showing how to optimize the $k_{ij}$ and $r_c^{ABij}$ for a mixture with induced association.First it's needed to import the necessary modules | import numpy as np
from sgtpy import component, mixture, saftvrmie
from sgtpy.fit import fit_cross | _____no_output_____ | MIT | examples/SGTPy's paper notebooks/Fit Equilibrium Ethanol + CPME.ipynb | MatKie/SGTPy |
Now that the functions are available it is necessary to create the mixture. | ethanol = component('ethanol2C', ms = 1.7728, sigma = 3.5592 , eps = 224.50,
lambda_r = 11.319, lambda_a = 6., eAB = 3018.05, rcAB = 0.3547,
rdAB = 0.4, sites = [1,0,1], cii= 5.3141080872882285e-20)
cpme = component('cpme', ms = 2.32521144, sigma = 4.13606074, eps = 343.9119379... | _____no_output_____ | MIT | examples/SGTPy's paper notebooks/Fit Equilibrium Ethanol + CPME.ipynb | MatKie/SGTPy |
Now the experimental equilibria data is read and a tuple is created. It includes the experimental liquid composition, vapor composition, equilibrium temperature and pressure. This is done with ```datavle = (Xexp, Yexp, Texp, Pexp)``` | # Experimental data obtained from Mejia, Cartes, J. Chem. Eng. Data, vol. 64, no. 5, pp. 1970–1977, 2019
# Experimental temperature saturation in K
Texp = np.array([355.77, 346.42, 342.82, 340.41, 338.95, 337.78, 336.95, 336.29,
335.72, 335.3 , 334.92, 334.61, 334.35, 334.09, 333.92, 333.79,
333.72, 333.... | _____no_output_____ | MIT | examples/SGTPy's paper notebooks/Fit Equilibrium Ethanol + CPME.ipynb | MatKie/SGTPy |
The function ```fit_cross``` optimize the $k_{ij}$ correction and $r_c^{ABij}$ distance. An initial guess is needed, as well as the mixture object, the index of the self-associating component and the equilibria data. | #initial guesses for kij and rcij
x0 = [0.01015194, 2.23153033]
fit_cross(x0, mix, assoc=0, datavle=datavle) | _____no_output_____ | MIT | examples/SGTPy's paper notebooks/Fit Equilibrium Ethanol + CPME.ipynb | MatKie/SGTPy |
BAYES CLASSIFIERSFor any classifier $f:{X \to Y}$, it's prediction error is:$P(f(x) \ne Y) = \mathbb{E}[ \mathbb{1}(f(X) \ne Y)] = \mathbb{E}[\mathbb{E}[ \mathbb{1}(f(X) \ne Y)|X]]$For each $x \in X$,$$\mathbb{E}[ \mathbb{1}(f(X) \ne Y)|X = x] = \sum\limits_{y \in Y} P(Y = y|X = x) \cdot \mathbb{1}(f(x) \ne y)$$The ... | ##IMPORTING ALL NECESSARY SUPPORT LIBRARIES
import math as mt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def separate_by_label(dataset):
separate = dict()
for i in range(len(dataset)):
row = dataset[i]
label = row[-1]
if (label not in separa... | _____no_output_____ | MIT | ML SERIES - NAIVE BAYES/MACHINE LEARNING TOP ALGORITHMS - NAIVE BAYES CLASSIFIER.ipynb | acadena-repo/MACHINE-LEARNING-TOP-ALGORITHMS-SERIES |
Now it is time to use the statistics calculated from the data to calculate probabilities for new data.Probabilities are calculated separately for each class, so we calculate the probability that a new piece of data belongs to the first class, then calculate the probability that it belongs to the second class, and so on... | def class_probabilities(summary, row):
total = sum([summary[label][0][2] for label in summary])
probabilities = dict()
for class_, class_summary in summary.items():
probabilities[class_] = summary[class_][0][2]/total
for i in range(len(class_summary)):
mean, stdev, count = c... | _____no_output_____ | MIT | ML SERIES - NAIVE BAYES/MACHINE LEARNING TOP ALGORITHMS - NAIVE BAYES CLASSIFIER.ipynb | acadena-repo/MACHINE-LEARNING-TOP-ALGORITHMS-SERIES |
In order to verify proper implementation a **toy dataset** is used to evaluate the algorithm. | dataset = [[3.393533211,2.331273381,0],
[3.110073483,1.781539638,0],
[1.343808831,3.368360954,0],
[3.582294042,4.67917911,0],
[2.280362439,2.866990263,0],
[7.423436942,4.696522875,1],
[5.745051997,3.533989803,1],
[9.172168622,2.511101045,1],
[7.792783481,3.424088941,1],
[7.939820817,0.791637231,1]]
summaries = summary... | Expected=0, Predicted=0
Expected=0, Predicted=0
Expected=0, Predicted=0
Expected=0, Predicted=0
Expected=0, Predicted=0
Expected=1, Predicted=1
Expected=1, Predicted=1
Expected=1, Predicted=1
Expected=1, Predicted=1
Expected=1, Predicted=1
| MIT | ML SERIES - NAIVE BAYES/MACHINE LEARNING TOP ALGORITHMS - NAIVE BAYES CLASSIFIER.ipynb | acadena-repo/MACHINE-LEARNING-TOP-ALGORITHMS-SERIES |
_GAUSSIAN NAIVE BAYES APPLICATION_From the `UCI Machine Learning Repository` which contains Iris dataset, we will train our `Gaussian Naive Bayes` model. The Iris dataset is perhaps the best known database to be found in the pattern recognition literature. Fisher's paper is a classic in the field and is referenced fre... | from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import classification_report
##LOADING 'IRIS' DATASET
columns = ['sepal-len','sepal-wid','petal-len','petal-wid','class']
df = pd.read_csv('./data/Iris.csv', names = columns)
df.head()
df.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
sepal-len 150 non-null float64
sepal-wid 150 non-null float64
petal-len 150 non-null float64
petal-wid 150 non-null float64
class 150 non-null object
dtypes: float64(4), object(1)
memory usage: 5.9... | MIT | ML SERIES - NAIVE BAYES/MACHINE LEARNING TOP ALGORITHMS - NAIVE BAYES CLASSIFIER.ipynb | acadena-repo/MACHINE-LEARNING-TOP-ALGORITHMS-SERIES |
Due to the class variable type is `categorical` we need first to encode it as numeric type in order to be feed it into our models. | def encoder(df, class_value_pair):
for class_name, value in class_value_pair.items():
df['class'] = df['class'].replace(class_name, value)
return df
class_encoder = {'Iris-setosa':0, 'Iris-versicolor':1, 'Iris-virginica':2}
df = encoder(df, class_encoder)
df.head()
df['class'].value_counts().so... | _____no_output_____ | MIT | ML SERIES - NAIVE BAYES/MACHINE LEARNING TOP ALGORITHMS - NAIVE BAYES CLASSIFIER.ipynb | acadena-repo/MACHINE-LEARNING-TOP-ALGORITHMS-SERIES |
Once the preprocessing is complete the dataset will be split into a `Training` & `Test` dataset. | X_ = df.drop(['class'],axis = 1)
y = df['class']
X_train, X_test, y_train, y_test = train_test_split(X_, y, test_size = 0.30, random_state = 5) | _____no_output_____ | MIT | ML SERIES - NAIVE BAYES/MACHINE LEARNING TOP ALGORITHMS - NAIVE BAYES CLASSIFIER.ipynb | acadena-repo/MACHINE-LEARNING-TOP-ALGORITHMS-SERIES |
Now, we can `train` our customized model. Noticed that our _Gaussian Naive Bayes_ model expects a complete dataset (attributes and labels) in order to calculate the summaries. | ds_train = pd.concat([X_train, y_train], axis = 1)
GNB_custom = summary_by_class(ds_train.values.tolist())
ds_test = pd.concat([X_test, y_test], axis = 1)
cust_pred = [predict(GNB_custom, row) for row in ds_test.values.tolist()]
cust_pred = np.array(cust_pred, dtype = 'int64')
cust_pred | _____no_output_____ | MIT | ML SERIES - NAIVE BAYES/MACHINE LEARNING TOP ALGORITHMS - NAIVE BAYES CLASSIFIER.ipynb | acadena-repo/MACHINE-LEARNING-TOP-ALGORITHMS-SERIES |
Now an instance of `sklearn` _Gaussian Naive Bayes_ model is created and fit it with the training data and an array of predictions is obtained in order to get out performance comparation | ##GET AND INSTANCE OF GAUSSIAN NAIVE BAYES MODEL
GNB_skln = GaussianNB()
GNB_skln.fit(X_train, y_train)
##CREATE SKLEARN PREDICTIONS ARRAY
sk_pred = GNB_skln.predict(X_test)
sk_pred | _____no_output_____ | MIT | ML SERIES - NAIVE BAYES/MACHINE LEARNING TOP ALGORITHMS - NAIVE BAYES CLASSIFIER.ipynb | acadena-repo/MACHINE-LEARNING-TOP-ALGORITHMS-SERIES |
By last, a comparison on both models is performed thru a _Classification Report_ | print("Sklearn:")
print(classification_report(y_test, sk_pred))
print("Custom:")
print(classification_report(y_test, cust_pred)) | Sklearn:
precision recall f1-score support
0 1.00 1.00 1.00 15
1 0.88 0.94 0.91 16
2 0.92 0.86 0.89 14
micro avg 0.93 0.93 0.93 45
macro avg 0.94 0.93 ... | MIT | ML SERIES - NAIVE BAYES/MACHINE LEARNING TOP ALGORITHMS - NAIVE BAYES CLASSIFIER.ipynb | acadena-repo/MACHINE-LEARNING-TOP-ALGORITHMS-SERIES |
Mini Project: Temporal-Difference MethodsIn this notebook, you will write your own implementations of many Temporal-Difference (TD) methods.While we have provided some starter code, you are welcome to erase these hints and write your code from scratch. Part 0: Explore CliffWalkingEnvUse the code cell below to create ... | import gym
env = gym.make('CliffWalking-v0') | _____no_output_____ | MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
The agent moves through a $4\times 12$ gridworld, with states numbered as follows:```[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]]```At the start of any episode, sta... | print(env.action_space)
print(env.observation_space) | Discrete(4)
Discrete(48)
| MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
In this mini-project, we will build towards finding the optimal policy for the CliffWalking environment. The optimal state-value function is visualized below. Please take the time now to make sure that you understand _why_ this is the optimal state-value function. | import numpy as np
from plot_utils import plot_values
# define the optimal state-value function
V_opt = np.zeros((4,12))
V_opt[0:13][0] = -np.arange(3, 15)[::-1]
V_opt[0:13][1] = -np.arange(3, 15)[::-1] + 1
V_opt[0:13][2] = -np.arange(3, 15)[::-1] + 2
V_opt[3][0] = -13
plot_values(V_opt) | _____no_output_____ | MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
Part 1: TD Prediction: State ValuesIn this section, you will write your own implementation of TD prediction (for estimating the state-value function).We will begin by investigating a policy where the agent moves:- `RIGHT` in states `0` through `10`, inclusive, - `DOWN` in states `11`, `23`, and `35`, and- `UP` in sta... | policy = np.hstack([1*np.ones(11), 2, 0, np.zeros(10), 2, 0, np.zeros(10), 2, 0, -1*np.ones(11)])
print("\nPolicy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):")
print(policy.reshape(4,12)) |
Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):
[[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 2.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 2.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 2.]
[ 0. -1. -1. -1. -1. -1. -1. -1. -1. -1. -1. -1.]]
| MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
Run the next cell to visualize the state-value function that corresponds to this policy. Make sure that you take the time to understand why this is the corresponding value function! | V_true = np.zeros((4,12))
for i in range(3):
V_true[0:12][i] = -np.arange(3, 15)[::-1] - i
V_true[1][11] = -2
V_true[2][11] = -1
V_true[3][0] = -17
plot_values(V_true) | _____no_output_____ | MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
The above figure is what you will try to approximate through the TD prediction algorithm.Your algorithm for TD prediction has five arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.- `policy`: Thi... | from collections import defaultdict, deque
import sys
def td_prediction(env, num_episodes, policy, alpha, gamma=1.0):
# initialize empty dictionaries of floats
V = defaultdict(float)
# loop over episodes
for i_episode in range(1, num_episodes+1):
# monitor progress
if i_episode % 100 ==... | _____no_output_____ | MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
Run the code cell below to test your implementation and visualize the estimated state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd like to ensur... | import check_test
# evaluate the policy and reshape the state-value function
V_pred = td_prediction(env, 5000, policy, .01)
# please do not change the code below this line
V_pred_plot = np.reshape([V_pred[key] if key in V_pred else 0 for key in np.arange(48)], (4,12))
check_test.run_check('td_prediction_check', V_pr... | Episode 5000/5000 | MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
How close is your estimated state-value function to the true state-value function corresponding to the policy? You might notice that some of the state values are not estimated by the agent. This is because under this policy, the agent will not visit all of the states. In the TD prediction algorithm, the agent can on... | def update_Q(Qsa, Qsa_next, reward, alpha, gamma):
""" updates the action-value function estimate using the most recent time step """
return Qsa + (alpha * (reward + (gamma * Qsa_next) - Qsa))
def epsilon_greedy_probs(env, Q_s, i_episode, eps=None):
""" obtains the action probabilities corresponding to eps... | _____no_output_____ | MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd ... | # obtain the estimated optimal policy and corresponding action-value function
Q_sarsa = sarsa(env, 5000, .01)
# print the estimated optimal policy
policy_sarsa = np.array([np.argmax(Q_sarsa[key]) if key in Q_sarsa else -1 for key in np.arange(48)]).reshape(4,12)
check_test.run_check('td_control_check', policy_sarsa)
p... | Episode 5000/5000 | MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
Part 3: TD Control: Q-learningIn this section, you will write your own implementation of the Q-learning control algorithm.Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction... | def q_learning(env, num_episodes, alpha, gamma=1.0):
# initialize action-value function (empty dictionary of arrays)
Q = defaultdict(lambda: np.zeros(env.nA))
# initialize performance monitor
plot_every = 100
tmp_scores = deque(maxlen=plot_every)
scores = deque(maxlen=num_episodes)
# loop ov... | _____no_output_____ | MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd l... | # obtain the estimated optimal policy and corresponding action-value function
Q_sarsamax = q_learning(env, 5000, .01)
# print the estimated optimal policy
policy_sarsamax = np.array([np.argmax(Q_sarsamax[key]) if key in Q_sarsamax else -1 for key in np.arange(48)]).reshape((4,12))
check_test.run_check('td_control_chec... | Episode 5000/5000 | MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
Part 4: TD Control: Expected SarsaIn this section, you will write your own implementation of the Expected Sarsa control algorithm.Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment int... | def expected_sarsa(env, num_episodes, alpha, gamma=1.0):
# initialize action-value function (empty dictionary of arrays)
Q = defaultdict(lambda: np.zeros(env.nA))
# initialize performance monitor
plot_every = 100
tmp_scores = deque(maxlen=plot_every)
scores = deque(maxlen=num_episodes)
# loo... | _____no_output_____ | MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd ... | # obtain the estimated optimal policy and corresponding action-value function
Q_expsarsa = expected_sarsa(env, 10000, 1)
# print the estimated optimal policy
policy_expsarsa = np.array([np.argmax(Q_expsarsa[key]) if key in Q_expsarsa else -1 for key in np.arange(48)]).reshape(4,12)
check_test.run_check('td_control_che... | Episode 10000/10000 | MIT | ReinforcementLearning/TemporalDifference/Temporal_Difference_Solution.ipynb | xuebai1990/DeepLearningNanodegree |
Lambda School Data Science - Making Data-backed AssertionsThis is, for many, the main point of data science - to create and support reasoned arguments based on evidence. It's not a topic to master in a day, but it is worth some focused time thinking about and structuring your approach to it. Lecture - generating a c... | import random
dir(random) # Reminding ourselves what we can do here
random.seed(10) # Sets Random Seed for Reproducibility
# Let's think of another scenario:
# We work for a company that sells accessories for mobile phones.
# They have an ecommerce site, and we are supposed to analyze logs
# to determine what sort of ... | _____no_output_____ | MIT | LS_DS_114_Making_Data_backed_Assertions.ipynb | elizabethts/DS-Unit-1-Sprint-1-Dealing-With-Data |
Assignment - what's going on here?Consider the data in `persons.csv` (already prepared for you, in the repo for the week). It has four columns - a unique id, followed by age (in years), weight (in lbs), and exercise time (in minutes/week) of 1200 (hypothetical) people.Try to figure out which variables are possibly rel... | import matplotlib.pyplot as plt
# TODO - your code here
# Use what we did live in lecture as an example
# HINT - you can find the raw URL on GitHub and potentially use that
# to load the data with read_csv, or you can upload it yourself
#load data
persons_url = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit... | _____no_output_____ | MIT | LS_DS_114_Making_Data_backed_Assertions.ipynb | elizabethts/DS-Unit-1-Sprint-1-Dealing-With-Data |
train cnn | util.train(model, device, train_loader, test_loader, optimizer, num_epochs, criterion) | Train Epoch: 1 [45000/50000 (90%)] Loss: 1.500776
Test set: Average loss: 0.0002, Accuracy: 4550/10000 (45.50%)
Train Epoch: 2 [45000/50000 (90%)] Loss: 1.379729
Test set: Average loss: 0.0001, Accuracy: 5390/10000 (53.90%)
Train Epoch: 3 [45000/50000 (90%)] Loss: 1.330050
Test set: Average loss: 0.0001, Accuracy: 56... | MIT | notebooks/cifar10/01_train_cifar.ipynb | Yu-Group/adaptive-wavelets |
Monthly Aggregates - Work in Progress - I forgot to set price to 0 - Need to rewatch video! | merged['date_trunc_month'] = merged.apply(lambda x: dt.datetime.strftime(x['Date'],'%Y-%m'), axis=1)
merged['date_trunc_month']
merged['is_start_of_month'] = merged.apply(lambda x: x.name == min(merged[merged['date_trunc_month'] == x['date_trunc_month']].index), axis=1)
merged['is_end_of_month'] = merged.apply(lambda x... | _____no_output_____ | Apache-2.0 | pairs_trading.ipynb | snowr/statarb_rw |
```sqlSELECT startofmonth, stock1, stock2, SUM(lsr) as lsrFROM dailyreturnsGROUP BY startofmonth, stock1, stock2``` | merged[(merged['is_start_of_month'] == True)][['date_trunc_month','lsr']]
merged[(merged['is_start_of_month'] == True) | (merged['is_end_of_month'] == True)][['date_trunc_month','lsr']].plot()
merged['lsr'] = merged.apply(lambda x: 0 if x['is_end_of_month'] is True else x['lsr'], axis=1)
merged[merged['is_end_of_month'... | _____no_output_____ | Apache-2.0 | pairs_trading.ipynb | snowr/statarb_rw |
Convolutional Neural Networks---In this notebook, we train a **CNN** to classify images from the CIFAR-10 database.The images in this database are small color images that fall into one of ten classes; some example images are pictured below. Test for [CUDA](http://pytorch.org/docs/stable/cuda.html)Since these are larg... | import torch
import numpy as np
# check if CUDA is available
train_on_gpu = torch.cuda.is_available()
if not train_on_gpu:
print('CUDA is not available. Training on CPU ...')
else:
print('CUDA is available! Training on GPU ...') | CUDA is available! Training on GPU ...
| MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_augmentation.ipynb | gaoxiao/deep-learning-v2-pytorch |
--- Load and Augment the [Data](http://pytorch.org/docs/stable/torchvision/datasets.html)Downloading may take a minute. We load in the training and test data, split the training data into a training and validation set, then create DataLoaders for each of these sets of data. AugmentationIn this cell, we perform some sim... | from torchvision import datasets
import torchvision.transforms as transforms
from torch.utils.data.sampler import SubsetRandomSampler
# number of subprocesses to use for data loading
num_workers = 0
# how many samples per batch to load
batch_size = 20
# percentage of training set to use as validation
valid_size = 0.2
... | Files already downloaded and verified
Files already downloaded and verified
| MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_augmentation.ipynb | gaoxiao/deep-learning-v2-pytorch |
Visualize a Batch of Training Data | import matplotlib.pyplot as plt
%matplotlib inline
# helper function to un-normalize and display an image
def imshow(img):
img = img / 2 + 0.5 # unnormalize
plt.imshow(np.transpose(img, (1, 2, 0))) # convert from Tensor image
# obtain one batch of training images
dataiter = iter(train_loader)
images, labels ... | _____no_output_____ | MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_augmentation.ipynb | gaoxiao/deep-learning-v2-pytorch |
View an Image in More DetailHere, we look at the normalized red, green, and blue (RGB) color channels as three separate, grayscale intensity images. | rgb_img = np.squeeze(images[3])
channels = ['red channel', 'green channel', 'blue channel']
fig = plt.figure(figsize = (36, 36))
for idx in np.arange(rgb_img.shape[0]):
ax = fig.add_subplot(1, 3, idx + 1)
img = rgb_img[idx]
ax.imshow(img, cmap='gray')
ax.set_title(channels[idx])
width, height = im... | _____no_output_____ | MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_augmentation.ipynb | gaoxiao/deep-learning-v2-pytorch |
--- Define the Network [Architecture](http://pytorch.org/docs/stable/nn.html)This time, you'll define a CNN architecture. Instead of an MLP, which used linear, fully-connected layers, you'll use the following:* [Convolutional layers](https://pytorch.org/docs/stable/nn.htmlconv2d), which can be thought of as stack of fi... | import torch.nn as nn
import torch.nn.functional as F
# define the CNN architecture
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# convolutional layer (sees 32x32x3 image tensor)
self.conv1 = nn.Conv2d(3, 16, 3, padding=1)
# convolutional layer (sees 16x16x1... | Net(
(conv1): Conv2d(3, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(conv2): Conv2d(16, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(conv3): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
... | MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_augmentation.ipynb | gaoxiao/deep-learning-v2-pytorch |
Specify [Loss Function](http://pytorch.org/docs/stable/nn.htmlloss-functions) and [Optimizer](http://pytorch.org/docs/stable/optim.html)Decide on a loss and optimization function that is best suited for this classification task. The linked code examples from above, may be a good starting point; [this PyTorch classific... | import torch.optim as optim
# specify loss function (categorical cross-entropy)
criterion = nn.CrossEntropyLoss()
# specify optimizer
optimizer = optim.SGD(model.parameters(), lr=0.01) | _____no_output_____ | MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_augmentation.ipynb | gaoxiao/deep-learning-v2-pytorch |
--- Train the NetworkRemember to look at how the training and validation loss decreases over time; if the validation loss ever increases it indicates possible overfitting. | # number of epochs to train the model
n_epochs = 30
valid_loss_min = np.Inf # track change in validation loss
for epoch in range(1, n_epochs+1):
# keep track of training and validation loss
train_loss = 0.0
valid_loss = 0.0
###################
# train the model #
###################
... | Epoch: 1 Training Loss: 1.483400 Validation Loss: 0.357015
Validation loss decreased (inf --> 0.357015). Saving model ...
Epoch: 2 Training Loss: 1.462634 Validation Loss: 0.355032
Validation loss decreased (0.357015 --> 0.355032). Saving model ...
Epoch: 3 Training Loss: 1.454201 Validation Loss: 0.351629
Vali... | MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_augmentation.ipynb | gaoxiao/deep-learning-v2-pytorch |
Load the Model with the Lowest Validation Loss | model.load_state_dict(torch.load('model_augmented.pt')) | _____no_output_____ | MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_augmentation.ipynb | gaoxiao/deep-learning-v2-pytorch |
--- Test the Trained NetworkTest your trained model on previously unseen data! A "good" result will be a CNN that gets around 70% (or more, try your best!) accuracy on these test images. | # track test loss
test_loss = 0.0
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
model.eval()
# iterate over test data
for batch_idx, (data, target) in enumerate(test_loader):
# move tensors to GPU if CUDA is available
if train_on_gpu:
data, target = data.cuda(), ... | Test Loss: 1.650751
Test Accuracy of airplane: 37% (374/1000)
Test Accuracy of automobile: 47% (471/1000)
Test Accuracy of bird: 8% (80/1000)
Test Accuracy of cat: 20% (203/1000)
Test Accuracy of deer: 39% (390/1000)
Test Accuracy of dog: 27% (274/1000)
Test Accuracy of frog: 37% (372/1000)
Test Accuracy of ho... | MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_augmentation.ipynb | gaoxiao/deep-learning-v2-pytorch |
Visualize Sample Test Results | # obtain one batch of test images
dataiter = iter(test_loader)
images, labels = dataiter.next()
images.numpy()
# move model inputs to cuda, if GPU available
if train_on_gpu:
images = images.cuda()
# get sample outputs
output = model(images)
# convert output probabilities to predicted class
_, preds_tensor = torch... | _____no_output_____ | MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_augmentation.ipynb | gaoxiao/deep-learning-v2-pytorch |
Data core> Core functionality for gathering data The classes here provide functionality for applying a list of transforms to a set of items (`TfmdLists`, `Datasets`) or a `DataLoader` (`TfmdDl`) as well as the base class used to gather the data for model training: `DataLoaders`. TfmdDL - | #export
@typedispatch
def show_batch(x, y, samples, ctxs=None, max_n=9, **kwargs):
if ctxs is None: ctxs = Inf.nones
if hasattr(samples[0], 'show'):
ctxs = [s.show(ctx=c, **kwargs) for s,c,_ in zip(samples,ctxs,range(max_n))]
else:
for i in range_of(samples[0]):
ctxs = [b.show(ct... | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
`show_batch` is a type-dispatched function that is responsible for showing decoded `samples`. `x` and `y` are the input and the target in the batch to be shown, and are passed along to dispatch on their types. There is a different implementation of `show_batch` if `x` is a `TensorImage` or a `TensorText` for instance (... | #export
@typedispatch
def show_results(x, y, samples, outs, ctxs=None, max_n=9, **kwargs):
if ctxs is None: ctxs = Inf.nones
for i in range(len(samples[0])):
ctxs = [b.show(ctx=c, **kwargs) for b,c,_ in zip(samples.itemgot(i),ctxs,range(max_n))]
for i in range(len(outs[0])):
ctxs = [b.show(c... | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
`show_results` is a type-dispatched function that is responsible for showing decoded `samples` and their corresponding `outs`. Like in `show_batch`, `x` and `y` are the input and the target in the batch to be shown, and are passed along to dispatch on their types. `ctxs` can be passed but the function is responsible to... | #export
_all_ = ["show_batch", "show_results"]
#export
_batch_tfms = ('after_item','before_batch','after_batch')
#export
@log_args(but_as=DataLoader.__init__)
@delegates()
class TfmdDL(DataLoader):
"Transformed `DataLoader`"
def __init__(self, dataset, bs=64, shuffle=False, num_workers=None, verbose=False, do_s... | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
A `TfmdDL` is a `DataLoader` that creates `Pipeline` from a list of `Transform`s for the callbacks `after_item`, `before_batch` and `after_batch`. As a result, it can decode or show a processed `batch`. | #export
add_docs(TfmdDL,
decode="Decode `b` using `tfms`",
decode_batch="Decode `b` entirely",
new="Create a new version of self with a few changed attributes",
show_batch="Show `b` (defaults to `one_batch`), a list of lists of pipeline outputs (i.e. output of a `DataLoader`)",
... | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
Methods | show_doc(TfmdDL.one_batch)
tfm = NegTfm()
tdl = TfmdDL(start, after_batch=tfm, bs=4)
b = tdl.one_batch()
test_eq(tensor([0,-1,-2,-3]), b)
show_doc(TfmdDL.decode)
test_eq(tdl.decode(b), tensor(0,1,2,3))
show_doc(TfmdDL.decode_batch)
test_eq(tdl.decode_batch(b), [0,1,2,3])
show_doc(TfmdDL.show_batch)
show_doc(TfmdDL.to) | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
DataLoaders - | # export
@docs
class DataLoaders(GetAttr):
"Basic wrapper around several `DataLoader`s."
_default='train'
def __init__(self, *loaders, path='.', device=None):
self.loaders,self.path = list(loaders),Path(path)
if device is not None or hasattr(loaders[0],'to'): self.device = device
def __... | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
Methods | show_doc(DataLoaders.__getitem__)
x2 = dls[0].one_batch()
test_eq(x,x2)
show_doc(DataLoaders.train, name="DataLoaders.train")
show_doc(DataLoaders.valid, name="DataLoaders.valid")
show_doc(DataLoaders.train_ds, name="DataLoaders.train_ds")
show_doc(DataLoaders.valid_ds, name="DataLoaders.valid_ds") | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
TfmdLists - | #export
class FilteredBase:
"Base class for lists with subsets"
_dl_type,_dbunch_type = TfmdDL,DataLoaders
def __init__(self, *args, dl_type=None, **kwargs):
if dl_type is not None: self._dl_type = dl_type
self.dataloaders = delegates(self._dl_type.__init__)(self.dataloaders)
super()... | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
A `TfmdLists` combines a collection of object with a `Pipeline`. `tfms` can either be a `Pipeline` or a list of transforms, in which case, it will wrap them in a `Pipeline`. `use_list` is passed along to `L` with the `items` and `split_idx` are passed to each transform of the `Pipeline`. `do_setup` indicates if the `Pi... | class _IntFloatTfm(Transform):
def encodes(self, o): return TitledInt(o)
def decodes(self, o): return TitledFloat(o)
int2f_tfm=_IntFloatTfm()
def _neg(o): return -o
neg_tfm = Transform(_neg, _neg)
items = L([1.,2.,3.]); tfms = [neg_tfm, int2f_tfm]
tl = TfmdLists(items, tfms=tfms)
test_eq_type(tl[0], TitledIn... | TfmdLists: [1.0, 2.0, 3.0]
tfms - (#0) []
| Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
Here's how we can use `TfmdLists.setup` to implement a simple category list, getting labels from a mock file list: | class _Cat(Transform):
order = 1
def encodes(self, o): return int(self.o2i[o])
def decodes(self, o): return TitledStr(self.vocab[o])
def setups(self, items): self.vocab,self.o2i = uniqueify(L(items), sort=True, bidir=True)
tcat = _Cat()
def _lbl(o): return TitledStr(o.split('_')[0])
# Check that... | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
Datasets - | #export
@docs
@delegates(TfmdLists)
class Datasets(FilteredBase):
"A dataset that creates a tuple from each `tfms`, passed through `item_tfms`"
def __init__(self, items=None, tfms=None, tls=None, n_inp=None, dl_type=None, **kwargs):
super().__init__(dl_type=dl_type)
self.tls = L(tls if tls else ... | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
A `Datasets` creates a tuple from `items` (typically input,target) by applying to them each list of `Transform` (or `Pipeline`) in `tfms`. Note that if `tfms` contains only one list of `tfms`, the items given by `Datasets` will be tuples of one element. `n_inp` is the number of elements in the tuples that should be con... | items = [1,2,3,4]
dsets = Datasets(items, [[neg_tfm,int2f_tfm], [add(1)]])
t = dsets[0]
test_eq(t, (-1,2))
test_eq(dsets[0,1,2], [(-1,2),(-2,3),(-3,4)])
test_eq(dsets.n_inp, 1)
dsets.decode(t)
class Norm(Transform):
def encodes(self, o): return (o-self.m)/self.s
def decodes(self, o): return (o*self.s)+self.m
... | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
Methods | items = [1,2,3,4]
dsets = Datasets(items, [[neg_tfm,int2f_tfm]])
#hide_input
_dsrc = Datasets([1,2])
show_doc(_dsrc.dataloaders, name="Datasets.dataloaders")
show_doc(Datasets.decode)
test_eq(*dsets[0], -1)
test_eq(*dsets.decode((-1,)), 1)
show_doc(Datasets.show)
test_stdout(lambda:dsets.show(dsets[1]), '-2')
show_doc(... | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/fastai |
Add test set for inference | # only transform subset 1
class _Tfm1(Transform):
split_idx=0
def encodes(self, x): return x*3
dsets = Datasets(range(8), [[_Tfm(),_Tfm1()]], splits=[[1,2,5,7],[0,3,4,6]])
test_eq(dsets.train, [(3,),(6,),(15,),(21,)])
test_eq(dsets.valid, [(0,),(6,),(8,),(12,)])
#export
def test_set(dsets, test_items, rm_tfms=... | _____no_output_____ | Apache-2.0 | nbs/03_data.core.ipynb | aaminggo/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/03_data.core.ipynb | aaminggo/fastai |
התנהגות של פונקציות בפסקאות הקרובות נבחן פונקציות מזווית ראייה מעט שונה מהרגיל. בואו נקפוץ ישירות למים! שם של פונקציה תכונה מעניינת שמתקיימת בפייתון היא שפונקציה היא ערך, בדיוק כמו כל ערך אחר. נגדיר פונקציה שמעלה מספר בריבוע: | def square(x):
return x ** 2 | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
נוכל לבדוק מאיזה טיפוס הפונקציה (אנחנו לא קוראים לה עם סוגריים אחרי שמה – רק מציינים את שמה): | type(square) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
ואפילו לבצע השמה שלה למשתנה, כך ששם המשתנה החדש יצביע עליה: | ribua = square
print(square(5))
print(ribua(5)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
מה מתרחש בתא למעלה? כשהגדרנו את הפונקציה square, יצרנו לייזר עם התווית square שמצביע לפונקציה שמעלה מספר בריבוע. בהשמה שביצענו בשורה הראשונה בתא שלמעלה, הלייזר שעליו מודבקת התווית ribua כוון אל אותה הפונקציה שעליה מצביע הלייזר square. כעת square ו־ribua מצביעים לאותה פונקציה. אפשר לבדוק זאת כך: | ribua is square | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
בשלב הזה אצטרך לבקש מכם לחגור חגורות, כי זה לא הולך להיות טיול רגיל הפעם. פונקציות במבנים מורכבים אם פונקציה היא בסך הכול ערך, ואם אפשר להתייחס לשם שלה בכל מקום, אין סיבה שלא נוכל ליצור רשימה של פונקציות! ננסה לממש את הרעיון: | def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
functions = [add, subtract, multiply, divide] | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
כעת יש לנו רשימה בעלת 4 איברים, שכל אחד מהם מצביע לפונקציה שונה. אם נרצה לבצע פעולת חיבור, נוכל לקרוא ישירות ל־add או (בשביל התרגול) לנסות לאחזר אותה מהרשימה שיצרנו: | # Option 1
print(add(5, 2))
# Option 2
math_function = functions[0]
print(math_function(5, 2))
# Option 3 (ugly, but works!)
print(functions[0](5, 2)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
אם נרצה, נוכל אפילו לעבור על רשימת הפונקציות בעזרת לולאה ולהפעיל את כולן, זו אחר זו: | for function in functions:
print(function(5, 2)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
בכל איטרציה של לולאת ה־for, המשתנה function עבר להצביע על הפונקציה הבאה מתוך רשימת functions. בשורה הבאה קראנו לאותה הפונקציה ש־function מצביע עליה, והדפסנו את הערך שהיא החזירה. כיוון שרשימה היא מבנה ששומר על סדר האיברים שבו, התוצאות מודפסות בסדר שבו הפונקציות שמורות ברשימה. התוצאה הראשונה שאנחנו רואי... | def calculate(function, num1, num2):
return function(num1, num2) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
בקריאה ל־calculate, נצטרך להעביר פונקציה ושני מספרים. נעביר לדוגמה את הפונקציה divide שהגדרנו קודם לכן: | calculate(divide, 5, 2) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
מה שמתרחש במקרה הזה הוא שהעברנו את הפונקציה divide כארגומנט ראשון. הפרמטר function בפונקציה calculate מצביע כעת על פונקציית החילוק שהגדרנו למעלה. מכאן, שהפונקציה תחזיר את התוצאה של divide(5, 2) – הרי היא 2.5. תרגיל ביניים: מפה לפה כתבו generator בשם apply שמקבל כפרמטר ראשון פונקציה (func), וכפרמטר שני it... | def square(number):
return number ** 2
square_check = apply(square, [5, -1, 6, -8, 0])
tuple(square_check) == (25, 1, 36, 64, 0) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
סיכום ביניים וואו. זה היה די משוגע. אז למעשה, פונקציות בפייתון הן ערך לכל דבר, כמו מחרוזות ומספרים! אפשר לאחסן אותן במשתנים, לשלוח אותן כארגומנטים ולכלול אותם בתוך מבני נתונים מורכבים יותר. אנשי התיאוריה של מדעי המחשב נתנו להתנהגות כזו שם: "אזרח ממדרגה ראשונה" (first class citizen). אם כך, אפשר להגיד ... | squared_items = map(square, [1, 6, -1, 8, 0, 3, -3, 9, -8, 8, -7])
print(tuple(squared_items)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
הפונקציה קיבלה כארגומנט ראשון את הפונקציה square שהגדרנו למעלה, שמטרתה העלאת מספר בריבוע. כארגומנט שני היא קיבלה את רשימת כל המספרים שאנחנו רוצים שהפונקציה תרוץ עליהם. כשהעברנו ל־map את הארגומנטים הללו, map החזירה לנו ב־iterator (מבנה שאפשר לעבור עליו איבר־איבר) את התוצאה: הריבוע, קרי החזקה השנייה, של כל א... | def my_map(function, iterable):
for item in iterable:
yield function(item) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
הנה דוגמה נוספת לשימוש ב־map: | numbers = [(2, 4), (1, 4, 2), (1, 3, 5, 6, 2), (3, )]
sums = map(sum, numbers)
print(tuple(sums)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
במקרה הזה, בכל מעבר, קיבלה הפונקציה sum איבר אחד מתוך הרשימה – tuple. היא סכמה את האיברים של כל tuple שקיבלה, וכך החזירה לנו את הסכומים של כל ה־tuple־ים – זה אחרי זה. ודוגמה אחרונה: | def add_one(number):
return number + 1
incremented = map(add_one, (1, 2, 3))
print(tuple(incremented)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
בדוגמה הזו יצרנו פונקציה משל עצמנו, ואותה העברנו ל־map. מטרת דוגמה זו היא להדגיש שאין שוני בין העברת פונקציה שקיימת בפייתון לבין פונקציה שאנחנו יצרנו. כתבו פונקציה שמקבלת רשימת מחרוזות של שתי מילים: שם פרטי ושם משפחה. הפונקציה תשתמש ב־map כדי להחזיר מכולן רק את... | def is_mature(age):
return age >= 18 | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.