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['pr... | 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 acn... | 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... | 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... | _____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 ... | 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... | _____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 limi... | 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['Secon... | _____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
## Discipli... | _____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-darkgr... | _____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 ... | _____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/mas... | 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 = "../exa... | (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]: [... | _____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)
... | _____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_inde... | _____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(le... | _____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") ... | _____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/... | # 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 Parallel... | _____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 w... | ## 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...
... | _____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 mo... | 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]... | _____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... | # 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 Feat... | # 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 = [ f... | _____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 t... | 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'... | #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, "mast... | /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.htm... | 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 l... | 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.... | _____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 = "... | _____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 ... | 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... | 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 an... | 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 == ... | _____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):
checkBoolea... | _____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)
... | _____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 (ro... | 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... | 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` bel... | 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)))
pri... | 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 indice... | 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) ... | _____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 t... | 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.](http... | 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 k... | _____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 repr... | # 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... | _____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... | # 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... | _____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 arch... | # 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 -> AVGP... | _____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 ("n... | _____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 s... | 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 correc... | 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-a... | 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... | _____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/dat... | 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,)
... | _____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... | 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 瓶颈:- **到达第一字节用时**:从远程存储空间中读取文件的第一个字节所花费的时间要比从本地存储空间中读取所花费的时间长几个数量级。- **读取吞吐量**:... | 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` 转换也提供了... | 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` 转换后应用该函数,或者考虑在训练作业之前对数据进行预处理以减少资源使用... | 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` 转换的用户定义函数更改了元素大小,则映射转换和缓冲元素的转换的顺序会影响内存使用量。通常,我们建议选择能够降低内存占用的顺序,除非需要不同的顺序以提高性能。 缓存部分计... | 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(it... | _____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(n... | _____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[... | _____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, [[... | _____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... | _____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 re... | 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/e... | 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 e... | 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.