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 |
|---|---|---|---|---|---|
视频 在每个步骤渲染环境有助于可视化代理的性能。在此之前,我们先创建一个函数,在该 Colab 中嵌入视频。 | def embed_mp4(filename):
"""Embeds an mp4 file in the notebook."""
video = open(filename,'rb').read()
b64 = base64.b64encode(video)
tag = '''
<video width="640" height="480" controls>
<source src="data:video/mp4;base64,{0}" type="video/mp4">
Your browser does not support the video tag.
</video>'''.for... | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
以下代码用于为代理可视化几个片段的策略: | num_episodes = 3
video_filename = 'imageio.mp4'
with imageio.get_writer(video_filename, fps=60) as video:
for _ in range(num_episodes):
time_step = eval_env.reset()
video.append_data(eval_py_env.render())
while not time_step.is_last():
action_step = tf_agent.policy.action(time_step)
time_step ... | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
LogisticRegression with MinMaxScaler & PolynomialTransformer **This Code template is for the Classification task using LogisticRegression with MinMaxScaler feature scaling technique and PolynomialTransformer as Feature Transformation Technique in a pipeline.** Required Packages | !pip install imblearn
import warnings as wr
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler,PolynomialFeatures
from sklearn.model_selec... | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
InitializationFilepath of CSV file | #filepath
file_path= "" | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
List of features which are required for model training . | #x_values
features=[''] | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Target feature for prediction. | #y_value
target='' | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Data FetchingPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. | df=pd.read_csv(file_path) #reading file
df.head()#displaying initial entries
print('Number of rows are :',df.shape[0], ',and number of columns are :',df.shape[1])
df.columns.tolist()
| _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Data PreprocessingSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the da... | def NullClearner(df):
if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])):
df.fillna(df.mean(),inplace=True)
return df
elif(isinstance(df, pd.Series)):
df.fillna(df.mode()[0],inplace=True)
return df
else:return df
def EncodeX(df):
return pd.get_dummies(df)... | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Correlation MapIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. | plt.figure(figsize = (20, 12))
corr = df.corr()
mask = np.triu(np.ones_like(corr, dtype = bool))
sns.heatmap(corr, mask = mask, linewidths = 1, annot = True, fmt = ".2f")
plt.show() | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Feature SelectionsIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.We will assign all the required input features to... | #spliting data into X(features) and Y(Target)
X=df[features]
Y=df[target]
x=X.columns.to_list()
for i in x:
X[i]=NullClearner(X[i])
X=EncodeX(X)
Y=EncodeY(NullClearner(Y))
X.head() | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Distribution Of Target Variable | plt.figure(figsize = (10,6))
sns.countplot(Y,palette='pastel') | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Data SplittingThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of th... | #we can choose randomstate and test_size as over requerment
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 123) #performing datasplitting | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Handling Target ImbalanceThe challenge of working with imbalanced datasets is that most machine learning techniques will ignore, and in turn have poor performance on, the minority class, although typically it is performance on the minority class that is most important.One approach to addressing imbalanced datasets is ... | X_train,y_train = RandomOverSampler(random_state=123).fit_resample(X_train, y_train) | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Feature Transformation**Polynomial Features**Generate polynomial and interaction features.Generate a new feature matrix consisting of all polynomial combinations of the features with degree less than or equal to the specified degree. For example, if an input sample is two dimensional and of the form [a, b], the degree... | # Build Model here
model=make_pipeline(MinMaxScaler(),PolynomialFeatures(),LogisticRegression(random_state=42))
model.fit(X_train,y_train) | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Model Accuracyscore() method return the mean accuracy on the given test data and labels.In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. | print("Accuracy score {:.2f} %\n".format(model.score(X_test,y_test)*100))
#prediction on testing set
prediction=model.predict(X_test) | _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Confusion MatrixA confusion matrix is utilized to understand the performance of the classification model or algorithm in machine learning for a given test set where results are known. |
cf_matrix=confusion_matrix(y_test,prediction)
plt.figure(figsize=(7,6))
sns.heatmap(cf_matrix,annot=True,fmt="d")
| _____no_output_____ | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Classification ReportA Classification report is used to measure the quality of predictions from a classification algorithm. How many predictions are True, how many are False.* **where**: - Precision:- Accuracy of positive predictions. - Recall:- Fraction of positives that were correctly identified. - f1-score... | print(classification_report(y_test,model.predict(X_test))) | precision recall f1-score support
0 0.83 0.83 0.83 96
1 0.72 0.72 0.72 58
accuracy 0.79 154
macro avg 0.78 0.78 0.78 154
weighted avg 0.79 0.79 0.79 ... | Apache-2.0 | Classification/Linear Models/LogisticRegression_MinMaxScaler_PolynomialFeatures.ipynb | mohityogesh44/ds-seed |
Description This file takes the raw xarray files (which can be found at https://figshare.com/collections/Large_ensemble_pCO2_testbed/4568555), applies feature transformations, and saves it into a pandas dataframe. Inputs | # =========================================
# For accessing directories
# =========================================
root_dir = "/local/data/artemis/workspace/jfs2167/recon_eval" # Set this to the path of the project
ensemble_dir_head = "/local/data/artemis/simulations/LET" # Set this to where you have placed the raw da... | _____no_output_____ | FTL | notebooks/01_create_datasets.ipynb | charlesm93/ML_for_ocean_pCO2_interpolation |
Modules | # standard imports
import os
import datetime
from pathlib import Path
from collections import defaultdict
import scipy
import random
import numpy as np
import xarray as xr
import pandas as pd
import joblib
import pickle
# machine learning libraries
from sklearn.model_selection import train_test_split
# Python file wi... | Using TensorFlow backend.
| FTL | notebooks/01_create_datasets.ipynb | charlesm93/ML_for_ocean_pCO2_interpolation |
Predefined values | # Loading references
path_LET = f"{reference_output_dir}/members_LET_dict.pickle"
path_seeds = f"{reference_output_dir}/random_seeds.npy"
path_loc = f"{reference_output_dir}/members_seed_loc_dict.pickle"
with open(path_LET,'rb') as handle:
mems_dict = pickle.load(handle)
random_seeds = np.load(path_seeds)
... | _____no_output_____ | FTL | notebooks/01_create_datasets.ipynb | charlesm93/ML_for_ocean_pCO2_interpolation |
Loop to load in data, clean it, and save it | # ensemble_list = ['CanESM2', 'CESM', 'GFDL', 'MPI']
ensemble_list = []
for ens, mem_list in mems_dict.items():
for member in mem_list:
# This function loads in the data, cleans it, and creates a pandas data frame
df = pre.create_inputs(ensemble_dir_head, ens, member, dates, xco2_path=xco2_path)
... | _____no_output_____ | FTL | notebooks/01_create_datasets.ipynb | charlesm93/ML_for_ocean_pCO2_interpolation |
Capítulo 07 : Coleções em Python Capítulo 07b | #1.
#a.
A = [1, 0, 5, -2, -5, 7] #Lista A
print(type(A))
print(A)
#b.
soma = A[0] + A[1] + A[5] #Somando os índices 0, 1 e 5
print(f'A soma dos índices 0, 1 e 5 é {soma}.')
#c.
A[4] = 100 #Modificando valor do índice 4
print(A)
#d.
print(A[0])
print(A[1])
print(A[2])
print(A[3])
print(A[4])
print(A[5])
#2.
valor... | 12
14
16
18
19
13
15
17
19
23
[12, 14, 16, 18, 19, 13, 15, 17, 19, 23]
16.6
98.39999999999999
O desvio padrão do vetor v é 3.306559138036598.
| MIT | Geek Univesity/Cap07.ipynb | otaviosanluz/learning-Python |
Capítulo 07a | #Exemplo.
galera = list()
dados = list()
for c in range(3):
dados.append(str(input('Nome: ')))
dados.append(int(input('Idade: ')))
galera.append(dados[:])
dados.clear()
print(galera)
#Crie um programa que cria uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado. No final, mostre a matr... | Matriz 1 posição [1,1]:1
Matriz 2 posição [1,1]:2
Matriz 1 posição [1,2]:3
Matriz 2 posição [1,2]:4
Matriz 1 posição [2,1]:5
Matriz 2 posição [2,1]:6
Matriz 1 posição [2,2]:7
Matriz 2 posição [2,2]:8
-=-=-=-=-=-=-=-=-=-=
Matriz 1
[[1.0, 3.0], [5.0, 7.0]]
-=-=-=-=-=-=-=-=-=-=
Matriz 2
[[2.0, 4.0], [6.0, 8.0]]
-=-=-=-=-=... | MIT | Geek Univesity/Cap07.ipynb | otaviosanluz/learning-Python |
Creating a more elegant bounding box | import cv2
import numpy as np
from google.colab.patches import cv2_imshow
def draw_bbox(img, coord1, coord2, color1=(6, 253, 2), color2=(4,230,1), r=5, d=5, thickness=1):
x1, y1 = coord1
x2, y2 = coord2
if color2 is not None:
# Top left
cv2.line(img, (x1 + r, y1), (x1 + r + d, y1), color2,... | _____no_output_____ | MIT | BoundingBoxBeautiful.ipynb | escudero/BoundingBoxBeautiful |
Chapter 4: Trees and Graphs | # Adjancency list graph
class Graph():
def __init__(self):
self.nodes = []
def add(node):
self.nodes.append(node)
class Node():
def __init__(self, name, adjacent=[],marked=False):
self.name = name
self.adjacent = adjacent
self.marked = marked | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.1 Route Between NodesGiven a directed graph, design an algorithm to find out whether there is a route between two nodes. | # Bidirectional breadth-first search.
def route(node1, node2):
# Create the queue
queue1 = []
queue2 = []
node1.marked = True
node2.marked = True
queue1.append(node1)
queue2.append(node2)
while (len(queue1) > 0) and (len(queue2) > 0):
n1 = queue1.pop(0)
n2 = queue2.p... | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.2 Minimal TreeGiven a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height. | class Node():
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def minimal(array):
start = 0
end = len(array) - 1
if end < start:
return None
mid = int((start + end) / 2)
# Recursively place the nodes
retur... | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.3 List of DepthsGiven a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists). | class LinkedList():
def __init__(self, data):
self.data = data
self.next = None
def insert(node):
self.next = node
def list_of_depths(root, full_list, level):
if root is None:
return
lnkedlst = LinkedList(None)
if len(full_list) == level:
lnkedlst = LinkedLis... | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.4 Check BalancedImplement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one. | def check_height(root):
# Define an error code to return if a sub-tree is not balanced
min_int = -sys.maxsize - 1
# The height of the null tree is -1
if root is None:
return -1
# Check the height of the left sub-tree. If it's min-int, it is unbalanced
left_height = check_height(root.left... | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.5 Validate BSTImplement a function to check if a binary tree is a binary search tree. | # A binary tree is a binary search tree if the left child is lower than the parent node which is lower than the right node (pre-order traversal)
def validate_bst(root):
to_visit = [root]
while len(to_visit) > 0:
node = to_visit.pop(0)
if node.left.data is not None:
if node.data <= no... | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.6 SuccessorWrite an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent. | def successor(node):
if node is None:
return None
# If the node has a right sub-tree, return the leftmost node in that sub-tree
if node.right is not None:
return leftmost(node.right)
else:
q = node
# Find node's parent
x = q.parent # Not implemented in my Node cla... | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.7 Build OrderYou are given a list of projects and a list of dependencies (which is a list of pairs of projects, where the second project is dependent on the first project). All of a project'sdependencies must be built before the project is. Find a build order that will allow the projects to be built. If there is no ... | # Topological sort using DFS
# Store the possible states of nodes
class State():
BLANK = 0
PARTIAL = 1
COMPLETED = 2
# Create a class to store each vertex
class Vertex():
# Store the vertex's data, state and adjacent vertices
def __init__(self, key):
self.id = key
self.adj = set()
... | ['f', 'e', 'b', 'a', 'd', 'c']
| Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.8 First Common AncestorDesign an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree. | def common_ancestor(root, node1, node2):
# Check if both nodes are in the tree
if (not covers(root, node1)) or (not covers(root, node2)):
return None
return ancestor_helper(root, node1, node2)
def ancestor_helper(root, node1, node2):
if root is None or root == node1 or root == node2:
re... | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.9 BST SequencesA binary search tree was created by traversing through an array from left to right and inserting each element. Given a binary search tree with distinct elements, print all possible arrays that could have led to this tree. | def bst_sequences(root):
result = []
if root is None:
result.append([])
return result
prefix = []
prefix.append(root.data)
# Recurse on the left and right sub-trees
left_seq = bst_sequences(root.left)
right_seq = bst_sequences(root.right)
# Weave together the lists
fo... | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.10 Check SubtreeT1 and T2 are two very large binary trees, with T1 much bigger than T2. Create an algorithm to determine if T2 is a subtree of T1.A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2.That is, if you cut off the tree at node n, the two trees would b... | # The following approach converts the trees to strings based on pre-order traversal (node -> left -> right). If one string is a sub-string of the other, it is a sub-tree
def contains_tree(node1, node2):
string1 = ""
string2 = ""
get_order(node1, string1)
get_order(node2, string2)
return string2 in s... | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.11 Random NodeYou are implementing a binary tree class from scratch which, in addition to insert, find, and delete, has a method getRandomNode() which returns a random node from the tree. All nodes should be equally likely to be chosen. Design and implement an algorithm for getRandomNode, and explain how you would i... | import random
# Create a tree class that stores the size of the tree
class Tree():
def __init__(self, root=None):
self.root = root
self.size = 0 if self.root is None else self.root.size()
def get_random():
if root is None:
return None
# The index is a random ... | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
4.12 Paths with SumYou are given a binary tree in which each node contains an integer value (which might be positive or negative). Design an algorithm to count the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from pare... | def count_sum_paths(node, target_sum, running_sum, path_count):
if node is None:
return 0
running_sum += node.data
cur_sum = running_sum - target_sum
if cur_sum in path_count:
total_paths = path_count[cur_sum]
else:
total_paths = 0
if running_sum == target_sum:
to... | _____no_output_____ | Apache-2.0 | chapter4.ipynb | hangulu/ctci |
An Introduction to the Amazon SageMaker IP Insights Algorithm Unsupervised anomaly detection for susicipous IP addresses-------1. [Introduction](Introduction)2. [Setup](Setup)3. [Training](Training)4. [Inference](Inference)5. [Epilogue](Epilogue) Introduction-------The Amazon SageMaker IP Insights algorithm uses stati... | !python --version
bucket = sagemaker.Session().default_bucket()
prefix = "sagemaker/ipinsights-tutorial-bwx"
execution_role = sagemaker.get_execution_role()
region = boto3.Session().region_name
boto3.Session().client("s3").head_bucket(Bucket=bucket)
s3://{bucket}/{prefix}")
import boto3
import botocore
import os
impor... | Training input/output will be stored in: s3://sagemaker-us-east-1-017681292549/sagemaker/ipinsights-tutorial-bwx
| MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Next we download the modules necessary for synthetic data generation they do not exist. | from os import path
tools_bucket = f"jumpstart-cache-prod-{region}" # Bucket containing the data generation module.
tools_prefix = "1p-algorithms-assets/ip-insights" # Prefix for the data generation module
s3 = boto3.client("s3")
data_generation_file = "generate_data.py" # Synthetic data generation module
script_p... | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
DatasetApache Web Server ("httpd") is the most popular web server used on the internet. And luckily for us, it logs all requests processed by the server - by default. If a web page requires HTTP authentication, the Apache Web Server will log the IP address and authenticated user name for each requested resource. The [... | from generate_data import generate_dataset
# We simulate traffic for 10,000 users. This should yield about 3 million log lines (~700 MB).
NUM_USERS = 10000
log_file = "ipinsights_web_traffic.log"
generate_dataset(NUM_USERS, log_file)
# Visualize a few log lines
!head $log_file | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Prepare the datasetNow that we have our logs, we need to transform them into a format that IP Insights can use. As we mentioned above, we need to:1. Choose the resource which we want to analyze users' history for2. Extract our users' usage history of IP addresses3. In addition, we want to separate our dataset into a t... | log_file = "ipinsights_web_traffic.log"
import pandas as pd
df = pd.read_csv(
log_file,
sep=" ",
na_values="-",
header=None,
names=[
"ip_address",
"rcf_id",
"user",
"timestamp",
"time_zone",
"request",
"status",
"size",
"refer... | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
We convert the log timestamp strings into Python datetimes so that we can sort and compare the data more easily. | # Convert time stamps to DateTime objects
df["timestamp"] = pd.to_datetime(df["timestamp"], format="[%d/%b/%Y:%H:%M:%S")
df.head() | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
We also verify the time zones of all of the time stamps. If the log contains more than one time zone, we would need to standardize the timestamps. | # Check if they are all in the same timezone
num_time_zones = len(df["time_zone"].unique())
num_time_zones | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
As we see above, there is only one value in the entire `time_zone` column. Therefore, all of the timestamps are in the same time zone, and we do not need to standardize them. We can skip the next cell and go to [1. Selecting a Resource](1.-Select-Resource).If there is more than one time_zone in your dataset, then we pa... | from datetime import datetime
# from datetime import datetime
import pytz
def apply_timezone(row):
tz = row[1]
tz_offset = int(tz[:3]) * 60 # Hour offset
tz_offset += int(tz[3:5]) # Minutes offset
return row[0].replace(tzinfo=pytz.FixedOffset(tz_offset))
if num_time_zones > 1:
df["timestamp"] ... | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
1. Select ResourceOur goal is to train an IP Insights algorithm to analyze the history of user logins such that we can predict how suspicious a login event is. In our simulated web server, the server logs a `GET` request to the `/login_success` page everytime a user successfully logs in. We filter our Apache logs for ... | df.head()
df = df[(df["request"].str.startswith("GET /login_success")) & (df["status"] == 200)] | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
2. Extract Users and IP addressNow that our DataFrame only includes log events for the resource we want to analyze, we extract the relevant fields to construct a IP Insights dataset.IP Insights takes in a headerless CSV file with two columns: an entity (username) ID string and the IPv4 address in decimal-dot notation.... | df = df[["user", "ip_address", "timestamp"]] | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
3. Create training and test datasetAs part of training a model, we want to evaluate how it generalizes to data it has never seen before.Typically, you create a test set by reserving a random percentage of your dataset and evaluating the model after training. However, for machine learning models that make future predic... | df["timestamp"].describe() | /usr/local/lib/python3.6/site-packages/ipykernel_launcher.py:1: FutureWarning: Treating datetime data as categorical rather than numeric in `.describe` is deprecated and will be removed in a future version of pandas. Specify `datetime_is_numeric=True` to silence this warning and adopt the future behavior now.
"""Entr... | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
We have login events for 10 days. Let's take the first week (7 days) of data as training and then use the last 3 days for the test set. | time_partition = (
datetime(2018, 11, 11, tzinfo=pytz.FixedOffset(0))
if num_time_zones > 1
else datetime(2018, 11, 11)
)
train_df = df[df["timestamp"] <= time_partition]
test_df = df[df["timestamp"] > time_partition] | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Now that we have our training dataset, we shuffle it. Shuffling improves the model's performance since SageMaker IP Insights uses stochastic gradient descent. This ensures that login events for the same user are less likely to occur in the same mini batch. This allows the model to improve its performance in between pre... | # Shuffle train data
train_df = train_df.sample(frac=1)
train_df.head()
# check the shape of training and testing
print(train_df.shape, test_df.shape) | (2107898, 3) (904736, 3)
| MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Store Data on S3 Now that we have simulated (or scraped) our datasets, we have to prepare and upload it to S3.We will be doing local inference, therefore we don't need to upload our test dataset. | # Output dataset as headerless CSV
train_data = train_df.to_csv(index=False, header=False, columns=["user", "ip_address"])
re
train_data_file = "train.csv"
key = os.path.join(prefix, "train", train_data_file)
s3_train_data = f"s3://{bucket}/{key}"
print(f"Uploading data to: {s3_train_data}")
boto3.resource("s3").Bucke... | Uploading data to: s3://sagemaker-us-east-1-017681292549/sagemaker/ipinsights-tutorial-bwx/train/train.csv
| MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Training---Once the data is preprocessed and available in the necessary format, the next step is to train our model on the data. There are number of parameters required by the SageMaker IP Insights algorithm to configure the model and define the computational environment in which training will take place. The first of... | from sagemaker.amazon.amazon_estimator import get_image_uri
image = get_image_uri(boto3.Session().region_name, "ipinsights") | The method get_image_uri has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1.
| MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Then, we need to determine the training cluster to use. The IP Insights algorithm supports both CPU and GPU training. We recommend using GPU machines as they will train faster. However, when the size of your dataset increases, it can become more economical to use multiple CPU machines running with distributed training.... | # Set up the estimator with training job configuration
ip_insights = sagemaker.estimator.Estimator(
image,
execution_role,
instance_count=1,
#instance_type="ml.p3.2xlarge",
instance_type = 'ml.m5.xlarge',
output_path=f"s3://{bucket}/{prefix}/output",
sagemaker_session=sagemaker.Session(),
)
... | 2021-12-30 01:57:12 Starting - Starting the training job...
2021-12-30 01:57:36 Starting - Launching requested ML instancesProfilerReport-1640829432: InProgress
......
2021-12-30 01:58:36 Starting - Preparing the instances for training......
2021-12-30 01:59:38 Downloading - Downloading input data...
2021-12-30 01:59:5... | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
If you see the message > Completed - Training job completedat the bottom of the output logs then that means training successfully completed and the output of the SageMaker IP Insights model was stored in the specified output path. You can also view information about and the status of a training job using the AWS Sag... | print(f"Training job name: {ip_insights.latest_training_job.job_name}") | Training job name: ipinsights-2021-12-30-01-57-12-007
| MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Inference-----Now that we have trained a SageMaker IP Insights model, we can deploy the model to an endpoint to start performing inference on data. In this case, that means providing it a `` pair and predicting their compatability scores.We can create an inference endpoint using the SageMaker Python SDK `deploy()`func... | # predictor = ip_insights.deploy(initial_instance_count=1, instance_type="ml.m5.xlarge")
predictor = ip_insights.deploy(initial_instance_count=1, instance_type="ml.m5.xlarge")
| -------! | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Congratulations, you now have a SageMaker IP Insights inference endpoint! You could start integrating this endpoint with your production services to start querying incoming requests for abnormal behavior. You can confirm the endpoint configuration and status by navigating to the "Endpoints" tab in the AWS SageMaker con... | print(f"Endpoint name: {predictor.endpoint}") | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Data Serialization/DeserializationWe can pass data in a variety of formats to our inference endpoint. In this example, we will pass CSV-formmated data. Other available formats are JSON-formated and JSON Lines-formatted. We make use of the SageMaker Python SDK utilities: `csv_serializer` and `json_deserializer` when co... | from sagemaker.predictor import csv_serializer, json_deserializer
predictor.serializer = csv_serializer
predictor.deserializer = json_deserializer | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Now that the predictor is configured, it is as easy as passing in a matrix of inference data.We can take a few samples from the simulated dataset above, so we can see what the output looks like. | inference_data = [(data[0], data[1]) for data in train_df[:5].values]
predictor.predict(
inference_data, initial_args={"ContentType": "text/csv", "Accept": "application/json"}
) | The csv_serializer has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
The json_deserializer has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
| MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
By default, the predictor will only output the `dot_product` between the learned IP address and the online resource (in this case, the user ID). The dot product summarizes the compatibility between the IP address and online resource. The larger the value, the more the algorithm thinks the IP address is likely to be use... | predictor.predict(
inference_data,
initial_args={"ContentType": "text/csv", "Accept": "application/json; verbose=True"},
) | The csv_serializer has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
The json_deserializer has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
| MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Compute Anomaly Scores----The `dot_product` output of the model provides a good measure of how compatible an IP address and online resource are. However, the range of the dot_product is unbounded. This means to be able to consider an event as anomolous we need to define a threshold. Such that when we score an event, i... | test_df.head() | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
2. Inject Malicious TrafficIf we had a dataset with enough real malicious activity, we would use that to determine a good threshold. Those are hard to come by. So instead, we simulate malicious web traffic that mimics a realistic attack scenario. We take a set of user accounts from the test set and randomly generate I... | import numpy as np
from generate_data import draw_ip
def score_ip_insights(predictor, df):
def get_score(result):
"""Return the negative to the dot product of the predictions from the model."""
return [-prediction["dot_product"] for prediction in result["predictions"]]
df = df[["user", "ip_ad... | The csv_serializer has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
The json_deserializer has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
| MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
3. Plot DistributionNow, we plot the distribution of scores. Looking at this distribution will inform us on where we can set a good threshold, based on our risk tolerance. | %matplotlib inline
import matplotlib.pyplot as plt
n, x = np.histogram(test_case_scores[:NUM_SAMPLES], bins=100, density=True)
plt.plot(x[1:], n)
n, x = np.histogram(test_case_scores[NUM_SAMPLES:], bins=100, density=True)
plt.plot(x[1:], n)
plt.legend(["Normal", "Random IP"])
plt.xlabel("IP Insights Score")
plt.ylab... | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
4. Selecting a Good ThresholdAs we see in the figure above, there is a clear separation between normal traffic and random traffic. We could select a threshold depending on the application.- If we were working with low impact decisions, such as whether to ask for another factor or authentication during login, we could ... | threshold = 0.0
flagged_cases = test_case[np.array(test_case_scores) > threshold]
num_flagged_cases = len(flagged_cases)
num_true_positives = len(flagged_cases[flagged_cases["label"] == 1])
num_false_positives = len(flagged_cases[flagged_cases["label"] == 0])
num_all_positives = len(test_case.loc[test_case["label"] =... | When threshold is set to: 0.0
Total of 102539 flagged cases
Total of 98149 flagged cases are true positives
True Positive Rate: 0.9571870215235179
Recall: 0.98149
Precision: 0.9571870215235179
| MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Epilogue----In this notebook, we have showed how to configure the basic training, deployment, and usage of the Amazon SageMaker IP Insights algorithm. All SageMaker algorithms come with support for two additional services that make optimizing and using the algorithm that much easier: Automatic Model Tuning and Batch T... | test_df["timestamp"].describe() | /usr/local/lib/python3.6/site-packages/ipykernel_launcher.py:1: FutureWarning: Treating datetime data as categorical rather than numeric in `.describe` is deprecated and will be removed in a future version of pandas. Specify `datetime_is_numeric=True` to silence this warning and adopt the future behavior now.
"""Entr... | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
The test set we constructed above spans 3 days. We reserve the first day as the validation set and the subsequent two days for the test set. | time_partition = (
datetime(2018, 11, 13, tzinfo=pytz.FixedOffset(0))
if num_time_zones > 1
else datetime(2018, 11, 13)
)
validation_df = test_df[test_df["timestamp"] < time_partition]
test_df = test_df[test_df["timestamp"] >= time_partition]
valid_data = validation_df.to_csv(index=False, header=False, co... | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
We then upload the validation data to S3 and specify it as the validation channel. | # Upload data to S3 key
validation_data_file = "valid.csv"
key = os.path.join(prefix, "validation", validation_data_file)
boto3.resource("s3").Bucket(bucket).Object(key).put(Body=valid_data)
s3_valid_data = f"s3://{bucket}/{key}"
print(f"Validation data has been uploaded to: {s3_valid_data}")
# Configure SageMaker IP... | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
We should have the best performing model from the training job! Now we can determine thresholds and make predictions just like we did with the inference endpoint [above](Inference). Batch TransformLet's say we want to score all of the login events at the end of the day and aggregate flagged cases for investigators to ... | transformer = ip_insights.transformer(instance_count=1, instance_type="ml.m4.xlarge")
transformer.transform(s3_valid_data, content_type="text/csv", split_type="Line")
# Wait for Transform Job to finish
transformer.wait()
print(f"Batch Transform output is at: {transformer.output_path}") | _____no_output_____ | MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
Stop and Delete the EndpointIf you are done with this model, then we should delete the endpoint before we close the notebook. Or else you will continue to pay for the endpoint while it is running. To do so execute the cell below. Alternately, you can navigate to the "Endpoints" tab in the SageMaker console, select the... | ip_insights_tuner.delete_endpoint()
sagemaker.Session().delete_endpoint(predictor.endpoint) | The function delete_endpoint is a no-op in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
The endpoint attribute has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
| MIT | ipinsights-tutorial.ipynb | avoca-dorable/aws_ipinsights |
GLUE sets: model will be trained on eval set, so you shouldn't also test on the eval set. The problem is that the labels are withheld for the test set. Start with SNLI. MultiNLI is a later option too. As is rotten_tomatoes. * Victim model performance on dataset train, valid, test set. (done, written code to measure it)... | %load_ext autoreload
%autoreload 2
import os
import torch
from torch.utils.data import DataLoader
from datasets import load_dataset, load_metric
import datasets, transformers
from transformers import pipeline, AutoModelForSeq2SeqLM, AutoModelForSequenceClassification, AutoTokenizer
from pprint import pprint
import num... | _____no_output_____ | Apache-2.0 | archive/sentiment_paraphraser.ipynb | puzzler10/travis_attack |
Permutation method to detect label flips Take each example $Ex$ in the filtered set and generate paraphrases (e.g. 16) of it (or it might work better with a simple token-replacement strategy). Run each through the victim model (might be better with a different model, but still trained on dataset) and record prediction... | # Read in manually labelled data. This is to track results.
fname = path_cache + 'results_df_48_20210514_labelled_subset.csv'
dset_advlbl = load_dataset('csv', data_files=fname)['train'].train_test_split(test_size=0.25)
train_advlbl,test_advlbl = dset_advlbl['train'],dset_advlbl['test']
# # as pandas df
# df_advlbl =... | Using custom data configuration default-ebc62bd8d2fb84e0
Reusing dataset csv (/data/tproth/.cache/huggingface/datasets/csv/default-ebc62bd8d2fb84e0/0.0.0/2dc6629a9ff6b5697d82c25b73731dd440507a69cbce8b425db50b751e8fcfd0)
| Apache-2.0 | archive/sentiment_paraphraser.ipynb | puzzler10/travis_attack |
Paraphrases of paraphrases nlp dataset -> gen_paraphrases (returns dataset) -> create_paraphrase_dataset -> get vm labels -> save in data frame | n = 48
cols_to_drop = ['is_adversarial','label_true','label_vm_orig','orig','sim_score']
def paraphrase_and_return_dict(x, n_seed_seqs=16):
x['perms'] = get_paraphrases(x['para'], num_return_sequences=n, num_beams=n,
num_beam_groups=8, diversity_penalty=100000.0)
return x
trai... | _____no_output_____ | Apache-2.0 | archive/sentiment_paraphraser.ipynb | puzzler10/travis_attack |
Basic Linear Algebra- **Pythonic Code**로 짜보기> https://github.com/TEAMLAB-Lecture/AI-python-connect/tree/master/lab_assignments/lab_1 Problem 1 - vector_size_check | # 정답 코드
def vector_size_check(*vector_variables): # input값의 개수가 그때그때 다를 수 있게 asterisk 사용 => input값을 tuple로 묶음
return all(len(vector_variables[0]) == x # all([True,True]) : True, all([True,False]) : False
for x in [len(vector) for vector in vector_variables[1:]])
# 실행결과
print(vector_size_check([1,2... | True
True
False
| MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Problem 2 - vector_addition | # 정답 코드
def vector_addition(*vector_variables):
if vector_size_check(*vector_variables) == False:
raise ArithmeticError
return [sum(elements) for elements in zip(*vector_variables)]
# 실행결과
print(vector_addition([1,3], [2,4], [6,7]))
print(vector_addition([1,5], [10,4], [4,7]))
print(vector_addition([1,3... | [9, 14]
[15, 16]
| MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Problem 3 - vector_subtraction | # 내가 짠 코드
def vector_subtraction(*vector_variables):
if vector_size_check(*vector_variables) == False:
raise ArithmeticError
return [elements[0] - sum(elements[1:]) for elements in zip(*vector_variables)]
# 정답 코드
def vector_subtraction(*vector_variables):
if vector_size_check(*vector_variables) == F... | [-1, -1]
[-13, -6]
| MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Problem 4 - scalar_vector_product | # 내가 짠 코드
def scalar_vector_product(alpha, vector_variable):
return [alpha*vec for vec in vector_variable]
# 실행결과
print(scalar_vector_product(5, [1,2,3]))
print(scalar_vector_product(3, [2,2]))
print(scalar_vector_product(4, [1])) | [5, 10, 15]
[6, 6]
[4]
| MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Problem 5 - matrix_size_check | # 내가 짠 코드
def matrix_size_check(*matrix_variables):
return (all(len(matrix_variables[0]) == xdim
for xdim in [len(x) for x in matrix_variables]) and
all(len(matrix_variables[0][0]) == ydim
for ydim in set([len(y) for matrix in matrix_variables for y in matrix])))
# 정답 코... | False
True
True
| MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Problem 6 - is_matrix_equal | # 내가 짠 코드
# 각 원소별로 같은 list에 넣은 다음 set을 취해 중복제거 => length=1
# 이 과정을 모든 matrix의 위치에서 반복해서 전체 length list를 만들고 set을 취해 중복제거한 length가 1이면 같은 matrix
def is_matrix_equal(*matrix_variables):
return len(set([len(set(elements)) for row in zip(*matrix_variables) for elements in zip(*row)])) == 1
# 정답 코드
def is_matrix_equal(*... | False
True
| MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Problem 7 - matrix_addition | # 내가 짠 코드
def matrix_addition(*matrix_variables):
if matrix_size_check(*matrix_variables) == False:
raise ArithmeticError
return [ [sum(element) for element in zip(*row)]
for row in zip(*matrix_variables)]
# 실행결과
matrix_x = [[2, 2], [2, 2]]
matrix_y = [[2, 5], [2, 1]]
matrix_z = [[2, 4], [5,... | [[4, 7], [4, 3]]
[[6, 11], [9, 6]]
| MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Problem 8 - matrix_subtraction | # 내가 짠 코드
def matrix_subtraction(*matrix_variables):
if matrix_size_check(*matrix_variables) == False:
raise ArithmeticError
return [ [element[0] - sum(element[1:]) for element in zip(*row)]
for row in zip(*matrix_variables)]
# 정답 코드
def matrix_subtraction(*matrix_variables):
if matrix_s... | [[0, -3], [0, 1]]
[[-2, -7], [-5, -2]]
| MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Problem 9 - matrix_transpose | # 내가 짠 코드
def matrix_transpose(matrix_variable):
return [[*new_row] for new_row in zip(*matrix_variable)]
# 정답 코드
def matrix_transpose(matrix_variable):
return [ [element for element in row] for row in zip(*matrix_variable)]
# 실행결과
matrix_w = [[2, 5], [1, 1], [2, 2]]
matrix_transpose(matrix_w) | _____no_output_____ | MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Problem 10 - scalar_matrix_product | # 내가 짠 코드
def scalar_matrix_product(alpha, matrix_variable):
return [ [alpha*element for element in row] for row in matrix_variable]
# 정답 코드
def scalar_matrix_product(alpha, matrix_variable):
return [ scalar_vector_product(alpha, row) for row in matrix_variable]
# 실행결과
matrix_x = [[2, 2], [2, 2], [2, 2]]
matrix... | [[6, 6], [6, 6], [6, 6]]
[[4, 10], [4, 2]]
[[8, 16], [20, 12]]
[[6, 15], [3, 3], [6, 6]]
| MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Problem 11 - is_product_availability_matrix | # 내가 짠 코드
def is_product_availability_matrix(matrix_a, matrix_b):
return len(matrix_a[0]) == len(matrix_b)
# 정답 코드
def is_product_availability_matrix(matrix_a, matrix_b):
return len([column_vector for column_vector in zip(*matrix_a)]) == len(matrix_b)
# 실행결과
matrix_x= [[2, 5], [1, 1]]
matrix_y = [[1, 1, 2], [2,... | True
True
False
True
| MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Problem 12 - matrix_product | # 내가 짠 코드
def matrix_product(matrix_a, matrix_b):
if is_product_availability_matrix(matrix_a, matrix_b) == False:
raise ArithmeticError
return [ [ sum( [element[0] * element[1] for element in zip(column, row)] ) for column in zip(*matrix_b) ]
for row in matrix_a]
# 정답 코드
def matrix_product(m... | [[9, 13], [10, 14]]
[[8, 14], [13, 28], [5, 8]]
[[9, 15], [3, 6]]
| MIT | Python/ML_basic/1.Pythonic Code/1-3.Basic Linear Algebra.ipynb | statKim/TIL |
Copyright 2018 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... | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Transfer learning with TensorFlow Hub View on TensorFlow.org Run in Google Colab View on GitHub Download notebook See TF Hub model [TensorFlow Hub](https://tfhub.dev/) is a repository of pre-trained TensorFlow models.This tutorial demonstrates how to:1. Use models from TensorFlow Hub... | import numpy as np
import time
import PIL.Image as Image
import matplotlib.pylab as plt
import tensorflow as tf
import tensorflow_hub as hub | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
An ImageNet classifierYou'll start by using a pretrained classifer model to take an image and predict what it's an image of - no training required! Download the classifierUse `hub.KerasLayer` to load a [MobileNetV2 model](https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/2) from TensorFlow Hub. Any [co... | classifier_model ="https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4" #@param {type:"string"}
IMAGE_SHAPE = (224, 224)
classifier = tf.keras.Sequential([
hub.KerasLayer(classifier_model, input_shape=IMAGE_SHAPE+(3,))
]) | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Run it on a single image Download a single image to try the model on. | grace_hopper = tf.keras.utils.get_file('image.jpg','https://storage.googleapis.com/download.tensorflow.org/example_images/grace_hopper.jpg')
grace_hopper = Image.open(grace_hopper).resize(IMAGE_SHAPE)
grace_hopper
grace_hopper = np.array(grace_hopper)/255.0
grace_hopper.shape | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Add a batch dimension, and pass the image to the model. | result = classifier.predict(grace_hopper[np.newaxis, ...])
result.shape | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
The result is a 1001 element vector of logits, rating the probability of each class for the image.So the top class ID can be found with argmax: | predicted_class = np.argmax(result[0], axis=-1)
predicted_class | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Decode the predictionsTake the predicted class ID and fetch the `ImageNet` labels to decode the predictions | labels_path = tf.keras.utils.get_file('ImageNetLabels.txt','https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')
imagenet_labels = np.array(open(labels_path).read().splitlines())
plt.imshow(grace_hopper)
plt.axis('off')
predicted_class_name = imagenet_labels[predicted_class]
_ = plt.title("P... | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Simple transfer learning But what if you want to train a classifier for a dataset with different classes? You can also use a model from TFHub to train a custom image classier by retraining the top layer of the model to recognize the classes in our dataset. Dataset For this example you will use the TensorFlow flowers ... | data_root = tf.keras.utils.get_file(
'flower_photos','https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',
untar=True) | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
The simplest way to load this data into our model is using `tf.keras.preprocessing.image.ImageDataGenerator`,TensorFlow Hub's conventions for image models is to expect float inputs in the `[0, 1]` range. Use the `ImageDataGenerator`'s `rescale` parameter to achieve this. | image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)
image_data = image_generator.flow_from_directory(str(data_root), target_size=IMAGE_SHAPE) | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
The resulting object is an iterator that returns `image_batch, label_batch` pairs. | for image_batch, label_batch in image_data:
print("Image batch shape: ", image_batch.shape)
print("Label batch shape: ", label_batch.shape)
break | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Run the classifier on a batch of images Now run the classifier on the image batch. | result_batch = classifier.predict(image_batch)
result_batch.shape
predicted_class_names = imagenet_labels[np.argmax(result_batch, axis=-1)]
predicted_class_names | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Now check how these predictions line up with the images: | plt.figure(figsize=(10,9))
plt.subplots_adjust(hspace=0.5)
for n in range(30):
plt.subplot(6,5,n+1)
plt.imshow(image_batch[n])
plt.title(predicted_class_names[n])
plt.axis('off')
_ = plt.suptitle("ImageNet predictions") | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
See the `LICENSE.txt` file for image attributions.The results are far from perfect, but reasonable considering that these are not the classes the model was trained for (except "daisy"). Download the headless modelTensorFlow Hub also distributes models without the top classification layer. These can be used to easily d... | feature_extractor_model = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4" #@param {type:"string"} | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Create the feature extractor. Use `trainable=False` to freeze the variables in the feature extractor layer, so that the training only modifies the new classifier layer. | feature_extractor_layer = hub.KerasLayer(
feature_extractor_model, input_shape=(224, 224, 3), trainable=False) | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
It returns a 1280-length vector for each image: | feature_batch = feature_extractor_layer(image_batch)
print(feature_batch.shape) | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Attach a classification headNow wrap the hub layer in a `tf.keras.Sequential` model, and add a new classification layer. | model = tf.keras.Sequential([
feature_extractor_layer,
tf.keras.layers.Dense(image_data.num_classes)
])
model.summary()
predictions = model(image_batch)
predictions.shape | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Train the modelUse compile to configure the training process: | model.compile(
optimizer=tf.keras.optimizers.Adam(),
loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=['acc']) | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Now use the `.fit` method to train the model.To keep this example short train just 2 epochs. To visualize the training progress, use a custom callback to log the loss and accuracy of each batch individually, instead of the epoch average. | class CollectBatchStats(tf.keras.callbacks.Callback):
def __init__(self):
self.batch_losses = []
self.batch_acc = []
def on_train_batch_end(self, batch, logs=None):
self.batch_losses.append(logs['loss'])
self.batch_acc.append(logs['acc'])
self.model.reset_metrics()
steps_per_epoch = np.ceil(ima... | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.