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
|
---|---|---|---|---|---|
Experimenting with Final Model | y_pred_all = rf.predict(X)
y_pred_all = pd.Series(y_pred_all)
predictions = df.merge(y_pred_all.rename('pred_'), how = 'left', on = df.index)
predictions = predictions.merge(ozdf, how = 'left', left_on='fips',right_on='Census_Tract_Number')
final_zones = predictions.dropna()
(final_zones.pred_).unique()
predictions['pred_'].value_counts()
y_pred_train = rf.predict(X_train)
print("Precision: {}".format(precision_score(y_train, y_pred_train)))
print("Recall: {}".format(recall_score(y_train, y_pred_train)))
print("Accuracy: {}".format(accuracy_score(y_train, y_pred_train)))
print("F1 Score: {}".format(f1_score(y_train, y_pred_train))) | Precision: 0.7939935224261458
Recall: 0.7292449145157898
Accuracy: 0.7700189297196599
F1 Score: 0.760243077308608
| MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
*If running in a new enviroment, such as Google Colab, run this first.* | !git clone https://github.com/zach401/acnportal.git
!pip install acnportal/. | fatal: destination path 'acnportal' already exists and is not an empty directory.
Processing ./acnportal
Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (1.19.5)
Requirement already satisfied: pandas<1.2.0,>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (1.1.5)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (3.2.2)
Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (2.23.0)
Requirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (2018.9)
Requirement already satisfied: typing_extensions in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (3.7.4.3)
Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (0.22.2.post1)
Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas<1.2.0,>=1.1.0->acnportal==0.3.2) (2.8.1)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->acnportal==0.3.2) (2.4.7)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->acnportal==0.3.2) (1.3.1)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->acnportal==0.3.2) (0.10.0)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->acnportal==0.3.2) (2.10)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->acnportal==0.3.2) (2021.5.30)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->acnportal==0.3.2) (1.24.3)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->acnportal==0.3.2) (3.0.4)
Requirement already satisfied: scipy>=0.17.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->acnportal==0.3.2) (1.4.1)
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->acnportal==0.3.2) (1.0.1)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas<1.2.0,>=1.1.0->acnportal==0.3.2) (1.15.0)
Building wheels for collected packages: acnportal
Building wheel for acnportal (setup.py) ... [?25l[?25hdone
Created wheel for acnportal: filename=acnportal-0.3.2-cp37-none-any.whl size=138186 sha256=3368733c1dec9d05de7908b976c4e4a822ef7b38cfa5a8c88fdbe873ea4a51eb
Stored in directory: /tmp/pip-ephem-wheel-cache-4zjo5oug/wheels/6d/6a/19/10aef74a8c705c23f53e3e1d696420b07fcdbc88af47701336
Successfully built acnportal
Installing collected packages: acnportal
Found existing installation: acnportal 0.3.2
Uninstalling acnportal-0.3.2:
Successfully uninstalled acnportal-0.3.2
Successfully installed acnportal-0.3.2
| BSD-3-Clause | Example_EDF_vs_Uncontrolled.ipynb | zach401/eEnergy_acnsim_abstract |
ACN-Sim Example Comparing EDF and Uncontrolled Charging by Zachary Lee Last updated: 04/19/2019In this example we implement a custom version of the Earliest Deadline First algorithm and compare it with Uncontrolled Charging. We show how easy it is to implement a custom algorithm using ACN-Sim as well as the simplicity of running a common experiment. Custom AlgorithmAll custom algorithms inherit from the abstract class BaseAlgorithm. It is the responsibility of all derived classes to implement the schedule method. This method takes as an input a list of EVs which are currently connected to the system but have not yet finished charging. Its output is a dictionary which maps a station_id to a list of charging rates. Each charging rate is valid for one period measured relative to the current period.For Example: * schedule[‘abc’][0] is the charging rate for station ‘abc’ during the current period * schedule[‘abc’][1] is the charging rate for the next period * and so on. def __init__(self, increment=1):We can override the __init__() method if we need to pass additional configuration information to the algorithm. In this case we pass in the increment which will be used when searching for a feasible rate. schedule(self, active_evs)We next need to override the schedule() method. The signature of this method should remain the same, as it is called internally in Simulator. If an algorithm needs additional parameters consider passing them through the constructor. | from acnportal.algorithms import BaseAlgorithm
class EarliestDeadlineFirstAlgo(BaseAlgorithm):
""" Algorithm which assigns charging rates to each EV in order or departure time.
Implements abstract class BaseAlgorithm.
For this algorithm EVs will first be sorted by departure time. We will then allocate as much
current as possible to each EV in order until the EV is finished charging or an infrastructure
limit is met.
Args:
increment (number): Minimum increment of charging rate. Default: 1.
"""
def __init__(self, increment=1):
super().__init__()
self._increment = increment
def schedule(self, active_evs):
schedule = {ev.station_id: [0] for ev in active_evs}
# Next, we sort the active_evs by their departure time.
sorted_evs = sorted(active_evs, key=lambda x: x.departure)
# We now iterate over the sorted list of EVs.
for ev in sorted_evs:
# First try to charge the EV at its maximum rate. Remember that each schedule value
# must be a list, even if it only has one element.
schedule[ev.station_id] = [self.interface.max_pilot_signal(ev.station_id)]
# If this is not feasible, we will reduce the rate.
# interface.is_feasible() is one way to interact with the constraint set
# of the network. We will explore another more direct method in lesson 3.
while not self.interface.is_feasible(schedule, 0):
# Since the maximum rate was not feasible, we should try a lower rate.
schedule[ev.station_id][0] -= self._increment
# EVs should never charge below 0 (i.e. discharge) so we will clip the value at 0.
if schedule[ev.station_id][0] < 0:
schedule[ev.station_id] = [0]
break
return schedule | _____no_output_____ | BSD-3-Clause | Example_EDF_vs_Uncontrolled.ipynb | zach401/eEnergy_acnsim_abstract |
Note the structure of the schedule dict which is returned should be something like:```{ 'CA-301': [32, 32, 32, 16, 16, ..., 8], 'CA-302': [8, 13, 13, 15, 6, ..., 0], ..., 'CA-408': [24, 24, 24, 24, 0, ..., 0]}```For the special case when an algorithm only calculates a target rate for the next time interval instead of an entire schedule of rates, the structure should be:```{ 'CA-301': [32], 'CA-302': [8], ..., 'CA-408': [24]}```Note that these are single element lists and NOT floats or integers. Running the AlgorithmNow that we have implemented our algorithm, we can try it out. ACN-Sim provides useful utilities to make defining an experiment and running a simulation extremely simple. | import pytz
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='ticks', palette='Set2')
from copy import deepcopy
from acnportal.algorithms import SortedSchedulingAlgo, UncontrolledCharging
from acnportal.algorithms import earliest_deadline_first
from acnportal.acnsim.events import acndata_events
from acnportal.acnsim.network.sites import CaltechACN
from acnportal.acnsim.analysis import *
from acnportal.acnsim import Simulator
from datetime import datetime
# -- Experiment Parameters ---------------------------------------------------------------------------------------------
timezone = pytz.timezone('America/Los_Angeles')
start = datetime(2018, 9, 5).astimezone(timezone)
end = datetime(2018, 9, 6).astimezone(timezone)
period = 5 # minute
voltage = 220 # volts
max_rate = 32 # amps
site = 'caltech'
# -- Network -----------------------------------------------------------------------------------------------------------
cn = CaltechACN(basic_evse=True)
# -- Events ------------------------------------------------------------------------------------------------------------
API_KEY = 'DEMO_TOKEN'
events = acndata_events.generate_events(API_KEY, site, start, end, period, voltage, max_rate)
# -- Scheduling Algorithm ----------------------------------------------------------------------------------------------
schEDF = EarliestDeadlineFirstAlgo(increment=1)
schUC = UncontrolledCharging()
%%capture
# -- Simulator ---------------------------------------------------------------------------------------------------------
simEDF = Simulator(deepcopy(cn), schEDF, deepcopy(events), start, period=period)
simEDF.run()
%%capture
# For comparison we will also run the builtin UncontrolledCharging algorithm
simUC = Simulator(deepcopy(cn), schUC, deepcopy(events), start, period=period)
simUC.run() | _____no_output_____ | BSD-3-Clause | Example_EDF_vs_Uncontrolled.ipynb | zach401/eEnergy_acnsim_abstract |
ResultsWe can now compare the two algorithms side by side by looking that the plots of aggregated current. We can see from this plot that UncontrolledCharging peaks before EDF and at a higher rate. This is because UncontrolledCharging does not factor in the constraints of infrastructure. | %matplotlib inline
plt.plot(aggregate_current(simEDF), label='Earliest Deadline First', alpha=0.75)
plt.plot(aggregate_current(simUC), label='Uncontrolled Charging', alpha=0.75)
plt.xlim(125, 325)
plt.legend()
plt.xlabel('Time (periods)')
plt.ylabel('Current (A)')
plt.title('Total Aggregate Current')
plt.show() | _____no_output_____ | BSD-3-Clause | Example_EDF_vs_Uncontrolled.ipynb | zach401/eEnergy_acnsim_abstract |
To see this more clearly, we can example line currents in the three-phase system. Here we plot the line currents at the secondary side of the Caltech ACN transformer. We also include the current limit for these lines as a grey dashed line. We can see that in the uncontrolled case, the current in line A exceeds its limit, while in our EDF algorithm, all currents are below their limits. | cc_EDF = constraint_currents(simEDF)
cc_UC = constraint_currents(simUC)
fig, axes = plt.subplots(1, 2, sharey=True, sharex=True, figsize=(5,2.5))
fig.subplots_adjust(wspace=0.07)
axes[0].set_xlim(125, 325)
for line in 'ABC':
axes[0].plot(cc_EDF['Secondary {0}'.format(line)], label=line)
axes[1].plot(cc_UC['Secondary {0}'.format(line)], label=line)
axes[0].axhline(420, color='gray', linestyle='--')
axes[1].axhline(420, color='gray', linestyle='--')
axes[1].legend()
axes[0].set_xlabel('Time (periods)')
axes[1].set_xlabel('Time (periods)')
axes[0].set_ylabel('Current (A)')
sns.despine()
plt.show()
| _____no_output_____ | BSD-3-Clause | Example_EDF_vs_Uncontrolled.ipynb | zach401/eEnergy_acnsim_abstract |
01. Data Tables, Plots & Basic Concepts of Programming Doubts? → Ask me in Discord Tutorials → YouTube Book Private Lessons → @ sotastica | # Define a Variable
> Asign an `object` (numbers, text) to a `variable`.
# The Registry (_aka The Environment_)
> Place where Python goes to **recognise what we type**.
# Use of Functions
## Predefined Functions in Python (_Built-in_ Functions)
> https://docs.python.org/3/library/functions.html
## Discipline to Search Solutions in Google
> Apply the following steps when **looking for solutions in Google**:
>
> 1. **Necesity**: How to load an Excel in Python?
> 2. **Search in Google**: by keywords
> - `load excel python`
> - ~~how to load excel in python~~
> 3. **Solution**: What's the `function()` that loads an Excel in Python?
> - A Function to Programming is what the Atom to Phisics.
> - Every time you want to do something in programming
> - **You will need a `function()`** to make it
> - Theferore, you must **detect parenthesis `()`**
> - Out of all the words that you see in a website
> - Because they indicate the presence of a `function()`.
## External Functions
> Download [this Excel](https://github.com/sotastica/data/raw/main/internet_usage_spain.xlsx).
> Apply the above discipline and make it happen 🚀
> I want to see the table, c'mon 👇
## The Elements of Programming
> - `Library`: where the code of functions are stored.
> - `Function`: execute several lines of code with one `word()`.
> - `Parameter`: to **configure** the function's behaviour.
> - `Object`: **data structure** to store information.
## Code Syntax
**What happens inside the computer when we run the code?**
> In which order Python reads the line of code?
> - From left to right.
> - From up to down.
> Which elements are being used in the previous line of code?
## Functions inside Objects
> - The `dog` makes `guau()`: `dog.guau()`
> - The `cat` makes `miau()`: `cat.miau()`
> - What could a `DataFrame` make? `object.` + `[tab key]`
## Conclusion | Types of Functions
> 1. Buit-in (Predefined) Functions
> 2. External Functions from Libraries
> 3. Functions within Objects
# Accessing `Objects`
> Objects are **data structures** that store information.
> Which **syntax** do we use to access the information?
## Dot Notation `.`
## Square Brackets `[]`
# Filter & Masking
| _____no_output_____ | MIT | #01. Data Tables & Basic Concepts of Programming/01session-Copy1.ipynb | jesusmartinezprofesor/machine-learning-program |
Medical Checkup Problem | # Enable the commands below when running this program on Google Colab.
# !pip install arviz==0.7
# !pip install pymc3==3.8
# !pip install Theano==1.0.4
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
import pymc3 as pm
plt.style.use('seaborn-darkgrid')
np.set_printoptions(precision=3)
pd.set_option('display.precision', 3)
EXPERIMENT_GROUP = [56, 55, 55, 62, 54, 63, 47, 58, 56, 56, 57, 52, 53, 50, 50, 57, 57, 55, 60, 65, 53, 43, 60, 51, 52, 60, 54, 49, 56, 54, 55, 57, 53, 58, 54, 57, 60, 57, 53, 61, 60, 58, 56, 52, 62, 52, 66, 63, 54, 50]
CONTROL_GROUP = [33, 37, 59, 41, 42, 61, 46, 25, 32, 35, 55, 44, 45, 41, 33, 61, 46, 16, 48, 34, 27, 37, 28, 31, 32, 20, 50, 42, 26, 55, 45, 36, 51, 51, 50, 48, 47, 39, 36, 35, 32, 38, 25, 66, 54, 27, 35, 34, 49, 39]
# Data vsualization
plt.boxplot([EXPERIMENT_GROUP, CONTROL_GROUP], labels=['EXPERIMENT GROUP', 'CONTROL GROUP'])
plt.ylabel('Biomarker')
plt.show()
# Summary
data = pd.DataFrame([EXPERIMENT_GROUP, CONTROL_GROUP], index=['Experiment', 'Control']).transpose()
# display(data)
data.describe() | _____no_output_____ | MIT | src/bayes/practice/mean/two/independent/medical_checkup.ipynb | shigeodayo/ex_design_analysis |
Bayesian analysis | with pm.Model() as model:
# Prior distribution
mu = pm.Uniform('mu', 0, 100, shape=2)
sigma = pm.Uniform('sigma', 0, 50)
# Likelihood
y_pred = pm.Normal('y_pred', mu=mu, sd=sigma, observed=data.values)
# Difference of mean
delta_mu = pm.Deterministic('mu1 - mu2', mu[0] - mu[1])
trace = pm.sample(21000, chains=5)
chain = trace[1000:]
pm.traceplot(chain)
plt.show()
pm.summary(chain) | _____no_output_____ | MIT | src/bayes/practice/mean/two/independent/medical_checkup.ipynb | shigeodayo/ex_design_analysis |
RQ1: 第1群の平均値が第2群の平均値より高い確率 | print('p(mu1 - mu2 > 0) = {:.3f}'.format((chain['mu'][:,0] - chain['mu'][:,1] > 0).mean()))
# 「罹患群の平均値が健常群の平均値より大きい」という研究仮説が正しい確率は100% | _____no_output_____ | MIT | src/bayes/practice/mean/two/independent/medical_checkup.ipynb | shigeodayo/ex_design_analysis |
RQ2: 第1群と第2群の平均値の差の点推定、平均値の差の区間推定 | print('Point estimation (difference of mean): {:.3f}'.format(chain['mu1 - mu2'].mean()))
# 平均値差に関するEAP推定値
hpd_0025 = np.quantile(chain['mu1 - mu2'], 0.025)
hpd_0975 = np.quantile(chain['mu1 - mu2'], 0.975)
print('Credible Interval (95%): ({:.3f}, {:.3f})'.format(hpd_0025, hpd_0975))
# 平均値差は95%の確率で上記の区間に入る | _____no_output_____ | MIT | src/bayes/practice/mean/two/independent/medical_checkup.ipynb | shigeodayo/ex_design_analysis |
RQ3: 平均値の差の片側区間推定の下限・上限 | hpd_005 = np.quantile(chain['mu1 - mu2'], 0.05)
hpd_0950 = np.quantile(chain['mu1 - mu2'], 0.95)
print('At most (95%): {:.3f}'.format(hpd_0950)) # 95%の確信で高々これだけの差がある
print('At least (95%): {:.3f}'.format(hpd_005)) # 95%の確信で少なくともこれだけの差がある | _____no_output_____ | MIT | src/bayes/practice/mean/two/independent/medical_checkup.ipynb | shigeodayo/ex_design_analysis |
RQ4: 平均値の差が基準点cより大きい確率 | print('p(mu1 - mu2 > 10) = {:.3f}'.format((chain['mu'][:,0] - chain['mu'][:,1] > 10).mean()))
print('p(mu1 - mu2 > 12) = {:.3f}'.format((chain['mu'][:,0] - chain['mu'][:,1] > 12).mean()))
print('p(mu1 - mu2 > 14) = {:.3f}'.format((chain['mu'][:,0] - chain['mu'][:,1] > 14).mean())) | _____no_output_____ | MIT | src/bayes/practice/mean/two/independent/medical_checkup.ipynb | shigeodayo/ex_design_analysis |
Congratulations Already!- This is a Jupyter Notebook. It is made of executable cells.- Some cells have text (in Markdown), some have executable code!- Abdullah will be demonstrating how to use it soon, but if he is too boring or unclear, [read through this](https://nbviewer.jupyter.org/github/jupyter/notebook/blob/master/docs/source/examples/Notebook/Notebook%20Basics.ipynb)--- Acquire the `data.zip`- Somehow, from someone, you will get a `data.zip` file.- Unzip it.- Copy all the contents to the directory where you have cloned this repository. + directory `prepared` to `data/prepared` + directory `models` to `data/models`- **Once done** copying the directories, run the code cells below. They should not throw any errors. | from pathlib import Path
dir_pickles = Path.cwd().joinpath("data/prepared/pickles/20190909-vggish_embedding")
assert all(
dir_pickles.joinpath(f'{split_name}.tfrecord').exists() for split_name in ['trn', 'val']
), 'Missing prepared tfrecord files in `data/prepared`'
from audioset.vggish_smoke_test import * | _____no_output_____ | Apache-2.0 | 00-check-setup.ipynb | fraunhofer-iais/UoC-ml-school-2019 |
inference yolo-fastest model with one image | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = "2"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import cv2
from matplotlib import pyplot as plt
%matplotlib inline
import time
import colorsys
import numpy as np
from pathlib import Path
import tensorflow as tf
from tensorflow import keras
tf.__version__
img_path = "../example/person.jpg"
model_path = "../weights/yolo-fastest.h5"
class_path = "../configs/voc_classes.txt"
tflite_path = "../weights/yolo-fastest.tflite"
# 预选框
anchors = [[26, 48], [67, 84], [72, 175], [189, 126], [137, 236], [265, 259]]
anchors = np.array(anchors)
num_classes = 20
model_image_size = (320, 320)
conf_threshold, elim_grid_sense = 0.5, False
classes_path = "../configs/voc_classes.txt"
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_shape = img.shape[:-1] # height, width
print(img.shape)
plt.imshow(img)
plt.show() | (424, 640, 3)
| MIT | yolo-fastest_inference/inference_one_picture.ipynb | Lebhoryi/keras-YOLOv3-model-set |
1. preprocess input data | img_resize = cv2.resize(img, model_image_size)
img_bn = img_resize / 255
img_bn = img_bn.astype("float32")
input_data = np.expand_dims(img_bn, axis=0)
input_data.shape | _____no_output_____ | MIT | yolo-fastest_inference/inference_one_picture.ipynb | Lebhoryi/keras-YOLOv3-model-set |
2.1 load keras model | # load model
model = keras.models.load_model(model_path, compile=False)
yolo_output = model.predict(input_data)
# keep large-scale feature map is first
yolo_output = sorted(yolo_output, key=lambda x:len(x[0]))
yolo_output[0].shape, yolo_output[1].shape | _____no_output_____ | MIT | yolo-fastest_inference/inference_one_picture.ipynb | Lebhoryi/keras-YOLOv3-model-set |
2.2 load tflite model | class YoloFastest(object):
def __init__(self, landmark_model_path):
self.interp_joint = tf.lite.Interpreter(landmark_model_path)
self.interp_joint.allocate_tensors()
# input & input shape
self.in_idx_joint = self.interp_joint.get_input_details()[0]['index']
# [b, h, w, c]: [1, 320, 320, 3]
self.input_shape = self.interp_joint.get_input_details()[0]['shape']
# output
self.out_idx = self.interp_joint.get_output_details()[0]['index']
self.out_idx2 = self.interp_joint.get_output_details()[1]['index']
def predict_joint(self, img_norm):
"""inference tflite model"""
self.interp_joint.set_tensor(self.in_idx_joint, img_norm.reshape(self.input_shape))
self.interp_joint.invoke()
output = self.interp_joint.get_tensor(self.out_idx)
output2 = self.interp_joint.get_tensor(self.out_idx2)
return [output, output2]
def __call__(self, img):
yolo_output = self.predict_joint(img)
return yolo_output
yolo_fastest = YoloFastest(tflite_path)
yolo_output = yolo_fastest(input_data)
yolo_output[1].shape | _____no_output_____ | MIT | yolo-fastest_inference/inference_one_picture.ipynb | Lebhoryi/keras-YOLOv3-model-set |
3. yolo decode | def yolo_decode(prediction, anchors, num_classes, input_dims, scale_x_y=None, use_softmax=False):
'''Decode final layer features to bounding box parameters.'''
num_anchors = len(anchors) # anchors *3
grid_size = prediction.shape[1:3] # 10*10 grids in a image
# shape: (10*10*3, 25); (20*20*3, 25)
prediction = np.reshape(prediction,
(grid_size[0] * grid_size[1] * num_anchors, num_classes + 5))
# generate x_y_offset grid map
x_y_offset = [[[j, i]] * num_anchors for i in range(grid_size[0]) for j in range(grid_size[0])]
# shape: (10*10*3, 2)
x_y_offset = np.array(x_y_offset).reshape(grid_size[0] * grid_size[1] * num_anchors , 2)
# print(f"x_y_offset shape: {x_y_offset.shape}")
# sigmoid: expit(x) = 1 / (1 + exp(-x))
x_y_tmp = 1 / (1 + np.exp(-prediction[..., :2]))
# shape: (300, 2)
box_xy = (x_y_tmp + x_y_offset) / np.array(grid_size)[::-1]
# Log space transform of the height and width
# anchors = np.array(anchors.tolist()*(grid_size[0] * grid_size[1]))
anchors_expand = np.tile(anchors, (grid_size[0]*grid_size[1], 1))
# shape: (300, 2)
box_wh = (np.exp(prediction[..., 2:4]) * anchors_expand) / np.array(input_dims)[::-1]
# sigmoid function; objectness score
# shape: (300, 1)
objectness = 1 / (1 + np.exp(-prediction[..., 4]))
objectness = np.expand_dims(objectness, axis=-1)
# sigmoid function
# shape: (300, 20)
if use_softmax:
class_scores = np.exp(prediction[..., 5:]) / np.sum(np.exp(prediction[..., 5:]))
else:
class_scores = 1 / (1 + np.exp(-prediction[..., 5:]))
return np.concatenate([box_xy, box_wh, objectness, class_scores], axis=-1)
def yolo3_decode(predictions, anchors, num_classes, input_dims, elim_grid_sense=False):
"""
YOLOv3 Head to process predictions from YOLOv3 models
:param num_classes: Total number of classes
:param anchors: YOLO style anchor list for bounding box assignment
:param input_dims: Input dimensions of the image
:param predictions: A list of three tensors with shape (N, 19, 19, 255), (N, 38, 38, 255) and (N, 76, 76, 255)
:return: A tensor with the shape (N, num_boxes, 85)
"""
# weather right dims of prediction outputs
assert len(predictions) == len(anchors)//3, 'anchor numbers does not match prediction.'
if len(predictions) == 3: # assume 3 set of predictions is YOLOv3
anchor_mask = [[6,7,8], [3,4,5], [0,1,2]]
scale_x_y = [1.05, 1.1, 1.2] if elim_grid_sense else [None, None, None]
elif len(predictions) == 2: # 2 set of predictions is YOLOv3-tiny or yolo-fastest
anchor_mask = [[3,4,5], [0,1,2]]
scale_x_y = [1.05, 1.05] if elim_grid_sense else [None, None]
else:
raise ValueError('Unsupported prediction length: {}'.format(len(predictions)))
results = []
for i, prediction in enumerate(predictions):
results.append(yolo_decode(prediction, anchors[anchor_mask[i]], num_classes, input_dims,
scale_x_y=scale_x_y[i], use_softmax=False))
return np.concatenate(results, axis=0)
predictions_bn = yolo3_decode(yolo_output, anchors, num_classes, model_image_size, elim_grid_sense)
predictions_bn.shape | _____no_output_____ | MIT | yolo-fastest_inference/inference_one_picture.ipynb | Lebhoryi/keras-YOLOv3-model-set |
4. Post-processing output | def nms_boxes(boxes, classes, scores, iou_threshold, confidence=0.1):
# center_xy, box_wh
x = boxes[:, 0]
y = boxes[:, 1]
w = boxes[:, 2]
h = boxes[:, 3]
xmin, ymin = x - w/2, y - h/2
xmax, ymax = x + w/2, y + h/2
order = np.argsort(scores)[::-1]
all_areas = w * h
keep_index = [] # valid index
while order.size > 0:
keep_index.append(order[0]) # 永远保留置信度最高的索引
# 最大置信度的左上角坐标分别与剩余所有的框的左上角坐标进行比较,分别保存较大值
inter_xmin = np.maximum(xmin[order[0]], xmin[order[1:]])
inter_ymin = np.maximum(ymin[order[0]], ymin[order[1:]])
inter_xmax = np.minimum(xmax[order[0]], xmax[order[1:]])
inter_ymax = np.minimum(ymax[order[0]], ymax[order[1:]])
# 当前类所有框的面积
# x1=3,x2=5,习惯上计算x方向长度就是x=3、4、5这三个像素,即5-3+1=3,
# 而不是5-3=2,所以需要加1
inter_w = np.maximum(0., inter_xmax - inter_xmin + 1)
inter_h = np.maximum(0., inter_ymax - inter_ymin + 1)
inter = inter_w * inter_h
#计算重叠度IOU:重叠面积/(面积1+面积2-重叠面积)
iou = inter / (all_areas[order[0]] + all_areas[order[1:]] - inter)
# 计算iou的时候, 并没有计算第一个数, 所以索引对应的是order[1:]之后的, 所以需要加1
indexs = np.where(iou <= iou_threshold)[0]
order = order[indexs+1]
keep_boxes = boxes[keep_index]
keep_classes = classes[keep_index]
keep_scores = scores[keep_index]
return keep_boxes, keep_classes, keep_scores
def yolo_handle_predictions(predictions, image_shape, confidence=0.1, iou_threshold=0.4, use_cluster_nms=False, use_wbf=False):
boxes = predictions[..., :4]
box_confidences = np.expand_dims(predictions[..., 4], -1)
box_class_probs = predictions[..., 5:]
# filter boxes with confidence threshold
box_scores = box_confidences * box_class_probs
box_classes = np.argmax(box_scores, axis=-1) # max probability index(class)
box_class_scores = np.max(box_scores, axis=-1) # max scores
pos = np.where(box_class_scores >= confidence)
boxes = boxes[pos]
classes = box_classes[pos]
scores = box_class_scores[pos]
# rescale predicition boxes back to original image shap
image_shape = image_shape[::-1] # width, height
boxes[..., :2] *= image_shape # xy
boxes[..., 2:] *= image_shape # wh
n_boxes, n_classes, n_scores = nms_boxes(boxes, classes, scores, iou_threshold, confidence=confidence)
if n_boxes.size:
classes = n_classes.astype('int32')
return n_boxes, classes, n_scores
else:
return [], [], []
confidence, iou_threshold = 0.5, 0.4
boxes, classes, scores = yolo_handle_predictions(predictions_bn, img_shape,
confidence=confidence,
iou_threshold=iou_threshold)
boxes, classes, scores
def yolo_adjust_boxes(boxes, img_shape):
'''
change box format from (x,y,w,h) top left coordinate to
(xmin,ymin,xmax,ymax) format
'''
if boxes is None or len(boxes) == 0:
return []
image_shape = np.array(img_shape, dtype='float32')
height, width = image_shape
adjusted_boxes = []
for box in boxes:
x, y, w, h = box
xmin = x - w/2
ymin = y - h/2
xmax = x + w/2
ymax = y + h/2
ymin = max(0, np.floor(ymin + 0.5).astype('int32'))
xmin = max(0, np.floor(xmin + 0.5).astype('int32'))
ymax = min(height, np.floor(ymax + 0.5).astype('int32'))
xmax = min(width, np.floor(xmax + 0.5).astype('int32'))
adjusted_boxes.append([xmin,ymin,xmax,ymax])
return np.array(adjusted_boxes,dtype=np.int32)
boxes_real = yolo_adjust_boxes(boxes, img_shape)
boxes_real | _____no_output_____ | MIT | yolo-fastest_inference/inference_one_picture.ipynb | Lebhoryi/keras-YOLOv3-model-set |
5. draw predictions in image | def get_classes(classes_path):
'''loads the classes'''
with open(classes_path) as f:
class_names = f.read().split()
return class_names
def get_colors(class_names):
# Generate colors for drawing bounding boxes.
hsv_tuples = [(x / len(class_names), 1., 1.)
for x in range(len(class_names))]
colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
colors = list(
map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
colors))
np.random.seed(10101) # Fixed seed for consistent colors across runs.
np.random.shuffle(colors) # Shuffle colors to decorrelate adjacent classes.
np.random.seed(None) # Reset seed to default.
return colors
class_names = get_classes(classes_path)
colors = get_colors(class_names)
len(class_names)
def draw_label(image, text, color, coords):
font = cv2.FONT_HERSHEY_PLAIN
font_scale = 1.
(text_width, text_height) = cv2.getTextSize(text, font, fontScale=font_scale, thickness=1)[0]
padding = 5
rect_height = text_height + padding * 2
rect_width = text_width + padding * 2
(x, y) = coords
cv2.rectangle(image, (x, y), (x + rect_width, y - rect_height), color, cv2.FILLED)
cv2.putText(image, text, (x + padding, y - text_height + padding), font,
fontScale=font_scale,
color=(255, 255, 255),
lineType=cv2.LINE_AA)
return image
def draw_boxes(image, boxes, classes, scores, class_names, colors, show_score=True):
if boxes is None or len(boxes) == 0:
return image
if classes is None or len(classes) == 0:
return image
for box, cls, score in zip(boxes, classes, scores):
xmin, ymin, xmax, ymax = map(int, box)
class_name = class_names[cls]
if show_score:
label = '{} {:.2f}'.format(class_name, score)
else:
label = '{}'.format(class_name)
# print(label, (xmin, ymin), (xmax, ymax))
# if no color info, use black(0,0,0)
if colors == None:
color = (0,0,0)
else:
color = colors[cls]
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 1, cv2.LINE_AA)
image = draw_label(image, label, color, (xmin, ymin))
return image
img_copy = img.copy()
image_array = draw_boxes(img_copy, boxes_real, classes, scores, class_names, colors)
plt.imshow(image_array)
plt.show() | _____no_output_____ | MIT | yolo-fastest_inference/inference_one_picture.ipynb | Lebhoryi/keras-YOLOv3-model-set |
Pandas DataFrame BasicsLoading CSV/TSV data to pandas, then examine the data frame object using `shape`, `columns`, `dtypes` and `info()`. | # Data can be downloaded from https://raw.githubusercontent.com/jennybc/gapminder/master/inst/extdata/gapminder.tsv
import pandas as pd
df = pd.read_csv("gapminder.tsv", sep="\t")
type(df)
df.shape
df.columns
df.dtypes | _____no_output_____ | MIT | pandas_for_everyone/1_Introduction.ipynb | o3c9/playgrounds |
Subsetting DataFrame`loc` uses the index label and `iloc` uses the index number. Don't get confused! | df[["country", "year", "pop"]].head()
df.loc[0] # using index label
df.loc[-1] # label "-1" doesn't exist
df.iloc[0] # using row index number
df.iloc[-1]
df.loc[:5, ["country", "year"]]
df.iloc[:5, [0, 2]] | _____no_output_____ | MIT | pandas_for_everyone/1_Introduction.ipynb | o3c9/playgrounds |
Summarization | df.groupby("year")["lifeExp"].mean()
df.groupby("year").mean()
df_grouped_by = df.groupby(["year", "continent"])[["lifeExp", "gdpPercap"]].mean()
# To flatten group by, you can use `reset_index`
df_grouped_by.reset_index() | _____no_output_____ | MIT | pandas_for_everyone/1_Introduction.ipynb | o3c9/playgrounds |
Basic Plot | import matplotlib.pyplot as plt
%matplotlib inline
df.groupby("year")["lifeExp"].mean().plot() | _____no_output_____ | MIT | pandas_for_everyone/1_Introduction.ipynb | o3c9/playgrounds |
Developing a regex1. Think of the PATTERN you want to capture in general terms. "I want three letter words."2. Write `pattern = "\w{3}"` and then try it on a few practice strings. **The goal is to BREAK your pattern, find out where it fails, and notice new parts of the pattern you missed.** | import re
pattern = "\w{3}"
re.findall(pattern,"hey there guy") # whoops, "the" isnt a 3 letter word
# tried but failed:
# "(\w{3}) " <-- a space
# "(\w{3})\b" <-- a word boundary should work! why not?
pattern = r"(\w{3})\b" # trying that raw string notation thing
re.findall(pattern,"hey there guy")
# it made the `\b` work!, but pattern still it is failing...
pattern = r"\b(\w{3})\b" # make sur the word has a boundary before it
re.findall(pattern,"hey there guy") # got it! | _____no_output_____ | MIT | content/04/02c_developing a regex.ipynb | Theo-Faucher/ledatascifi-2022 |
Feature EngineeringThis worksheet covers concepts covered in the first part of day 2 - Feature Engineering. It should take no more than 30-40 minutes to complete. Please raise your hand if you get stuck. Import the LibrariesFor this exercise, we will be using:* Pandas (http://pandas.pydata.org/pandas-docs/stable/)* Numpy (https://docs.scipy.org/doc/numpy/reference/)* Matplotlib (http://matplotlib.org/api/pyplot_api.html)* Scikit-learn (http://scikit-learn.org/stable/documentation.html)* YellowBrick (http://www.scikit-yb.org/en/latest/)* Seaborn (https://seaborn.pydata.org) | # Load Libraries - Make sure to run this cell!
import pandas as pd
import numpy as np
import re
from collections import Counter
from sklearn import feature_extraction, tree, model_selection, metrics
from yellowbrick.features import Rank2D
from yellowbrick.features import RadViz
from yellowbrick.features import ParallelCoordinates
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline | _____no_output_____ | BSD-3-Clause | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals |
Feature EngineeringThis worksheet is a step-by-step guide on how to detect domains that were generated using "Domain Generation Algorithm" (DGA). We will walk you through the process of transforming raw domain strings to Machine Learning features and creating a decision tree classifer which you will use to determine whether a given domain is legit or not. Once you have implemented the classifier, the worksheet will walk you through evaluating your model. Overview 2 main steps:1. **Feature Engineering** - from raw domain strings to numeric Machine Learning features using DataFrame manipulations2. **Machine Learning Classification** - predict whether a domain is legit or not using a Decision Tree Classifier **DGA - Background**"Various families of malware use domain generationalgorithms (DGAs) to generate a large number of pseudo-randomdomain names to connect to a command and control (C2) server.In order to block DGA C2 traffic, security organizations mustfirst discover the algorithm by reverse engineering malwaresamples, then generate a list of domains for a given seed. Thedomains are then either preregistered, sink-holed or publishedin a DNS blacklist. This process is not only tedious, but canbe readily circumvented by malware authors. An alternativeapproach to stop malware from using DGAs is to intercept DNSqueries on a network and predict whether domains are DGAgenerated. Much of the previous work in DGA detection is basedon finding groupings of like domains and using their statisticalproperties to determine if they are DGA generated. However,these techniques are run over large time windows and cannot beused for real-time detection and prevention. In addition, many ofthese techniques also use contextual information such as passiveDNS and aggregations of all NXDomains throughout a network.Such requirements are not only costly to integrate, they may notbe possible due to real-world constraints of many systems (suchas endpoint detection). An alternative to these systems is a muchharder problem: detect DGA generation on a per domain basiswith no information except for the domain name. Previous workto solve this harder problem exhibits poor performance and manyof these systems rely heavily on manual creation of features;a time consuming process that can easily be circumvented bymalware authors..." [Citation: Woodbridge et. al 2016: "Predicting Domain Generation Algorithms with Long Short-Term Memory Networks"]A better alternative for real-world deployment would be to use "featureless deep learning" - We have a separate notebook where you can see how this can be implemented!( https://www.endgame.com/blog/technical-blog/using-deep-learning-detect-dgas, https://github.com/endgameinc/dga_predict)**However, let's learn the basics first!!!** Worksheet for Part 1 - Feature Engineering | ## Load data
df = pd.read_csv('../../Data/dga_data_small.csv')
df.drop(['host', 'subclass'], axis=1, inplace=True)
print(df.shape)
df.sample(n=5).head() # print a random sample of the DataFrame
df[df.isDGA == 'legit'].head()
# Google's 10000 most common english words will be needed to derive a feature called ngrams...
# therefore we already load them here.
top_en_words = pd.read_csv('../../Data/google-10000-english.txt', header=None, names=['words'])
top_en_words.sample(n=5).head()
# Source: https://github.com/first20hours/google-10000-english
d = top_en_words | _____no_output_____ | BSD-3-Clause | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals |
Part 1 - Feature EngineeringOption 1 to derive Machine Learning features is to manually hand-craft useful contextual information of the domain string. An alternative approach (not covered in this notebook) is "Featureless Deep Learning", where an embedding layer takes care of deriving features - a huge step towards more "AI".Previous academic research has focused on the following features that are based on contextual information:**List of features**:1. Length ["length"]2. Number of digits ["digits"]3. Entropy ["entropy"] - use ```H_entropy``` function provided 4. Vowel to consonant ratio ["vowel-cons"] - use ```vowel_consonant_ratio``` function provided5. N-grams ["n-grams"] - use ```ngram``` functions provided**Tasks**: Split into A and B parts, see below...Please run the following function cell and then continue reading the next markdown cell with more details on how to derive those features. Have fun! | def H_entropy (x):
# Calculate Shannon Entropy
prob = [ float(x.count(c)) / len(x) for c in dict.fromkeys(list(x)) ]
H = - sum([ p * np.log2(p) for p in prob ])
return H
def vowel_consonant_ratio (x):
# Calculate vowel to consonant ratio
x = x.lower()
vowels_pattern = re.compile('([aeiou])')
consonants_pattern = re.compile('([b-df-hj-np-tv-z])')
vowels = re.findall(vowels_pattern, x)
consonants = re.findall(consonants_pattern, x)
try:
ratio = len(vowels) / len(consonants)
except: # catch zero devision exception
ratio = 0
return ratio | _____no_output_____ | BSD-3-Clause | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals |
Tasks - A - Feature EngineeringPlease try to derive a new pandas 2D DataFrame with a new column for each of feature. Focus on ```length```, ```digits```, ```entropy``` and ```vowel-cons``` here. Also make sure to encode the ```isDGA``` column as integers. [pandas.Series.str](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.html), [pandas.Series.replace](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html) and [pandas.Series,apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html) can be very helpful to quickly derive those features. Functions you need to apply here are provided in above cell.The ```ngram``` is a bit more complicated, see next instruction cell to add this feature... | # Derive Features
# Encode strings of target variable as integers
# Check intermediate 2D pandas DataFrame
df.sample(n=5).head()
| _____no_output_____ | BSD-3-Clause | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals |
Tasks - B - Feature EngineeringFinally, let's tackle the **ngram** feature. There are multiple steps involved to derive this feature. Here in this notebook, we use an implementation outlined in the this academic paper [Schiavoni 2014: "Phoenix: DGA-based Botnet Tracking and Intelligence" - see section: Linguistic Features](http://s2lab.isg.rhul.ac.uk/papers/files/dimva2014.pdf).- **What are ngrams???** Imagine a string like 'facebook', if I were to derive all n-grams for n=2 (aka bi-grams) I would get '['fa', 'ac', 'ce', 'eb', 'bo', 'oo', 'ok']', so you see that you slide with one step from the left and just group 2 characters together each time, a tri-gram for 'facebook' would yielfd '['fac', 'ace', 'ceb', 'ebo', 'boo', 'ook']'. Ngrams have a long history in natural language processing, but are also used a lot for example in detecting malicious executable (raw byte ngrams in this case).Steps involved:1. We have the 10000 most common english words (see data file we loaded, we call this DataFrame ```top_en_words``` in this notebook). Now we run the ```ngrams``` functions on a list of all these words. The output here is a list that contains ALL 1-grams, bi-grams and tri-grams of these 10000 most common english words.2. We use the ```Counter``` function from collections to derive a dictionary ```d``` that contains the counts of all unique 1-grams, bi-grams and tri-grams.3. Our ```ngram_feature``` function will do the core magic. It takes your domain as input, splits it into ngrams (n is a function parameter) and then looks up these ngrams in the english dictionary ```d``` we derived in step 2. Function returns the normalized sum of all ngrams that were contained in the english dictionary. For example, running ```ngram_feature('facebook', d, 2)``` will return 171.28 (this value is just like the one published in the Schiavoni paper).4. Finally ```average_ngram_feature``` wraps around ```ngram_feature```. You will use this function as your task is to derive a feature that gives the average of the ngram_feature for n=1,2 and 3. Input to this function should be a simple list with entries calling ```ngram_feature``` with n=1,2 and 3, hence a list of 3 ngram_feature results. 5. **YOUR TURN: Apply ```average_ngram_feature``` to you domain column in the DataFrame thereby adding ```ngram``` to the df.**6. **YOUR TURN: Finally drop the ```domain``` column from your DataFrame**.Please run the following function cell and then write your code in the following cell. | # For simplicity let's just copy the needed function in here again
# Load dictionary of common english words from part 1
from six.moves import cPickle as pickle
with open('../../Data/d_common_en_words' + '.pickle', 'rb') as f:
d = pickle.load(f)
def H_entropy (x):
# Calculate Shannon Entropy
prob = [ float(x.count(c)) / len(x) for c in dict.fromkeys(list(x)) ]
H = - sum([ p * np.log2(p) for p in prob ])
return H
def vowel_consonant_ratio (x):
# Calculate vowel to consonant ratio
x = x.lower()
vowels_pattern = re.compile('([aeiou])')
consonants_pattern = re.compile('([b-df-hj-np-tv-z])')
vowels = re.findall(vowels_pattern, x)
consonants = re.findall(consonants_pattern, x)
try:
ratio = len(vowels) / len(consonants)
except: # catch zero devision exception
ratio = 0
return ratio
# ngrams: Implementation according to Schiavoni 2014: "Phoenix: DGA-based Botnet Tracking and Intelligence"
# http://s2lab.isg.rhul.ac.uk/papers/files/dimva2014.pdf
def ngrams(word, n):
# Extract all ngrams and return a regular Python list
# Input word: can be a simple string or a list of strings
# Input n: Can be one integer or a list of integers
# if you want to extract multipe ngrams and have them all in one list
l_ngrams = []
if isinstance(word, list):
for w in word:
if isinstance(n, list):
for curr_n in n:
ngrams = [w[i:i+curr_n] for i in range(0,len(w)-curr_n+1)]
l_ngrams.extend(ngrams)
else:
ngrams = [w[i:i+n] for i in range(0,len(w)-n+1)]
l_ngrams.extend(ngrams)
else:
if isinstance(n, list):
for curr_n in n:
ngrams = [word[i:i+curr_n] for i in range(0,len(word)-curr_n+1)]
l_ngrams.extend(ngrams)
else:
ngrams = [word[i:i+n] for i in range(0,len(word)-n+1)]
l_ngrams.extend(ngrams)
# print(l_ngrams)
return l_ngrams
def ngram_feature(domain, d, n):
# Input is your domain string or list of domain strings
# a dictionary object d that contains the count for most common english words
# finally you n either as int list or simple int defining the ngram length
# Core magic: Looks up domain ngrams in english dictionary ngrams and sums up the
# respective english dictionary counts for the respective domain ngram
# sum is normalized
l_ngrams = ngrams(domain, n)
# print(l_ngrams)
count_sum=0
for ngram in l_ngrams:
if d[ngram]:
count_sum+=d[ngram]
try:
feature = count_sum/(len(domain)-n+1)
except:
feature = 0
return feature
def average_ngram_feature(l_ngram_feature):
# input is a list of calls to ngram_feature(domain, d, n)
# usually you would use various n values, like 1,2,3...
return sum(l_ngram_feature)/len(l_ngram_feature)
#Your code here.. | _____no_output_____ | BSD-3-Clause | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals |
Breakpoint: Load Features and LabelsIf you got stuck in Part 1, please simply load the feature matrix we prepared for you, so you can move on to Part 2 and train a Decision Tree Classifier. | df_final = pd.read_csv('../../Data/our_data_dga_features_final_df.csv')
print(df_final.isDGA.value_counts())
df_final.sample(5) | _____no_output_____ | BSD-3-Clause | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals |
Visualizing the ResultsAt this point, we've created a dataset which has many features that can be used for classification. Using YellowBrick, your final step is to visualize the features to see which will be of value and which will not. First, let's create a Rank2D visualizer to compute the correlations between all the features. Detailed documentation available here: http://www.scikit-yb.org/en/latest/examples/methods.htmlfeature-analysis | feature_names = ['length','digits','entropy','vowel-cons','ngrams']
features = df_final[feature_names]
target = df_final.isDGA
#Your code here... | _____no_output_____ | BSD-3-Clause | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals |
Now let's use a Seaborn pairplot as well. This will really show you which features have clear dividing lines between the classes. Docs are available here: http://seaborn.pydata.org/generated/seaborn.pairplot.html | #Your code here... | _____no_output_____ | BSD-3-Clause | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals |
Finally, let's try making a RadViz of the features. This visualization will help us see whether there is too much noise to make accurate classifications. | #Your code here... | _____no_output_____ | BSD-3-Clause | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals |
"Windows Store dataset Exploatory Data Analysis II"> "Exploatory Data Analysis (EDA) on The Windows Store dataset from Kaggle: https://www.kaggle.com/vishnuvarthanrao/windows-store Part 2"- toc: false- badges: false Hi everyone, this is part 2 of the series "Window Store Explonatory Data Analysis (EDA)". If you haven't checked out part 2 already then please use this link to access the article:https://www.kaggle.com/sanchitagarwal/windows-store-eda-1 A quick look at the data revealed that the majority of the data (97%) are free apps (price = 0), so I decided to stratify the dataset into categories "Free" and "Paid" based on the value of the PRICE column; The intutition being that the behviour of the population intenting to purchase an application and the resultant characterstics will be significantly different than those who aren't. Nevertheless, later on, I shall seek correlation between both the stratas.Lets start with the "Paid" category first.P.S: SQL related code have been commented and replaced with Kaggle appropriate code. | #import pymssql
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates
%matplotlib inline
import seaborn as sns
"""server = "You seriously thought"
user = "that I'm stupid enough to"
password = "expose my credentials to the public ? "
connection = pymssql.connect(server, user, password, "master")
with connection:
with connection.cursor(as_dict = True) as cursor:
sql = "SELECT * FROM windows_store WHERE price != 0.0"
cursor.execute(sql)
result = cursor.fetchall()
#print(result)
paid_apps_df = pd.DataFrame(result)"""
apps_df = pd.read_csv("../input/windows-store/msft.csv")
apps_df["Price"].fillna(value = "Free", inplace = True)
paid_apps_df = apps_df.loc[apps_df.Price != "Free"]
paid_apps_df['Date'] = pd.to_datetime(paid_apps_df['Date'])
paid_apps_df['Price'] = paid_apps_df['Price'].replace("[\₹,\,]","",regex=True).astype(float)
paid_apps_df.head() | /opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:19: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
/opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:21: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
| Apache-2.0 | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io |
P.S: Its important to convert the DATE column into pandas datetime datatype to avoid any conflicts when doing datetime analysis through Pandas. | paid_apps_df.describe() | _____no_output_____ | Apache-2.0 | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io |
In the RATING column we can see that the average rating for paid apps is a mere 2.47, a horrondous result considering that one would expect a better user experience on apps which have been paid for. In the PRICE column, the range is pretty large (5449 - 54 = 5395), and so is the standard deviation, meaning there is a lot of variance in the prices. Interesting thing to know is that both the 50th & 75th percentile equals 269, meaning that 269 is the most commonly used to price apps. This can be verified by finding the mode of the PRICE column. | paid_apps_df["Price"].mode() | _____no_output_____ | Apache-2.0 | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io |
Voila!! | paid_apps_df.Category.describe()
paid_apps_df.Category.unique() | _____no_output_____ | Apache-2.0 | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io |
"Book" being the top category in paid apps confirms books to be the most popular product a person is willing to pay for, though abeit by a very small margin (56/158 = 0.3544 * 100 = 35.44%). Also to note that there are 8 records with NULL entry for the CATEGORY column.Now lets do some plotting! | df_plot_count = paid_apps_df[["Rating", "Date"]].groupby(pd.Grouper(key="Date", freq='Y')).count()
#print(df_plot_count)
plt.figure(figsize=(15,6))
plt.title("Paid Apps launched per year")
plot = sns.lineplot(data=df_plot_count)
plot.xaxis.set_major_formatter(dates.DateFormatter("%Y"))
plot.set(ylabel = "Count")
plot.legend(labels=["Count"])
plt.show() | _____no_output_____ | Apache-2.0 | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io |
This graph shows that the number of paid apps launched is increasing almost exponentially. This tells us the increase in popularity of Windows app ecosystem. I am interested in knowing if there is any seasonality trend amongest PRICE, RATING and NO_OF_PEOPLE. | df_plot = paid_apps_df[["Date", "Rating", 'No of people Rated', "Price"]]
df_plot.set_index('Date', inplace=True)
df_plot = df_plot.groupby(pd.Grouper(freq='M')).mean().dropna(how="all")
plt.figure(figsize=(15,6))
plt.title("PRICE Seasonality analysis")
plot = sns.lineplot(data= df_plot["Price"])
plot.set(ylabel = "Price")
plot.xaxis.set_minor_locator(dates.MonthLocator())
plot.xaxis.set_major_formatter(dates.DateFormatter("%Y"))
plt.show() | _____no_output_____ | Apache-2.0 | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io |
From 2011 to 2013, the increase was almost linear but later on there are sudden surges followed by a decrease, like a sine wave.Also to note that for years 2013, 2015, 2017, 2018 and 2020, surge in price are detected in the first months (Jan, Feb, March). What could cause this pattern to reemerge ? Something to ponder about.Lastly, from 2020 onwards, the prices are in the low territory compared to previous year's. I believe this can be attributed to the change in pricing strategy (where apps are free to download with additional content available to purchase) and/or increase in piracy. | plt.figure(figsize=(15,6))
plt.title("RATING seasonality analysis")
plot = sns.lineplot(data= df_plot[["Rating"]])
plot.xaxis.set_minor_locator(dates.MonthLocator())
plot.set(ylabel = "Rating")
plot.xaxis.set_major_formatter(dates.DateFormatter("%Y"))
plt.show() | _____no_output_____ | Apache-2.0 | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io |
We can see that there is an increase in volatility as we move further down the x-axis. This could be attributed to the increase in number of apps published through the years as explored in the first graph. | plt.figure(figsize=(15,6))
plt.title("No of people seasonality analysis")
plot = sns.lineplot(data= df_plot[["No of people Rated"]])
plot.xaxis.set_minor_locator(dates.MonthLocator())
plot.xaxis.set_major_formatter(dates.DateFormatter("%Y"))
plt.show() | _____no_output_____ | Apache-2.0 | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io |
This graph and the previous graph are almost similar (which makes perfect sense since the set of people who rated the apps is subset of set of people who have downloaded the app, i.e not all people who downloaded the app may have rated the app but those who have rated the app have definitely downloaded it!).Nothing new to explore here.Now lets find any correlation between PRICE and RATING. | plt.figure(figsize=(15,6))
plt.title("Correlation between Price & Rating")
plot = sns.scatterplot(y=paid_apps_df["Price"], x=paid_apps_df["Rating"])
plt.show() | _____no_output_____ | Apache-2.0 | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io |
**cs3102 Fall 2019** Problem Set 4 (Jupyter Part): Computing Models and Universality **Purpose** The goal of this part of Problem Set 4 is to develop your understanding of universality by building the EVAL function discussed in Class 9. For better readability, we will be using some simple data structures (tuples and lists) throughout this notebook. To make this as formal as the algorithm discussed in class, you should "flatten" each of these datastructures (convert them into a bitstring by just listing all of the contained bits in order).Note: you should not use any loops in this notebook. NAND and ProceduresWe begin by giving you NAND. The asserts ensure that we only work with 0s and 1s | def checkBoolean(b):
"""Tests a value is a valid Boolean. We use the int values 0 and 1 to represent
Boolean False and True. (Technically, checkBoolean should not be allowed in a
"straightline" program since it is a function call, but we are just using it to
check assertions.)
"""
assert b == 0 or b == 1
def NAND(a,b):
checkBoolean(a)
checkBoolean(b)
return 1 - (a * b)
assert(NAND(0, 0) == 1)
assert(NAND(0, 1) == 1)
assert(NAND(1, 0) == 1)
assert(NAND(1, 1) == 0) | _____no_output_____ | MIT | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io |
Next, we provide several of the boolean functions we've discussed so far. You're welcome to use any of these throughout this notebook. | def NOT(a):
checkBoolean(a)
return NAND(a, a)
def AND(a, b):
checkBoolean(a)
checkBoolean(b)
temp = NAND(a, b)
return NAND(temp, temp)
def OR(a, b):
checkBoolean(a)
checkBoolean(b)
temp1 = NAND(a,a)
temp2 = NAND(b,b)
return NAND(temp1, temp2)
def XOR(a, b):
checkBoolean(a)
checkBoolean(b)
or_ab = OR(a, b)
and_ab = AND(a, b)
not_and_ab = NOT(and_ab)
return AND(or_ab, not_and_ab)
def IF(cond,a,b):
checkBoolean(cond)
checkBoolean(a)
checkBoolean(b)
not_cond = NAND(cond, cond)
temp1 = NAND(cond, a)
temp2 = NAND(not_cond, b)
return NAND(temp1, temp2)
def LOOKUP1(x0, x1, i0):
[checkBoolean(x) for x in (x0, x1, i0)] # not strightline code, but just checking
return IF(i0, x1, x0)
def LOOKUP2(x0,x1,x2,x3,i0,i1):
[checkBoolean(x) for x in (x0, x1, x2, x3, i0, i1)] # just checking
first_half = LOOKUP1(x0, x1, i1)
second_half = LOOKUP1(x2, x3, i1)
return IF(i0, second_half, first_half)
def LOOKUP3(x0,x1,x2,x3,x4,x5,x6,x7,i0,i1,i2):
[checkBoolean(x) for x in (x0, x1, x2, x3, x4, x5, x6, x7, i0, i1, i2)] # just checking
first_half = LOOKUP2(x0, x1, x2, x3, i1, i2)
second_half = LOOKUP2(x4, x5, x6, x7, i1, i2)
return IF(i0, second_half, first_half) | _____no_output_____ | MIT | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io |
Representing a program as bitsNext we represent the `IF` program as a list of triples. For readability, we'll write this as integers, and convert to bits.This first cell provides two functions for converting triples of integers into triples of bitstrings. You should understand why they exist. | def int2bits(number, num_bits):
binary = tuple()
for i in range(num_bits):
bit = number % 2
number = number // 2
binary = tuple([bit]) + binary
return binary
def prog2bits(prog, num_bits):
bits_prog = []
for triple in prog:
bits0 = int2bits(triple[0], num_bits)
bits1 = int2bits(triple[1], num_bits)
bits2 = int2bits(triple[2], num_bits)
triple_bits = (bits0,bits1,bits2)
bits_prog.append(triple_bits)
return bits_prog | _____no_output_____ | MIT | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io |
Now we give `IF` as a list of triples. It is first given as a list of triples of integers, then converted into a list of triples of 3-bit strings.Note that this program has 3 inputs, 1 output, 7 variables (including those 3 inputs and 1 output), and 4 lines of code. | if_program = [(3,0,0),(4,0,1),(5,3,2),(6,4,5)]
if_program = prog2bits(if_program, 3)
print("The IF program represented as triples of bitstrings:")
print(if_program) | The IF program represented as triples of bitstrings:
[((0, 1, 1), (0, 0, 0), (0, 0, 0)), ((1, 0, 0), (0, 0, 0), (0, 0, 1)), ((1, 0, 1), (0, 1, 1), (0, 1, 0)), ((1, 1, 0), (1, 0, 0), (1, 0, 1))]
| MIT | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io |
For the remainder of this notebook we will build and use the `EVAL_3_7_4_1` function for NAND programs with 3 input bits, 7 internal variables, 4 lines, and 1 output bit. As mentioned in Class 9, to do EVAL we will have a table we called `T` that will contain the value of all the variables throughout our evaluation (row `i` of `T` will contain the value of variable `i`), note that the length of `T` should therefore be equal to the number of variables in the program (in this case 7). To find the value of a variable, we mentioned the function `GET`, which was very similar to lookup. **Problem J1.** Implement the function `GET_7` below, which will index into the table `T` of 7 rows (since the programs we're evaluating will have 7 variables). You may use `LOOKUP`. | def GET_7(T, i):
assert(len(T) == 7) # not straightline, just checking
assert(len(i) == 3) # not straightline, just checking
# gives the value of the variable indexed by the length 3 bitstring from a 6-bit table
#TODO: Replace the body of this function to implement GET_7 correctly
return 0
T = (0,0,0,1,0,0,0)
i = (0,1,1)
assert(GET_7(T,i) == 1)
print("Jolly good!")
T = (1,1,1,1,0,1,1)
i = (1,0,0)
assert(GET_7(T,i) == 0)
print("Cheerio!") | Jolly good!
Cheerio!
| MIT | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io |
We use `GET` to retrieve one element from the table `T`. We will use `UPDATE` to change one of the elements from table `T`. Before we can implement `UPDATE`, we will want to implement an `EQUAL_3` function. This will determine whether two given 3-bit numbers are equal**Problem J2.** Implement the function `EQUAL_3` below, which will return 1 if two given 3-bit numbers are the same, and 0 otherwise. | def EQUAL_3(i, j):
assert(len(i) == len(j) == 3)
#TODO: Replace the body of this function to implement EQUAL_3 correctly
return 0
assert(EQUAL_3((0,0,0),(0,0,0)))
assert(EQUAL_3((0,0,1),(0,0,1)))
assert(EQUAL_3((1,0,1),(1,0,1)))
assert(not EQUAL_3((1,1,1),(0,0,0)))
assert(not EQUAL_3((1,1,0),(0,0,0)))
print("Huzzah!")
| Huzzah!
| MIT | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io |
**Problem J3.** Implement the function `UPDATE_7` below, which will change the given index (given by the triple of bits `i`) of the 7-row table `T` to become the bit `b`. You will likely need `EQUAL_3` and `IF` to do this. | def UPDATE_7(T, b, i):
assert(len(T) == 7)
#TODO: Replace the body of this function to implement UPDATE_7 correctly
t0 = 0
t1 = 0
t2 = 0
t3 = 0
t4 = 0
t5 = 0
t6 = 0
return (t0,t1,t2,t3,t4,t5,t6)
def pseudo_update_7(T, b, i):
# This update works by manipulating indices directly. It is meant to show you what your update should return.
index = i[2] + 2*i[1] + 4*i[0]
return T[:index] + tuple([b]) + T[index+1:]
T = (0,0,0,1,0,0,0)
i= (0,1,1)
assert(pseudo_update_7(T, 0, i) == UPDATE_7(T, 0, i))
print("GRRRRRREAT!!")
T = (1,1,1,1,0,1,1)
i = (1,0,0)
assert(pseudo_update_7(T, 1, i) == UPDATE_7(T, 1, i))
print("Fabulous")
T = (1,1,1,1,1,1,0)
i = (1,1,0)
assert(pseudo_update_7(T, 1, i) == UPDATE_7(T, 1, i))
print("Correct!")
T = (1,0,0,0,0,0,0)
i = (0,0,0)
assert(pseudo_update_7(T, 0, i) == UPDATE_7(T, 0, i))
print("You got it!") | GRRRRRREAT!!
Fabulous
Correct!
You got it!
| MIT | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io |
We finally have enough to implement our `EVAL_3_7_4_1` function!**Problem J4.** Implement `EVAL_3_7_4_1`. | def EVAL_3_7_4_1(program, in0, in1, in2):
assert(len(program) == 4)
T = (0,0,0,0,0,0,0)
# TODO: fill in the body of this function.
return T[6]
cond,a,b = 0,1,0
assert(EVAL_3_7_4_1(if_program, cond, a, b) == IF(cond,a,b))
print("Gucci!")
cond,a,b = 1,1,0
assert(EVAL_3_7_4_1(if_program, cond, a, b) == IF(cond,a,b))
print("Sweet!")
cond,a,b = 0,0,1
assert(EVAL_3_7_4_1(if_program, cond, a, b) == IF(cond,a,b))
print("Cool Beans!")
cond,a,b = 1,0,1
assert(EVAL_3_7_4_1(if_program, cond, a, b) == IF(cond,a,b))
print("You Rock!") | _____no_output_____ | MIT | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io |
If we were to slightly modify our procedure for converting programs into a list of triples, we can use `EVAL_3_7_4_1` to evaluate any program that uses no more than 3 inputs, 7 variables, 4 lines, and 1 output. **Problem J5.** Write `OR` as a list of triples so that we can evaluate it using `EVAL_3_7_4_1` above. Note that `OR` requires fewer inputs, variables, and lines of code than `IF` does. You'll need to do something about that. You may use the `prog2bits` function we provided above. | or_program = [] # TODO: fill this in
a,b = 0,0
assert(EVAL_3_7_4_1(or_program, a, b, 0) == OR(a,b))
a,b = 0,1
assert(EVAL_3_7_4_1(or_program, a, b, 0) == OR(a,b))
a,b = 1,0
assert(EVAL_3_7_4_1(or_program, a, b, 0) == OR(a,b))
a,b = 1,1
assert(EVAL_3_7_4_1(or_program, a, b, 0) == OR(a,b))
print("You did it!!") | you did it!!
| MIT | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io |
Residual NetworksWelcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](https://arxiv.org/pdf/1512.03385.pdf), allow you to train much deeper networks than were previously practically feasible.**In this assignment, you will:**- Implement the basic building blocks of ResNets. - Put together these building blocks to implement and train a state-of-the-art neural network for image classification. This assignment will be done in Keras. Before jumping into the problem, let's run the cell below to load the required packages. | import numpy as np
from resnets_utils import *
from keras import layers
from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D
from keras.models import Model, load_model
from keras.preprocessing import image
from keras.utils import layer_utils
from keras.utils.data_utils import get_file
from keras.applications.imagenet_utils import preprocess_input
from keras.utils.vis_utils import model_to_dot
from keras.utils import plot_model
from keras.initializers import glorot_uniform
import pydot
from IPython.display import SVG
import scipy.misc
from matplotlib.pyplot import imshow
%matplotlib inline
import keras.backend as K
K.set_image_data_format('channels_last')
K.set_learning_phase(1) | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
1 - The problem of very deep neural networksLast week, you built your first convolutional neural network. In recent years, neural networks have become deeper, with state-of-the-art networks going from just a few layers (e.g., AlexNet) to over a hundred layers.The main benefit of a very deep network is that it can represent very complex functions. It can also learn features at many different levels of abstraction, from edges (at the lower layers) to very complex features (at the deeper layers). However, using a deeper network doesn't always help. A huge barrier to training them is vanishing gradients: very deep networks often have a gradient signal that goes to zero quickly, thus making gradient descent unbearably slow. More specifically, during gradient descent, as you backprop from the final layer back to the first layer, you are multiplying by the weight matrix on each step, and thus the gradient can decrease exponentially quickly to zero (or, in rare cases, grow exponentially quickly and "explode" to take very large values). During training, you might therefore see the magnitude (or norm) of the gradient for the earlier layers descrease to zero very rapidly as training proceeds: **Figure 1** : **Vanishing gradient** The speed of learning decreases very rapidly for the early layers as the network trains You are now going to solve this problem by building a Residual Network! 2 - Building a Residual NetworkIn ResNets, a "shortcut" or a "skip connection" allows the gradient to be directly backpropagated to earlier layers: **Figure 2** : A ResNet block showing a **skip-connection** The image on the left shows the "main path" through the network. The image on the right adds a shortcut to the main path. By stacking these ResNet blocks on top of each other, you can form a very deep network. We also saw in lecture that having ResNet blocks with the shortcut also makes it very easy for one of the blocks to learn an identity function. This means that you can stack on additional ResNet blocks with little risk of harming training set performance. (There is also some evidence that the ease of learning an identity function--even more than skip connections helping with vanishing gradients--accounts for ResNets' remarkable performance.)Two main types of blocks are used in a ResNet, depending mainly on whether the input/output dimensions are same or different. You are going to implement both of them. 2.1 - The identity blockThe identity block is the standard block used in ResNets, and corresponds to the case where the input activation (say $a^{[l]}$) has the same dimension as the output activation (say $a^{[l+2]}$). To flesh out the different steps of what happens in a ResNet's identity block, here is an alternative diagram showing the individual steps: **Figure 3** : **Identity block.** Skip connection "skips over" 2 layers. The upper path is the "shortcut path." The lower path is the "main path." In this diagram, we have also made explicit the CONV2D and ReLU steps in each layer. To speed up training we have also added a BatchNorm step. Don't worry about this being complicated to implement--you'll see that BatchNorm is just one line of code in Keras! In this exercise, you'll actually implement a slightly more powerful version of this identity block, in which the skip connection "skips over" 3 hidden layers rather than 2 layers. It looks like this: **Figure 4** : **Identity block.** Skip connection "skips over" 3 layers.Here're the individual steps.First component of main path: - The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (1,1). Its padding is "valid" and its name should be `conv_name_base + '2a'`. Use 0 as the seed for the random initialization. - The first BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2a'`.- Then apply the ReLU activation function. This has no name and no hyperparameters. Second component of main path:- The second CONV2D has $F_2$ filters of shape $(f,f)$ and a stride of (1,1). Its padding is "same" and its name should be `conv_name_base + '2b'`. Use 0 as the seed for the random initialization. - The second BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2b'`.- Then apply the ReLU activation function. This has no name and no hyperparameters. Third component of main path:- The third CONV2D has $F_3$ filters of shape (1,1) and a stride of (1,1). Its padding is "valid" and its name should be `conv_name_base + '2c'`. Use 0 as the seed for the random initialization. - The third BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2c'`. Note that there is no ReLU activation function in this component. Final step: - The shortcut and the input are added together.- Then apply the ReLU activation function. This has no name and no hyperparameters. **Exercise**: Implement the ResNet identity block. We have implemented the first component of the main path. Please read over this carefully to make sure you understand what it is doing. You should implement the rest. - To implement the Conv2D step: [See reference](https://keras.io/layers/convolutional/conv2d)- To implement BatchNorm: [See reference](https://keras.io/layers/normalization/) (axis: Integer, the axis that should be normalized (typically the channels axis))- For the activation, use: Activation('relu')(X)- To add the value passed forward by the shortcut: [See reference](https://keras.io/layers/merge/add) | # GRADED FUNCTION: identity_block
def identity_block(X, f, filters, stage, block):
"""
Implementation of the identity block as defined in Figure 3
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main path
filters -- python list of integers, defining the number of filters in the CONV layers of the main path
stage -- integer, used to name the layers, depending on their position in the network
block -- string/character, used to name the layers, depending on their position in the network
Returns:
X -- output of the identity block, tensor of shape (n_H, n_W, n_C)
"""
# defining name basis
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
# Retrieve Filters
F1, F2, F3 = filters
# Save the input value. You'll need this later to add back to the main path.
X_shortcut = X
# First component of main path
X = Conv2D(filters = F1, kernel_size = (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed=0))(X)
X = BatchNormalization(name = bn_name_base + '2a')(X)
X = Activation('relu')(X)
### START CODE HERE ###
# Second component of main path (≈3 lines)
X = Conv2D(filters = F2, kernel_size = (f, f), strides = (1,1), padding = 'same', name = conv_name_base + '2b', kernel_initializer = glorot_uniform(seed=0))(X)
X = BatchNormalization(name = bn_name_base + '2b')(X)
X = Activation('relu')(X)
# Third component of main path (≈2 lines)
X = Conv2D(filters = F3, kernel_size = (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2c', kernel_initializer = glorot_uniform(seed=0))(X)
X = BatchNormalization(name = bn_name_base + '2c')(X)
# Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)
X = Add()([X, X_shortcut])
X = Activation('relu')(X)
### END CODE HERE ###
return X
tf.reset_default_graph()
with tf.Session() as test:
X = np.random.randn(3, 4, 4, 6)
np.random.seed(1)
A_prev = tf.placeholder("float", [3, 4, 4, 6])
A = identity_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a')
test.run(tf.global_variables_initializer())
out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})
print("out = " + str(out[0][1][1][0])) | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
**Expected Output**: **out** [0.9482299 0. 1.1610144 2.747859 0. 1.36677 ] 2.2 - The convolutional blockYou've implemented the ResNet identity block. Next, the ResNet "convolutional block" is the other type of block. You can use this type of block **when the input and output dimensions don't match up**. The difference with the identity block is that there is a CONV2D layer in the shortcut path: **Figure 4** : **Convolutional block** The CONV2D layer in the shortcut path is used to resize the input $x$ to a different dimension, so that the dimensions match up in the final addition needed to add the shortcut value back to the main path. (This plays a similar role as the matrix $W_s$ discussed in lecture.) For example, to reduce the activation dimensions's height and width by a factor of 2, you can use a 1x1 convolution with a stride of 2. The CONV2D layer on the shortcut path does not use any non-linear activation function. Its main role is to just apply a (learned) linear function that reduces the dimension of the input, so that the dimensions match up for the later addition step. The details of the convolutional block are as follows. First component of main path:- The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (s,s). Its padding is "valid" and its name should be `conv_name_base + '2a'`. - The first BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2a'`.- Then apply the ReLU activation function. This has no name and no hyperparameters. Second component of main path:- The second CONV2D has $F_2$ filters of (f,f) and a stride of (1,1). Its padding is "same" and it's name should be `conv_name_base + '2b'`.- The second BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2b'`.- Then apply the ReLU activation function. This has no name and no hyperparameters. Third component of main path:- The third CONV2D has $F_3$ filters of (1,1) and a stride of (1,1). Its padding is "valid" and it's name should be `conv_name_base + '2c'`.- The third BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2c'`. Note that there is no ReLU activation function in this component. Shortcut path:- The CONV2D has $F_3$ filters of shape (1,1) and a stride of (s,s). Its padding is "valid" and its name should be `conv_name_base + '1'`.- The BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '1'`. Final step: - The shortcut and the main path values are added together.- Then apply the ReLU activation function. This has no name and no hyperparameters. **Exercise**: Implement the convolutional block. We have implemented the first component of the main path; you should implement the rest. As before, always use 0 as the seed for the random initialization, to ensure consistency with our grader.- [Conv Hint](https://keras.io/layers/convolutional/conv2d)- [BatchNorm Hint](https://keras.io/layers/normalization/batchnormalization) (axis: Integer, the axis that should be normalized (typically the features axis))- For the activation, use: Activation('relu')(X)- [Addition Hint](https://keras.io/layers/merge/add) | # GRADED FUNCTION: convolutional_block
def convolutional_block(X, f, filters, stage, block, s = 2):
"""
Implementation of the convolutional block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main path
filters -- python list of integers, defining the number of filters in the CONV layers of the main path
stage -- integer, used to name the layers, depending on their position in the network
block -- string/character, used to name the layers, depending on their position in the network
s -- Integer, specifying the stride to be used
Returns:
X -- output of the convolutional block, tensor of shape (n_H, n_W, n_C)
"""
# defining name basis
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
# Retrieve Filters
F1, F2, F3 = filters
# Save the input value
X_shortcut = X
##### MAIN PATH #####
# First component of main path
X = Conv2D(F1, (1, 1), strides = (s,s), padding = 'valid', name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed=0))(X)
X = BatchNormalization(name = bn_name_base + '2a')(X)
X = Activation('relu')(X)
### START CODE HERE ###
# Second component of main path (≈3 lines)
X = Conv2D(F2, (f, f), strides = (1,1), padding = 'same', name = conv_name_base + '2b', kernel_initializer = glorot_uniform(seed=0))(X)
X = BatchNormalization(name = bn_name_base + '2b')(X)
X = Activation('relu')(X)
# Third component of main path (≈2 lines)
X = Conv2D(F3, (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2c', kernel_initializer = glorot_uniform(seed=0))(X)
X = BatchNormalization(name = bn_name_base + '2c')(X)
##### SHORTCUT PATH #### (≈2 lines)
X_shortcut = Conv2D(F3, (1, 1), strides = (s,s), padding = 'valid', name = conv_name_base + '1', kernel_initializer = glorot_uniform(seed=0))(X_shortcut)
X_shortcut = BatchNormalization(name = bn_name_base + '1')(X_shortcut)
# Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)
X = Add()([X, X_shortcut])
X = Activation('relu')(X)
### END CODE HERE ###
return X
tf.reset_default_graph()
with tf.Session() as test:
np.random.seed(1)
A_prev = tf.placeholder("float", [3, 4, 4, 6])
X = np.random.randn(3, 4, 4, 6)
A = convolutional_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a')
test.run(tf.global_variables_initializer())
out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})
print("out = " + str(out[0][1][1][0])) | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
**Expected Output**: **out** [0.09018461 1.2348977 0.46822017 0.0367176 0. 0.655166 ] 3 - Building your first ResNet model (50 layers)You now have the necessary blocks to build a very deep ResNet. The following figure describes in detail the architecture of this neural network. "ID BLOCK" in the diagram stands for "Identity block," and "ID BLOCK x3" means you should stack 3 identity blocks together. **Figure 5** : **ResNet-50 model** The details of this ResNet-50 model are:- Zero-padding pads the input with a pad of (3,3)- Stage 1: - The 2D Convolution has 64 filters of shape (7,7) and uses a stride of (2,2). Its name is "conv1". - BatchNorm is applied to the channels axis of the input. - MaxPooling uses a (3,3) window and a (2,2) stride.- Stage 2: - The convolutional block uses three set of filters of size [64,64,256], "f" is 3, "s" is 1 and the block is "a". - The 2 identity blocks use three set of filters of size [64,64,256], "f" is 3 and the blocks are "b" and "c".- Stage 3: - The convolutional block uses three set of filters of size [128,128,512], "f" is 3, "s" is 2 and the block is "a". - The 3 identity blocks use three set of filters of size [128,128,512], "f" is 3 and the blocks are "b", "c" and "d".- Stage 4: - The convolutional block uses three set of filters of size [256, 256, 1024], "f" is 3, "s" is 2 and the block is "a". - The 5 identity blocks use three set of filters of size [256, 256, 1024], "f" is 3 and the blocks are "b", "c", "d", "e" and "f".- Stage 5: - The convolutional block uses three set of filters of size [512, 512, 2048], "f" is 3, "s" is 2 and the block is "a". - The 2 identity blocks use three set of filters of size [256, 256, 2048], "f" is 3 and the blocks are "b" and "c".- The 2D Average Pooling uses a window of shape (2,2) and its name is "avg_pool".- The flatten doesn't have any hyperparameters or name.- The Fully Connected (Dense) layer reduces its input to the number of classes using a softmax activation. Its name should be `'fc' + str(classes)`.**Exercise**: Implement the ResNet with 50 layers described in the figure above. We have implemented Stages 1 and 2. Please implement the rest. (The syntax for implementing Stages 3-5 should be quite similar to that of Stage 2.) Make sure you follow the naming convention in the text above. You'll need to use this function: - Average pooling [see reference](https://keras.io/layers/pooling/averagepooling2d)Here're some other functions we used in the code below:- Conv2D: [See reference](https://keras.io/layers/convolutional/conv2d)- BatchNorm: [See reference](https://keras.io/layers/normalization/batchnormalization) (axis: Integer, the axis that should be normalized (typically the features axis))- Zero padding: [See reference](https://keras.io/layers/convolutional/zeropadding2d)- Max pooling: [See reference](https://keras.io/layers/pooling/maxpooling2d)- Fully conected layer: [See reference](https://keras.io/layers/core/dense)- Addition: [See reference](https://keras.io/layers/merge/add) | # GRADED FUNCTION: ResNet50
def ResNet50(input_shape = (64, 64, 3), classes = 6):
"""
Implementation of the popular ResNet50 the following architecture:
CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3
-> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYER
Arguments:
input_shape -- shape of the images of the dataset
classes -- integer, number of classes
Returns:
model -- a Model() instance in Keras
"""
# Define the input as a tensor with shape input_shape
X_input = Input(input_shape)
# Zero-Padding
X = ZeroPadding2D((3, 3))(X_input)
# Stage 1
X = Conv2D(64, (7, 7), strides = (2, 2), name = 'conv1', kernel_initializer = glorot_uniform(seed=0))(X)
X = BatchNormalization(axis = 3, name = 'bn_conv1')(X)
X = Activation('relu')(X)
X = MaxPooling2D((3, 3), strides=(2, 2))(X)
# Stage 2
X = convolutional_block(X, f = 3, filters = [64, 64, 256], stage = 2, block='a', s = 1)
X = identity_block(X, 3, [64, 64, 256], stage=2, block='b')
X = identity_block(X, 3, [64, 64, 256], stage=2, block='c')
### START CODE HERE ###
# Stage 3 (≈4 lines)
X = convolutional_block(X, f = 3, filters = [128,128,512], stage = 3, block='a', s = 2)
X = identity_block(X, 3, [128,128,512], stage=3, block='b')
X = identity_block(X, 3, [128,128,512], stage=3, block='c')
X = identity_block(X, 3, [128,128,512], stage=3, block='d')
# Stage 4 (≈6 lines)
X = convolutional_block(X, f = 3, filters = [256, 256, 1024], stage = 4, block='a', s = 2)
X = identity_block(X, 3, [256, 256, 1024], stage=4, block='b')
X = identity_block(X, 3, [256, 256, 1024], stage=4, block='c')
X = identity_block(X, 3, [256, 256, 1024], stage=4, block='d')
X = identity_block(X, 3, [256, 256, 1024], stage=4, block='e')
X = identity_block(X, 3, [256, 256, 1024], stage=4, block='f')
# Stage 5 (≈3 lines)
X = convolutional_block(X, f = 3, filters = [512, 512, 2048], stage = 5, block='a', s = 2)
X = identity_block(X, 3, [512, 512, 2048], stage=5, block='b')
X = identity_block(X, 3, [512, 512, 2048], stage=5, block='c')
# AVGPOOL (≈1 line). Use "X = AveragePooling2D(...)(X)"
X = AveragePooling2D(pool_size=(2, 2), name = "avg_pool")(X)
### END CODE HERE ###
# output layer
X = Flatten()(X)
X = Dense(classes, activation='softmax', name='fc' + str(classes), kernel_initializer = glorot_uniform(seed=0))(X)
# Create model
model = Model(inputs = X_input, outputs = X, name='ResNet50')
return model | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
Run the following code to build the model's graph. If your implementation is not correct you will know it by checking your accuracy when running `model.fit(...)` below. | model = ResNet50(input_shape = (64, 64, 3), classes = 6) | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
As seen in the Keras Tutorial Notebook, prior training a model, you need to configure the learning process by compiling the model. | model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
The model is now ready to be trained. The only thing you need is a dataset. Let's load the SIGNS Dataset. **Figure 6** : **SIGNS dataset** | X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
# Normalize image vectors
X_train = X_train_orig/255.
X_test = X_test_orig/255.
# Convert training and test labels to one hot matrices
Y_train = convert_to_one_hot(Y_train_orig, 6).T
Y_test = convert_to_one_hot(Y_test_orig, 6).T
print ("number of training examples = " + str(X_train.shape[0]))
print ("number of test examples = " + str(X_test.shape[0]))
print ("X_train shape: " + str(X_train.shape))
print ("Y_train shape: " + str(Y_train.shape))
print ("X_test shape: " + str(X_test.shape))
print ("Y_test shape: " + str(Y_test.shape)) | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
Run the following cell to train your model on 2 epochs with a batch size of 32. On a CPU it should take you around 5min per epoch. | model.fit(X_train, Y_train, epochs = 50, batch_size = 32) | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
**Expected Output**: ** Epoch 1/50** loss: between 1 and 5, acc: between 0.2 and 0.5, although your results can be different from ours. ** Epoch 2/50** loss: between 0.5 and 1, acc: between 0.5 and 0.9, you should see your loss decreasing and the accuracy increasing. Let's see how this model (trained on only two epochs) performs on the test set. | preds = model.evaluate(X_test, Y_test)
print ("Loss = " + str(preds[0]))
print ("Test Accuracy = " + str(preds[1]))
model.save('ResNet50.h5') | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
**Expected Output**: **Test Accuracy** between 0.9 and 1.0 For the purpose of this assignment, we've asked you to train the model only for two epochs. You can see that it achieves poor performances. Please go ahead and submit your assignment; to check correctness, the online grader will run your code only for a small number of epochs as well. After you have finished this official (graded) part of this assignment, you can also optionally train the ResNet for more iterations, if you want. We get a lot better performance when we train for ~20 epochs, but this will take more than an hour when training on a CPU. Using a GPU, we've trained our own ResNet50 model's weights on the SIGNS dataset. You can load and run our trained model on the test set in the cells below. It may take ≈1min to load the model. | model = load_model('ResNet50.h5')
preds = model.evaluate(X_test, Y_test)
print ("Loss = " + str(preds[0]))
print ("Test Accuracy = " + str(preds[1])) | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
ResNet50 is a powerful model for image classification when it is trained for an adequate number of iterations. We hope you can use what you've learnt and apply it to your own classification problem to perform state-of-the-art accuracy.Congratulations on finishing this assignment! You've now implemented a state-of-the-art image classification system! You can also print a summary of your model by running the following code. | model.summary() | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
Finally, run the code below to visualize your ResNet50. You can also download a .png picture of your model by going to "File -> Open...-> model.png". | plot_model(model, to_file='model.png') | _____no_output_____ | Apache-2.0 | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning |
Copyright 2019 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License. | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
使用 tf.data API 获得更高性能 View on TensorFlow.org 在 Google Colab 中运行 在 GitHub 上查看源代码 下载笔记本 概述GPU 和 TPU 能够极大缩短执行单个训练步骤所需的时间。为了达到最佳性能,需要高效的输入流水线,以在当前步骤完成之前为下一步提供数据。`tf.data` API 有助于构建灵活高效的输入流水线。本文档演示了如何使用 `tf.data` API 构建高性能的 TensorFlow 输入流水线。继续之前,请阅读“[构建 TensorFlow 输入流水线](https://render.githubusercontent.com/view/data.ipynb)”指南,了解如何使用 `tf.data` API。 资源- [构建 TensorFlow 输入流水线](https://render.githubusercontent.com/view/data.ipynb)- `tf.data.Dataset` API- [使用 TF Profiler 分析tf.data 性能](https://render.githubusercontent.com/view/data_performance_analysis.md) 设置 | import tensorflow as tf
import time | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
在本指南中,您将迭代数据集并衡量性能。制定可重现的性能基准可能很困难,不同的因素会对其产生影响:- 当前的 CPU 负载- 网络流量- 缓存等复杂机制因此,要提供可重现的基准,需要构建人工样本。 数据集定义一个继承自 `tf.data.Dataset` 的类,称为 `ArtificialDataset`。此数据集:- 会生成 `num_samples` 样本(默认数量为 3)- 会在第一项模拟打开文件之前休眠一段时间- 会在生成每一个模拟从文件读取数据的项之前休眠一段时间 | class ArtificialDataset(tf.data.Dataset):
def _generator(num_samples):
# Opening the file
time.sleep(0.03)
for sample_idx in range(num_samples):
# Reading data (line, record) from the file
time.sleep(0.015)
yield (sample_idx,)
def __new__(cls, num_samples=3):
return tf.data.Dataset.from_generator(
cls._generator,
output_types=tf.dtypes.int64,
output_shapes=(1,),
args=(num_samples,)
) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
此数据集类似 `tf.data.Dataset.range`,在开头和每个样本之间添加了固定延迟。 训练循环编写一个虚拟的训练循环,以测量迭代数据集所用的时间。训练时间是模拟的。 | def benchmark(dataset, num_epochs=2):
start_time = time.perf_counter()
for epoch_num in range(num_epochs):
for sample in dataset:
# Performing a training step
time.sleep(0.01)
tf.print("Execution time:", time.perf_counter() - start_time) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
优化性能为了展示如何优化性能,下面我们将优化 `ArtificialDataset` 的性能。 朴素的方法先从不使用任何技巧的朴素流水线开始,按原样迭代数据集。 | benchmark(ArtificialDataset()) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
从后台可以看到执行时间的花费情况:可以看到,执行一个训练步骤涉及以下操作:- 打开文件(如果尚未打开)- 从文件获取数据条目- 使用数据进行训练但是,在类似这里的朴素同步实现中,当流水线在获取数据时,模型会处于空闲状态。相反,当模型在进行训练时,输入流水线会处于空闲状态。因此,训练步骤的用时是打开、读取和训练时间的总和。接下来的各部分将基于此输入流水线,演示设计高效 TensorFlow 输入流水线的最佳做法。 预提取预提取会与训练步骤的预处理和模型执行重叠。在模型执行第 `s` 步训练的同时,输入流水线会读取第 `s+1` 步的数据。这样做能够最大程度减少训练的单步用时(而非总和),并减少提取数据所需的时间。`tf.data` API 提供了 `tf.data.Dataset.prefetch` 转换。它可以用来将数据的生成时间和使用时间分离。特别是,该转换会使用后台线程和内部缓冲区在请求元素之前从输入数据集中预提取这些元素。要预提取的元素数量应等于(或可能大于)单个训练步骤使用的批次数。您可以手动调整这个值,或者将其设置为 `tf.data.experimental.AUTOTUNE`,这将提示 `tf.data` 运行时在运行期间动态调整该值。注意,只要有机会将“生产者”的工作和“使用者”的工作重叠,预提取转换就能带来好处。 | benchmark(
ArtificialDataset()
.prefetch(tf.data.experimental.AUTOTUNE)
) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
这次您可以看到,在针对样本 0 运行训练步骤的同时,输入流水线正在读取样本 1 的数据,依此类推。 并行数据提取在实际设置中,输入数据可能会远程存储(例如,GCS 或 HDFS)。由于在本地存储空间和远程存储空间之间存在以下差异,在本地读取数据时运行良好的数据集流水线可能会在远程读取数据时成为 I/O 瓶颈:- **到达第一字节用时**:从远程存储空间中读取文件的第一个字节所花费的时间要比从本地存储空间中读取所花费的时间长几个数量级。- **读取吞吐量**:虽然远程存储空间通常提供较大的聚合带宽,但读取单个文件可能只能使用此带宽的一小部分。此外,将原始字节加载到内存中后,可能还需要对数据进行反序列化和/或解密(例如 [protobuf](https://developers.google.com/protocol-buffers/)),这需要进行额外计算。无论数据是本地存储还是远程存储,都会存在此开销,但如果没有高效地预提取数据,在远程情况下会更糟。为了减轻各种数据提取开销的影响,可以使用 `tf.data.Dataset.interleave` 转换来并行化数据加载步骤,从而交错其他数据集(如数据文件读取器)的内容。可以通过 `cycle_length` 参数指定想要重叠的数据集数量,并通过 `num_parallel_calls` 参数指定并行度级别。与 `prefetch` 转换类似,`interleave` 转换也支持 `tf.data.experimental.AUTOTUNE`,它将让 `tf.data` 运行时决定要使用的并行度级别。 顺序交错`tf.data.Dataset.interleave` 转换的默认参数会使其按顺序交错两个数据集中的单个样本。 | benchmark(
tf.data.Dataset.range(2)
.interleave(ArtificialDataset)
) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
该图可以展示 `interleave` 转换的行为,从两个可用的数据集中交替预提取样本。但是,这里不涉及性能改进。 并行交错现在,使用 `interleave` 转换的 `num_parallel_calls` 参数。这样可以并行加载多个数据集,从而减少等待打开文件的时间。 | benchmark(
tf.data.Dataset.range(2)
.interleave(
ArtificialDataset,
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
这次,两个数据集的读取并行进行,从而减少了全局数据处理时间。 并行数据转换准备数据时,可能需要对输入元素进行预处理。为此,`tf.data` API 提供了 `tf.data.Dataset.map` 转换,该转换会将用户定义的函数应用于输入数据集的每个元素。由于输入元素彼此独立,可以在多个 CPU 核心之间并行预处理。为了实现这一点,类似 `prefetch` 和 `interleave` 转换,`map` 转换也提供了`num_parallel_calls` 参数来指定并行度级别。`num_parallel_calls` 参数最佳值的选择取决于您的硬件、训练数据的特性(如数据大小和形状)、映射函数的开销,以及同一时间在 CPU 上进行的其他处理。一个简单的试探法是使用可用的 CPU 核心数。但是,对于 `prefetch` 和 `interleave` 转换,`map` 转换支持 `tf.data.experimental.AUTOTUNE`,它将让 `tf.data` 运行时决定要使用的并行度级别。 | def mapped_function(s):
# Do some hard pre-processing
tf.py_function(lambda: time.sleep(0.03), [], ())
return s | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
顺序映射首先使用不具有并行度的 `map` 转换作为基准示例。 | benchmark(
ArtificialDataset()
.map(mapped_function)
) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
对于[朴素方法](The-naive-approach)来说,单次迭代的用时就是花费在打开、读取、预处理(映射)和训练步骤上的时间总和。 并行映射现在,使用相同的预处理函数,但将其并行应用于多个样本。 | benchmark(
ArtificialDataset()
.map(
mapped_function,
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
现在,您可以在图上看到预处理步骤重叠,从而减少了单次迭代的总时间。 缓存`tf.data.Dataset.cache` 转换可以在内存中或本地存储空间中缓存数据集。这样可以避免一些运算(如文件打开和数据读取)在每个周期都被执行。 | benchmark(
ArtificialDataset()
.map( # Apply time consuming operations before cache
mapped_function
).cache(
),
5
) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
缓存数据集时,仅在第一个周期执行一次 `cache` 之前的转换(如文件打开和数据读取)。后续周期将重用通过 `cache` 转换缓存的数据。如果传递到 `map` 转换的用户定义函数开销很大,可在 `map` 转换后应用 `cache` 转换,只要生成的数据集仍然可以放入内存或本地存储空间即可。如果用户定义函数增加了存储数据集所需的空间(超出缓存容量),在 `cache` 转换后应用该函数,或者考虑在训练作业之前对数据进行预处理以减少资源使用。 向量化映射调用传递给 `map` 转换的用户定义函数会产生与调度和执行用户定义函数相关的开销。我们建议对用户定义函数进行向量化处理(即,让它一次运算一批输入)并在 `map` 转换*之前*应用 `batch` 转换。为了说明这种良好做法,不适合使用您的人工数据集。调度延迟大约为 10 微妙(10e-6 秒),远远小于 `ArtificialDataset` 中使用的数十毫秒,因此很难看出它的影响。在本示例中,我们使用基本 `tf.data.Dataset.range` 函数并将训练循环简化为最简形式。 | fast_dataset = tf.data.Dataset.range(10000)
def fast_benchmark(dataset, num_epochs=2):
start_time = time.perf_counter()
for _ in tf.data.Dataset.range(num_epochs):
for _ in dataset:
pass
tf.print("Execution time:", time.perf_counter() - start_time)
def increment(x):
return x+1 | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
标量映射 | fast_benchmark(
fast_dataset
# Apply function one item at a time
.map(increment)
# Batch
.batch(256)
) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
上图说明了正在发生的事情(样本较少)。您可以看到已将映射函数应用于每个样本。虽然此函数速度很快,但会产生一些开销影响时间性能。 向量化映射 | fast_benchmark(
fast_dataset
.batch(256)
# Apply function on a batch of items
# The tf.Tensor.__add__ method already handle batches
.map(increment)
) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
这次,映射函数被调用了一次,并被应用于一批样本。虽然该函数可能需要花费更多时间执行,但开销仅出现了一次,从而改善了整体时间性能。 减少内存占用许多转换(包括 `interleave`、`prefetch` 和 `shuffle`)会维护元素的内部缓冲区。如果传递给 `map` 转换的用户定义函数更改了元素大小,则映射转换和缓冲元素的转换的顺序会影响内存使用量。通常,我们建议选择能够降低内存占用的顺序,除非需要不同的顺序以提高性能。 缓存部分计算建议在 `map` 转换后缓存数据集,除非此转换会使数据过大而不适合放在内存中。如果映射函数可以分成两个部分,则能实现折衷:一个耗时的部分和一个消耗内存的部分。在这种情况下,您可以按如下方式将转换链接起来:```pythondataset.map(time_consuming_mapping).cache().map(memory_consuming_mapping)```这样,耗时部分仅在第一个周期执行,从而避免了使用过多缓存空间。 最佳做法总结以下是设计高效 TensorFlow 输入流水线的最佳做法总结:- [使用 `prefetch` 转换](Pipelining)使生产者和使用者的工作重叠。- 使用 `interleave` 转换实现[并行数据读取转换](Parallelizing-data-extraction)。- 通过设置 `num_parallel_calls` 参数实现[并行 `map` 转换](Parallelizing-data-transformation)。- 第一个周期[使用 `cache` 转换](Caching)将数据缓存在内存中。- [向量化](Map-and-batch)传递给 `map` 转换的用户定义函数- 应用 `interleave`、`prefetch` 和 `shuffle` 转换时[减少内存使用量](Reducing-memory-footprint)。 重现图表注:本笔记本的剩余部分是关于如何重现上述图表的,请随意使用以下代码,但请了解其并非本教程的主要内容。要更深入地了解 `tf.data.Dataset` API,您可以使用自己的流水线。下面是用来绘制本指南中图像的代码。这可以作为一个好的起点,展示了一些常见困难的解决方法,例如:- 执行时间的可重现性;- 映射函数的 Eager Execution;- `interleave` 转换的可调用对象。 | import itertools
from collections import defaultdict
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
数据集与 `ArtificialDataset` 类似,您可以构建一个返回每步用时的数据集。 | class TimeMeasuredDataset(tf.data.Dataset):
# OUTPUT: (steps, timings, counters)
OUTPUT_TYPES = (tf.dtypes.string, tf.dtypes.float32, tf.dtypes.int32)
OUTPUT_SHAPES = ((2, 1), (2, 2), (2, 3))
_INSTANCES_COUNTER = itertools.count() # Number of datasets generated
_EPOCHS_COUNTER = defaultdict(itertools.count) # Number of epochs done for each dataset
def _generator(instance_idx, num_samples):
epoch_idx = next(TimeMeasuredDataset._EPOCHS_COUNTER[instance_idx])
# Opening the file
open_enter = time.perf_counter()
time.sleep(0.03)
open_elapsed = time.perf_counter() - open_enter
for sample_idx in range(num_samples):
# Reading data (line, record) from the file
read_enter = time.perf_counter()
time.sleep(0.015)
read_elapsed = time.perf_counter() - read_enter
yield (
[("Open",), ("Read",)],
[(open_enter, open_elapsed), (read_enter, read_elapsed)],
[(instance_idx, epoch_idx, -1), (instance_idx, epoch_idx, sample_idx)]
)
open_enter, open_elapsed = -1., -1. # Negative values will be filtered
def __new__(cls, num_samples=3):
return tf.data.Dataset.from_generator(
cls._generator,
output_types=cls.OUTPUT_TYPES,
output_shapes=cls.OUTPUT_SHAPES,
args=(next(cls._INSTANCES_COUNTER), num_samples)
) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
此数据集会提供形状为 `[[2, 1], [2, 2], [2, 3]]` 且类型为 `[tf.dtypes.string, tf.dtypes.float32, tf.dtypes.int32]` 的样本。每个样本为:```( [("Open"), ("Read")], [(t0, d), (t0, d)], [(i, e, -1), (i, e, s)] )```其中:- `Open` 和 `Read` 是步骤标识符- `t0` 是相应步骤开始时的时间戳- `d` 是在相应步骤中花费的时间- `i` 是实例索引- `e` 是周期索引(数据集被迭代的次数)- `s` 是样本索引 迭代循环使迭代循环稍微复杂一点,以汇总所有计时。这仅适用于生成上述样本的数据集。 | def timelined_benchmark(dataset, num_epochs=2):
# Initialize accumulators
steps_acc = tf.zeros([0, 1], dtype=tf.dtypes.string)
times_acc = tf.zeros([0, 2], dtype=tf.dtypes.float32)
values_acc = tf.zeros([0, 3], dtype=tf.dtypes.int32)
start_time = time.perf_counter()
for epoch_num in range(num_epochs):
epoch_enter = time.perf_counter()
for (steps, times, values) in dataset:
# Record dataset preparation informations
steps_acc = tf.concat((steps_acc, steps), axis=0)
times_acc = tf.concat((times_acc, times), axis=0)
values_acc = tf.concat((values_acc, values), axis=0)
# Simulate training time
train_enter = time.perf_counter()
time.sleep(0.01)
train_elapsed = time.perf_counter() - train_enter
# Record training informations
steps_acc = tf.concat((steps_acc, [["Train"]]), axis=0)
times_acc = tf.concat((times_acc, [(train_enter, train_elapsed)]), axis=0)
values_acc = tf.concat((values_acc, [values[-1]]), axis=0)
epoch_elapsed = time.perf_counter() - epoch_enter
# Record epoch informations
steps_acc = tf.concat((steps_acc, [["Epoch"]]), axis=0)
times_acc = tf.concat((times_acc, [(epoch_enter, epoch_elapsed)]), axis=0)
values_acc = tf.concat((values_acc, [[-1, epoch_num, -1]]), axis=0)
time.sleep(0.001)
tf.print("Execution time:", time.perf_counter() - start_time)
return {"steps": steps_acc, "times": times_acc, "values": values_acc} | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
绘图方法最后,定义一个函数,根据 `timelined_benchmark` 函数返回的值绘制时间线。 | def draw_timeline(timeline, title, width=0.5, annotate=False, save=False):
# Remove invalid entries (negative times, or empty steps) from the timelines
invalid_mask = np.logical_and(timeline['times'] > 0, timeline['steps'] != b'')[:,0]
steps = timeline['steps'][invalid_mask].numpy()
times = timeline['times'][invalid_mask].numpy()
values = timeline['values'][invalid_mask].numpy()
# Get a set of different steps, ordered by the first time they are encountered
step_ids, indices = np.stack(np.unique(steps, return_index=True))
step_ids = step_ids[np.argsort(indices)]
# Shift the starting time to 0 and compute the maximal time value
min_time = times[:,0].min()
times[:,0] = (times[:,0] - min_time)
end = max(width, (times[:,0]+times[:,1]).max() + 0.01)
cmap = mpl.cm.get_cmap("plasma")
plt.close()
fig, axs = plt.subplots(len(step_ids), sharex=True, gridspec_kw={'hspace': 0})
fig.suptitle(title)
fig.set_size_inches(17.0, len(step_ids))
plt.xlim(-0.01, end)
for i, step in enumerate(step_ids):
step_name = step.decode()
ax = axs[i]
ax.set_ylabel(step_name)
ax.set_ylim(0, 1)
ax.set_yticks([])
ax.set_xlabel("time (s)")
ax.set_xticklabels([])
ax.grid(which="both", axis="x", color="k", linestyle=":")
# Get timings and annotation for the given step
entries_mask = np.squeeze(steps==step)
serie = np.unique(times[entries_mask], axis=0)
annotations = values[entries_mask]
ax.broken_barh(serie, (0, 1), color=cmap(i / len(step_ids)), linewidth=1, alpha=0.66)
if annotate:
for j, (start, width) in enumerate(serie):
annotation = "\n".join([f"{l}: {v}" for l,v in zip(("i", "e", "s"), annotations[j])])
ax.text(start + 0.001 + (0.001 * (j % 2)), 0.55 - (0.1 * (j % 2)), annotation,
horizontalalignment='left', verticalalignment='center')
if save:
plt.savefig(title.lower().translate(str.maketrans(" ", "_")) + ".svg") | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
对映射函数使用包装器要在 Eager 上下文中运行映射函数,必须将其包装在 `tf.py_function` 调用中。 | def map_decorator(func):
def wrapper(steps, times, values):
# Use a tf.py_function to prevent auto-graph from compiling the method
return tf.py_function(
func,
inp=(steps, times, values),
Tout=(steps.dtype, times.dtype, values.dtype)
)
return wrapper | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
流水线对比 | _batch_map_num_items = 50
def dataset_generator_fun(*args):
return TimeMeasuredDataset(num_samples=_batch_map_num_items) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
朴素流水线 | @map_decorator
def naive_map(steps, times, values):
map_enter = time.perf_counter()
time.sleep(0.001) # Time consuming step
time.sleep(0.0001) # Memory consuming step
map_elapsed = time.perf_counter() - map_enter
return (
tf.concat((steps, [["Map"]]), axis=0),
tf.concat((times, [[map_enter, map_elapsed]]), axis=0),
tf.concat((values, [values[-1]]), axis=0)
)
naive_timeline = timelined_benchmark(
tf.data.Dataset.range(2)
.flat_map(dataset_generator_fun)
.map(naive_map)
.batch(_batch_map_num_items, drop_remainder=True)
.unbatch(),
5
) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
优化后的流水线 | @map_decorator
def time_consuming_map(steps, times, values):
map_enter = time.perf_counter()
time.sleep(0.001 * values.shape[0]) # Time consuming step
map_elapsed = time.perf_counter() - map_enter
return (
tf.concat((steps, tf.tile([[["1st map"]]], [steps.shape[0], 1, 1])), axis=1),
tf.concat((times, tf.tile([[[map_enter, map_elapsed]]], [times.shape[0], 1, 1])), axis=1),
tf.concat((values, tf.tile([[values[:][-1][0]]], [values.shape[0], 1, 1])), axis=1)
)
@map_decorator
def memory_consuming_map(steps, times, values):
map_enter = time.perf_counter()
time.sleep(0.0001 * values.shape[0]) # Memory consuming step
map_elapsed = time.perf_counter() - map_enter
# Use tf.tile to handle batch dimension
return (
tf.concat((steps, tf.tile([[["2nd map"]]], [steps.shape[0], 1, 1])), axis=1),
tf.concat((times, tf.tile([[[map_enter, map_elapsed]]], [times.shape[0], 1, 1])), axis=1),
tf.concat((values, tf.tile([[values[:][-1][0]]], [values.shape[0], 1, 1])), axis=1)
)
optimized_timeline = timelined_benchmark(
tf.data.Dataset.range(2)
.interleave( # Parallelize data reading
dataset_generator_fun,
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
.batch( # Vectorize your mapped function
_batch_map_num_items,
drop_remainder=True)
.map( # Parallelize map transformation
time_consuming_map,
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
.cache() # Cache data
.map( # Reduce memory usage
memory_consuming_map,
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
.prefetch( # Overlap producer and consumer works
tf.data.experimental.AUTOTUNE
)
.unbatch(),
5
)
draw_timeline(naive_timeline, "Naive", 15)
draw_timeline(optimized_timeline, "Optimized", 15) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n |
spaCyspaCy is a free, open-source library for advanced NaturalLanguage Processing (NLP) in Python. It's designedspecifically for production use and helps you buildapplications that process and "understand" large volumesof text. **Documentation**: [spacy.io](spacy.io) Install and import | # To install
!pip install spacy -q
# imports
import spacy | [K 100% |████████████████████████████████| 17.3MB 2.0MB/s
[31mfeaturetools 0.4.1 has requirement pandas>=0.23.0, but you'll have pandas 0.22.0 which is incompatible.[0m
[31mdatascience 0.10.6 has requirement folium==0.2.1, but you'll have folium 0.8.3 which is incompatible.[0m
[31malbumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.8 which is incompatible.[0m
[?25h | MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Statistical models Download statistical modelsPredict part-of-speech tags, dependency labels, namedentities and more. See here for available models:[spacy.io/models](spacy.io/models) | !python -m spacy download en_core_web_sm | Requirement already satisfied: en_core_web_sm==2.0.0 from https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz#egg=en_core_web_sm==2.0.0 in /usr/local/lib/python3.6/dist-packages (2.0.0)
[93m Linking successful[0m
/usr/local/lib/python3.6/dist-packages/en_core_web_sm -->
/usr/local/lib/python3.6/dist-packages/spacy/data/en_core_web_sm
You can now load the model via spacy.load('en_core_web_sm')
| MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Check that your installed models are up to date | !python -m spacy validate |
[93m Installed models (spaCy v2.0.18)[0m
/usr/local/lib/python3.6/dist-packages/spacy
TYPE NAME MODEL VERSION
package en-core-web-sm en_core_web_sm [38;5;2m2.0.0[0m [38;5;2m✔[0m
link en en_core_web_sm [38;5;2m2.0.0[0m [38;5;2m✔[0m
link en_core_web_sm en_core_web_sm [38;5;2m2.0.0[0m [38;5;2m✔[0m
| MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Loading statistical models | import spacy
# Load the installed model "en_core_web_sm"
nlp = spacy.load("en_core_web_sm") | _____no_output_____ | MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Documents and tokens Processing textProcessing text with the nlp object returns a Doc objectthat holds all information about the tokens, their linguisticfeatures and their relationships Accessing token attributes | doc = nlp("This is a text")
# Token texts
[token.text for token in doc] | _____no_output_____ | MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Spans Accessing spansSpan indices are **exclusive**. So `doc[2:4]` is a span starting attoken 2, up to – but not including! – token 4. | doc = nlp("This is a text")
span = doc[2:4]
span.text | _____no_output_____ | MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Linguistic featuresAttributes return label IDs. For string labels, use theattributes with an underscore. For example, `token.pos_` . Part-of-speech tags *PREDICTED BY STATISTICAL MODEL* | doc = nlp("This is a text.")
# Coarse-grained part-of-speech tags
print([token.pos_ for token in doc])
# Fine-grained part-of-speech tags
print([token.tag_ for token in doc]) | ['DET', 'VERB', 'DET', 'NOUN', 'PUNCT']
['DT', 'VBZ', 'DT', 'NN', '.']
| MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Syntactic dependencies*PREDICTED BY STATISTICAL MODEL* | doc = nlp("This is a text.")
# Dependency labels
print([token.dep_ for token in doc])
# Syntactic head token (governor)
print([token.head.text for token in doc]) | ['nsubj', 'ROOT', 'det', 'attr', 'punct']
['is', 'is', 'text', 'is', 'is']
| MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Named entities*PREDICTED BY STATISTICAL MODEL* | doc = nlp("Larry Page founded Google")
# Text and label of named entity span
print([(ent.text, ent.label_) for ent in doc.ents]) | [('Larry Page', 'PERSON'), ('Google', 'ORG')]
| MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Syntax iterators Sentences *USUALLY NEEDS THE DEPENDENCY PARSER* | doc = nlp("This a sentence. This is another one.")
# doc.sents is a generator that yields sentence spans
print([sent.text for sent in doc.sents]) | ['This a sentence.', 'This is another one.']
| MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Base noun phrases *NEEDS THE TAGGER AND PARSER* | doc = nlp("I have a red car")
# doc.noun_chunks is a generator that yields spans
print([chunk.text for chunk in doc.noun_chunks]) | ['I', 'a red car']
| MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Label explanations | print(spacy.explain("RB"))
print(spacy.explain("GPE")) | adverb
Countries, cities, states
| MIT | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.